diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json
index dc7051cf..74bbbbc9 100644
--- a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json
+++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/47.json
@@ -2,7 +2,7 @@
"formatVersion": 1,
"database": {
"version": 47,
- "identityHash": "2b132d5cb114b5084d1e0d153af39294",
+ "identityHash": "f999f93f24434e50c0425191e2bcccb5",
"entities": [
{
"tableName": "BroadcastNostrEventReceipt",
@@ -671,7 +671,7 @@
},
{
"tableName": "ChatRoom",
- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `lastReadMessageId` INTEGER, `notifications` TEXT NOT NULL DEFAULT 'all', `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 )",
+ "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",
@@ -725,18 +725,6 @@
"columnName": "parentChatRoomId",
"affinity": "TEXT"
},
- {
- "fieldPath": "lastReadMessageId",
- "columnName": "lastReadMessageId",
- "affinity": "INTEGER"
- },
- {
- "fieldPath": "notifications",
- "columnName": "notifications",
- "affinity": "TEXT",
- "notNull": true,
- "defaultValue": "'all'"
- },
{
"fieldPath": "createdAt",
"columnName": "createdAt",
@@ -2341,6 +2329,524 @@
}
]
},
+ {
+ "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 )",
@@ -5427,86 +5933,6 @@
}
]
},
- {
- "tableName": "NotificationLedger",
- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, `enabled` INTEGER NOT NULL DEFAULT 1, `messages` INTEGER NOT NULL DEFAULT 1, `needsYou` INTEGER NOT NULL DEFAULT 1, `groupActivity` INTEGER NOT NULL DEFAULT 0, `showMessageText` INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(`userPublicKey`))",
- "fields": [
- {
- "fieldPath": "userPublicKey",
- "columnName": "userPublicKey",
- "affinity": "TEXT",
- "notNull": true
- },
- {
- "fieldPath": "armedAt",
- "columnName": "armedAt",
- "affinity": "INTEGER",
- "notNull": true
- },
- {
- "fieldPath": "cursorMessageId",
- "columnName": "cursorMessageId",
- "affinity": "INTEGER",
- "notNull": true
- },
- {
- "fieldPath": "lastBackgroundSyncAt",
- "columnName": "lastBackgroundSyncAt",
- "affinity": "INTEGER"
- },
- {
- "fieldPath": "lastBackgroundSyncOutcome",
- "columnName": "lastBackgroundSyncOutcome",
- "affinity": "TEXT"
- },
- {
- "fieldPath": "lastBackgroundSyncKind",
- "columnName": "lastBackgroundSyncKind",
- "affinity": "TEXT"
- },
- {
- "fieldPath": "enabled",
- "columnName": "enabled",
- "affinity": "INTEGER",
- "notNull": true,
- "defaultValue": "1"
- },
- {
- "fieldPath": "messages",
- "columnName": "messages",
- "affinity": "INTEGER",
- "notNull": true,
- "defaultValue": "1"
- },
- {
- "fieldPath": "needsYou",
- "columnName": "needsYou",
- "affinity": "INTEGER",
- "notNull": true,
- "defaultValue": "1"
- },
- {
- "fieldPath": "groupActivity",
- "columnName": "groupActivity",
- "affinity": "INTEGER",
- "notNull": true,
- "defaultValue": "0"
- },
- {
- "fieldPath": "showMessageText",
- "columnName": "showMessageText",
- "affinity": "INTEGER",
- "notNull": true,
- "defaultValue": "1"
- }
- ],
- "primaryKey": {
- "autoGenerate": false,
- "columnNames": [
- "userPublicKey"
- ]
- }
- },
{
"tableName": "Participant",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
@@ -6785,7 +7211,7 @@
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2b132d5cb114b5084d1e0d153af39294')"
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'f999f93f24434e50c0425191e2bcccb5')"
]
}
}
\ No newline at end of file
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..6cdac574
--- /dev/null
+++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/48.json
@@ -0,0 +1,7309 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 48,
+ "identityHash": "52760b3d39bf88b82aab044fe52eb413",
+ "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, `lastReadMessageId` INTEGER, `notifications` TEXT NOT NULL DEFAULT 'all', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userPublicKey",
+ "columnName": "userPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "subject",
+ "columnName": "subject",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "mlsGroupState",
+ "columnName": "mlsGroupState",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "initialGiftWrapPayloadId",
+ "columnName": "initialGiftWrapPayloadId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "leftGroupAt",
+ "columnName": "leftGroupAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "joinedGroupAt",
+ "columnName": "joinedGroupAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "chronicleRequestedAt",
+ "columnName": "chronicleRequestedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "parentChatRoomId",
+ "columnName": "parentChatRoomId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastReadMessageId",
+ "columnName": "lastReadMessageId",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "notifications",
+ "columnName": "notifications",
+ "affinity": "TEXT",
+ "notNull": true,
+ "defaultValue": "'all'"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "userPublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "GiftWrapPayload",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "initialGiftWrapPayloadId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "Confederation",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "publicKey",
+ "columnName": "publicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "proposalId",
+ "columnName": "proposalId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "ceremonyId",
+ "columnName": "ceremonyId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "roster",
+ "columnName": "roster",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "keyState",
+ "columnName": "keyState",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "genesis",
+ "columnName": "genesis",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "configSeq",
+ "columnName": "configSeq",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rosterHash",
+ "columnName": "rosterHash",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "keyStateHash",
+ "columnName": "keyStateHash",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recoveryPackages",
+ "columnName": "recoveryPackages",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_Confederation_proposalId",
+ "unique": false,
+ "columnNames": [
+ "proposalId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)"
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationCeremony",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `openingJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "chatRoomId",
+ "columnName": "chatRoomId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "proposalId",
+ "columnName": "proposalId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "coordinatorPublicKey",
+ "columnName": "coordinatorPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userPublicKey",
+ "columnName": "userPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "openingJson",
+ "columnName": "openingJson",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stage",
+ "columnName": "stage",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "approvedAt",
+ "columnName": "approvedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "dealerSeeds",
+ "columnName": "dealerSeeds",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "recoveryNonces",
+ "columnName": "recoveryNonces",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "keyState",
+ "columnName": "keyState",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "transitionHash",
+ "columnName": "transitionHash",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genesis",
+ "columnName": "genesis",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "recoveryPackages",
+ "columnName": "recoveryPackages",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "confederationPublicKey",
+ "columnName": "confederationPublicKey",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failureReason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "culprit",
+ "columnName": "culprit",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_ConfederationCeremony_chatRoomId",
+ "unique": false,
+ "columnNames": [
+ "chatRoomId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)"
+ },
+ {
+ "name": "index_ConfederationCeremony_proposalId",
+ "unique": false,
+ "columnNames": [
+ "proposalId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "ChatRoom",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "chatRoomId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationMember",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))",
+ "fields": [
+ {
+ "fieldPath": "confederationId",
+ "columnName": "confederationId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupPublicKey",
+ "columnName": "groupPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "confederationId",
+ "groupPublicKey"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_ConfederationMember_groupPublicKey",
+ "unique": false,
+ "columnNames": [
+ "groupPublicKey"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)"
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationSigningAttempt",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `confederationId` TEXT NOT NULL, `proposerPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `eventJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `declinedAt` INTEGER, `signedEventJson` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`confederationId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "confederationId",
+ "columnName": "confederationId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "proposerPublicKey",
+ "columnName": "proposerPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userPublicKey",
+ "columnName": "userPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "eventJson",
+ "columnName": "eventJson",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stage",
+ "columnName": "stage",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "approvedAt",
+ "columnName": "approvedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "declinedAt",
+ "columnName": "declinedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "signedEventJson",
+ "columnName": "signedEventJson",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failureReason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_ConfederationSigningAttempt_confederationId",
+ "unique": false,
+ "columnNames": [
+ "confederationId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationSigningAttempt_confederationId` ON `${TABLE_NAME}` (`confederationId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "ChatRoom",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "confederationId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationSigningMessage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`attemptId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`attemptId`, `senderPublicKey`, `kind`), FOREIGN KEY(`attemptId`) REFERENCES `ConfederationSigningAttempt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "attemptId",
+ "columnName": "attemptId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "senderPublicKey",
+ "columnName": "senderPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "payload",
+ "columnName": "payload",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "receivedAt",
+ "columnName": "receivedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "attemptId",
+ "senderPublicKey",
+ "kind"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "ConfederationSigningAttempt",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "attemptId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationCeremonyMessage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "sessionId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "senderPublicKey",
+ "columnName": "senderPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "payload",
+ "columnName": "payload",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "receivedAt",
+ "columnName": "receivedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "sessionId",
+ "senderPublicKey",
+ "kind"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "ConfederationCeremony",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "sessionId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationEvent",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pubKey",
+ "columnName": "pubKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "proposalId",
+ "columnName": "proposalId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "eventCreatedAt",
+ "columnName": "eventCreatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "eventJson",
+ "columnName": "eventJson",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "receivedAt",
+ "columnName": "receivedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "ownSessionId",
+ "columnName": "ownSessionId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "publishedAt",
+ "columnName": "publishedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_ConfederationEvent_proposalId",
+ "unique": false,
+ "columnNames": [
+ "proposalId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)"
+ },
+ {
+ "name": "index_ConfederationEvent_kind",
+ "unique": false,
+ "columnNames": [
+ "kind"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)"
+ },
+ {
+ "name": "index_ConfederationEvent_publishedAt",
+ "unique": false,
+ "columnNames": [
+ "publishedAt"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)"
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationInvitee",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))",
+ "fields": [
+ {
+ "fieldPath": "proposalId",
+ "columnName": "proposalId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupPublicKey",
+ "columnName": "groupPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "proposalId",
+ "groupPublicKey"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_ConfederationInvitee_groupPublicKey",
+ "unique": false,
+ "columnNames": [
+ "groupPublicKey"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)"
+ }
+ ]
+ },
+ {
+ "tableName": "ConfederationSigning",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `sealSecret` TEXT, `proposalJson` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "sessionId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sealSecret",
+ "columnName": "sealSecret",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "proposalJson",
+ "columnName": "proposalJson",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "refusal",
+ "columnName": "refusal",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "sessionId"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "FrostSigningSession",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "sessionId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "DkgParticipantMessage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "sessionId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "participantPublicKey",
+ "columnName": "participantPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "payload",
+ "columnName": "payload",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "sessionId",
+ "participantPublicKey",
+ "kind"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_DkgParticipantMessage_sessionId",
+ "unique": false,
+ "columnNames": [
+ "sessionId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "DkgSession",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "sessionId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "DkgSession",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "chatRoomId",
+ "columnName": "chatRoomId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "coordinatorPublicKey",
+ "columnName": "coordinatorPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userPublicKey",
+ "columnName": "userPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "threshold",
+ "columnName": "threshold",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "participantCount",
+ "columnName": "participantCount",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "participantPublicKeys",
+ "columnName": "participantPublicKeys",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "subject",
+ "columnName": "subject",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "walletPolicy",
+ "columnName": "walletPolicy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "stage",
+ "columnName": "stage",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "hostPublicKey",
+ "columnName": "hostPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "round1Random",
+ "columnName": "round1Random",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "round2AuxRandom",
+ "columnName": "round2AuxRandom",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "coordinatorRound1",
+ "columnName": "coordinatorRound1",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "certificate",
+ "columnName": "certificate",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "thresholdPublicKey",
+ "columnName": "thresholdPublicKey",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "secretShare",
+ "columnName": "secretShare",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "publicShares",
+ "columnName": "publicShares",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "recoveryData",
+ "columnName": "recoveryData",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failureReason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hostKeyApprovedAt",
+ "columnName": "hostKeyApprovedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "round1ApprovedAt",
+ "columnName": "round1ApprovedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "round2ApprovedAt",
+ "columnName": "round2ApprovedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "approvalRequestedThrough",
+ "columnName": "approvalRequestedThrough",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "parentChatRoomId",
+ "columnName": "parentChatRoomId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_DkgSession_chatRoomId",
+ "unique": false,
+ "columnNames": [
+ "chatRoomId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "ChatRoom",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "chatRoomId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "FrostSignerMessage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "sessionId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "signerPublicKey",
+ "columnName": "signerPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "payload",
+ "columnName": "payload",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "sessionId",
+ "signerPublicKey",
+ "kind"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_FrostSignerMessage_sessionId",
+ "unique": false,
+ "columnNames": [
+ "sessionId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "FrostSigningSession",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "sessionId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "FrostSigningItem",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "sessionId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemIndex",
+ "columnName": "itemIndex",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "unsignedEventJson",
+ "columnName": "unsignedEventJson",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "eventId",
+ "columnName": "eventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nonceRandom",
+ "columnName": "nonceRandom",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aggregatedNonce",
+ "columnName": "aggregatedNonce",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "signature",
+ "columnName": "signature",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "sessionId",
+ "itemIndex"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_FrostSigningItem_sessionId",
+ "unique": false,
+ "columnNames": [
+ "sessionId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "FrostSigningSession",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "sessionId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "FrostSigningSession",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `generation` INTEGER, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "chatRoomId",
+ "columnName": "chatRoomId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "coordinatorPublicKey",
+ "columnName": "coordinatorPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userPublicKey",
+ "columnName": "userPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "dkgSessionId",
+ "columnName": "dkgSessionId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "threshold",
+ "columnName": "threshold",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "participantCount",
+ "columnName": "participantCount",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "signerId",
+ "columnName": "signerId",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "derivationPath",
+ "columnName": "derivationPath",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "generation",
+ "columnName": "generation",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "stage",
+ "columnName": "stage",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "signerIds",
+ "columnName": "signerIds",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failureReason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "signApprovedAt",
+ "columnName": "signApprovedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "signDeclinedAt",
+ "columnName": "signDeclinedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "approvalRequestedAt",
+ "columnName": "approvalRequestedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "resentAt",
+ "columnName": "resentAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "subject",
+ "columnName": "subject",
+ "affinity": "TEXT",
+ "notNull": true,
+ "defaultValue": "'EVENTS'"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_FrostSigningSession_chatRoomId",
+ "unique": false,
+ "columnNames": [
+ "chatRoomId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)"
+ },
+ {
+ "name": "index_FrostSigningSession_dkgSessionId",
+ "unique": false,
+ "columnNames": [
+ "dkgSessionId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "ChatRoom",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "chatRoomId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "GiftWrapMessage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "publicKey",
+ "columnName": "publicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "receiverPublicKey",
+ "columnName": "receiverPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "receiverRelayHit",
+ "columnName": "receiverRelayHit",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "content",
+ "columnName": "content",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "signature",
+ "columnName": "signature",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "GiftWrapSeal",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "publicKey",
+ "columnName": "publicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tags",
+ "columnName": "tags",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "content",
+ "columnName": "content",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "signature",
+ "columnName": "signature",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "giftWrapMessageId",
+ "columnName": "giftWrapMessageId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "GiftWrapMessage",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "giftWrapMessageId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "GiftWrapPayload",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "publicKey",
+ "columnName": "publicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "chatRoomId",
+ "columnName": "chatRoomId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tags",
+ "columnName": "tags",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "content",
+ "columnName": "content",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "quotedEventId",
+ "columnName": "quotedEventId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "giftWrapSealId",
+ "columnName": "giftWrapSealId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "GiftWrapSeal",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "giftWrapSealId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "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": "NotificationLedger",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, `enabled` INTEGER NOT NULL DEFAULT 1, `messages` INTEGER NOT NULL DEFAULT 1, `needsYou` INTEGER NOT NULL DEFAULT 1, `groupActivity` INTEGER NOT NULL DEFAULT 0, `showMessageText` INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(`userPublicKey`))",
+ "fields": [
+ {
+ "fieldPath": "userPublicKey",
+ "columnName": "userPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "armedAt",
+ "columnName": "armedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cursorMessageId",
+ "columnName": "cursorMessageId",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastBackgroundSyncAt",
+ "columnName": "lastBackgroundSyncAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "lastBackgroundSyncOutcome",
+ "columnName": "lastBackgroundSyncOutcome",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastBackgroundSyncKind",
+ "columnName": "lastBackgroundSyncKind",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "1"
+ },
+ {
+ "fieldPath": "messages",
+ "columnName": "messages",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "1"
+ },
+ {
+ "fieldPath": "needsYou",
+ "columnName": "needsYou",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "1"
+ },
+ {
+ "fieldPath": "groupActivity",
+ "columnName": "groupActivity",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "0"
+ },
+ {
+ "fieldPath": "showMessageText",
+ "columnName": "showMessageText",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "1"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "userPublicKey"
+ ]
+ }
+ },
+ {
+ "tableName": "Participant",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "participantPublicKey",
+ "columnName": "participantPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "chatRoomId",
+ "columnName": "chatRoomId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "relayHint",
+ "columnName": "relayHint",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "adminAt",
+ "columnName": "adminAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "participantPublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "ChatRoom",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "chatRoomId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "Post",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "repostId",
+ "columnName": "repostId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "quote",
+ "columnName": "quote",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "content",
+ "columnName": "content",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "replyToId",
+ "columnName": "replyToId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "profilePublicKey",
+ "columnName": "profilePublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_Post_profilePublicKey",
+ "unique": false,
+ "columnNames": [
+ "profilePublicKey"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)"
+ },
+ {
+ "name": "index_Post_nostrEventId",
+ "unique": false,
+ "columnNames": [
+ "nostrEventId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)"
+ },
+ {
+ "name": "index_Post_replyToId",
+ "unique": false,
+ "columnNames": [
+ "replyToId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)"
+ },
+ {
+ "name": "index_Post_repostId",
+ "unique": false,
+ "columnNames": [
+ "repostId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "profilePublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "Post",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "replyToId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "Post",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "repostId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "Profile",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "publicKey",
+ "columnName": "publicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userName",
+ "columnName": "userName",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "displayName",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "picture",
+ "columnName": "picture",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "banner",
+ "columnName": "banner",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "website",
+ "columnName": "website",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "about",
+ "columnName": "about",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bot",
+ "columnName": "bot",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "pronouns",
+ "columnName": "pronouns",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "nip05",
+ "columnName": "nip05",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "domain",
+ "columnName": "domain",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lud06",
+ "columnName": "lud06",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lud16",
+ "columnName": "lud16",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "twitter",
+ "columnName": "twitter",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "publicKey"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_Profile_nostrEventId",
+ "unique": false,
+ "columnNames": [
+ "nostrEventId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "QuotedRelation",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "quotingNostrEventId",
+ "columnName": "quotingNostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "quotedNostrEventId",
+ "columnName": "quotedNostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "quotedProfilePublicKey",
+ "columnName": "quotedProfilePublicKey",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "quotingNostrEventId",
+ "quotedNostrEventId"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "quotedProfilePublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "quotingNostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "quotedNostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "Reaction",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "content",
+ "columnName": "content",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "replyToId",
+ "columnName": "replyToId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "profilePublicKey",
+ "columnName": "profilePublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_Reaction_profilePublicKey",
+ "unique": false,
+ "columnNames": [
+ "profilePublicKey"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)"
+ },
+ {
+ "name": "index_Reaction_nostrEventId",
+ "unique": false,
+ "columnNames": [
+ "nostrEventId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)"
+ },
+ {
+ "name": "index_Reaction_replyToId",
+ "unique": false,
+ "columnNames": [
+ "replyToId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "profilePublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "Post",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "replyToId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "RecentSearch",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))",
+ "fields": [
+ {
+ "fieldPath": "query",
+ "columnName": "query",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "synchronizationFilters",
+ "columnName": "synchronizationFilters",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "query"
+ ]
+ }
+ },
+ {
+ "tableName": "Relay",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))",
+ "fields": [
+ {
+ "fieldPath": "publicKey",
+ "columnName": "publicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "url",
+ "columnName": "url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "read",
+ "columnName": "read",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "write",
+ "columnName": "write",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "publicKey",
+ "type",
+ "url"
+ ]
+ }
+ },
+ {
+ "tableName": "RepostedRelation",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "repostingNostrEventId",
+ "columnName": "repostingNostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "repostedNostrEventId",
+ "columnName": "repostedNostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "repostedProfilePublicKey",
+ "columnName": "repostedProfilePublicKey",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "repostingNostrEventId",
+ "repostedNostrEventId"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "repostedProfilePublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "repostedNostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "repostingNostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "SynchronizeNostrEventRequest",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "purpose",
+ "columnName": "purpose",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "relayURL",
+ "columnName": "relayURL",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isRecommendedRelay",
+ "columnName": "isRecommendedRelay",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "level",
+ "columnName": "level",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "synchronizationFilters",
+ "columnName": "synchronizationFilters",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "ownerPublicKey",
+ "columnName": "ownerPublicKey",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "unsignedNostrEventId",
+ "columnName": "unsignedNostrEventId",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_SynchronizeNostrEventRequest_nostrEventId",
+ "unique": false,
+ "columnNames": [
+ "nostrEventId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)"
+ },
+ {
+ "name": "index_SynchronizeNostrEventRequest_status",
+ "unique": false,
+ "columnNames": [
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "UnsignedNostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "unsignedNostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "SynchronizeNostrEventResult",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "relayURL",
+ "columnName": "relayURL",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_SynchronizeNostrEventResult_nostrEventId",
+ "unique": false,
+ "columnNames": [
+ "nostrEventId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "UnsignedNostrEvent",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pubKey",
+ "columnName": "pubKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "kind",
+ "columnName": "kind",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tags",
+ "columnName": "tags",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "privateTags",
+ "columnName": "privateTags",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "content",
+ "columnName": "content",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "signedAt",
+ "columnName": "signedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_UnsignedNostrEvent_pubKey",
+ "unique": false,
+ "columnNames": [
+ "pubKey"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)"
+ },
+ {
+ "name": "index_UnsignedNostrEvent_kind",
+ "unique": false,
+ "columnNames": [
+ "kind"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)"
+ }
+ ]
+ },
+ {
+ "tableName": "Zap",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "postId",
+ "columnName": "postId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "senderPublicKey",
+ "columnName": "senderPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "receiverPublicKey",
+ "columnName": "receiverPublicKey",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "message",
+ "columnName": "message",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "invoice",
+ "columnName": "invoice",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "amountInMillisatoshis",
+ "columnName": "amountInMillisatoshis",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "nostrEventId",
+ "columnName": "nostrEventId",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "createdAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updatedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "savedAt",
+ "columnName": "savedAt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "viewedAt",
+ "columnName": "viewedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deletedAt",
+ "columnName": "deletedAt",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "broadcastedAt",
+ "columnName": "broadcastedAt",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_Zap_senderPublicKey",
+ "unique": false,
+ "columnNames": [
+ "senderPublicKey"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)"
+ },
+ {
+ "name": "index_Zap_nostrEventId",
+ "unique": false,
+ "columnNames": [
+ "nostrEventId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)"
+ },
+ {
+ "name": "index_Zap_postId",
+ "unique": false,
+ "columnNames": [
+ "postId"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "senderPublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "Profile",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "receiverPublicKey"
+ ],
+ "referencedColumns": [
+ "publicKey"
+ ]
+ },
+ {
+ "table": "NostrEvent",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "nostrEventId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "Post",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "postId"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '52760b3d39bf88b82aab044fe52eb413')"
+ ]
+ }
+}
\ 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 c59dd7ff..0fe8957b 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -794,6 +794,48 @@
Send again
Sent again
The group's admins have changed since this key was made. It changes on its own once an admin's device starts a new ceremony, or you can rotate it now.
+
+ Open the group's messages
+ Nobody can write to the group yet
+ Messages
+ Nothing unread
+ %1$d unread
+ This group receives direct messages
+ Only its admins read them
+ Anyone on nostr will be able to write to the group, and every admin will be able to read what it is sent.
+ The group signs where it receives messages, so it takes a quorum. Nothing is opened until it has.
+ Message relays
+ One wss:// address per line
+ Every relay has to be a public wss:// address
+ Senders' apps deliver to these relays. Choose ones that turn away spam: they are the group's first line against being flooded.
+ Ask the group to sign
+ Couldn't ask the group to sign where it receives messages.
+ Only a current admin holding a share can open the group's messages.
+ 1 message being opened
+ %1$d messages being opened
+ Waiting for 1 more admin to open this
+ Waiting for %1$d more admins to open this
+ Not yet answered by %1$s
+ %1$d more are queued: the group was sent more than its admins open in an hour
+ A message this screen can't show yet
+ Signed, not yet sent
+ Sent
+ Signed but not sent
+ Declined by the group
+ Send again
+ Only the group's current admins see its messages.
+ The group's quorum has to sign before anything is sent.
+ Write a message
+ Send
+ Preparing: the admins are working out how to write to them
+ Nothing signed by this person is on this device yet, so the group can't write to them
+ Couldn't ask the group to send this.
+ Asked the group to sign this message
+ New message
+ Their npub
+ That isn't a nostr key
+ Write to them
+ Sending again
Unread: %1$d
Conversations with unread messages: %1$d
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt
index 73435fe0..af7e27c3 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt
@@ -29,6 +29,18 @@ object ExperimentalFeatures {
val confederation: Boolean
get() = confederationOverride ?: isDevelopmentBuild()
+ /** Set by a test that has to see the build a release would be. */
+ var groupDirectMessagesOverride: Boolean? = null
+
+ /**
+ * A group sending and receiving NIP-17 at its own npub, through its admins' shares
+ * (docs/group-threshold-ecdh.md, D15). Off in a release until the device run has passed:
+ * off, nothing subscribes for the group's mail and no round is answered. The refusals --
+ * a kind 13 or 10050 a device cannot check -- run whatever this says.
+ */
+ val groupDirectMessages: Boolean
+ get() = groupDirectMessagesOverride ?: isDevelopmentBuild()
+
/** Set by a test that has to see the build a release would be. */
var groupInboxOverride: Boolean? = null
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt
index 2bf0796f..c1162e86 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt
@@ -96,6 +96,13 @@ class GizaRuntime(
DatabaseConfederationRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity)
}
+ val groupDmRepository: mobi.giza.compose.database.repository.DatabaseGroupDmRepository by lazy {
+ mobi.giza.compose.database.repository.DatabaseGroupDmRepository(
+ database = auxDatabaseManager.auxDatabase,
+ activeIdentity = activeIdentity,
+ )
+ }
+
val groupInboxRepository: DatabaseGroupInboxRepository by lazy {
DatabaseGroupInboxRepository(database = auxDatabaseManager.auxDatabase, ioScope, activeIdentity = activeIdentity)
}
@@ -128,6 +135,7 @@ class GizaRuntime(
relayRepository = nostrRepository,
scope = ioScope,
confederationRepository = confederationRepository,
+ groupDmRepository = groupDmRepository,
groupInboxRepository = groupInboxRepository,
)
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Dleq.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Dleq.kt
new file mode 100644
index 00000000..06073202
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Dleq.kt
@@ -0,0 +1,96 @@
+package mobi.giza.compose.cryptography.threshold
+
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+import mobi.giza.compose.extensions.toHex
+
+/**
+ * A Chaum-Pedersen proof that `log_G(Yᵢ) = log_P(Dᵢ)`: that a partial was made with the share
+ * whose public half the group already knows (D3 of docs/group-threshold-ecdh.md).
+ *
+ * Without it a wrong partial would make the combined point wrong, NIP-44's MAC would catch
+ * that, and nobody could say whose partial it was. With it, a bad partial is dropped and its
+ * sender named.
+ *
+ * ```
+ * k = H_nonce(s || P || D || aux) mod n R₁ = k·G, R₂ = k·P
+ * c = H(context || Y || P || D || R₁ || R₂) z = k + c·s
+ * verify: R₁ = z·G − c·Y, R₂ = z·P − c·D, and c recomputes
+ * ```
+ *
+ * The one piece of cryptography the plan writes by hand. Every operation on `s` or `k` is a
+ * libsecp256k1 call. A hash at or above `n` is refused rather than reduced: bitcoin-kmp's
+ * `PrivateKey` does not range-check (Phase 0, check 4), so [scalarOrNull] does.
+ */
+object Dleq {
+ /**
+ * Hash inputs, and so protocol rather than brand: `mantra/` as every tag is
+ * (docs/giza-rebrand.md). Renaming one makes every proof from a peer fail.
+ */
+ private const val NONCE_TAG = "mantra/threshold-ecdh/dleq-nonce/v1"
+ private const val CHALLENGE_TAG = "mantra/threshold-ecdh/dleq/v1"
+
+ data class Proof(val c: ByteVector32, val z: ByteVector32) {
+ fun toHex(): String = c.toHex() + z.toHex()
+
+ companion object {
+ fun fromHex(hex: String): Proof? {
+ if (hex.length != 128 || hex.any { it !in "0123456789abcdef" }) return null
+ return Proof(ByteVector32(hex.take(64)), ByteVector32(hex.drop(64)))
+ }
+ }
+ }
+
+ /**
+ * What a proof is bound to, so it cannot be replayed into another round: the room, the
+ * share generation and the participant id.
+ */
+ fun context(room: String, generation: Int, id: Int): ByteArray =
+ room.encodeToByteArray() + int(generation) + int(id)
+
+ private fun int(v: Int) = byteArrayOf((v ushr 24).toByte(), (v ushr 16).toByte(), (v ushr 8).toByte(), v.toByte())
+
+ private fun scalarOrNull(hash: ByteVector32): PrivateKey? = PrivateKey(hash).takeIf { it.isValid() }
+
+ private fun challenge(context: ByteArray, y: PublicKey, p: PublicKey, d: PublicKey, r1: PublicKey, r2: PublicKey): ByteVector32 =
+ Crypto.taggedHash(
+ context + y.value.toByteArray() + p.value.toByteArray() + d.value.toByteArray() +
+ r1.value.toByteArray() + r2.value.toByteArray(),
+ CHALLENGE_TAG,
+ )
+
+ /**
+ * @param aux 32 fresh random bytes, so a fault in one run cannot repeat a nonce in another.
+ * @throws IllegalStateException in the ~2⁻¹²⁸ case a hash is not a scalar; try other [aux].
+ */
+ fun prove(share: PrivateKey, y: PublicKey, p: PublicKey, d: PublicKey, context: ByteArray, aux: ByteArray): Proof {
+ require(aux.size == 32) { "aux is 32 bytes" }
+ val k = scalarOrNull(
+ Crypto.taggedHash(share.value.toByteArray() + p.value.toByteArray() + d.value.toByteArray() + aux, NONCE_TAG)
+ ) ?: error("The nonce hash was not a scalar")
+ val r1 = k.publicKey()
+ val r2 = p * k
+ val cHash = challenge(context, y, p, d, r1, r2)
+ val c = scalarOrNull(cHash) ?: error("The challenge hash was not a scalar")
+ val z = k + c * share
+ return Proof(cHash, z.value)
+ }
+
+ fun verify(y: PublicKey, p: PublicKey, d: PublicKey, context: ByteArray, proof: Proof): Boolean = try {
+ val c = scalarOrNull(proof.c)
+ val z = scalarOrNull(proof.z)
+ if (c == null || z == null || !y.isValid() || !p.isValid() || !d.isValid()) {
+ false
+ } else {
+ // Either sum may be the point at infinity, which libsecp256k1 refuses to
+ // serialise: no valid proof gives one, so the throw is a failure.
+ val r1 = z.publicKey() - y * c
+ val r2 = p * z - d * c
+ challenge(context, y, p, d, r1, r2) == proof.c
+ }
+ } catch (_: Throwable) {
+ false
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/EcdhPartial.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/EcdhPartial.kt
new file mode 100644
index 00000000..180ceb23
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/EcdhPartial.kt
@@ -0,0 +1,22 @@
+package mobi.giza.compose.cryptography.threshold
+
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+
+/**
+ * One holder's part of `x·P`: `Dᵢ = sᵢ·P`.
+ *
+ * A Diffie-Hellman value, so it says nothing about `sᵢ`, and fewer than `t` of them say
+ * nothing about `x·P`. The one scalar multiplication by a share in the whole scheme, and it
+ * is libsecp256k1's.
+ *
+ * [point] has to be a key whose owner the caller has seen sign something (D5): a point
+ * nobody can sign for may be `x^k·G`, and answering those is how a Diffie-Hellman oracle is
+ * worn down. This function cannot check that; `Evidence` does, before it is called.
+ */
+object EcdhPartial {
+ fun compute(share: PrivateKey, point: PublicKey): PublicKey {
+ require(point.isValid()) { "Not a point on the curve" }
+ return point * share
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Lagrange.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Lagrange.kt
new file mode 100644
index 00000000..209018e9
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Lagrange.kt
@@ -0,0 +1,48 @@
+package mobi.giza.compose.cryptography.threshold
+
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+
+/**
+ * Lagrange coefficients at zero, over FROST participant ids.
+ *
+ * A participant id is 0-based, as `KeyMaterial.publicSharesOf` and [mobi.giza.compose.managers.ShareGenerations]
+ * index it; the point its share was evaluated at is the id plus one, as BIP 445 says
+ * (docs/group-threshold-ecdh.md, Phase 0, check 1).
+ */
+object Lagrange {
+ /**
+ * A coefficient that can only scale a point.
+ *
+ * `Σ λᵢ·sᵢ` over shares is the group's secret, and building it is the thing
+ * shared-key-derivation.md forbids. So the scalar stays private, and the only thing a
+ * coefficient does is multiply a public point: `λᵢ·Dᵢ`, never `λᵢ·sᵢ`. The compiler
+ * keeps it that way, and `ThresholdEcdhJvmTest` reads this package's sources for the
+ * rest.
+ */
+ class Coefficient internal constructor(private val scalar: PrivateKey) {
+ fun scale(point: PublicKey): PublicKey = point * scalar
+
+ override fun equals(other: Any?): Boolean = other is Coefficient && other.scalar == scalar
+ override fun hashCode(): Int = scalar.hashCode()
+ override fun toString(): String = "Coefficient(${scalar.value.toHex()})"
+ }
+
+ /**
+ * `λ_id = Π_{j ≠ id} xⱼ / (xⱼ − x_id)`, where `x = id + 1`.
+ *
+ * @throws IllegalArgumentException if [id] is not in [ids], or an id repeats.
+ */
+ fun coefficient(id: Int, ids: Collection): Coefficient {
+ require(id in ids) { "participant $id is not among $ids" }
+ require(ids.size == ids.toSet().size) { "participant ids repeat: $ids" }
+ require(ids.all { it >= 0 }) { "participant ids are 0-based: $ids" }
+
+ val xi = Scalars.of(id + 1)
+ val lambda = ids.filter { it != id }.fold(Scalars.ONE) { acc, j ->
+ val xj = Scalars.of(j + 1)
+ acc * xj * Scalars.inverse(xj - xi)
+ }
+ return Coefficient(lambda)
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/NpubTweak.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/NpubTweak.kt
new file mode 100644
index 00000000..8ad2ba23
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/NpubTweak.kt
@@ -0,0 +1,68 @@
+package mobi.giza.compose.cryptography.threshold
+
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.SharedKeyDerivation
+
+/**
+ * How a group's npub's secret relates to its threshold key's, as public values:
+ * `d = a·x + b`, with `a ∈ {1, −1}` (D2 of docs/group-threshold-ecdh.md).
+ *
+ * The npub is the threshold key walked through x-only tweaks, and BIP 327 negates the key
+ * before each x-only tweak when its y is odd. So the sign of `x` inside `d` is the product of
+ * those negations, and `b` collects the tweaks with the signs that came after them. The
+ * library's `TweakCache` is opaque, so this replays the walk rather than reading it.
+ *
+ * Getting [negate] wrong does not fail loudly: it gives another point, whose x-coordinate
+ * opens nothing. Phase 0's check 3 and `ThresholdEcdhJvmTest` pin it against quartz.
+ */
+class NpubTweak private constructor(
+ /** True when `a = −1`. */
+ val negate: Boolean,
+ /** `b`, or null when no tweak was applied and `b = 0`, which libsecp256k1 cannot hold as a scalar. */
+ private val b: PrivateKey?,
+ /** The x-only npub the walk reached, 32 bytes as hex. */
+ val npub: String,
+) {
+ /** `d·P`, from `x·P`: `a·(x·P) + b·P`. */
+ fun apply(xP: PublicKey, p: PublicKey): PublicKey {
+ val signed = if (negate) -xP else xP
+ return if (b == null) signed else signed + p * b
+ }
+
+ override fun toString(): String = "NpubTweak(negate=$negate, npub=$npub)"
+
+ companion object {
+ /**
+ * The tweak for the key [SharedKeyDerivation.derive] reaches at [path].
+ *
+ * @throws IllegalStateException if the replay does not reach the derived key, which
+ * would mean D2's signs are wrong and every conversation key with them would be too.
+ */
+ fun of(thresholdPublicKey: PublicKey, path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH): NpubTweak {
+ val derived = SharedKeyDerivation.derive(thresholdPublicKey.value.toByteArray().toHex(), path)
+ val tweak = replay(thresholdPublicKey, derived.tweaks)
+ check(tweak.npub == derived.hex) { "The tweak replay did not reach the group's npub" }
+ return tweak
+ }
+
+ internal fun replay(x: PublicKey, tweaks: List): NpubTweak {
+ var negate = false
+ var b: PrivateKey? = null
+ var q = x
+ tweaks.forEach { scalar ->
+ val tau = PrivateKey(scalar)
+ if (q.isOdd()) {
+ q = -q
+ negate = !negate
+ b = b?.let { -it }
+ }
+ q += tau.publicKey()
+ b = b?.let { it + tau } ?: tau
+ }
+ return NpubTweak(negate, b, q.xOnly().value.toHex())
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Scalars.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Scalars.kt
new file mode 100644
index 00000000..fb1a0cfa
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Scalars.kt
@@ -0,0 +1,47 @@
+package mobi.giza.compose.cryptography.threshold
+
+import fr.acinq.bitcoin.PrivateKey
+
+/**
+ * The public scalars threshold ECDH needs, mod the curve order `n`: small integers, and their
+ * inverses. Every operation is a libsecp256k1 call through bitcoin-kmp's [PrivateKey], so
+ * nothing here is Kotlin arithmetic on a number, and none of it ever touches a share.
+ *
+ * Internal to the package. A scalar leaving it would be a scalar some other file could
+ * multiply a share by, which is the one thing [Lagrange] is shaped to prevent.
+ */
+internal object Scalars {
+ val ONE: PrivateKey = of(1)
+
+ /** `n − 2`, Fermat's exponent: `v^(n−2) = v⁻¹` in a group of prime order `n`. */
+ private const val N_MINUS_2 = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f"
+
+ /** [v] as a scalar. Zero is not a scalar libsecp256k1 accepts, and is never asked for. */
+ fun of(v: Int): PrivateKey {
+ require(v > 0) { "a scalar here is a positive integer, not $v" }
+ return PrivateKey(ByteArray(32).also {
+ it[28] = (v ushr 24).toByte()
+ it[29] = (v ushr 16).toByte()
+ it[30] = (v ushr 8).toByte()
+ it[31] = v.toByte()
+ })
+ }
+
+ /**
+ * `v⁻¹ mod n`, by square-and-multiply. 256 squarings and about 128 products, each one
+ * libsecp256k1 call: slow next to an extended Euclid, and fast next to anything a round
+ * waits on. Public values only, so constant time is not the point; using the library's
+ * own arithmetic is.
+ */
+ fun inverse(v: PrivateKey): PrivateKey {
+ var result = ONE
+ N_MINUS_2.chunked(2).forEach { pair ->
+ val byte = pair.toInt(16)
+ for (bit in 7 downTo 0) {
+ result = result * result
+ if ((byte ushr bit) and 1 == 1) result = result * v
+ }
+ }
+ return result
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdh.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdh.kt
new file mode 100644
index 00000000..4ff1a508
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdh.kt
@@ -0,0 +1,48 @@
+package mobi.giza.compose.cryptography.threshold
+
+import com.vitorpamplona.crypto.kdf.Hkdf
+import fr.acinq.bitcoin.PublicKey
+import fr.acinq.secp256k1.Hex
+
+/**
+ * Threshold ECDH for a group's npub: `d·P` from `t` holders' partials, and the NIP-44
+ * conversation key it gives (docs/group-threshold-ecdh.md, *The arithmetic*).
+ *
+ * ```
+ * x·P = Σ λᵢ·Dᵢ d·P = a·(x·P) + b·P convKey = HKDF-extract("nip44-v2", x(d·P))
+ * ```
+ *
+ * The key that comes out is the one any NIP-44 library computes from `d` and `P`, which is
+ * the whole of the interoperability argument: a sender's app cannot tell the group's key
+ * from a person's. Nothing here holds `x` or `d`; the only secret a device contributes is
+ * its own `Dᵢ`, made by [EcdhPartial].
+ */
+object ThresholdEcdh {
+ private val SALT = "nip44-v2".encodeToByteArray()
+
+ /**
+ * `d·P` from verified partials, keyed by 0-based participant id. Any `t` or more partials
+ * of one generation give the same point; fewer give a point that opens nothing, which a
+ * caller cannot tell from here, so it counts before calling.
+ */
+ fun combine(partials: Map, tweak: NpubTweak, p: PublicKey): PublicKey {
+ require(partials.isNotEmpty()) { "Nothing to combine" }
+ val ids = partials.keys
+ val xP = partials.entries
+ .map { (id, d) -> Lagrange.coefficient(id, ids).scale(d) }
+ .reduce { acc, term -> acc + term }
+ return tweak.apply(xP, p)
+ }
+
+ /** NIP-44's conversation key from the shared point: only its x-coordinate counts. */
+ fun conversationKey(point: PublicKey): ByteArray =
+ Hkdf().extract(point.value.toByteArray().copyOfRange(1, 33), SALT)
+
+ /** A nostr key, given as 32-byte x-only hex, as a point. Its parity does not matter (D2). */
+ fun pointOf(xOnlyHex: String): PublicKey? = try {
+ if (xOnlyHex.length != 64) null
+ else PublicKey(byteArrayOf(2) + Hex.decode(xOnlyHex)).takeIf { it.isValid() }
+ } catch (_: Throwable) {
+ null
+ }
+}
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 ef9540a4..816b6b41 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt
@@ -23,6 +23,7 @@ import mobi.giza.compose.database.dao.FrostSigningSessionDao
import mobi.giza.compose.database.dao.GiftWrapMessageDao
import mobi.giza.compose.database.dao.GiftWrapPayloadDao
import mobi.giza.compose.database.dao.GiftWrapSealDao
+import mobi.giza.compose.database.dao.GroupDmDao
import mobi.giza.compose.database.dao.GroupKeyStateDao
import mobi.giza.compose.database.dao.GroupSignedEventDao
import mobi.giza.compose.database.dao.GroupInboxDao
@@ -71,6 +72,12 @@ import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventRequestRel
import mobi.giza.compose.database.model.ChatMessageNostrEventRelation
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.Confederation
+import mobi.giza.compose.database.model.GroupConversationKey
+import mobi.giza.compose.database.model.GroupDmMessage
+import mobi.giza.compose.database.model.GroupDmOutbound
+import mobi.giza.compose.database.model.GroupDmWrap
+import mobi.giza.compose.database.model.GroupEcdhPartial
+import mobi.giza.compose.database.model.GroupEcdhRound
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationMember
import mobi.giza.compose.database.model.ConfederationSigningAttempt
@@ -166,6 +173,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
GiftWrapMessage::class,
GiftWrapSeal::class,
GiftWrapPayload::class,
+ GroupConversationKey::class,
+ GroupDmMessage::class,
+ GroupDmOutbound::class,
+ GroupDmWrap::class,
+ GroupEcdhPartial::class,
+ GroupEcdhRound::class,
GroupInboxMessage::class,
GroupInboxPublication::class,
GroupInboxWrap::class,
@@ -213,7 +226,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.
@@ -493,11 +506,15 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// can find a threshold-1 key, and GroupInboxWrap, GroupInboxMessage and
// GroupInboxPublication, and InboxSigning (Phase 5). New tables only, so Room generates it.
AutoMigration(from = 45, to = 46),
- // v47 adds notifications' storage (docs/notifications-and-background-sync.md, Phase 3):
+ // v47 adds a group's direct messages by threshold ECDH (docs/group-threshold-ecdh.md,
+ // Phase 4): GroupEcdhRound, GroupEcdhPartial, GroupConversationKey, GroupDmWrap,
+ // GroupDmMessage and GroupDmOutbound. New tables only, so Room generates it.
+ AutoMigration(from = 46, to = 47),
+ // v48 adds notifications' storage (docs/notifications-and-background-sync.md, Phase 3):
// ChatRoom.lastReadMessageId, ChatRoom.notifications and the NotificationLedger table.
// Room generates the shape; ReadMarkMigrationSpec then marks every existing room read up
// to its newest line, so an upgrade does not turn the user's whole history unread.
- AutoMigration(from = 46, to = 47, spec = ReadMarkMigrationSpec::class),
+ AutoMigration(from = 47, to = 48, spec = ReadMarkMigrationSpec::class),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -532,6 +549,8 @@ abstract class GizaDatabase: RoomDatabase() {
abstract fun frostSigningSessionDao(): FrostSigningSessionDao
+ abstract fun groupDmDao(): GroupDmDao
+
abstract fun groupKeyStateDao(): GroupKeyStateDao
abstract fun keyShareDao(): KeyShareDao
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt
new file mode 100644
index 00000000..138cf92f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupDmDao.kt
@@ -0,0 +1,182 @@
+package mobi.giza.compose.database.dao
+
+import androidx.room3.Dao
+import androidx.room3.Insert
+import androidx.room3.OnConflictStrategy
+import androidx.room3.Query
+import androidx.room3.Transaction
+import androidx.room3.Upsert
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlin.time.Instant
+import kotlinx.coroutines.flow.Flow
+import mobi.giza.compose.database.model.GroupConversationKey
+import mobi.giza.compose.database.model.GroupDmMessage
+import mobi.giza.compose.database.model.GroupDmOutbound
+import mobi.giza.compose.database.model.GroupDmWrap
+import mobi.giza.compose.database.model.GroupEcdhPartial
+import mobi.giza.compose.database.model.GroupEcdhRound
+
+/** A group's direct messages and the rounds that open them (docs/group-threshold-ecdh.md, Phase 4). */
+@Dao
+abstract class GroupDmDao {
+ // --- rounds
+
+ @Query("SELECT * FROM GroupEcdhRound WHERE id = :id")
+ abstract suspend fun getRound(id: HexKey): GroupEcdhRound?
+
+ @Query("SELECT * FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND state = 'OPEN'")
+ abstract suspend fun getOpenRounds(chatRoomId: HexKey): List
+
+ @Query("SELECT * FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND state = 'OPEN'")
+ abstract fun observeOpenRounds(chatRoomId: HexKey): Flow>
+
+ @Query("SELECT * FROM GroupEcdhRound WHERE state = 'OPEN'")
+ abstract suspend fun getAllOpenRounds(): List
+
+ @Query("SELECT COUNT(*) FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND purpose = 'WRAP' AND openedAt >= :since")
+ abstract suspend fun countWrapRoundsSince(chatRoomId: HexKey, since: Instant): Int
+
+ /** Once per round: two devices opening the same wrap open the same round. */
+ @Insert(onConflict = OnConflictStrategy.IGNORE)
+ abstract suspend fun insertRound(round: GroupEcdhRound): Long
+
+ @Upsert
+ abstract suspend fun upsertRound(round: GroupEcdhRound)
+
+ // --- partials
+
+ @Query("SELECT * FROM GroupEcdhPartial WHERE roundId = :roundId")
+ abstract suspend fun getPartials(roundId: HexKey): List
+
+ @Query("SELECT * FROM GroupEcdhPartial WHERE roundId IN (SELECT id FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND state = 'OPEN')")
+ abstract fun observeOpenPartials(chatRoomId: HexKey): Flow>
+
+ /** Once per round and participant: redelivery is a no-op, as `DkgParticipantMessage` absorbs it. */
+ @Insert(onConflict = OnConflictStrategy.IGNORE)
+ abstract suspend fun insertPartial(partial: GroupEcdhPartial): Long
+
+ @Upsert
+ abstract suspend fun upsertPartial(partial: GroupEcdhPartial)
+
+ // --- kept conversation keys
+
+ @Query("SELECT * FROM GroupConversationKey WHERE chatRoomId = :chatRoomId AND peer = :peer")
+ abstract suspend fun getConversationKey(chatRoomId: HexKey, peer: HexKey): GroupConversationKey?
+
+ @Query("SELECT * FROM GroupConversationKey WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun getConversationKeys(chatRoomId: HexKey): List
+
+ @Insert(onConflict = OnConflictStrategy.IGNORE)
+ abstract suspend fun insertConversationKey(key: GroupConversationKey): Long
+
+ // --- the wrap ledger
+
+ @Query("SELECT * FROM GroupDmWrap WHERE id = :id")
+ abstract suspend fun getWrap(id: HexKey): GroupDmWrap?
+
+ @Query("SELECT * FROM GroupDmWrap WHERE chatRoomId = :chatRoomId AND state = :state ORDER BY createdAt DESC")
+ abstract suspend fun getWrapsInState(chatRoomId: HexKey, state: String): List
+
+ @Query("SELECT * FROM GroupDmWrap WHERE chatRoomId = :chatRoomId AND state IN ('WAITING', 'QUEUED') ORDER BY createdAt DESC")
+ abstract fun observePendingWraps(chatRoomId: HexKey): Flow>
+
+ /** Emits as the ledger grows, so the subscription's catch-up window moves with it. */
+ @Query("SELECT MAX(createdAt) FROM GroupDmWrap")
+ abstract fun observeNewestWrapTimes(): Flow
+
+ @Query("SELECT MAX(createdAt) FROM GroupDmWrap WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun newestWrapCreatedAt(chatRoomId: HexKey): Instant?
+
+ @Insert(onConflict = OnConflictStrategy.IGNORE)
+ abstract suspend fun insertWrap(wrap: GroupDmWrap): Long
+
+ @Upsert
+ abstract suspend fun upsertWrap(wrap: GroupDmWrap)
+
+ // --- messages
+
+ @Query("SELECT * FROM GroupDmMessage WHERE rumorId = :rumorId")
+ abstract suspend fun getMessage(rumorId: HexKey): GroupDmMessage?
+
+ @Query("SELECT * FROM GroupDmMessage WHERE signingSessionId = :signingSessionId LIMIT 1")
+ abstract suspend fun getMessageBySigningSession(signingSessionId: String): GroupDmMessage?
+
+ @Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
+ abstract fun observeMessages(chatRoomId: HexKey): Flow>
+
+ @Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId ORDER BY createdAt ASC")
+ abstract fun observeConversation(chatRoomId: HexKey, conversationId: HexKey): Flow>
+
+ @Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun getMessages(chatRoomId: HexKey): List
+
+ @Query("SELECT COUNT(*) FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL")
+ abstract fun observeUnreadCount(chatRoomId: HexKey): Flow
+
+ @Query("SELECT COUNT(*) FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL")
+ abstract suspend fun countUnread(chatRoomId: HexKey): Int
+
+ @Query("UPDATE GroupDmMessage SET readAt = :at WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId AND readAt IS NULL")
+ abstract suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey, at: Instant)
+
+ /** Once per rumor: the same rumor in two wraps is one message. */
+ @Insert(onConflict = OnConflictStrategy.IGNORE)
+ abstract suspend fun insertMessage(message: GroupDmMessage): Long
+
+ // --- what the group owes recipients
+
+ @Query("SELECT * FROM GroupDmOutbound WHERE publishedAt IS NULL")
+ abstract suspend fun getOwed(): List
+
+ /** What this device owes relays and has the event for: what [mobi.giza.compose.managers.GroupDmPublisher] sends. */
+ @Query("SELECT * FROM GroupDmOutbound WHERE publishedAt IS NULL AND wrapJson IS NOT NULL")
+ abstract fun observeOwed(): Flow>
+
+ @Query("UPDATE GroupDmOutbound SET publishedAt = :at WHERE signingSessionId = :signingSessionId AND sealId = :sealId")
+ abstract suspend fun markPublished(signingSessionId: String, sealId: HexKey, at: Instant)
+
+ @Query("UPDATE GroupDmOutbound SET attempts = attempts + 1, nextAttemptAt = :next WHERE signingSessionId = :signingSessionId AND sealId = :sealId")
+ abstract suspend fun markAttempt(signingSessionId: String, sealId: HexKey, next: Instant)
+
+ @Query("SELECT * FROM GroupDmOutbound WHERE signingSessionId = :signingSessionId")
+ abstract suspend fun getOutbound(signingSessionId: String): List
+
+ @Query("SELECT * FROM GroupDmOutbound WHERE chatRoomId = :chatRoomId")
+ abstract fun observeOutbound(chatRoomId: HexKey): Flow>
+
+ @Insert(onConflict = OnConflictStrategy.IGNORE)
+ abstract suspend fun insertOutbound(outbound: GroupDmOutbound): Long
+
+ @Upsert
+ abstract suspend fun upsertOutbound(outbound: GroupDmOutbound)
+
+ // --- wiping
+
+ @Query("DELETE FROM GroupConversationKey WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun deleteConversationKeys(chatRoomId: HexKey)
+
+ @Query("DELETE FROM GroupDmMessage WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun deleteMessages(chatRoomId: HexKey)
+
+ @Query("DELETE FROM GroupDmWrap WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun deleteWraps(chatRoomId: HexKey)
+
+ @Query("DELETE FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun deleteRounds(chatRoomId: HexKey)
+
+ @Query("DELETE FROM GroupDmOutbound WHERE chatRoomId = :chatRoomId")
+ abstract suspend fun deleteOutbound(chatRoomId: HexKey)
+
+ /**
+ * Everything this device holds of a room's mail: its kept keys, what it opened, and the
+ * rounds in flight (D14). Cooperation, not enforcement: what was read stays read.
+ */
+ @Transaction
+ open suspend fun wipeRoom(chatRoomId: HexKey) {
+ deleteConversationKeys(chatRoomId)
+ deleteMessages(chatRoomId)
+ deleteWraps(chatRoomId)
+ deleteRounds(chatRoomId)
+ deleteOutbound(chatRoomId)
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt
index 1a3e7eb5..7d96f30b 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt
@@ -25,7 +25,14 @@ interface GroupInboxDao {
@Query("SELECT * FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL ORDER BY receivedAt")
suspend fun getUnopenedWraps(chatRoomId: String): List
- @Query("SELECT COUNT(*) FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL")
+ /**
+ * Wraps no inbox key opened, less those the admins opened by threshold ECDH instead
+ * (docs/group-threshold-ecdh.md): those are in the group's messages, not unread mail.
+ */
+ @Query(
+ "SELECT COUNT(*) FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL " +
+ "AND id NOT IN (SELECT id FROM GroupDmWrap WHERE state = 'OPENED')"
+ )
fun observeUnopenedCount(chatRoomId: String): Flow
/** The newest wrap's own time in a room: where a catch-up starts, less NIP-59's two days. */
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt
index 2f1d88c1..1cd27d48 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt
@@ -95,6 +95,9 @@ import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
import mobi.giza.compose.nostr.frost.ShareRepairEvents
+import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents
+import mobi.giza.compose.managers.GroupEcdhManager
+import mobi.giza.compose.managers.GroupDmReceiver
import mobi.giza.compose.nostr.frost.FrostSigningEvents
@Dao
@@ -236,6 +239,14 @@ abstract class NostrDao(
level: Int,
activeKeyPair: KeyPair
) {
+ // A wrap to a group whose mail this device reads goes to the group's own pipeline,
+ // and leaves no NostrEvent or GiftWrapMessage row: the personal inbox is built around
+ // one identity (docs/group-threshold-ecdh.md, D9).
+ if (nostrEvent.kind == GiftWrapEvent.KIND && ExperimentalFeatures.groupDirectMessages) {
+ val secret = activeKeyPair.privKey
+ if (secret != null && GroupDmReceiver.receive(database, nostrEvent.toEvent(), activeKeyPair.pubKey.toHex(), secret)) return
+ }
+
val storedNostrEvent = database.nostrEventDao().getNostrEventById(nostrEvent.id)
if (storedNostrEvent == null) {
@@ -1116,7 +1127,8 @@ abstract class NostrDao(
content = decryptedGiftWrapPayload.content,
sig = ""
),
- userPublicKey = activeKeyPair.pubKey.toHex()
+ userPublicKey = activeKeyPair.pubKey.toHex(),
+ nostrPrivateKey = activeKeyPair.privKey,
)
}
} else {
@@ -1698,7 +1710,8 @@ abstract class NostrDao(
database = database,
localChatRoom = localChatRoom,
innerEvent = innerEvent,
- userPublicKey = activeKeyPair.pubKey.toHex()
+ userPublicKey = activeKeyPair.pubKey.toHex(),
+ nostrPrivateKey = activeKeyPair.privKey,
)
DkgRitualEvents.isDkgRitualKind(innerEvent.kind) ->
@@ -1746,6 +1759,18 @@ abstract class NostrDao(
nostrPrivateKey = activeKeyPair.privKey!!
)
+ // The admins opening the group's direct messages together, in the
+ // room the key derives (docs/group-threshold-ecdh.md, Phase 5).
+ // Answered unasked, and only while the feature is on.
+ innerEvent.kind in GroupEcdhEvents.ALL && ExperimentalFeatures.groupDirectMessages ->
+ GroupEcdhManager.process(
+ database = database,
+ localChatRoom = localChatRoom,
+ innerEvent = innerEvent,
+ userPublicKey = activeKeyPair.pubKey.toHex(),
+ nostrPrivateKey = activeKeyPair.privKey!!
+ )
+
// A change to a governed room, inside the group's signature or,
// for a member's own leave, its committer's. Checked, and its
// commit applied, only here (docs/member-admin-promotion.md).
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt
index d4580ee9..a585d28d 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigration.kt
@@ -5,7 +5,7 @@ import androidx.sqlite.SQLiteConnection
import androidx.sqlite.execSQL
/**
- * v47's data half: every room an upgraded install already has is read up to its newest line.
+ * v48's data half: every room an upgraded install already has is read up to its newest line.
*
* Room generates the shape -- `ChatRoom.lastReadMessageId`, `ChatRoom.notifications` and the
* `NotificationLedger` table -- and runs this after. Without it the column is null for every
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt
index 99d2c6b8..f5d6a774 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt
@@ -47,6 +47,7 @@ import mobi.giza.compose.nostr.dkg.DkgRitualEvents
import mobi.giza.compose.nostr.frost.GovernanceEvents
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
import mobi.giza.compose.nostr.frost.ShareRepairEvents
+import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents
import mobi.giza.compose.nostr.frost.FrostSigningEvents
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
@@ -525,6 +526,12 @@ data class ChatMessage(
*/
private const val TYPE_LEGACY_GROUP_RELAYS_SIGNED = "groupRelaysSigned"
+ /**
+ * This device forgot the group's direct messages on seeing its member removed as an
+ * admin. docs/group-threshold-ecdh.md, D14.
+ */
+ const val TYPE_GROUP_DM_FORGOTTEN = "groupDmForgotten"
+
/**
* Every line the group signed, for the one check the transcript
* dispatches on. A type missing from here renders as a chat bubble,
@@ -598,6 +605,7 @@ data class ChatMessage(
TYPE_GROUP_PROFILE_SIGNED,
TYPE_LEGACY_GROUP_RELAYS_SIGNED,
TYPE_GROUP_POST_SIGNED,
+ TYPE_GROUP_DM_FORGOTTEN,
TYPE_LEGACY_GROUP_SCHEMA_SIGNED,
TYPE_LEGACY_GROUP_ENTRY_CURATED,
TYPE_WALLET_NOT_TAKEN_PART_IN,
@@ -1033,6 +1041,7 @@ data class ChatMessage(
event.kind in FrostSigningEvents.ALL ||
event.kind in ShareRefreshEvents.ALL ||
event.kind in ShareRepairEvents.ALL ||
+ event.kind in GroupEcdhEvents.ALL ||
event.kind in GovernanceEvents.ALL ||
event.kind in ConfederationSigningEvents.ALL
)
@@ -1309,6 +1318,10 @@ data class ChatMessage(
in ShareRefreshEvents.ALL -> null
in ShareRepairEvents.ALL -> null
+ // The admins' partials for the group's mail: one message per pass, and
+ // a line each would bury the room (docs/group-threshold-ecdh.md, D11).
+ in GroupEcdhEvents.ALL -> null
+
// The inbox key ceremony's messages (docs/group-inbox.md).
// `InboxKeyRitualManager` files them and writes its own lines.
in InboxKeyRitualEvents.ALL -> null
@@ -1316,7 +1329,8 @@ data class ChatMessage(
// A reply's seals, signed by the group (docs/group-inbox.md, D10). The
// signing session's own lines say the group signed something; a line naming
// the reply would reach members who are not admins, who must learn nothing of
- // the inbox (D9).
+ // the inbox (D9). The same for a message the group writes by threshold ECDH
+ // (docs/group-threshold-ecdh.md, D12).
com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND -> null
ChatEvent.KIND -> {
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt
new file mode 100644
index 00000000..71e31e9c
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupDm.kt
@@ -0,0 +1,170 @@
+package mobi.giza.compose.database.model
+
+import androidx.room3.Entity
+import androidx.room3.ForeignKey
+import androidx.room3.Index
+import androidx.room3.PrimaryKey
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlin.time.Clock
+import kotlin.time.Instant
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+
+/*
+ * A group's direct messages, by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4).
+ *
+ * None of this writes a GiftWrapMessage, GiftWrapPayload or NostrEvent row: the group's mail
+ * is its own pipeline (D9), and the personal one is built around one identity.
+ */
+
+/** Where a round has got to. */
+enum class GroupEcdhRoundState { OPEN, COMBINED, FAILED }
+
+/**
+ * One point the admins are multiplying their shares by: `(room, generation, P)`, its id a hash
+ * of the three, so two devices that open a round for the same wrap open the same round (D11).
+ */
+@Entity(
+ foreignKeys = [
+ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
+ ],
+ indices = [Index("chatRoomId"), Index("point")],
+)
+data class GroupEcdhRound(
+ @PrimaryKey
+ val id: HexKey,
+ val chatRoomId: HexKey,
+ val generation: Int,
+ /** The x-only key multiplied. */
+ val point: HexKey,
+ val purpose: EcdhPurpose,
+ /** A wrap or a seal is named by the wrap's id. */
+ val ref: HexKey? = null,
+ /** A recipient's evidence, as JSON: the only evidence that travels whole. */
+ val evidenceJson: String? = null,
+ val state: GroupEcdhRoundState = GroupEcdhRoundState.OPEN,
+ /** When this device's own partial went out; null while it is owed or not yet answerable. */
+ val partialSentAt: Instant? = null,
+ val openedAt: Instant = Clock.System.now(),
+ val combinedAt: Instant? = null,
+)
+
+/** One holder's partial for a round, once per participant id: redelivery is a no-op. */
+@Entity(
+ primaryKeys = ["roundId", "participantId"],
+ foreignKeys = [
+ ForeignKey(entity = GroupEcdhRound::class, parentColumns = ["id"], childColumns = ["roundId"], onDelete = ForeignKey.CASCADE)
+ ],
+)
+data class GroupEcdhPartial(
+ val roundId: HexKey,
+ val participantId: Int,
+ val senderPublicKey: HexKey,
+ /** `Dᵢ`, compressed. */
+ val partial: String,
+ val proof: String,
+ /** False for a partial whose proof failed: kept so its sender is named once. */
+ val verified: Boolean,
+ /** When this device published the round's failure naming this participant. */
+ val blamedAt: Instant? = null,
+ val receivedAt: Instant = Clock.System.now(),
+)
+
+/**
+ * The conversation key between the group and one correspondent, kept so their next message
+ * costs one round instead of two, and writing to them costs none (D6). A secret: wiped with the
+ * room's shares, and on this device's member being removed as an admin (D14).
+ */
+@Entity(
+ primaryKeys = ["chatRoomId", "peer"],
+ foreignKeys = [
+ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
+ ],
+)
+data class GroupConversationKey(
+ val chatRoomId: HexKey,
+ val peer: HexKey,
+ val conversationKey: String,
+ val roundId: HexKey,
+ val computedAt: Instant = Clock.System.now(),
+) {
+ override fun toString(): String = "GroupConversationKey(chatRoomId=$chatRoomId, peer=$peer, conversationKey=)"
+}
+
+/** Where a wrap to the group has got to. */
+enum class GroupDmWrapState {
+ /** Waiting on the admins: its wrap round, or its seal's. */
+ WAITING,
+
+ /** Beyond this hour's rate cap; opened newest first when there is room (Phase 7). */
+ QUEUED,
+ OPENED,
+
+ /** The combined key did not open it, or what was inside was not a seal with a rumor. */
+ UNREADABLE,
+}
+
+/** The ledger of wraps addressed to the group's npub, keyed by id: redelivery is a no-op. */
+@Entity(
+ foreignKeys = [
+ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
+ ],
+ indices = [Index("chatRoomId"), Index("state")],
+)
+data class GroupDmWrap(
+ @PrimaryKey
+ val id: HexKey,
+ val chatRoomId: HexKey,
+ val wrapJson: String,
+ /** The wrap's own created_at, back-dated by up to two days as NIP-59 does. */
+ val createdAt: Instant,
+ val state: GroupDmWrapState = GroupDmWrapState.WAITING,
+ /** The seal, once the wrap round combined: it is the seal round's evidence. */
+ val sealJson: String? = null,
+ val receivedAt: Instant = Clock.System.now(),
+)
+
+/** A message in one of the group's conversations, in or out, keyed by rumor id. */
+@Entity(
+ foreignKeys = [
+ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
+ ],
+ indices = [Index("chatRoomId"), Index("conversationId")],
+)
+data class GroupDmMessage(
+ @PrimaryKey
+ val rumorId: HexKey,
+ val chatRoomId: HexKey,
+ val conversationId: HexKey,
+ val senderPublicKey: HexKey,
+ val rumorJson: String,
+ val createdAt: Instant,
+ val outgoing: Boolean,
+ /** The wrap it came in, for a message the group was sent. */
+ val wrapId: HexKey? = null,
+ /** The signing session it went out in, for a message the group sent. */
+ val signingSessionId: String? = null,
+ val readAt: Instant? = null,
+ val filedAt: Instant = Clock.System.now(),
+)
+
+/** One recipient's copy of a message the group signed, owed until a relay takes it (D10). */
+@Entity(
+ primaryKeys = ["signingSessionId", "sealId"],
+ foreignKeys = [
+ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
+ ],
+ indices = [Index("chatRoomId")],
+)
+data class GroupDmOutbound(
+ val signingSessionId: String,
+ val sealId: HexKey,
+ val chatRoomId: HexKey,
+ val recipient: HexKey,
+ /** Comma-separated: the recipient's 10050, or the publish set when there is none. */
+ val relays: String,
+ /** The wrap, built once so every retry sends the same event. */
+ val wrapJson: String? = null,
+ val publishedAt: Instant? = null,
+ val attempts: Int = 0,
+ val nextAttemptAt: Instant? = null,
+)
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt
index 5977ba25..af5c9c28 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt
@@ -85,11 +85,15 @@ import mobi.giza.compose.managers.ConfederationRitualManager
import mobi.giza.compose.managers.ConfederationSigningManager
import mobi.giza.compose.managers.ConfederationFormation
import mobi.giza.compose.managers.ConfederationFollowThrough
+import mobi.giza.compose.managers.GroupEcdhManager
import mobi.giza.compose.managers.GroupKeyStateManager
import mobi.giza.compose.managers.MarmotGroupCreation
import mobi.giza.compose.managers.SubgroupManager
import mobi.giza.compose.nostr.MarmotProfile
+/** How often the group's direct-message rounds are swept while the app runs (docs/group-threshold-ecdh.md, Phase 5). */
+private val GROUP_DM_SWEEP_INTERVAL = kotlin.time.Duration.parse("20s")
+
/**
* @param activeIdentity the identity the app runs as. Read by the one write here that
* has to sign as it -- creating a direct-message room on the current profile puts
@@ -181,6 +185,24 @@ class DatabaseChatRepository(
}
}
}
+ // The rounds that open and write a group's direct messages: restarted where a
+ // refresh overtook them, owed partials sent, ready ones combined. Messages move
+ // them as they arrive; this catches what a dead app or a missed message left.
+ // docs/group-threshold-ecdh.md, Phase 5.
+ if (ExperimentalFeatures.groupDirectMessages) {
+ keyPair.privKey?.let { secret ->
+ launch {
+ while (true) {
+ runCatching { GroupEcdhManager.sweep(database, keyPair.pubKey.toHex(), secret) }
+ .onFailure {
+ if (it is kotlinx.coroutines.CancellationException) throw it
+ logger.e("Could not sweep the group's direct messages", it)
+ }
+ kotlinx.coroutines.delay(GROUP_DM_SWEEP_INTERVAL)
+ }
+ }
+ }
+ }
Unit
}
@@ -280,6 +302,22 @@ class DatabaseChatRepository(
null
}
+ override suspend fun groupDmRow(chatRoomId: String, userPublicKey: HexKey): mobi.giza.compose.ui.view.state.GroupDmRow? {
+ if (!ExperimentalFeatures.groupDirectMessages) return null
+ val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return null
+ val receives = mobi.giza.compose.managers.GroupDmRelays.relaysOf(database, chatRoomId) != null
+ val admin = RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) == true &&
+ ShareGenerations.active(database, key).signerIds.containsKey(userPublicKey)
+ return when {
+ admin && receives -> mobi.giza.compose.ui.view.state.GroupDmRow.Messages(
+ unread = database.groupDmDao().countUnread(chatRoomId)
+ )
+ admin -> mobi.giza.compose.ui.view.state.GroupDmRow.OpenMessages
+ receives -> mobi.giza.compose.ui.view.state.GroupDmRow.ReceivesMessages
+ else -> null
+ }
+ }
+
override suspend fun inboxSummary(localChatRoom: LocalChatRoom): mobi.giza.compose.ui.view.state.InboxRowSummary? {
if (!mobi.giza.compose.ExperimentalFeatures.groupInbox || localChatRoom.chatRoom.mlsGroupState == null) return null
val roomId = localChatRoom.chatRoom.id
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt
index 764db422..f0e23070 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt
@@ -32,7 +32,31 @@ class DatabaseFrostSigningRepository(
runCatching {
val user = database.frostSigningSessionDao().getSessionById(sessionId)?.userPublicKey ?: return@runCatching emptyList()
mobi.giza.compose.managers.InboxRefusal.notes(database, chatRoomId, user, sessionId, events)
- }.getOrDefault(emptyList())
+ }.getOrDefault(emptyList()) +
+ runCatching { groupDmNotes(sessionId, events) }.getOrDefault(emptyList())
+
+ /**
+ * A message from the group, as an admin's device read it from the manifest: its words,
+ * who it goes to and what it answers (docs/group-threshold-ecdh.md, D13). A device that
+ * could not read it says only what the seals are.
+ */
+ private suspend fun groupDmNotes(sessionId: String, events: List): List {
+ if (events.none { it.kind == com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND }) return emptyList()
+ val message = database.groupDmDao().getMessageBySigningSession(sessionId) ?: return emptyList()
+ val rumor = Event.fromJsonOrNull(message.rumorJson) ?: return emptyList()
+ val names = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { tag ->
+ database.profileDao().getProfileByPublicKey(tag[1])?.let { it.displayName?.takeIf { n -> n.isNotBlank() } ?: it.userName }
+ ?: tag[1].take(8)
+ }
+ val answering = rumor.tags.firstOrNull { it.size >= 2 && it[0] == "e" }?.get(1)
+ ?.let { database.groupDmDao().getMessage(it) }
+ ?.let { Event.fromJsonOrNull(it.rumorJson)?.content }
+ return listOfNotNull(
+ "A message from the group: ${rumor.content}",
+ "To ${names.joinToString(", ")}",
+ answering?.let { "Answering: $it" },
+ )
+ }
override fun observeSessionById(sessionId: String): Flow =
database.frostSigningSessionDao().observeSessionById(sessionId)
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt
new file mode 100644
index 00000000..7eb57cc9
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt
@@ -0,0 +1,183 @@
+package mobi.giza.compose.database.repository
+
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlin.time.Instant
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.FrostSigningSession
+import mobi.giza.compose.database.model.GroupDmOutbound
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.managers.FrostSigningManager
+import mobi.giza.compose.managers.GroupDmRelays
+import mobi.giza.compose.managers.RoomAdmins
+import mobi.giza.compose.managers.ShareGenerations
+import mobi.giza.compose.repository.GroupDmRepository
+
+class DatabaseGroupDmRepository(
+ private val database: GizaDatabase,
+ private val activeIdentity: kotlinx.coroutines.flow.StateFlow = kotlinx.coroutines.flow.MutableStateFlow(null),
+) : GroupDmRepository {
+ override suspend fun send(
+ localChatRoom: LocalChatRoom,
+ recipients: List,
+ text: String,
+ replyTo: HexKey?,
+ ): mobi.giza.compose.managers.GroupDmSender.Outcome {
+ val identity = activeIdentity.value ?: throw IllegalStateException("No identity is open")
+ val secret = identity.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign")
+ return mobi.giza.compose.managers.GroupDmSender.send(database, localChatRoom, identity.nostrPublicKey, secret.value.toByteArray(), recipients, text, replyTo)
+ }
+
+ override suspend fun sendAgain(signingSessionId: String): Boolean =
+ mobi.giza.compose.managers.GroupDmSender.sendAgain(database, signingSessionId)
+
+ override fun observeOwed(): Flow> = database.groupDmDao().observeOwed()
+
+ override suspend fun markPublished(outbound: GroupDmOutbound, at: Instant) =
+ database.groupDmDao().markPublished(outbound.signingSessionId, outbound.sealId, at)
+
+ override suspend fun markAttempt(outbound: GroupDmOutbound, next: Instant) =
+ database.groupDmDao().markAttempt(outbound.signingSessionId, outbound.sealId, next)
+
+ override fun observeRelays(chatRoomId: HexKey): Flow?> =
+ database.groupSignedEventDao().observeByKind(GroupDmRelays.KIND)
+ .map { rows ->
+ rows.filter { it.chatRoomId == chatRoomId && it.publicKey.equals(chatRoomId, ignoreCase = true) }
+ .maxByOrNull { it.createdAt }
+ ?.let { GroupDmRelays.relaysIn(it.tags) }
+ }
+ .distinctUntilChanged()
+
+ override fun observeReadableRooms(userPublicKey: HexKey): Flow> =
+ kotlinx.coroutines.flow.combine(
+ database.chatRoomDao().observeChatRoomListByUserPublicKey(userPublicKey),
+ database.groupSignedEventDao().observeByKind(GroupDmRelays.KIND),
+ database.groupDmDao().observeNewestWrapTimes(),
+ ) { rooms, _, _ -> rooms }
+ .map { rooms ->
+ rooms.filter { it.chatRoom.mlsGroupState != null && it.chatRoom.leftGroupAt == null && it.chatRoom.deletedAt == null }
+ .mapNotNull { room ->
+ val id = room.chatRoom.id
+ if (!mobi.giza.compose.managers.GroupDmReceiver.readsFor(database, id, userPublicKey)) return@mapNotNull null
+ mobi.giza.compose.managers.GroupDmInbox(
+ roomId = id,
+ relays = GroupDmRelays.relaysOf(database, id).orEmpty(),
+ newestWrapAt = database.groupDmDao().newestWrapCreatedAt(id)?.epochSeconds,
+ )
+ }
+ .sortedBy { it.roomId }
+ }
+ .distinctUntilChanged()
+
+ override suspend fun receiveWrap(wrap: com.vitorpamplona.quartz.nip01Core.core.Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Boolean =
+ mobi.giza.compose.managers.GroupDmReceiver.receive(database, wrap, userPublicKey, nostrPrivateKey)
+
+ override fun observeConversations(chatRoomId: HexKey): Flow> =
+ database.groupDmDao().observeMessages(chatRoomId).map { messages ->
+ messages.groupBy { it.conversationId }.map { (conversationId, inIt) ->
+ val newest = inIt.maxBy { it.createdAt }
+ val participants = participantsIn(chatRoomId, inIt)
+ mobi.giza.compose.ui.view.state.GroupDmConversationSummary(
+ conversationId = conversationId,
+ participants = participants,
+ names = participants.map { nameOf(it) },
+ lastLine = lineOf(newest.rumorJson),
+ lastAt = newest.createdAt,
+ unread = inIt.count { !it.outgoing && it.readAt == null },
+ )
+ }.sortedByDescending { it.lastAt }
+ }
+
+ override fun observePending(chatRoomId: HexKey): Flow =
+ kotlinx.coroutines.flow.combine(
+ database.groupDmDao().observePendingWraps(chatRoomId),
+ database.groupDmDao().observeOpenPartials(chatRoomId),
+ ) { wraps, _ -> wraps }.map { wraps ->
+ val waiting = wraps.filter { it.state == mobi.giza.compose.database.model.GroupDmWrapState.WAITING }
+ val newest = waiting.maxByOrNull { it.createdAt }
+ val (needed, notYet) = newest?.let { mobi.giza.compose.managers.GroupDmReceiver.waitingOn(database, chatRoomId, it) }
+ ?: (0 to emptyList())
+ mobi.giza.compose.ui.view.state.GroupDmPending(
+ waiting = waiting.size,
+ queued = wraps.count { it.state == mobi.giza.compose.database.model.GroupDmWrapState.QUEUED },
+ moreAdminsNeeded = needed,
+ notYetAnsweredBy = notYet.map { nameOf(it) },
+ )
+ }.distinctUntilChanged()
+
+ override fun observeConversation(chatRoomId: HexKey, conversationId: HexKey): Flow> =
+ kotlinx.coroutines.flow.combine(
+ database.groupDmDao().observeConversation(chatRoomId, conversationId),
+ database.groupDmDao().observeOutbound(chatRoomId),
+ ) { messages, outbound -> messages to outbound }.map { (messages, outbound) ->
+ messages.map { message ->
+ val owed = message.signingSessionId?.let { id -> outbound.filter { it.signingSessionId == id } }.orEmpty()
+ mobi.giza.compose.ui.view.state.GroupDmLine(
+ id = message.rumorId,
+ text = lineOf(message.rumorJson),
+ outgoing = message.outgoing,
+ senderName = nameOf(message.senderPublicKey),
+ at = message.createdAt,
+ outgoingState = if (message.outgoing) outgoingStateOf(message.signingSessionId, owed) else null,
+ signingSessionId = message.signingSessionId,
+ )
+ }
+ }
+
+ /**
+ * Where a message the group sent has got to: its signing session, then its wraps. Sent once
+ * every recipient's wrap is on a relay; signed but not sent when the session completed and
+ * no wrap is owed here, which is how every device but the proposer's sees it (D10).
+ */
+ private suspend fun outgoingStateOf(
+ signingSessionId: String?,
+ owed: List,
+ ): mobi.giza.compose.ui.view.state.GroupDmOutgoingState? {
+ val session = signingSessionId?.let { database.frostSigningSessionDao().getSessionById(it) } ?: return null
+ return when {
+ session.stage == mobi.giza.compose.database.model.types.FrostSigningStage.FAILED ->
+ mobi.giza.compose.ui.view.state.GroupDmOutgoingState.DECLINED
+ session.stage != mobi.giza.compose.database.model.types.FrostSigningStage.COMPLETE ->
+ mobi.giza.compose.ui.view.state.GroupDmOutgoingState.BEING_SIGNED
+ owed.isNotEmpty() && owed.all { it.publishedAt != null } -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.SENT
+ owed.isNotEmpty() && owed.any { it.attempts > 0 } -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.NOT_SENT
+ owed.isNotEmpty() -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.SIGNED
+ else -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.NOT_SENT
+ }
+ }
+
+ override suspend fun participantsOf(chatRoomId: HexKey, conversationId: HexKey): List =
+ participantsIn(chatRoomId, database.groupDmDao().getMessages(chatRoomId).filter { it.conversationId == conversationId })
+
+ private fun participantsIn(chatRoomId: HexKey, messages: List): List =
+ messages.flatMap { message ->
+ runCatching { com.vitorpamplona.quartz.nip01Core.core.Event.fromJson(message.rumorJson) }.getOrNull()
+ ?.let { mobi.giza.compose.nostr.groupdm.GroupDmConversation.participantsOf(it, chatRoomId) }
+ .orEmpty()
+ }.distinct().sorted()
+
+ /** A kind 14's words; null for anything else, which the screen says it cannot show yet. */
+ private fun lineOf(rumorJson: String): String? =
+ runCatching { com.vitorpamplona.quartz.nip01Core.core.Event.fromJson(rumorJson) }.getOrNull()
+ ?.takeIf { it.kind == 14 }?.content
+
+ override suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey) =
+ database.groupDmDao().markRead(chatRoomId, conversationId, kotlin.time.Clock.System.now())
+
+ override suspend fun nameOf(publicKey: HexKey): String =
+ database.profileDao().getProfileByPublicKey(publicKey)
+ ?.let { profile -> profile.displayName?.takeIf { it.isNotBlank() && it != "LOADING..." } ?: profile.userName?.takeIf { it.isNotBlank() } }
+ ?: publicKey.take(8)
+
+ override suspend fun isCurrentAdmin(chatRoomId: HexKey, userPublicKey: HexKey): Boolean {
+ val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return false
+ if (userPublicKey !in admins) return false
+ val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return false
+ return ShareGenerations.active(database, key).signerIds.containsKey(userPublicKey)
+ }
+
+ override suspend fun proposeRelays(localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession =
+ GroupDmRelays.propose(database, localChatRoom, userPublicKey, relays)
+}
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 0b8336a4..d1534267 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt
@@ -408,7 +408,13 @@ object FrostSigningManager {
database: GizaDatabase,
localChatRoom: LocalChatRoom,
innerEvent: Event,
- userPublicKey: HexKey
+ userPublicKey: HexKey,
+ /**
+ * This device's nostr key, for the one check that needs it: opening a message's
+ * manifest with the host key it derives (docs/group-threshold-ecdh.md, D13). Without
+ * it a batch of seals is held rather than asked about.
+ */
+ nostrPrivateKey: ByteArray? = null,
) {
val sessionId = FrostSigningEvents.parseSessionId(innerEvent.tags)
if (sessionId == null) {
@@ -422,7 +428,8 @@ object FrostSigningManager {
localChatRoom = localChatRoom,
innerEvent = innerEvent,
sessionId = sessionId,
- userPublicKey = userPublicKey
+ userPublicKey = userPublicKey,
+ nostrPrivateKey = nostrPrivateKey,
)
} else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL) {
declineWalletProposal(
@@ -559,7 +566,8 @@ object FrostSigningManager {
localChatRoom: LocalChatRoom,
innerEvent: Event,
sessionId: String,
- userPublicKey: HexKey
+ userPublicKey: HexKey,
+ nostrPrivateKey: ByteArray? = null,
): FrostSigningSession? {
database.frostSigningSessionDao().getSessionById(sessionId)?.let { existing ->
// The events a session signs are fixed at creation. A second proposal
@@ -683,6 +691,30 @@ object FrostSigningManager {
return declined
}
+ // A message the group would send: every signer reads it first, and declines one
+ // it cannot read or that says different things to different people. One still
+ // waiting on a recipient's key is held, stored, and asked once the key is made.
+ // docs/group-threshold-ecdh.md, D13.
+ var groupDm: GroupDmRefusal.Verdict.Readable? = null
+ if (GroupDmRefusal.involves(unsignedEvents)) {
+ when (val verdict = GroupDmRefusal.check(database, localChatRoom, innerEvent.pubKey, unsignedEvents, innerEvent.tags, userPublicKey, nostrPrivateKey)) {
+ is GroupDmRefusal.Verdict.Declined -> {
+ logger.w("Signing proposal $sessionId: a message from the group ${verdict.why}; declining")
+ val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n)
+ .copy(signDeclinedAt = Clock.System.now())
+ database.frostSigningSessionDao().upsert(declined)
+ database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
+ announceStarted(database, declined)
+ return declined
+ }
+ GroupDmRefusal.Verdict.Waiting -> {
+ logger.i("Signing proposal $sessionId: waiting on a recipient's key before asking")
+ return null
+ }
+ is GroupDmRefusal.Verdict.Readable -> groupDm = verdict
+ }
+ }
+
// A change to a governed room whose commit does not say what its statement
// says -- or that the group's door would refuse anyway -- is declined before
// anybody is asked, for the wallet's reason: a device that signs what it
@@ -783,6 +815,8 @@ object FrostSigningManager {
database.frostSigningSessionDao().upsert(session)
database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
confederation?.let { ConfederationRefusal.remember(database, sessionId, it, null) }
+ // Read, so filed: every admin's device sees what the group is sending (D12).
+ groupDm?.let { GroupDmSender.record(database, session, localChatRoom.chatRoom.id, it.rumor, it.manifest) }
if (inboxManifest != null && InboxRefusal.involves(unsignedEvents)) {
InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, null, inboxManifest)
}
@@ -1484,6 +1518,14 @@ object FrostSigningManager {
logger.e("Signed session ${session.id} but could not file its confederation event", e)
}
+ // A message from the group: wrapped for each recipient by the device that
+ // proposed it, and owed to their relays. docs/group-threshold-ecdh.md, D10.
+ try {
+ GroupDmSender.onSigned(database, session, signedEvents)
+ } catch (e: Throwable) {
+ logger.e("Signed session ${session.id} but could not wrap its message", e)
+ }
+
announce(
database = database,
session = session,
@@ -2293,6 +2335,18 @@ object FrostSigningManager {
return
}
+ // A message from the group this device did not read on arrival -- filed by an
+ // older build, or reached here some other way -- is declined, never signed blind.
+ // Read means filed: GroupDmSender.record wrote it as outgoing. D13.
+ if (session.subject == FrostSigningSubject.EVENTS && GroupDmRefusal.involvesItems(items) &&
+ database.groupDmDao().getMessageBySigningSession(sessionId) == null
+ ) {
+ logger.w("Session $sessionId signs a message from the group this device has not read; declining")
+ update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) }
+ advance(database, localChatRoom, sessionId)
+ return
+ }
+
// Checked again rather than trusted from arrival: the group's admins can change
// while a member decides, and the seal has to hold the ones it has when it signs.
// docs/confederation.md, D6.
@@ -2808,6 +2862,8 @@ object FrostSigningManager {
inboxReason != null -> inboxReason
isWalletSession(session, items) -> WalletRefusal.REASON
isUnshowableSession(session, items) -> GroupStatementRefusal.REASON
+ session.subject == FrostSigningSubject.EVENTS && GroupDmRefusal.involvesItems(items) ->
+ GroupDmRefusal.reasonFor(database, session.chatRoomId, session.userPublicKey)
!holdsShareFor(database, session) -> GENERATION_REFUSAL
else -> "Declined to sign"
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt
new file mode 100644
index 00000000..06352eb5
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmPublisher.kt
@@ -0,0 +1,90 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import kotlin.time.Clock
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.milliseconds
+import kotlin.time.Duration.Companion.minutes
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.TimeoutCancellationException
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.take
+import kotlinx.coroutines.withTimeout
+import mobi.giza.compose.database.model.GroupDmOutbound
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.network.dto.RelayDTO
+import mobi.giza.compose.network.relays.EventPublishTransport
+import mobi.giza.compose.network.relays.RelayPool
+import mobi.giza.compose.network.sockets.NostrIncomingMessage
+import mobi.giza.compose.repository.GroupDmRepository
+
+/**
+ * Sends what a group's direct messages owe relays, and keeps trying until one takes each
+ * (docs/group-threshold-ecdh.md, D8 and D10): the group's signed 10050 from the device that
+ * proposed it, and the gift wraps of a message the group signed.
+ *
+ * Not through the `BroadcastNostrEventRequest` queue, for the confederation's reason: that
+ * hangs off a `NostrEvent` row, and a group-signed event or a wrap is not one this app's
+ * feed should hold. The owed rows are [GroupDmOutbound], marked published once a relay
+ * accepts them, so a restart picks up where it left off.
+ */
+class GroupDmPublisher(
+ private val repository: GroupDmRepository,
+ private val transport: EventPublishTransport,
+ private val firstRetry: Duration = 1.minutes,
+ private val lastRetry: Duration = 30.minutes,
+) {
+ private val logger = Logger.withTag("GroupDmPublisher")
+
+ /** Runs until cancelled. */
+ suspend fun run() {
+ repository.observeOwed().collectLatest { owed ->
+ var wait = firstRetry
+ var remaining = owed
+ while (remaining.isNotEmpty()) {
+ remaining = remaining.filterNot { publish(it) }
+ if (remaining.isEmpty()) break
+ logger.w("${remaining.size} direct message event(s) not yet taken by any relay; trying again in $wait")
+ remaining.forEach { repository.markAttempt(it, Clock.System.now() + wait) }
+ delay(wait)
+ wait = minOf(wait * 2, lastRetry)
+ }
+ }
+ }
+
+ /** Sends [outbound] to every relay it names. Whether any accepted it. */
+ suspend fun publish(outbound: GroupDmOutbound): Boolean {
+ val event = outbound.wrapJson?.let { runCatching { Event.fromJson(it) }.getOrNull() } ?: return false
+ val targets = outbound.relays.split(",").map { it.trim() }.filter { it.startsWith("wss://") }.distinct()
+ if (targets.isEmpty()) return false
+ var accepted = false
+ try {
+ withTimeout((RelayPool.PUBLISH_TIMEOUT * 2).milliseconds) {
+ transport.publishEvent(
+ nostrEvent = NostrEvent(
+ id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags,
+ content = event.content, sig = event.sig,
+ createdAt = kotlin.time.Instant.fromEpochSeconds(event.createdAt),
+ ),
+ relays = targets.map { RelayDTO(url = it, read = false, write = true) }.toSet(),
+ ).take(targets.size).collect { result ->
+ val ok = result.result as? NostrIncomingMessage.OkMessage
+ if (result.error == null && ok?.success == true) accepted = true
+ }
+ }
+ } catch (_: TimeoutCancellationException) {
+ // A relay that never answers. Whatever answered in time counts.
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ logger.e("Could not send ${event.id.take(8)} of kind ${event.kind}", e)
+ }
+ if (accepted) {
+ repository.markPublished(outbound, Clock.System.now())
+ logger.i("${event.id.take(8)} of kind ${event.kind} is on a relay")
+ }
+ return accepted
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt
new file mode 100644
index 00000000..ac477406
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt
@@ -0,0 +1,237 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import kotlin.time.Clock
+import kotlin.time.Duration.Companion.hours
+import kotlin.time.Instant
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.GroupDmMessage
+import mobi.giza.compose.database.model.GroupDmWrap
+import mobi.giza.compose.database.model.GroupDmWrapState
+import mobi.giza.compose.database.model.GroupEcdhRoundState
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+import mobi.giza.compose.nostr.groupdm.Evidence
+import mobi.giza.compose.nostr.groupdm.GroupDmConversation
+import mobi.giza.compose.nostr.groupdm.GroupDmSeal
+import mobi.giza.compose.nostr.groupdm.GroupEcdhPayload
+
+/**
+ * A room whose mail this device reads: where to ask for it, and the newest wrap already in
+ * its ledger, from which `live-group-dm` asks two days back (NIP-59 back-dates wraps).
+ */
+data class GroupDmInbox(val roomId: HexKey, val relays: List, val newestWrapAt: Long?)
+
+/**
+ * A group's mail, from a wrap on a relay to a message on the admins' screens (D9 of
+ * docs/group-threshold-ecdh.md). Its own pipeline: nothing here writes a `GiftWrapMessage`,
+ * `GiftWrapPayload` or `NostrEvent` row, because the personal one is built around one
+ * identity and would file the group's correspondents among the admin's own.
+ *
+ * ```
+ * wrap → ledger → wrap round → seal → seal round, or the kept key → rumor → GroupDmMessage
+ * ```
+ *
+ * Every admin's device runs every step and combines for itself; nothing is decrypted once and
+ * passed round. [step] is driven from [GroupEcdhManager.advance], so a partial that completes
+ * a round moves the message on in the same pass.
+ */
+object GroupDmReceiver {
+ private val logger = Logger.withTag("GroupDmReceiver")
+
+ /**
+ * New wrap rounds this device opens per room per hour (Phase 7): anyone can make the
+ * admins' devices work by sending wraps. Beyond it wraps wait in the ledger, newest first.
+ * Two batches' worth at Phase 0's size. A `var` so a test can see the cap without sixty wraps.
+ */
+ internal var maxNewWrapRoundsPerHour = 60
+
+ /**
+ * Whether this device reads [chatRoomId]'s mail: the feature on, its member a current
+ * admin holding a share, and the group has signed where it receives messages (D7, D8).
+ */
+ suspend fun readsFor(database: GizaDatabase, chatRoomId: HexKey, userPublicKey: HexKey): Boolean {
+ if (!ExperimentalFeatures.groupDirectMessages) return false
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return false
+ if (room.chatRoom.userPublicKey != userPublicKey) return false
+ if (GroupDmRelays.relaysOf(database, chatRoomId) == null) return false
+ val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return false
+ if (userPublicKey !in admins) return false
+ val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return false
+ return ShareGenerations.active(database, key).signerIds.containsKey(userPublicKey)
+ }
+
+ /** Whether one of the group inbox's keys this device holds opens [wrap] (docs/group-inbox.md). */
+ private suspend fun opensWithInboxKey(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, wrap: Event): Boolean {
+ if (!ExperimentalFeatures.groupInbox) return false
+ val secrets = database.inboxKeyDao().getKeys(roomId, userPublicKey).mapNotNull { it.secretKey?.hexToByteArray() }
+ return secrets.isNotEmpty() && mobi.giza.compose.nostr.inbox.InboxWrap.open(wrap, secrets) != null
+ }
+
+ /** The room a wrap is addressed to, among those this device reads for. */
+ suspend fun roomFor(database: GizaDatabase, wrap: Event, userPublicKey: HexKey): HexKey? {
+ if (wrap.kind != GiftWrapEvent.KIND) return null
+ return wrap.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1].lowercase() }.distinct()
+ .firstOrNull { readsFor(database, it, userPublicKey) }
+ }
+
+ /**
+ * A wrap from a relay: into the ledger of the room it is addressed to, if this device reads
+ * for one, and moved as far as it can go. Whether it was the group's. Redelivery is a no-op.
+ */
+ suspend fun receive(database: GizaDatabase, wrap: Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Boolean {
+ val roomId = roomFor(database, wrap, userPublicKey) ?: return false
+ // The group's NIP-4E inbox key opens what a decoupled sender wrote, at once and with no
+ // round: it is tried first, and a round is opened only for what it cannot open
+ // (docs/group-threshold-ecdh.md, *Against the NIP-4E plan*).
+ if (opensWithInboxKey(database, roomId, userPublicKey, wrap)) {
+ GroupInboxManager.receive(database, wrap, userPublicKey)
+ return true
+ }
+ // The wrap is its own evidence (D5): signed by its pubkey and addressed to the group.
+ if (!Evidence.allows(EcdhPurpose.WRAP, wrap.pubKey, wrap, roomId)) return true
+ database.groupDmDao().insertWrap(
+ GroupDmWrap(id = wrap.id, chatRoomId = roomId, wrapJson = wrap.toJson(), createdAt = Instant.fromEpochSeconds(wrap.createdAt))
+ )
+ val room = database.chatRoomDao().findChatRoomById(roomId) ?: return true
+ GroupEcdhManager.contextFor(database, room, userPublicKey, nostrPrivateKey)?.let { GroupEcdhManager.advance(database, it) }
+ return true
+ }
+
+ /**
+ * One pass over [context]'s ledger: opens wrap rounds up to the cap, opens seal rounds for
+ * seals whose key is not kept, and files every message whose keys are in hand. Returns
+ * whether it changed anything, so the sweep knows to go round again.
+ */
+ suspend fun step(database: GizaDatabase, context: GroupEcdhManager.RoomContext): Boolean {
+ val dao = database.groupDmDao()
+ var changed = false
+
+ // Wraps whose round this device has not opened, queued ones included, newest first.
+ val pending = (dao.getWrapsInState(context.roomId, GroupDmWrapState.WAITING.name) +
+ dao.getWrapsInState(context.roomId, GroupDmWrapState.QUEUED.name))
+ .filter { it.sealJson == null }
+ .sortedByDescending { it.createdAt }
+ val since = Clock.System.now() - 1.hours
+ var budget = maxNewWrapRoundsPerHour - dao.countWrapRoundsSince(context.roomId, since)
+ pending.forEach { ledger ->
+ val wrap = runCatching { Event.fromJson(ledger.wrapJson) }.getOrNull() ?: return@forEach
+ val roundId = GroupEcdhPayload.roundId(context.roomId, context.generation, wrap.pubKey)
+ if (dao.getRound(roundId) != null) {
+ if (ledger.state == GroupDmWrapState.QUEUED) { dao.upsertWrap(ledger.copy(state = GroupDmWrapState.WAITING)); changed = true }
+ return@forEach
+ }
+ if (budget > 0) {
+ GroupEcdhManager.ensureRound(database, context, wrap.pubKey, EcdhPurpose.WRAP, ref = ledger.id)
+ if (ledger.state == GroupDmWrapState.QUEUED) dao.upsertWrap(ledger.copy(state = GroupDmWrapState.WAITING))
+ budget -= 1
+ changed = true
+ } else if (ledger.state != GroupDmWrapState.QUEUED) {
+ dao.upsertWrap(ledger.copy(state = GroupDmWrapState.QUEUED))
+ changed = true
+ }
+ }
+
+ // Wraps opened to a seal: the seal's key kept, or a round for it.
+ dao.getWrapsInState(context.roomId, GroupDmWrapState.WAITING.name).filter { it.sealJson != null }.forEach { ledger ->
+ val seal = runCatching { Event.fromJson(ledger.sealJson!!) }.getOrNull()
+ if (seal == null || !Evidence.allows(EcdhPurpose.SEAL, seal.pubKey, seal, context.roomId)) {
+ dao.upsertWrap(ledger.copy(state = GroupDmWrapState.UNREADABLE))
+ changed = true
+ return@forEach
+ }
+ val kept = dao.getConversationKey(context.roomId, seal.pubKey.lowercase())
+ if (kept == null) {
+ val roundId = GroupEcdhPayload.roundId(context.roomId, context.generation, seal.pubKey)
+ if (dao.getRound(roundId) == null) {
+ GroupEcdhManager.ensureRound(database, context, seal.pubKey, EcdhPurpose.SEAL, ref = ledger.id)
+ changed = true
+ }
+ return@forEach
+ }
+ val rumor = GroupDmSeal.open(seal, kept.conversationKey.hexToByteArray())
+ if (rumor == null) {
+ dao.upsertWrap(ledger.copy(state = GroupDmWrapState.UNREADABLE))
+ } else {
+ file(database, context.roomId, rumor, wrapId = ledger.id)
+ dao.upsertWrap(ledger.copy(state = GroupDmWrapState.OPENED))
+ }
+ changed = true
+ }
+ return changed
+ }
+
+ /**
+ * A rumor into its conversation, once: the same rumor in two wraps is one message. A rumor
+ * that is not kind 14 is filed as one the screen cannot show yet, not dropped.
+ */
+ private suspend fun file(database: GizaDatabase, roomId: HexKey, rumor: Event, wrapId: HexKey) {
+ val inserted = database.groupDmDao().insertMessage(
+ GroupDmMessage(
+ rumorId = rumor.id,
+ chatRoomId = roomId,
+ conversationId = GroupDmConversation.idOf(rumor, roomId),
+ senderPublicKey = rumor.pubKey,
+ rumorJson = rumor.toJson(),
+ createdAt = Instant.fromEpochSeconds(rumor.createdAt),
+ outgoing = false,
+ wrapId = wrapId,
+ )
+ )
+ if (inserted > 0) logger.i { "Filed a message of kind ${rumor.kind} to ${roomId.take(8)}" }
+ }
+
+ /**
+ * A device whose member is no longer one of [chatRoomId]'s admins forgets the room's mail:
+ * its kept conversation keys, what it opened and the rounds in flight, and says so in the
+ * room (D14). Cooperation, not enforcement -- what was read stays read -- and it is the
+ * device's own: the group cut it off from new mail the moment the removal landed (D4).
+ * Returns whether it forgot anything.
+ */
+ suspend fun forgetIfRemoved(database: GizaDatabase, chatRoomId: HexKey, userPublicKey: HexKey): Boolean {
+ val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return false
+ if (userPublicKey in admins) return false
+ val dao = database.groupDmDao()
+ val holds = dao.getConversationKeys(chatRoomId).isNotEmpty() || dao.getMessages(chatRoomId).isNotEmpty() ||
+ dao.getAllOpenRounds().any { it.chatRoomId == chatRoomId } || dao.newestWrapCreatedAt(chatRoomId) != null
+ if (!holds) return false
+ dao.wipeRoom(chatRoomId)
+ database.scrubFreedPages()
+ database.chatMessageDao().upsert(
+ mobi.giza.compose.database.model.ChatMessage(
+ senderPublicKey = userPublicKey,
+ isUserMessage = true,
+ giftWrapPayloadId = null,
+ marmotGroupEventId = null,
+ marmotInnerEventId = null,
+ chatRoomId = chatRoomId,
+ content = "You are no longer an admin, so this device forgot the group's direct messages",
+ messageType = mobi.giza.compose.database.model.ChatMessage.TYPE_GROUP_DM_FORGOTTEN,
+ )
+ )
+ logger.i { "Forgot ${chatRoomId.take(8)}'s direct messages: no longer an admin" }
+ return true
+ }
+
+ /**
+ * What [ledger] waits on: how many more admins have to answer its open round, and which
+ * current admins have not. Read from public rows only, so a screen can show it.
+ */
+ suspend fun waitingOn(database: GizaDatabase, roomId: HexKey, ledger: GroupDmWrap): Pair> {
+ val key = FrostSigningManager.completedKey(database, roomId) ?: return 0 to emptyList()
+ val shares = ShareGenerations.active(database, key)
+ val roomAdmins = RoomAdmins.of(database, roomId)?.admins.orEmpty()
+ val admins = shares.signerIds.filterKeys { it in roomAdmins }
+ val wrap = runCatching { Event.fromJson(ledger.wrapJson) }.getOrNull() ?: return 0 to emptyList()
+ val point = ledger.sealJson?.let { runCatching { Event.fromJson(it).pubKey }.getOrNull() } ?: wrap.pubKey
+ val round = database.groupDmDao().getRound(GroupEcdhPayload.roundId(roomId, shares.generation, point))
+ ?.takeIf { it.state == GroupEcdhRoundState.OPEN }
+ val answered = round?.let { r -> database.groupDmDao().getPartials(r.id).filter { it.verified }.map { it.participantId }.toSet() }.orEmpty()
+ val needed = (key.threshold - answered.size).coerceAtLeast(0)
+ return needed to admins.filterValues { it !in answered }.keys.sorted()
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt
new file mode 100644
index 00000000..62dd1af7
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRefusal.kt
@@ -0,0 +1,153 @@
+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.nip59Giftwrap.seals.SealEvent
+import kotlin.time.Clock
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.FrostSigningItem
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.nostr.groupdm.AdminSeal
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+import mobi.giza.compose.nostr.groupdm.Evidence
+import mobi.giza.compose.nostr.groupdm.GroupDmManifest
+import mobi.giza.compose.nostr.groupdm.GroupDmSeal
+
+/**
+ * Every signer reads a message before the group sends it (D13 of docs/group-threshold-ecdh.md).
+ *
+ * A seal is ciphertext, and a device that signs one it cannot read is the rubber stamp
+ * docs/giza-wallet-removal.md says a Giza device must never be. So a batch of kind 13s is
+ * checked on arrival, again at approval, and declined out loud with a reason when it fails:
+ *
+ * 1. the manifest opens with this device's host key, from a proposer who is a current admin;
+ * 2. every event is a kind 13 by the room, with no tags;
+ * 3. every recipient's evidence is signed by that recipient, and is not the group;
+ * 4. this device holds `conv(group, R)` for each, or it *waits* -- joins the round and asks
+ * nothing yet -- rather than declining;
+ * 5. every seal opens to the **same** rumor: kind 14, by the room, unsigned, words in it, and
+ * `p` tags exactly the manifest's recipients;
+ * 6. every `created_at` is within two days before now and not ahead of it.
+ *
+ * With the feature off, every batch of seals is declined: a release build cannot read one.
+ */
+object GroupDmRefusal {
+ const val REASON = "Giza doesn't sign a private message unless it can read it, and it says the same thing to everyone"
+ const val CANNOT_READ = "This device can't read what the group would be sending"
+ const val FEATURE_OFF = "Giza doesn't sign a private message it can't read"
+
+ /** How far a seal's `created_at` may be from now: NIP-59's two days back, and a little skew forward. */
+ private const val TWO_DAYS = 2L * 24 * 60 * 60
+ private const val SKEW = 10L * 60
+
+ sealed interface Verdict {
+ /** The message every seal carries, and the manifest it was read from. */
+ data class Readable(val rumor: Event, val manifest: GroupDmManifest) : Verdict
+
+ /** Declined, with the reason sent to the group. */
+ data class Declined(val reason: String, val why: String) : Verdict
+
+ /** This device is still computing a recipient's key; nothing is asked until it has. */
+ data object Waiting : Verdict
+ }
+
+ /**
+ * A seal this refusal is about: every one that does not name an inbox key. The group
+ * inbox's replies (docs/group-inbox.md, D10) are seals too, and name the inbox key they
+ * come from in one well-formed `n` tag; those are `InboxRefusal`'s. Split on the inbox's own
+ * reading of the tag, so no seal falls to neither -- a malformed `n` lands here, and check 2
+ * declines it.
+ */
+ fun isOurs(event: Event): Boolean =
+ event.kind == SealEvent.KIND && mobi.giza.compose.nostr.inbox.InboxSeal.encryptionKeyOf(event.tags) == null
+
+ fun involves(events: List): Boolean = events.any(::isOurs)
+
+ fun involvesItems(items: List): Boolean =
+ items.any { Event.fromJsonOrNull(it.unsignedEventJson)?.let(::isOurs) == true }
+
+ suspend fun check(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ proposer: HexKey,
+ events: List,
+ proposalTags: Array>,
+ userPublicKey: HexKey,
+ nostrPrivateKey: ByteArray?,
+ now: Long = Clock.System.now().epochSeconds,
+ ): Verdict {
+ if (!ExperimentalFeatures.groupDirectMessages) return Verdict.Declined(FEATURE_OFF, "the feature is off")
+ val roomId = localChatRoom.chatRoom.id
+ // A batch of seals with nothing to read them by is no message any device could check.
+ val sealed = GroupDmManifest.sealedIn(proposalTags) ?: return Verdict.Declined(CANNOT_READ, "there is no manifest")
+ val secret = nostrPrivateKey ?: return Verdict.Waiting
+
+ // 1. The manifest, addressed to this device's host key by a current admin.
+ val context = GroupEcdhManager.contextFor(database, localChatRoom, userPublicKey, secret)
+ ?: return Verdict.Declined(CANNOT_READ, "this device's member is not a current admin holding a share")
+ val proposerHost = context.admins[proposer]?.second
+ ?: return Verdict.Declined(CANNOT_READ, "the proposer is not a current admin")
+ val manifest = AdminSeal.open(sealed, ChillDkgRitualManager.deriveHostSecretKey(secret), context.myHostKey, proposerHost)
+ ?.let(GroupDmManifest::decode)
+ ?: return Verdict.Declined(CANNOT_READ, "the manifest has no slot this device can open")
+
+ // 2. Seals by the room, with nothing a recipient's app would not expect.
+ if (events.isEmpty() || events.size != manifest.seals.size) return Verdict.Declined(REASON, "the manifest names ${manifest.seals.size} recipients for ${events.size} seals")
+ events.forEach { seal ->
+ if (seal.kind != SealEvent.KIND || !seal.pubKey.equals(roomId, ignoreCase = true) || seal.tags.isNotEmpty()) {
+ return Verdict.Declined(REASON, "an item is not a bare kind 13 by the group")
+ }
+ }
+
+ // 3. Each recipient's evidence, as D5 asks of anyone a device multiplies by.
+ val recipients = manifest.seals.map { it.recipient.lowercase() }
+ if (recipients.toSet().size != recipients.size) return Verdict.Declined(REASON, "a recipient repeats")
+ manifest.seals.forEach { seal ->
+ Evidence.check(EcdhPurpose.RECIPIENT, seal.recipient, seal.evidence, roomId)?.let {
+ return Verdict.Declined(REASON, "a recipient's evidence was refused: $it")
+ }
+ }
+
+ // 4. The conversation keys, or a round for each missing one, and wait.
+ val keys = recipients.map { database.groupDmDao().getConversationKey(roomId, it) }
+ if (keys.any { it == null }) {
+ manifest.seals.filterIndexed { i, _ -> keys[i] == null }.forEach { seal ->
+ GroupEcdhManager.ensureRound(database, context, seal.recipient, EcdhPurpose.RECIPIENT, evidence = seal.evidence)
+ }
+ GroupEcdhManager.flush(database, context)
+ return Verdict.Waiting
+ }
+
+ // 5. One message, the same to everyone, to exactly the recipients named.
+ val rumors = events.mapIndexed { i, seal ->
+ GroupDmSeal.open(seal, keys[i]!!.conversationKey.hexToByteArray())
+ ?: return Verdict.Declined(REASON, "a seal does not open with its recipient's key")
+ }
+ val rumor = rumors.first()
+ if (rumors.any { it.id != rumor.id || it.toJson() != rumor.toJson() }) return Verdict.Declined(REASON, "the seals do not hold the same message")
+ if (rumor.kind != 14 || !rumor.pubKey.equals(roomId, ignoreCase = true) || rumor.content.isBlank()) {
+ return Verdict.Declined(REASON, "the message is not a kind 14 by the group with words in it")
+ }
+ val tagged = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1].lowercase() }
+ if (tagged.toSet() != recipients.toSet() || tagged.size != recipients.size) {
+ return Verdict.Declined(REASON, "the message names other recipients than the manifest")
+ }
+
+ // 6. Back-dated as NIP-59 does, and not from the future.
+ events.forEach { seal ->
+ if (seal.createdAt > now + SKEW || seal.createdAt < now - TWO_DAYS - SKEW) {
+ return Verdict.Declined(REASON, "a seal's time is outside NIP-59's two days")
+ }
+ }
+ return Verdict.Readable(rumor, manifest)
+ }
+
+ /** The reason a decline of [items] says, on a device without its key to hand. */
+ suspend fun reasonFor(database: GizaDatabase, chatRoomId: HexKey, userPublicKey: HexKey): String {
+ if (!ExperimentalFeatures.groupDirectMessages) return FEATURE_OFF
+ val admins = RoomAdmins.of(database, chatRoomId)?.admins.orEmpty()
+ return if (userPublicKey in admins) REASON else CANNOT_READ
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt
new file mode 100644
index 00000000..5aa1c02f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmRelays.kt
@@ -0,0 +1,64 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.FrostSigningSession
+import mobi.giza.compose.database.model.GroupSignedEvent
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.nostr.RelayUrlInput
+import mobi.giza.compose.nostr.Relays
+
+/**
+ * Where the group receives direct messages: a kind 10050 the group signs (D8 of
+ * docs/group-threshold-ecdh.md).
+ *
+ * A sender's app sends NIP-17 to the recipient's 10050 relays, and many send nothing when
+ * there are none, so signing one is the group's decision to receive. Until it has, no device
+ * subscribes for its mail. The signed list is a [GroupSignedEvent] row on every signer's
+ * device, read back by [relaysOf]; the proposer's device owes it to relays ([onSigned]).
+ */
+object GroupDmRelays {
+ const val KIND = 10050
+ private const val RELAY_TAG = "relay"
+
+ /** The relays a 10050's tags list, normalised, or null when any is not a public `wss://` relay or none is. */
+ fun relaysIn(tags: Array>): List? {
+ val raw = tags.filter { it.size >= 2 && it[0] == RELAY_TAG }.map { it[1] }
+ if (raw.isEmpty()) return null
+ return raw.map { RelayUrlInput.relayUrlOrNull(it)?.url ?: return null }.distinct()
+ }
+
+ fun tagsFor(relays: List): Array> = relays.map { arrayOf(RELAY_TAG, it) }.toTypedArray()
+
+ /** What the setup screen starts from. */
+ val defaultRelays: List get() = Relays.DefaultDMRelayList.map { it.url }
+
+ /**
+ * Asks the group to sign [relays] as where it receives messages.
+ *
+ * @throws IllegalArgumentException when a relay is not one [RelayUrlInput] accepts: the
+ * signers would decline it (`InboxRefusal.RELAYS_SHAPE`), so it is not proposed.
+ */
+ suspend fun propose(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession {
+ val normalised = relaysIn(tagsFor(relays)) ?: throw IllegalArgumentException("Every relay has to be a public wss:// address")
+ return FrostSigningManager.proposeSigning(
+ database = database,
+ localChatRoom = localChatRoom,
+ userPublicKey = userPublicKey,
+ kind = KIND,
+ tags = tagsFor(normalised),
+ content = "",
+ )
+ }
+
+ /** The newest 10050 the group signed in [chatRoomId], if it has signed one. */
+ suspend fun signedListOf(database: GizaDatabase, chatRoomId: HexKey): GroupSignedEvent? =
+ database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, KIND)
+ .filter { it.publicKey.equals(chatRoomId, ignoreCase = true) }
+ .maxByOrNull { it.createdAt }
+
+ /** Where the group receives messages, or null while it has not opened them. */
+ suspend fun relaysOf(database: GizaDatabase, chatRoomId: HexKey): List? =
+ signedListOf(database, chatRoomId)?.let { relaysIn(it.tags) }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt
new file mode 100644
index 00000000..0ad71d94
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmSender.kt
@@ -0,0 +1,231 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.crypto.random.RandomInstance
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.crypto.verify
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import kotlin.time.Clock
+import kotlin.time.Instant
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.FrostSigningSession
+import mobi.giza.compose.database.model.GroupDmMessage
+import mobi.giza.compose.database.model.GroupDmOutbound
+import mobi.giza.compose.database.model.GroupDmWrapState
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.nostr.Relays
+import mobi.giza.compose.nostr.frost.FrostSigningEvents
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+import mobi.giza.compose.nostr.groupdm.Evidence
+import mobi.giza.compose.nostr.groupdm.GroupDmConversation
+import mobi.giza.compose.nostr.groupdm.GroupDmManifest
+import mobi.giza.compose.nostr.groupdm.GroupDmSeal
+
+/**
+ * The group writing to someone (D10 and D12 of docs/group-threshold-ecdh.md): one rumor, one
+ * seal per recipient under the kept `conv(group, R)`, signed by the group in one batch, then
+ * wrapped by the proposer's device under a key of its own and sent to each recipient's 10050.
+ *
+ * There is no copy to the group itself: that would be ECDH with the group's own npub, which D5
+ * forbids. Every admin's device files the message as outgoing from the manifest instead.
+ */
+object GroupDmSender {
+ private val logger = Logger.withTag("GroupDmSender")
+
+ private const val TWO_DAYS = 2L * 24 * 60 * 60
+
+ sealed interface Outcome {
+ /** Proposed: the group's quorum signs it next. */
+ data class Proposed(val sessionId: String) : Outcome
+
+ /** A recipient's key is still being computed by the admins; try again when it is. */
+ data class Preparing(val recipients: List) : Outcome
+
+ /** Nothing signed by [recipient] is on this device, so no device may multiply by their key (D5). */
+ data class NoEvidence(val recipient: HexKey) : Outcome
+
+ /** This device's member is not a current admin holding a share. */
+ data object NotAnAdmin : Outcome
+ }
+
+ /**
+ * Something [recipient] signed that this device can check: a seal they sent the group, or
+ * any event of theirs it holds. The smallest of them, since the manifest carries it.
+ */
+ suspend fun evidenceFor(database: GizaDatabase, roomId: HexKey, recipient: HexKey): Event? {
+ val r = recipient.lowercase()
+ val seals = database.groupDmDao().getWrapsInState(roomId, GroupDmWrapState.OPENED.name)
+ .mapNotNull { it.sealJson?.let { json -> runCatching { Event.fromJson(json) }.getOrNull() } }
+ .filter { it.pubKey == r }
+ val own = listOf(10050, 0, 10002, 1).mapNotNull { kind ->
+ database.nostrEventDao().getNostrEventByPublicKeyAndKind(r, kind)?.takeIf { it.sig.length == 128 }?.toEvent()
+ }
+ return (own + seals)
+ .filter { Evidence.allows(EcdhPurpose.RECIPIENT, r, it, roomId) }
+ .minByOrNull { it.toJson().length }
+ }
+
+ /** Where [recipient] receives messages: their 10050, or the publish set and the app's DM relays. */
+ suspend fun relaysFor(database: GizaDatabase, recipient: HexKey): List {
+ val listed = database.nostrEventDao().getNostrEventByPublicKeyAndKind(recipient.lowercase(), GroupDmRelays.KIND)
+ ?.let { GroupDmRelays.relaysIn(it.tags) }
+ return listed?.takeIf { it.isNotEmpty() }
+ ?: (Relays.eventPublishRelaySet.map { it.url } + Relays.DefaultDMRelayList.map { it.url }).distinct()
+ }
+
+ /**
+ * Asks the group to send [text] to [recipients], answering [replyTo] if given. A recipient
+ * whose key the admins have not computed yet has a round opened, and the answer is
+ * [Outcome.Preparing]; the composer tries again once the round combines.
+ */
+ suspend fun send(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ userPublicKey: HexKey,
+ nostrPrivateKey: ByteArray,
+ recipients: List,
+ text: String,
+ replyTo: HexKey? = null,
+ now: Long = Clock.System.now().epochSeconds,
+ ): Outcome {
+ require(text.isNotBlank()) { "A message has words in it" }
+ val to = recipients.map { it.lowercase() }.distinct()
+ require(to.isNotEmpty()) { "A message has a recipient" }
+ val context = GroupEcdhManager.contextFor(database, localChatRoom, userPublicKey, nostrPrivateKey) ?: return Outcome.NotAnAdmin
+ val roomId = context.roomId
+ require(to.none { it == roomId }) { "The group does not write to itself (D5)" }
+
+ val evidence = to.associateWith { r -> evidenceFor(database, roomId, r) ?: return Outcome.NoEvidence(r) }
+ val keys = to.associateWith { database.groupDmDao().getConversationKey(roomId, it) }
+ val missing = to.filter { keys[it] == null }
+ if (missing.isNotEmpty()) {
+ missing.forEach { r -> GroupEcdhManager.ensureRound(database, context, r, EcdhPurpose.RECIPIENT, evidence = evidence.getValue(r)) }
+ GroupEcdhManager.advance(database, context)
+ val still = missing.filter { database.groupDmDao().getConversationKey(roomId, it) == null }
+ if (still.isNotEmpty()) return Outcome.Preparing(still)
+ }
+
+ val tags = to.map { arrayOf("p", it) } + listOfNotNull(replyTo?.let { arrayOf("e", it, "", "reply") })
+ val rumor = GroupDmSeal.rumor(roomId, now, 14, tags.toTypedArray(), text)
+ val seals = to.map { r ->
+ val key = database.groupDmDao().getConversationKey(roomId, r)!!.conversationKey.hexToByteArray()
+ GroupDmSeal.build(rumor, key, createdAt = now - randomBackdate())
+ }
+ val manifest = GroupDmManifest(to.map { GroupDmManifest.Seal(it, evidence.getValue(it)) }, replyTo)
+ val session = FrostSigningManager.proposeSigningBatch(
+ database = database,
+ localChatRoom = localChatRoom,
+ userPublicKey = userPublicKey,
+ events = seals,
+ key = context.key,
+ proposalTags = manifest.toTags(context.sealToAdmins(manifest.encode())),
+ )
+ record(database, session, roomId, rumor, manifest)
+ return Outcome.Proposed(session.id)
+ }
+
+ /** NIP-59's back-dating: up to two days, at random. */
+ private fun randomBackdate(): Long {
+ val bytes = RandomInstance.bytes(4)
+ val v = ((bytes[0].toLong() and 0xff) shl 24) or ((bytes[1].toLong() and 0xff) shl 16) or
+ ((bytes[2].toLong() and 0xff) shl 8) or (bytes[3].toLong() and 0xff)
+ return v % TWO_DAYS
+ }
+
+ /**
+ * Files a message the group is being asked to send, on any admin's device that has read it:
+ * outgoing in its conversation, and one owed wrap per recipient, keyed by the seal's id,
+ * waiting for the signature. Idempotent.
+ */
+ suspend fun record(database: GizaDatabase, session: FrostSigningSession, roomId: HexKey, rumor: Event, manifest: GroupDmManifest) {
+ val dao = database.groupDmDao()
+ dao.insertMessage(
+ GroupDmMessage(
+ rumorId = rumor.id,
+ chatRoomId = roomId,
+ conversationId = GroupDmConversation.idOf(rumor, roomId),
+ senderPublicKey = roomId,
+ rumorJson = rumor.toJson(),
+ createdAt = Instant.fromEpochSeconds(rumor.createdAt),
+ outgoing = true,
+ signingSessionId = session.id,
+ readAt = Clock.System.now(),
+ )
+ )
+ val items = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex }
+ items.forEachIndexed { i, item ->
+ val recipient = manifest.seals.getOrNull(i)?.recipient ?: return@forEachIndexed
+ dao.insertOutbound(
+ GroupDmOutbound(
+ signingSessionId = session.id,
+ sealId = item.eventId,
+ chatRoomId = roomId,
+ recipient = recipient,
+ relays = relaysFor(database, recipient).joinToString(","),
+ )
+ )
+ }
+ }
+
+ /**
+ * A batch of seals the group just signed: the proposer's device wraps each for its recipient
+ * and owes it to their relays. Other devices hold the same rows unwrapped, for Send again.
+ */
+ suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) {
+ if (signedEvents.none { it.kind == SealEvent.KIND }) return
+ if (!session.isCoordinator()) return
+ wrapOwed(database, session.id, signedEvents)
+ }
+
+ /**
+ * Send again, from any admin's device: wraps whatever this device has not wrapped, from the
+ * signed seals every signer holds, and owes them again. Whether there was anything to send.
+ */
+ suspend fun sendAgain(database: GizaDatabase, signingSessionId: String): Boolean {
+ val signed = database.groupDmDao().getOutbound(signingSessionId).mapNotNull { row ->
+ database.groupSignedEventDao().getById(row.sealId)?.toEvent()
+ }
+ val rows = wrapOwed(database, signingSessionId, signed)
+ database.groupDmDao().getOutbound(signingSessionId).filter { it.publishedAt == null && it.wrapJson != null }.forEach {
+ database.groupDmDao().upsertOutbound(it.copy(attempts = 0, nextAttemptAt = null))
+ }
+ return rows > 0 || database.groupDmDao().getOutbound(signingSessionId).any { it.publishedAt == null }
+ }
+
+ private suspend fun wrapOwed(database: GizaDatabase, signingSessionId: String, signedEvents: List): Int {
+ val dao = database.groupDmDao()
+ var wrapped = 0
+ dao.getOutbound(signingSessionId).filter { it.wrapJson == null }.forEach { row ->
+ val signed = signedEvents.firstOrNull { it.id == row.sealId }?.takeIf { it.verify() } ?: return@forEach
+ // Ordinary NIP-59: a fresh key of this device's, no group secret involved.
+ val wrap = GiftWrapEvent.create(event = signed, recipientPubKey = row.recipient)
+ dao.upsertOutbound(row.copy(wrapJson = wrap.toJson()))
+ wrapped += 1
+ }
+ if (wrapped > 0) logger.i { "Wrapped $wrapped seal(s) of $signingSessionId for their recipients" }
+ return wrapped
+ }
+
+ /**
+ * Proposals of the group's messages this device held back while it computed a recipient's
+ * key (D13, check 4): handed to the signing manager again now that a round has combined.
+ */
+ suspend fun retryHeld(database: GizaDatabase, context: GroupEcdhManager.RoomContext, nostrPrivateKey: ByteArray) {
+ database.marmotInnerEventDao().getByChatRoomAndKinds(context.roomId, listOf(FrostSigningEvents.PROPOSAL))
+ .filter { GroupDmManifest.isCarriedBy(it.tags) }
+ .forEach { stored ->
+ val sessionId = FrostSigningEvents.parseSessionId(stored.tags) ?: return@forEach
+ if (database.frostSigningSessionDao().getSessionById(sessionId) != null) return@forEach
+ FrostSigningManager.processSigningPayload(
+ database = database,
+ localChatRoom = context.room,
+ innerEvent = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, ""),
+ userPublicKey = context.userPublicKey,
+ nostrPrivateKey = nostrPrivateKey,
+ )
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt
new file mode 100644
index 00000000..304767b7
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupEcdhManager.kt
@@ -0,0 +1,453 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.crypto.random.RandomInstance
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+import kotlin.time.Clock
+import kotlin.time.Instant
+import mobi.giza.compose.cryptography.threshold.Dleq
+import mobi.giza.compose.cryptography.threshold.EcdhPartial
+import mobi.giza.compose.cryptography.threshold.NpubTweak
+import mobi.giza.compose.cryptography.threshold.ThresholdEcdh
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.GroupConversationKey
+import mobi.giza.compose.database.model.GroupDmWrapState
+import mobi.giza.compose.database.model.GroupEcdhPartial
+import mobi.giza.compose.database.model.GroupEcdhRound
+import mobi.giza.compose.database.model.GroupEcdhRoundState
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.groupdm.AdminSeal
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+import mobi.giza.compose.nostr.groupdm.Evidence
+import mobi.giza.compose.nostr.groupdm.GroupDmWrap
+import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents
+import mobi.giza.compose.nostr.groupdm.GroupEcdhPayload
+
+/**
+ * The admins' devices multiplying their shares by a point, together, until any `t` of them
+ * give `d·P` (D3, D4, D5 and D11 of docs/group-threshold-ecdh.md).
+ *
+ * Nobody is asked anything: being an admin is the decision to read the group's mail (D7). A
+ * device answers a round when its member is a current admin holding a share of the active
+ * generation, it has the round's evidence and that evidence checks out. It answers once,
+ * batches what it owes into one partials message per pass, seals it to the other current
+ * admins' host keys, and combines as soon as it holds `t` proven partials. Everything is a
+ * function of stored rows, so a device that dies mid-round picks up where it was.
+ *
+ * What a combined round gives is handed on through the database rather than a callback: a
+ * seal's or a recipient's conversation key is kept in [GroupConversationKey] (D6), and a
+ * wrap's opens its wrap at once, the seal going onto the ledger row for the receiver.
+ */
+object GroupEcdhManager {
+ private val logger = Logger.withTag("GroupEcdhManager")
+
+ /** Plaintext bytes per partials message: about thirty items, well inside a relay's event (Phase 0, check 6). */
+ const val MAX_PAYLOAD_BYTES = 16_000
+
+ /**
+ * What one device knows of one room, enough to answer and combine. Null from [contextFor]
+ * whenever this device must take no part: no completed key, no share of the active
+ * generation, or its member is not a current admin (D4).
+ */
+ class RoomContext(
+ val room: LocalChatRoom,
+ val userPublicKey: HexKey,
+ val key: DkgSession,
+ val generation: Int,
+ val myId: Int,
+ private val secretShare: PrivateKey,
+ val publicShares: List,
+ val threshold: Int,
+ val tweak: NpubTweak,
+ private val hostSecret: PrivateKey,
+ val myHostKey: HexKey,
+ /** For the one caller that hands a held proposal back to the signing manager ([GroupDmSender.retryHeld]). */
+ internal val nostrPrivateKey: ByteArray,
+ /** Current admins holding a share of [generation], this device's member included: member to (id, host key). */
+ val admins: Map>,
+ ) {
+ val roomId: HexKey get() = room.chatRoom.id
+
+ internal fun partial(point: PublicKey): PublicKey = EcdhPartial.compute(secretShare, point)
+
+ internal fun proof(point: PublicKey, partial: PublicKey): Dleq.Proof =
+ Dleq.prove(secretShare, publicShares[myId], point, partial, Dleq.context(roomId, generation, myId), RandomInstance.bytes(32))
+
+ internal fun seal(plaintext: String): AdminSeal.Sealed =
+ AdminSeal.seal(plaintext, hostSecret, admins.filterKeys { it != userPublicKey }.values.map { it.second })
+
+ /** [plaintext] for the other current admins: a message's manifest (D12). */
+ internal fun sealToAdmins(plaintext: String): AdminSeal.Sealed = seal(plaintext)
+
+ internal fun open(sealed: AdminSeal.Sealed, senderHostKey: HexKey): String? =
+ AdminSeal.open(sealed, hostSecret, myHostKey, senderHostKey)
+
+ override fun toString(): String = "RoomContext(room=$roomId, generation=$generation, id=$myId, admins=${admins.size})"
+ }
+
+ suspend fun contextFor(database: GizaDatabase, room: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray): RoomContext? {
+ val roomId = room.chatRoom.id
+ val key = FrostSigningManager.completedKey(database, roomId) ?: return null
+ val thresholdPublicKey = key.thresholdPublicKey ?: return null
+ val shares = ShareGenerations.active(database, key)
+ val secretShare = shares.secretShare ?: return null
+ val publicShares = shares.publicShares ?: return null
+ val myId = shares.signerIds[userPublicKey] ?: return null
+
+ val roomAdmins = RoomAdmins.of(database, roomId)?.admins ?: return null
+ if (userPublicKey !in roomAdmins) return null
+ val admins = shares.roster
+ .filter { it.memberPublicKey in roomAdmins && it.memberPublicKey in shares.signerIds }
+ .associate { it.memberPublicKey to (it.participantId to it.hostPublicKey.lowercase()) }
+
+ val hostSecret = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey)
+ val myHostKey = ChillDkgRitualManager.deriveHostPublicKey(nostrPrivateKey).value.toHex()
+ // A roster that names another host key for this member is one this device cannot
+ // open slots under; it takes no part rather than sealing to keys that are not there.
+ if (admins[userPublicKey]?.second != myHostKey) return null
+
+ val tweak = tweakFor(database, room, thresholdPublicKey) ?: return null
+ return RoomContext(
+ room = room, userPublicKey = userPublicKey, key = key, generation = shares.generation, myId = myId,
+ secretShare = secretShare, publicShares = publicShares, threshold = key.threshold, tweak = tweak,
+ hostSecret = hostSecret, myHostKey = myHostKey, nostrPrivateKey = nostrPrivateKey, admins = admins,
+ )
+ }
+
+ /** The tweak for whichever recorded path reaches the room's own id: the room id *is* the npub. */
+ private suspend fun tweakFor(database: GizaDatabase, room: LocalChatRoom, thresholdPublicKey: HexKey): NpubTweak? {
+ val roomId = room.chatRoom.id
+ val candidates = listOfNotNull(
+ GroupKeyStateManager.keyStateFor(database, roomId)?.pathIndices(),
+ SharedKeyDerivation.parsePath(room.chatRoom.description),
+ SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH,
+ )
+ val point = runCatching { PublicKey(thresholdPublicKey.hexToByteArray()) }.getOrNull() ?: return null
+ return candidates.firstNotNullOfOrNull { path ->
+ runCatching { NpubTweak.of(point, path) }.getOrNull()?.takeIf { it.npub == roomId }
+ }
+ }
+
+ // ---- opening a round --------------------------------------------------------------------------------------
+
+ /**
+ * Opens the round for [point] at the active generation, or finds the one already open,
+ * and sends this device's partial if it can. [evidence] travels only for a recipient;
+ * a wrap or a seal is named by [ref], the wrap's id, which the ledger must already hold.
+ */
+ suspend fun open(
+ database: GizaDatabase,
+ context: RoomContext,
+ point: HexKey,
+ purpose: EcdhPurpose,
+ ref: HexKey? = null,
+ evidence: Event? = null,
+ ): GroupEcdhRound {
+ val round = ensureRound(database, context, point, purpose, ref, evidence)
+ advance(database, context)
+ return database.groupDmDao().getRound(round.id)!!
+ }
+
+ /** [open] without the advance: the round's row, made or found. For a caller already inside a pass. */
+ suspend fun ensureRound(
+ database: GizaDatabase,
+ context: RoomContext,
+ point: HexKey,
+ purpose: EcdhPurpose,
+ ref: HexKey? = null,
+ evidence: Event? = null,
+ ): GroupEcdhRound {
+ val id = GroupEcdhPayload.roundId(context.roomId, context.generation, point)
+ database.groupDmDao().insertRound(
+ GroupEcdhRound(
+ id = id, chatRoomId = context.roomId, generation = context.generation, point = point.lowercase(),
+ purpose = purpose, ref = ref, evidenceJson = evidence?.toJson(),
+ )
+ )
+ val round = database.groupDmDao().getRound(id)!!
+ if (round.evidenceJson == null && evidence != null) {
+ database.groupDmDao().upsertRound(round.copy(evidenceJson = evidence.toJson()))
+ }
+ return database.groupDmDao().getRound(id)!!
+ }
+
+ // ---- receiving ---------------------------------------------------------------------------------------------
+
+ /**
+ * A partials message or a failure from another admin's device. A device that is not a
+ * current admin has no slot and reads nothing; one that is checks every proof, stores
+ * what proved, names once what did not, and then owes and combines as it can.
+ */
+ suspend fun process(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ innerEvent: Event,
+ userPublicKey: HexKey,
+ nostrPrivateKey: ByteArray,
+ ) {
+ if (innerEvent.kind == GroupEcdhEvents.FAILURE) {
+ // Every admin's device checks the same proofs itself; another's blame tells it
+ // nothing it will not see, so it is filed with the inner event and not acted on.
+ logger.i { "A round in ${localChatRoom.chatRoom.id} named participant ${GroupEcdhEvents.parseFailure(innerEvent.tags)?.second}" }
+ return
+ }
+ if (innerEvent.kind != GroupEcdhEvents.PARTIALS) return
+ val context = contextFor(database, localChatRoom, userPublicKey, nostrPrivateKey)
+ if (context == null) {
+ // Partials still reaching a device whose member was removed: it forgets (D14).
+ GroupDmReceiver.forgetIfRemoved(database, localChatRoom.chatRoom.id, userPublicKey)
+ return
+ }
+ val sender = innerEvent.pubKey
+ if (sender == userPublicKey) return
+ val (senderId, senderHost) = context.admins[sender] ?: return
+
+ val sealed = AdminSeal.Sealed(innerEvent.content, AdminSeal.parseSlots(innerEvent.tags))
+ val payload = context.open(sealed, senderHost)?.let(GroupEcdhPayload::decode) ?: return
+ if (payload.from != senderId) return
+ // Partials of two generations never combine, and this device answers only with its
+ // active share. A sender behind or ahead restarts its rounds when it catches up.
+ if (payload.generation != context.generation) return
+ val publicShare = context.publicShares.getOrNull(senderId) ?: return
+
+ val owedAgain = payload.items.mapNotNull { item -> receive(database, context, sender, senderId, publicShare, item) }
+ if (owedAgain.isNotEmpty()) send(database, context, owedAgain.mapNotNull { round -> evidenceFor(database, context, round)?.let { round to it } })
+ advance(database, context)
+ }
+
+ /**
+ * Files one item. Returns the round when this device has already answered it and the sender
+ * does not hold that answer ([GroupEcdhPayload.Item.have]): the partial goes out again.
+ */
+ private suspend fun receive(
+ database: GizaDatabase,
+ context: RoomContext,
+ sender: HexKey,
+ senderId: Int,
+ publicShare: PublicKey,
+ item: GroupEcdhPayload.Item,
+ ): GroupEcdhRound? {
+ val dao = database.groupDmDao()
+ val roundId = GroupEcdhPayload.roundId(context.roomId, context.generation, item.point)
+ dao.insertRound(
+ GroupEcdhRound(
+ id = roundId, chatRoomId = context.roomId, generation = context.generation, point = item.point,
+ purpose = item.purpose, ref = item.ref, evidenceJson = item.evidence?.toJson(),
+ )
+ )
+ val round = dao.getRound(roundId) ?: return null
+ if (round.evidenceJson == null && item.evidence != null) dao.upsertRound(round.copy(evidenceJson = item.evidence.toJson()))
+
+ val point = ThresholdEcdh.pointOf(item.point) ?: return null
+ val verified = Dleq.verify(publicShare, point, item.partial, Dleq.context(context.roomId, context.generation, senderId), item.proof)
+ val inserted = dao.insertPartial(
+ GroupEcdhPartial(
+ roundId = roundId, participantId = senderId, senderPublicKey = sender,
+ partial = item.partial.value.toHex(), proof = item.proof.toHex(), verified = verified,
+ )
+ )
+ if (!verified && inserted > 0) blame(database, context, roundId, senderId)
+ val answered = dao.getPartials(roundId).any { it.participantId == context.myId }
+ return round.takeIf { verified && inserted > 0 && answered && context.myId !in item.have }
+ }
+
+ /** A partial that did not prove: dropped, its sender named once per round (D3). */
+ private suspend fun blame(database: GizaDatabase, context: RoomContext, roundId: HexKey, participantId: Int) {
+ logger.w { "Participant $participantId's partial for round $roundId did not prove" }
+ broadcast(database, context, GroupEcdhEvents.FAILURE, GroupEcdhEvents.failureTags(roundId, participantId), "A partial did not prove")
+ database.groupDmDao().getPartials(roundId).firstOrNull { it.participantId == participantId }?.let {
+ database.groupDmDao().upsertPartial(it.copy(blamedAt = Clock.System.now()))
+ }
+ }
+
+ // ---- the sweep -----------------------------------------------------------------------------------------------
+
+ /**
+ * Everything a device can do for a room right now, in order: restart rounds a share
+ * refresh overtook, send what it owes, combine what it can. Idempotent.
+ */
+ suspend fun advance(database: GizaDatabase, context: RoomContext) {
+ restartOverTaken(database, context)
+ // What a combined round makes possible -- a wrap's seal, a seal's message -- can open
+ // another round, which this device can answer at once. A few turns settle it; each
+ // only moves rows forward, so the bound is a guard, not a budget.
+ repeat(4) {
+ val stepped = GroupDmReceiver.step(database, context)
+ val sent = flush(database, context)
+ val combined = combine(database, context)
+ // A recipient's key just made: a message held back for it can be read now (D13).
+ if (combined.any { it.purpose == EcdhPurpose.RECIPIENT }) GroupDmSender.retryHeld(database, context, context.nostrPrivateKey)
+ if (!stepped && sent == 0 && combined.isEmpty()) return
+ }
+ }
+
+ /** [advance], for every keyed room this profile is an admin of. */
+ suspend fun sweep(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray) {
+ database.chatRoomDao().getChatRoomListByUserPublicKey(userPublicKey).forEach { room ->
+ runCatching {
+ val context = contextFor(database, room, userPublicKey, nostrPrivateKey)
+ if (context != null) advance(database, context)
+ else GroupDmReceiver.forgetIfRemoved(database, room.chatRoom.id, userPublicKey)
+ }.onFailure { logger.e("Could not advance the rounds of ${room.chatRoom.id}", it) }
+ }
+ }
+
+ private suspend fun restartOverTaken(database: GizaDatabase, context: RoomContext) {
+ val dao = database.groupDmDao()
+ dao.getOpenRounds(context.roomId).filter { it.generation != context.generation }.forEach { stale ->
+ dao.upsertRound(stale.copy(state = GroupEcdhRoundState.FAILED))
+ if (stale.generation < context.generation) {
+ dao.insertRound(
+ stale.copy(
+ id = GroupEcdhPayload.roundId(context.roomId, context.generation, stale.point),
+ generation = context.generation, state = GroupEcdhRoundState.OPEN,
+ partialSentAt = null, openedAt = Clock.System.now(), combinedAt = null,
+ )
+ )
+ }
+ }
+ }
+
+ /** The event that lets this device multiply by [round]'s point, if it holds one that checks (D5). */
+ private suspend fun evidenceFor(database: GizaDatabase, context: RoomContext, round: GroupEcdhRound): Event? {
+ val event = when (round.purpose) {
+ EcdhPurpose.WRAP -> round.ref?.let { database.groupDmDao().getWrap(it) }?.wrapJson
+ EcdhPurpose.SEAL -> round.ref?.let { database.groupDmDao().getWrap(it) }?.sealJson
+ EcdhPurpose.RECIPIENT -> round.evidenceJson
+ }?.let { runCatching { Event.fromJson(it) }.getOrNull() } ?: return null
+ return event.takeIf { Evidence.allows(round.purpose, round.point, it, context.roomId) }
+ }
+
+ /**
+ * Sends this device's partial for every open round it can answer and has not, batched
+ * into as few partials messages as fit [MAX_PAYLOAD_BYTES]. Returns how many it sent.
+ */
+ suspend fun flush(database: GizaDatabase, context: RoomContext): Int {
+ val dao = database.groupDmDao()
+ val owed = dao.getOpenRounds(context.roomId)
+ .filter { it.generation == context.generation && it.partialSentAt == null }
+ .filter { round -> dao.getPartials(round.id).none { it.participantId == context.myId } }
+ .mapNotNull { round -> evidenceFor(database, context, round)?.let { round to it } }
+ if (owed.isEmpty()) return 0
+
+ return send(database, context, owed)
+ }
+
+ /**
+ * This device's partial for each of [rounds], batched into as few partials messages as fit
+ * [MAX_PAYLOAD_BYTES], sealed to the other current admins, and recorded. Each item says
+ * which partials this device already holds for its round. Returns how many it sent.
+ */
+ private suspend fun send(database: GizaDatabase, context: RoomContext, rounds: List>): Int {
+ if (rounds.isEmpty()) return 0
+ val dao = database.groupDmDao()
+ val items = rounds.mapNotNull { (round, evidence) ->
+ val point = ThresholdEcdh.pointOf(round.point) ?: return@mapNotNull null
+ val partial = context.partial(point)
+ val proof = context.proof(point, partial)
+ val have = (dao.getPartials(round.id).filter { it.verified }.map { it.participantId } + context.myId).distinct().sorted()
+ round to GroupEcdhPayload.Item(
+ point = round.point, purpose = round.purpose,
+ ref = round.ref.takeIf { round.purpose != EcdhPurpose.RECIPIENT },
+ evidence = evidence.takeIf { round.purpose == EcdhPurpose.RECIPIENT },
+ partial = partial, proof = proof, have = have,
+ )
+ }
+
+ val batches = mutableListOf>>(mutableListOf())
+ items.forEach { entry ->
+ val candidate = batches.last() + entry
+ val size = GroupEcdhPayload(context.generation, context.myId, candidate.map { it.second }).encode().length
+ if (batches.last().isNotEmpty() && size > MAX_PAYLOAD_BYTES) batches += mutableListOf(entry) else batches.last() += entry
+ }
+
+ val now = Clock.System.now()
+ batches.filter { it.isNotEmpty() }.forEach { batch ->
+ val payload = GroupEcdhPayload(context.generation, context.myId, batch.map { it.second })
+ if (context.admins.size > 1) {
+ val sealed = context.seal(payload.encode())
+ broadcast(database, context, GroupEcdhEvents.PARTIALS, GroupEcdhEvents.partialsTags(sealed), sealed.content)
+ }
+ batch.forEach { (round, item) ->
+ dao.insertPartial(
+ GroupEcdhPartial(
+ roundId = round.id, participantId = context.myId, senderPublicKey = context.userPublicKey,
+ partial = item.partial.value.toHex(), proof = item.proof.toHex(), verified = true,
+ )
+ )
+ dao.upsertRound(dao.getRound(round.id)!!.copy(partialSentAt = now))
+ }
+ }
+ return items.size
+ }
+
+ /**
+ * Every open round of the active generation holding `t` proven partials, combined. A
+ * seal's or a recipient's conversation key is kept; a wrap's opens its wrap, and is not.
+ */
+ suspend fun combine(database: GizaDatabase, context: RoomContext): List {
+ val dao = database.groupDmDao()
+ val combined = mutableListOf()
+ dao.getOpenRounds(context.roomId).filter { it.generation == context.generation }.forEach { round ->
+ val partials = dao.getPartials(round.id).filter { it.verified }
+ if (partials.size < context.threshold) return@forEach
+ val point = ThresholdEcdh.pointOf(round.point) ?: return@forEach
+ val shared = ThresholdEcdh.combine(
+ partials.associate { it.participantId to PublicKey(it.partial.hexToByteArray()) },
+ context.tweak,
+ point,
+ )
+ val conversationKey = ThresholdEcdh.conversationKey(shared)
+ when (round.purpose) {
+ EcdhPurpose.WRAP -> openWrap(database, round, conversationKey)
+ EcdhPurpose.SEAL, EcdhPurpose.RECIPIENT -> dao.insertConversationKey(
+ GroupConversationKey(chatRoomId = context.roomId, peer = round.point, conversationKey = conversationKey.toHex(), roundId = round.id)
+ )
+ }
+ val done = round.copy(state = GroupEcdhRoundState.COMBINED, combinedAt = Clock.System.now())
+ dao.upsertRound(done)
+ combined += done
+ }
+ return combined
+ }
+
+ /** `d·W` opens one wrap and is not kept (D6); the seal goes onto the ledger for the receiver. */
+ private suspend fun openWrap(database: GizaDatabase, round: GroupEcdhRound, conversationKey: ByteArray) {
+ val dao = database.groupDmDao()
+ val ledger = round.ref?.let { dao.getWrap(it) } ?: return
+ val wrap = runCatching { Event.fromJson(ledger.wrapJson) }.getOrNull()
+ val seal = wrap?.let { GroupDmWrap.open(it, conversationKey) }
+ dao.upsertWrap(
+ if (seal == null) ledger.copy(state = GroupDmWrapState.UNREADABLE)
+ else ledger.copy(sealJson = seal.toJson())
+ )
+ }
+
+ // ---- transport -------------------------------------------------------------------------------------------------
+
+ private suspend fun broadcast(database: GizaDatabase, context: RoomContext, kind: Int, tags: Array>, content: String) {
+ val author = context.userPublicKey
+ var createdAt = Clock.System.now().epochSeconds
+ var id = EventHasher.hashId(pubKey = author, createdAt = createdAt, kind = kind, tags = tags, content = content)
+ var attempts = 0
+ while (attempts < 16 && database.marmotInnerEventDao().getById(id) != null) {
+ createdAt += 1
+ id = EventHasher.hashId(pubKey = author, createdAt = createdAt, kind = kind, tags = tags, content = content)
+ attempts += 1
+ }
+ database.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(
+ id = id, publicKey = author, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt),
+ tags = tags, content = content, chatRoomId = context.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 e21aab0e..1a41d77f 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt
@@ -49,9 +49,15 @@ object InboxRefusal {
private const val TWO_DAYS = 2 * 24 * 60 * 60L
private const val CLOCK_SLACK = 10 * 60L
- /** Whether any of [events] is one this refusal is about. */
+ /**
+ * Whether any of [events] is one this refusal is about. A seal only when it names an inbox
+ * key in its `n` tag, as every reply does: a seal without one is the group writing by
+ * threshold ECDH, which `GroupDmRefusal` reads (docs/group-threshold-ecdh.md, D13).
+ */
fun involves(events: List): Boolean =
- events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND || it.kind == InboxSeal.KIND }
+ events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND || isReplySeal(it) }
+
+ private fun isReplySeal(event: Event): Boolean = event.kind == InboxSeal.KIND && InboxSeal.encryptionKeyOf(event.tags) != null
/**
* Why this device declines to sign [events] in [localChatRoom] as [userPublicKey] sees it, or
@@ -66,7 +72,7 @@ object InboxRefusal {
manifest: String? = null,
now: Long = Clock.System.now().epochSeconds,
): String? {
- if (events.any { it.kind == InboxSeal.KIND }) {
+ if (events.any(::isReplySeal)) {
return replyRefusal(database, localChatRoom.chatRoom.id, userPublicKey, events, manifest, now)
}
for (event in events) {
@@ -174,7 +180,7 @@ object InboxRefusal {
* open a message from a group (D13).
*/
suspend fun notes(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey, sessionId: String, events: List): List {
- if (events.none { it.kind == InboxSeal.KIND }) return emptyList()
+ if (events.none(::isReplySeal)) return emptyList()
val manifest = database.groupInboxDao().getSigning(sessionId)?.manifest
val reply = (readReply(database, chatRoomId, userPublicKey, events, manifest) as? Read.Ok)?.reply
?: return listOf("A private reply from the group's inbox, which this device cannot read")
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 ecdbe61a..11de5328 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt
@@ -129,7 +129,11 @@ object InboxReplies {
* an outgoing message at once. Every other admin's device files the copy when it arrives.
*/
suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) {
- val seals = signedEvents.filter { it.kind == InboxSeal.KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) }
+ // A reply's seals name the inbox key in an `n` tag; a seal without one is the group
+ // writing by threshold ECDH, which `GroupDmSender` wraps (docs/group-threshold-ecdh.md).
+ val seals = signedEvents.filter {
+ it.kind == InboxSeal.KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) && InboxSeal.encryptionKeyOf(it.tags) != null
+ }
if (seals.isEmpty() || !session.isCoordinator()) return
wrapAndOwe(database, session, seals)
}
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 35cc4d55..a173164a 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt
@@ -81,6 +81,11 @@ class LiveSubscriptionManager(
* (docs/confederation.md, Phase 5). Null, or the feature off, and nothing is asked for.
*/
private val confederationRepository: ConfederationRepository? = null,
+ /**
+ * Where a group's mail goes, rather than the `NostrEvent` table (docs/group-threshold-ecdh.md,
+ * Phase 7). Null, or the feature off, and nothing is asked for.
+ */
+ private val groupDmRepository: mobi.giza.compose.repository.GroupDmRepository? = null,
/**
* Where gift wraps to a group this identity holds an inbox key for are filed
* (docs/group-inbox.md, D8), never as `NostrEvent` rows nor through the personal inbox.
@@ -102,6 +107,34 @@ class LiveSubscriptionManager(
const val GROUP_SUB_ID_PREFIX = "live-groups-"
+ /** Gift wraps to the groups this device reads for, on their 10050 relays (docs/group-threshold-ecdh.md, D9). */
+ const val GROUP_DM_SUB_ID = "live-group-dm"
+
+ /** NIP-59 back-dates a wrap by up to two days, so catch-up asks that far before the newest one seen. */
+ private const val WRAP_BACKDATE_SECONDS = 2L * 24 * 60 * 60
+
+ /**
+ * What `live-group-dm` asks each relay for: kind 1059 p-tagged to the groups that list
+ * that relay, or every group on the app's own DM relays. Keyed by relay.
+ */
+ internal fun groupDmFilters(inboxes: List): Map> {
+ if (inboxes.isEmpty()) return emptyMap()
+ val byRelay = mutableMapOf>()
+ inboxes.forEach { inbox ->
+ (inbox.relays + Relays.DefaultDMRelayList.map { it.url }).distinct().forEach { relay ->
+ byRelay.getOrPut(relay) { mutableListOf() } += inbox
+ }
+ }
+ return byRelay.mapValues { (_, rooms) ->
+ val newest = rooms.mapNotNull { it.newestWrapAt }.minOrNull()
+ // The oldest of the rooms' watermarks, so no room on this relay misses a wrap.
+ val since = if (rooms.any { it.newestWrapAt == null }) null else newest?.let { it - WRAP_BACKDATE_SECONDS }
+ rooms.map { it.roomId }.sorted().chunked(MAX_CONFEDERATION_IDS).map { chunk ->
+ Filter(kinds = listOf(GiftWrapEvent.KIND), tags = mapOf("p" to chunk), since = since, limit = INITIAL_HISTORY_LIMIT)
+ }
+ }
+ }
+
/** The confederation's public events, on the public relays they are published to. */
const val CONFEDERATION_SUB_ID = "live-confederation"
@@ -313,11 +346,48 @@ class LiveSubscriptionManager(
launch { followConfederations(publicKey = publicKey, keyPair = keyPair, repository = repository) }
}
+ groupDmRepository?.takeIf { ExperimentalFeatures.groupDirectMessages }?.let { repository ->
+ launch { followGroupDirectMessages(publicKey = publicKey, keyPair = keyPair, repository = repository) }
+ }
+
groupInboxRepository?.takeIf { ExperimentalFeatures.groupInbox }?.let { repository ->
launch { followGroupInboxes(publicKey = publicKey, keyPair = keyPair, repository = repository) }
}
}
+ /**
+ * Keeps `live-group-dm` open on every relay a readable group names, re-sent as rooms gain or
+ * lose a 10050 or this device's member gains or loses admin. Wraps go to the group's own
+ * pipeline, never to the `NostrEvent` table (docs/group-threshold-ecdh.md, D9).
+ */
+ @OptIn(FlowPreview::class)
+ private suspend fun followGroupDirectMessages(publicKey: HexKey, keyPair: KeyPair, repository: mobi.giza.compose.repository.GroupDmRepository) {
+ val secret = keyPair.privKey ?: return
+ repository.observeReadableRooms(publicKey)
+ .map { groupDmFilters(it) }
+ .distinctUntilChanged()
+ .debounce(GROUP_CHANGE_DEBOUNCE)
+ .collectLatest { byRelay ->
+ if (byRelay.isEmpty()) return@collectLatest
+ coroutineScope {
+ byRelay.forEach { (relay, filters) ->
+ launch {
+ runLiveSubscription(
+ subId = GROUP_DM_SUB_ID,
+ relayUrl = relay,
+ filters = { filters },
+ keyPair = keyPair,
+ onEvent = { nostrEvent, _ ->
+ runCatching { repository.receiveWrap(nostrEvent.toEvent(), publicKey, secret) }
+ .onFailure { logger.w(throwable = it) { "Could not take wrap ${nostrEvent.id} for a group" } }
+ },
+ )
+ }
+ }
+ }
+ }
+ }
+
/**
* Keeps one subscription per relay a group's mail is announced to arrive on, for every
* group this identity holds an inbox key for, re-sent when that set changes. What arrives
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/AdminSeal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/AdminSeal.kt
new file mode 100644
index 00000000..4c11c643
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/AdminSeal.kt
@@ -0,0 +1,68 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.crypto.random.RandomInstance
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import fr.acinq.bitcoin.PrivateKey
+import mobi.giza.compose.extensions.toHex
+
+/**
+ * Something only the group's current admins may read, inside a room every member receives
+ * (D4 and D12 of docs/group-threshold-ecdh.md).
+ *
+ * The plaintext is NIP-44-encrypted once, under a fresh 32-byte key used as the conversation
+ * key, and only that key is sealed to each admin's ChillDKG host key over the share-repair
+ * channel. Phase 0's check 6 is why: sealing the whole plaintext per admin multiplied a batch
+ * of partials by the number of admins, past a relay's event.
+ *
+ * A host key is the 33-byte compressed one the roster carries, as 66 hex; NIP-44's ECDH reads
+ * only its x-coordinate.
+ */
+object AdminSeal {
+ private val nip44 = Nip44v2()
+
+ /** [content] for everyone; [slots] the content key, sealed per admin host key. */
+ data class Sealed(val content: String, val slots: Map)
+
+ fun seal(
+ plaintext: String,
+ senderHostSecret: PrivateKey,
+ recipientHostKeys: Collection,
+ contentKey: ByteArray = RandomInstance.bytes(32),
+ ): Sealed {
+ require(contentKey.size == 32) { "a content key is 32 bytes" }
+ val content = nip44.encrypt(plaintext, contentKey).encodePayload()
+ val slots = recipientHostKeys.distinct().associateWith { host ->
+ nip44.encrypt(contentKey.toHex(), senderHostSecret.value.toByteArray(), xOnly(host)).encodePayload()
+ }
+ return Sealed(content, slots)
+ }
+
+ /**
+ * The plaintext, or null when this device has no slot, its slot does not open under
+ * [senderHostKey], or the content does not open under what the slot held.
+ */
+ fun open(sealed: Sealed, myHostSecret: PrivateKey, myHostKey: HexKey, senderHostKey: HexKey): String? = runCatching {
+ val slot = sealed.slots[myHostKey.lowercase()] ?: return null
+ val contentKey = nip44.decrypt(slot, myHostSecret.value.toByteArray(), xOnly(senderHostKey))
+ .takeIf { it.length == 64 }?.hexToByteArray() ?: return null
+ nip44.decrypt(sealed.content, contentKey)
+ }.getOrNull()
+
+ /** The x-coordinate of a compressed host key, which is all NIP-44's ECDH reads. */
+ private fun xOnly(hostPublicKey: HexKey): ByteArray {
+ require(hostPublicKey.length == 66) { "a host key is 33 bytes" }
+ return hostPublicKey.hexToByteArray().copyOfRange(1, 33)
+ }
+
+ /** As tags: `["slot", , ]`, sorted so two devices agree byte for byte. */
+ const val SLOT_TAG = "slot"
+
+ fun slotTags(slots: Map, name: String = SLOT_TAG): List> =
+ slots.entries.sortedBy { it.key }.map { (host, sealed) -> arrayOf(name, host, sealed) }
+
+ fun parseSlots(tags: Array>, name: String = SLOT_TAG): Map =
+ tags.filter { it.size >= 3 && it[0] == name && it[1].length == 66 }
+ .associate { it[1].lowercase() to it[2] }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/EcdhPurpose.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/EcdhPurpose.kt
new file mode 100644
index 00000000..08dedb92
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/EcdhPurpose.kt
@@ -0,0 +1,22 @@
+package mobi.giza.compose.nostr.groupdm
+
+/**
+ * Why a device is asked to multiply by a point, which fixes what it must hold first (D5 of
+ * docs/group-threshold-ecdh.md). The wire name is the lowercase name.
+ */
+enum class EcdhPurpose {
+ /** The point is a gift wrap's pubkey `W`; the evidence is the wrap, p-tagged to the group. */
+ WRAP,
+
+ /** The point is a seal's pubkey `S`; the evidence is the seal, out of a wrap the device opened. */
+ SEAL,
+
+ /** The point is someone the group writes to, `R`; the evidence is any event `R` signed. */
+ RECIPIENT;
+
+ val wire: String get() = name.lowercase()
+
+ companion object {
+ fun fromWire(value: String): EcdhPurpose? = entries.firstOrNull { it.wire == value }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/Evidence.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/Evidence.kt
new file mode 100644
index 00000000..844260f6
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/Evidence.kt
@@ -0,0 +1,42 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.verify
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+
+/**
+ * D5 of docs/group-threshold-ecdh.md, in one function, so the device answering a round and the
+ * signer checking a message check the same thing: a device multiplies only by a key whose
+ * owner has signed something it can check, of the right shape for the purpose.
+ *
+ * A signature by `P` proves its signer knows `log_G(P)`, so no point asked about can be
+ * `x^k·G`, which is the query a static Diffie-Hellman oracle is worn down by. The group's own
+ * npub is refused outright: `x·(x·G)` is exactly that query, and why the group never encrypts
+ * to itself.
+ */
+object Evidence {
+ enum class Refusal { WRONG_KIND, WRONG_KEY, NOT_TO_GROUP, BAD_SIGNATURE, THE_GROUP_ITSELF }
+
+ /** Null when [event] lets a device multiply by [point] for [purpose]; otherwise why not. */
+ fun check(purpose: EcdhPurpose, point: HexKey, event: Event, groupNpub: HexKey): Refusal? {
+ val p = point.lowercase()
+ if (p == groupNpub.lowercase()) return Refusal.THE_GROUP_ITSELF
+ if (event.pubKey.lowercase() != p) return Refusal.WRONG_KEY
+ when (purpose) {
+ EcdhPurpose.WRAP -> {
+ if (event.kind != GiftWrapEvent.KIND) return Refusal.WRONG_KIND
+ val addressed = event.tags.any { it.size >= 2 && it[0] == "p" && it[1].lowercase() == groupNpub.lowercase() }
+ if (!addressed) return Refusal.NOT_TO_GROUP
+ }
+ EcdhPurpose.SEAL -> if (event.kind != SealEvent.KIND) return Refusal.WRONG_KIND
+ EcdhPurpose.RECIPIENT -> Unit
+ }
+ if (!event.verify()) return Refusal.BAD_SIGNATURE
+ return null
+ }
+
+ fun allows(purpose: EcdhPurpose, point: HexKey, event: Event, groupNpub: HexKey): Boolean =
+ check(purpose, point, event, groupNpub) == null
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmConversation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmConversation.kt
new file mode 100644
index 00000000..375ae730
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmConversation.kt
@@ -0,0 +1,26 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import fr.acinq.bitcoin.Crypto
+import mobi.giza.compose.extensions.toHex
+
+/**
+ * Which of the group's conversations a message belongs to. NIP-17 defines a chat as the set of
+ * its author and its `p` tags; the group is in every one of its own, so it is left out, and
+ * what remains is the group's correspondents.
+ */
+object GroupDmConversation {
+ fun participantsOf(rumor: Event, group: HexKey): List =
+ (listOf(rumor.pubKey) + rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1] })
+ .map { it.lowercase() }
+ .filter { it != group.lowercase() && it.length == 64 }
+ .distinct()
+ .sorted()
+
+ /** A hash of the sorted participants: the same conversation on every admin's device. */
+ fun idOf(rumor: Event, group: HexKey): HexKey = idOf(participantsOf(rumor, group))
+
+ fun idOf(participants: Collection): HexKey =
+ Crypto.sha256(participants.map { it.lowercase() }.distinct().sorted().joinToString(",").encodeToByteArray()).toHex()
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmLayers.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmLayers.kt
new file mode 100644
index 00000000..a20d11c9
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmLayers.kt
@@ -0,0 +1,63 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
+import com.vitorpamplona.quartz.nip01Core.crypto.verify
+import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import com.vitorpamplona.quartz.nip59Giftwrap.rumors.Rumor
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+
+/**
+ * NIP-59's two layers, opened and built with a conversation key that threshold ECDH gave,
+ * rather than with a key this device holds. quartz's own `GiftWrapEvent` and `SealEvent` take
+ * a signer, which the group does not have, so these are built by hand to the same shape
+ * (docs/group-threshold-ecdh.md, Phase 3).
+ */
+object GroupDmWrap {
+ private val nip44 = Nip44v2()
+
+ /** The seal inside [wrap], signed by its own pubkey, or null. */
+ fun open(wrap: Event, conversationKey: ByteArray): Event? = runCatching {
+ if (wrap.kind != GiftWrapEvent.KIND) return null
+ val seal = Event.fromJson(nip44.decrypt(wrap.content, conversationKey))
+ seal.takeIf { it.kind == SealEvent.KIND && it.verify() }
+ }.getOrNull()
+}
+
+object GroupDmSeal {
+ private val nip44 = Nip44v2()
+
+ /**
+ * The rumor inside [seal], or null. NIP-59's anti-spoofing check is the caller's job in
+ * quartz; here it is part of opening: a rumor whose pubkey is not the seal's is refused.
+ * Its id is recomputed, never taken from the rumor (quartz's `mergeWith` says why).
+ */
+ fun open(seal: Event, conversationKey: ByteArray): Event? = runCatching {
+ if (seal.kind != SealEvent.KIND) return null
+ val rumor = Rumor.fromJson(nip44.decrypt(seal.content, conversationKey))
+ if (rumor.pubKey != null && rumor.pubKey != seal.pubKey) return null
+ val tags = rumor.tags ?: emptyArray()
+ val createdAt = rumor.createdAt ?: return null
+ val kind = rumor.kind ?: return null
+ val content = rumor.content ?: ""
+ val id = EventHasher.hashId(seal.pubKey, createdAt, kind, tags, content)
+ Event(id, seal.pubKey, createdAt, kind, tags, content, "")
+ }.getOrNull()
+
+ /** The rumor as JSON, id included and no signature, as NIP-59 puts it inside a seal. */
+ fun rumorJson(rumor: Event): String = Rumor.toJson(Rumor.create(rumor))
+
+ /**
+ * An unsigned seal from the group to whoever [conversationKey] is shared with: kind 13,
+ * no tags, the rumor NIP-44-encrypted. The group signs it; nothing else changes it after.
+ */
+ fun build(rumor: Event, conversationKey: ByteArray, createdAt: Long): EventTemplate =
+ EventTemplate(createdAt, SealEvent.KIND, emptyArray(), nip44.encrypt(rumorJson(rumor), conversationKey).encodePayload())
+
+ /** An unsigned rumor, its id computed, as the group would author it. */
+ fun rumor(author: HexKey, createdAt: Long, kind: Int, tags: Array>, content: String): Event =
+ Event(EventHasher.hashId(author, createdAt, kind, tags, content), author, createdAt, kind, tags, content, "")
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmManifest.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmManifest.kt
new file mode 100644
index 00000000..a9fb61c8
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmManifest.kt
@@ -0,0 +1,92 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.put
+
+/**
+ * What a group's message is, for the admins who sign it (D12 of docs/group-threshold-ecdh.md).
+ *
+ * A signing proposal reaches every member of the room, and its events are seals, which are
+ * ciphertext. A signer also needs to know which seal is for whom and why its device may
+ * multiply by each recipient's key. That is this manifest, sealed to the current admins'
+ * host keys and carried as proposal tags:
+ *
+ * ```
+ * ["dm_manifest", ] ["dm_slot", , ] one per admin
+ *
+ * {"v":1,"seals":[{"recipient":"","evidence":}, …],"replying_to":}
+ * ```
+ *
+ * The seals are in the same order as the batch's events. The decoder accepts only its own
+ * encoding.
+ */
+class GroupDmManifest(
+ val seals: List,
+ val replyingTo: HexKey?,
+) {
+ class Seal(val recipient: HexKey, val evidence: Event)
+
+ val recipients: List get() = seals.map { it.recipient }
+
+ fun encode(): String = Json.encodeToString(JsonElement.serializer(), buildJsonObject {
+ put("v", VERSION)
+ put("seals", buildJsonArray {
+ seals.forEach { seal ->
+ add(buildJsonObject {
+ put("recipient", seal.recipient)
+ put("evidence", Json.parseToJsonElement(seal.evidence.toJson()))
+ })
+ }
+ })
+ put("replying_to", replyingTo?.let(::JsonPrimitive) ?: JsonNull)
+ })
+
+ /** As proposal tags, sealed to [adminHostKeys] from the proposer's host key. */
+ fun toTags(sealed: AdminSeal.Sealed): Array> =
+ (listOf(arrayOf(MANIFEST_TAG, sealed.content)) + AdminSeal.slotTags(sealed.slots, SLOT_TAG)).toTypedArray()
+
+ companion object {
+ const val VERSION = 1
+ const val MANIFEST_TAG = "dm_manifest"
+ const val SLOT_TAG = "dm_slot"
+
+ private fun isHex64(value: String) = value.length == 64 && value.all { it in "0123456789abcdef" }
+
+ /** Whether [tags] carry a manifest at all: what marks a batch of seals as the group's message. */
+ fun isCarriedBy(tags: Array>): Boolean = tags.any { it.size >= 2 && it[0] == MANIFEST_TAG }
+
+ /** The sealed manifest in [tags], or null if there is none. */
+ fun sealedIn(tags: Array>): AdminSeal.Sealed? {
+ val content = tags.firstOrNull { it.size >= 2 && it[0] == MANIFEST_TAG }?.get(1) ?: return null
+ return AdminSeal.Sealed(content, AdminSeal.parseSlots(tags, SLOT_TAG))
+ }
+
+ fun decode(text: String): GroupDmManifest? = runCatching {
+ val root = Json.parseToJsonElement(text) as? JsonObject ?: return null
+ if ((root["v"] as? JsonPrimitive)?.takeIf { !it.isString }?.int != VERSION) return null
+ val seals = (root["seals"] as? JsonArray)?.map { element ->
+ val o = element as? JsonObject ?: return null
+ val recipient = (o["recipient"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.takeIf(::isHex64) ?: return null
+ val evidence = o["evidence"]?.let { Event.fromJson(Json.encodeToString(JsonElement.serializer(), it)) } ?: return null
+ Seal(recipient, evidence)
+ } ?: return null
+ if (seals.isEmpty()) return null
+ val replyingTo = when (val r = root["replying_to"]) {
+ null, JsonNull -> null
+ is JsonPrimitive -> r.takeIf { it.isString }?.content?.takeIf(::isHex64) ?: return null
+ else -> return null
+ }
+ GroupDmManifest(seals, replyingTo).takeIf { it.encode() == text }
+ }.getOrNull()
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupEcdhEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupEcdhEvents.kt
new file mode 100644
index 00000000..43666df9
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupEcdhEvents.kt
@@ -0,0 +1,37 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.Kind
+
+/**
+ * The kinds threshold ECDH travels on (docs/group-threshold-ecdh.md, D4, D11 and Phase 0's
+ * check 5). Marmot inner events in the group's own room, like the signing and share refresh
+ * families.
+ *
+ * 30400 and 30401 were free in the NIP README (30402 and 30403 are NIP-99's), quartz, Bennu,
+ * and `RetiredKinds` when they were chosen.
+ */
+object GroupEcdhEvents {
+ /** An admin's partials for one or more rounds: [GroupEcdhPayload], sealed to the admins by [AdminSeal]. */
+ val PARTIALS: Kind = 30400
+
+ /** A round whose partial from [BLAME_TAG] did not prove. Content is the reason, in words. */
+ val FAILURE: Kind = 30401
+
+ val ALL: Set = setOf(PARTIALS, FAILURE)
+
+ const val ROUND_TAG = "ecdh_round"
+ const val BLAME_TAG = "ecdh_blame"
+
+ /** A partials message's tags: the slots, and nothing else a member who is not an admin can read. */
+ fun partialsTags(sealed: AdminSeal.Sealed): Array> = AdminSeal.slotTags(sealed.slots).toTypedArray()
+
+ fun failureTags(roundId: HexKey, participantId: Int): Array> =
+ arrayOf(arrayOf(ROUND_TAG, roundId), arrayOf(BLAME_TAG, participantId.toString()))
+
+ fun parseFailure(tags: Array>): Pair? {
+ val round = tags.firstOrNull { it.size >= 2 && it[0] == ROUND_TAG }?.get(1)?.takeIf { it.length == 64 } ?: return null
+ val blamed = tags.firstOrNull { it.size >= 2 && it[0] == BLAME_TAG }?.get(1)?.toIntOrNull()?.takeIf { it >= 0 } ?: return null
+ return round to blamed
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupEcdhPayload.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupEcdhPayload.kt
new file mode 100644
index 00000000..ad4ac203
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/groupdm/GroupEcdhPayload.kt
@@ -0,0 +1,114 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PublicKey
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.put
+import mobi.giza.compose.cryptography.threshold.Dleq
+import mobi.giza.compose.extensions.toHex
+
+/**
+ * What a partials message carries, once its [AdminSeal] is opened (D11 of
+ * docs/group-threshold-ecdh.md):
+ *
+ * ```
+ * {"v":1,"generation":g,"from":id,"items":[{"point","purpose","ref"?,"evidence"?,"partial","proof","have"}, …]}
+ * ```
+ *
+ * [Item.have] is the participant ids whose partials the sender already holds for that round.
+ * A device that has answered and is not among them sends its partial again: that is how an
+ * admin promoted after a round combined, or one that missed a message, is caught up, without
+ * any device re-sending to someone who already has it.
+ *
+ * [Item.point] is the x-only key multiplied, lifted to even y by everyone; [Item.partial] is
+ * `sᵢ·P`, compressed. A wrap or a seal is named by the wrap's id in [Item.ref], since every
+ * admin's device holds the wrap and opens the same seal from it (Phase 0, check 6). Only a
+ * recipient's evidence travels whole, in [Item.evidence].
+ *
+ * The decoder accepts only its own encoding, so there is one spelling of a payload.
+ */
+class GroupEcdhPayload(
+ val generation: Int,
+ val from: Int,
+ val items: List- ,
+) {
+ class Item(
+ val point: HexKey,
+ val purpose: EcdhPurpose,
+ val ref: HexKey? = null,
+ val evidence: Event? = null,
+ val partial: PublicKey,
+ val proof: Dleq.Proof,
+ val have: List = emptyList(),
+ )
+
+ fun encode(): String = json.encodeToString(JsonElement.serializer(), toJson())
+
+ private fun toJson(): JsonObject = buildJsonObject {
+ put("v", VERSION)
+ put("generation", generation)
+ put("from", from)
+ put("items", buildJsonArray {
+ items.forEach { item ->
+ add(buildJsonObject {
+ put("point", item.point)
+ put("purpose", item.purpose.wire)
+ item.ref?.let { put("ref", it) }
+ item.evidence?.let { put("evidence", json.parseToJsonElement(it.toJson())) }
+ put("partial", item.partial.value.toHex())
+ put("proof", item.proof.toHex())
+ put("have", buildJsonArray { item.have.distinct().sorted().forEach { add(JsonPrimitive(it)) } })
+ })
+ }
+ })
+ }
+
+ companion object {
+ const val VERSION = 1
+
+ private val json = Json
+
+ /** A round: its id commits to the room, the generation and the point (D11). */
+ fun roundId(room: HexKey, generation: Int, point: HexKey): HexKey =
+ Crypto.sha256(room.hexToByteArray() + "$generation".encodeToByteArray() + point.hexToByteArray()).toHex()
+
+ private fun isHex(value: String, length: Int) = value.length == length && value.all { it in "0123456789abcdef" }
+
+ fun decode(text: String): GroupEcdhPayload? = runCatching {
+ val root = json.parseToJsonElement(text) as? JsonObject ?: return null
+ if ((root["v"] as? JsonPrimitive)?.takeIf { !it.isString }?.int != VERSION) return null
+ val generation = (root["generation"] as? JsonPrimitive)?.takeIf { !it.isString }?.int?.takeIf { it >= 0 } ?: return null
+ val from = (root["from"] as? JsonPrimitive)?.takeIf { !it.isString }?.int?.takeIf { it >= 0 } ?: return null
+ val items = (root["items"] as? JsonArray)?.map { element ->
+ val o = element as? JsonObject ?: return null
+ fun string(name: String) = (o[name] as? JsonPrimitive)?.takeIf { it.isString }?.content
+ val point = string("point")?.takeIf { isHex(it, 64) } ?: return null
+ val purpose = string("purpose")?.let(EcdhPurpose::fromWire) ?: return null
+ val ref = string("ref")?.also { if (!isHex(it, 64)) return null }
+ val evidence = o["evidence"]?.let { Event.fromJson(json.encodeToString(JsonElement.serializer(), it)) }
+ val partial = string("partial")?.takeIf { isHex(it, 66) }?.let { PublicKey(it.hexToByteArray()) }
+ ?.takeIf { it.isValid() } ?: return null
+ val proof = string("proof")?.let(Dleq.Proof::fromHex) ?: return null
+ val have = (o["have"] as? JsonArray)?.map { (it as? JsonPrimitive)?.takeIf { p -> !p.isString }?.int ?: return null } ?: return null
+ // What each purpose names its evidence by, and nothing else.
+ when (purpose) {
+ EcdhPurpose.WRAP, EcdhPurpose.SEAL -> if (ref == null || evidence != null) return null
+ EcdhPurpose.RECIPIENT -> if (ref != null || evidence == null) return null
+ }
+ Item(point, purpose, ref, evidence, partial, proof, have)
+ } ?: return null
+ if (items.isEmpty()) return null
+ GroupEcdhPayload(generation, from, items).takeIf { it.encode() == text }
+ }.getOrNull()
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt
index 3f70c6a5..c13494b2 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt
@@ -107,6 +107,8 @@ object NotificationClassifier {
Line.TYPE_INBOX_ANNOUNCED,
Line.TYPE_INBOX_RELAYS_ANNOUNCED,
Line.TYPE_INBOX_FORGOTTEN,
+ // The same housekeeping for the group's direct messages (docs/group-threshold-ecdh.md, D14).
+ Line.TYPE_GROUP_DM_FORGOTTEN,
Line.TYPE_MEMBER_INVITED,
Line.TYPE_MEMBER_INVITE_SENT,
Line.TYPE_MEMBER_INVITE_FAILED,
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
index 42bfb909..c35d8f9f 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
@@ -157,6 +157,9 @@ interface ChatRepository {
/** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */
suspend fun confederationOfRoom(chatRoomId: String): String? = null
+ /** What [chatRoomId]'s screen says about its direct messages, to [userPublicKey]. docs/group-threshold-ecdh.md. */
+ suspend fun groupDmRow(chatRoomId: String, userPublicKey: HexKey): mobi.giza.compose.ui.view.state.GroupDmRow? = null
+
/** Whether this device holds a role in the confederation whose room [chatRoomId] is. docs/confederation.md, Phase 15. */
suspend fun canSignAsConfederation(chatRoomId: String): Boolean = false
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt
new file mode 100644
index 00000000..ef922b23
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt
@@ -0,0 +1,62 @@
+package mobi.giza.compose.repository
+
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlin.time.Instant
+import kotlinx.coroutines.flow.Flow
+import mobi.giza.compose.database.model.FrostSigningSession
+import mobi.giza.compose.database.model.GroupDmOutbound
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+
+/**
+ * A group's direct messages on this device, for the relay layer and the screens
+ * (docs/group-threshold-ecdh.md).
+ */
+interface GroupDmRepository {
+ /** What this device owes relays: a signed 10050, or a wrap of a message the group signed. */
+ fun observeOwed(): Flow
>
+
+ suspend fun markPublished(outbound: GroupDmOutbound, at: Instant)
+
+ suspend fun markAttempt(outbound: GroupDmOutbound, next: Instant)
+
+ /** Where [chatRoomId] receives messages, as it changes; null while it has not opened them. */
+ fun observeRelays(chatRoomId: HexKey): Flow?>
+
+ /** Whether [userPublicKey] is a current admin of [chatRoomId] holding a share: who sees the group's mail (D4, D12). */
+ suspend fun isCurrentAdmin(chatRoomId: HexKey, userPublicKey: HexKey): Boolean
+
+ /**
+ * The rooms whose mail [userPublicKey] reads, with the relays to ask on and how far back,
+ * as they change: what `live-group-dm` subscribes to (D9).
+ */
+ fun observeReadableRooms(userPublicKey: HexKey): Flow>
+
+ /** A wrap a relay sent: into the group's own pipeline if it is one of its, else nothing. Whether it was. */
+ suspend fun receiveWrap(wrap: com.vitorpamplona.quartz.nip01Core.core.Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Boolean
+
+ /** The group's conversations, newest first (Phase 8). */
+ fun observeConversations(chatRoomId: HexKey): Flow>
+
+ /** What the group was sent and has not opened yet, and on whom it waits. */
+ fun observePending(chatRoomId: HexKey): Flow
+
+ /** One conversation's messages, oldest first, in and out. */
+ fun observeConversation(chatRoomId: HexKey, conversationId: HexKey): Flow>
+
+ /** The participants of [conversationId], from the messages this device holds. */
+ suspend fun participantsOf(chatRoomId: HexKey, conversationId: HexKey): List
+
+ suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey)
+
+ /** How a screen names a person: their profile's name, or the start of their key. */
+ suspend fun nameOf(publicKey: HexKey): String
+
+ /** Asks the group to send [text] to [recipients] (D10), as the active identity. */
+ suspend fun send(localChatRoom: LocalChatRoom, recipients: List, text: String, replyTo: HexKey?): mobi.giza.compose.managers.GroupDmSender.Outcome
+
+ /** Wraps and sends again what a signed message still owes its recipients. */
+ suspend fun sendAgain(signingSessionId: String): Boolean
+
+ /** Asks the group to sign [relays] as where it receives messages (D8). */
+ suspend fun proposeRelays(localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession
+}
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 bec249b4..1eabdb19 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt
@@ -106,10 +106,16 @@ object ProposedEvent {
// A reply from the group's inbox: sealed, so said for what it is. The signing screen
// reads it out for a device that holds the inbox key (docs/group-inbox.md, D12), and a
// member without one sees only that it exists (D11).
- InboxSeal.KIND -> Summary(
- label = "A private reply from the group's inbox",
- detail = "Sealed: only the group's inbox key opens it",
- )
+ // A seal with no `n` tag is the group writing by threshold ECDH instead
+ // (docs/group-threshold-ecdh.md, D12): ciphertext to its recipient's own key.
+ InboxSeal.KIND -> if (InboxSeal.encryptionKeyOf(event.tags) != null) {
+ Summary(
+ label = "A private reply from the group's inbox",
+ detail = "Sealed: only the group's inbox key opens it",
+ )
+ } else {
+ Summary(label = "A private message from the group", detail = "Sealed to its recipient")
+ }
InboxAnnouncement.RELAYS_KIND -> Summary(
label = "Where the group receives private messages",
detail = InboxAnnouncement.announcedRelaysOf(event).joinToString(", ") { it.url.removePrefix("wss://").trimEnd('/') }
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt
index fa049e3d..c0900421 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt
@@ -21,6 +21,16 @@ import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute
import mobi.giza.compose.ui.view.state.InboxRowSummary
import androidx.compose.material.icons.filled.Mail
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute
+import mobi.giza.compose.ui.composable.navigation.routes.GroupDmSetupRoute
+import mobi.giza.compose.ui.view.state.GroupDmRow
+import androidx.compose.material.icons.filled.Mail
+import mobi.giza.compose.resources.open_the_groups_messages
+import mobi.giza.compose.resources.group_messages
+import mobi.giza.compose.resources.this_group_receives_direct_messages
+import mobi.giza.compose.resources.nobody_can_write_to_the_group_yet
+import mobi.giza.compose.resources.nothing_unread
+import mobi.giza.compose.resources.n_unread
+import mobi.giza.compose.resources.only_its_admins_read_them
import mobi.giza.compose.ExperimentalFeatures
import androidx.compose.material.icons.filled.Hub
import mobi.giza.compose.resources.confederations
@@ -834,6 +844,32 @@ fun ChatRoomDetailScreen(
}
}
+ // The group's direct messages: the way to open them for an
+ // admin, the way in once open, and for anyone else only that
+ // the group receives them. docs/group-threshold-ecdh.md.
+ chatRoomDetailUIState.groupDmRow?.let { row ->
+ item {
+ GroupDmRowCard(
+ row = row,
+ onClick = {
+ onNavigateToRoute.invoke(
+ if (row is GroupDmRow.Messages) {
+ mobi.giza.compose.ui.composable.navigation.routes.GroupDmListRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ chatRoomId = chatRoomId,
+ )
+ } else {
+ GroupDmSetupRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ chatRoomId = chatRoomId,
+ )
+ }
+ )
+ }
+ )
+ }
+ }
+
// The untyped way in: an unsigned event, pasted. It
// lands on its kind's screen above once the quorum
// signs. Behind the same gate as the editors, and the
@@ -2308,3 +2344,37 @@ private fun ConfederationsRow(
)
}
}
+
+/** A group's direct messages, on its screen (docs/group-threshold-ecdh.md, Phases 6 and 8). */
+@Composable
+private fun GroupDmRowCard(
+ row: GroupDmRow,
+ onClick: () -> Unit,
+) {
+ val headline = when (row) {
+ GroupDmRow.OpenMessages -> stringResource(Res.string.open_the_groups_messages)
+ is GroupDmRow.Messages -> stringResource(Res.string.group_messages)
+ GroupDmRow.ReceivesMessages -> stringResource(Res.string.this_group_receives_direct_messages)
+ }
+ val supporting = when (row) {
+ GroupDmRow.OpenMessages -> stringResource(Res.string.nobody_can_write_to_the_group_yet)
+ is GroupDmRow.Messages ->
+ if (row.unread == 0) stringResource(Res.string.nothing_unread) else stringResource(Res.string.n_unread, row.unread)
+ GroupDmRow.ReceivesMessages -> stringResource(Res.string.only_its_admins_read_them)
+ }
+ val content: @Composable () -> Unit = {
+ ListItem(
+ leadingContent = { Icon(Icons.Default.Mail, contentDescription = Decorative) },
+ trailingContent = if (row == GroupDmRow.ReceivesMessages) null else {
+ { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }
+ },
+ headlineContent = { Text(text = headline) },
+ supportingContent = { Text(text = supporting) },
+ )
+ }
+ if (row == GroupDmRow.ReceivesMessages) {
+ Card(modifier = Modifier.fillMaxWidth()) { content() }
+ } else {
+ Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { content() }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt
new file mode 100644
index 00000000..3ff52ef8
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt
@@ -0,0 +1,427 @@
+package mobi.giza.compose.ui.composable
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.ChevronRight
+import androidx.compose.material.icons.filled.HourglassTop
+import androidx.compose.material.icons.filled.Mail
+import androidx.compose.material3.Badge
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.ListItem
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.text.input.TextFieldLineLimits
+import androidx.compose.foundation.text.input.clearText
+import androidx.compose.foundation.text.input.rememberTextFieldState
+import androidx.compose.material.icons.automirrored.filled.Send
+import androidx.compose.material.icons.filled.Edit
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.FilledIconButton
+import androidx.compose.material3.OutlinedTextField
+import mobi.giza.compose.extensions.bech32ToHexOrThrow
+import mobi.giza.compose.resources.asked_the_group_to_sign_this_message
+import mobi.giza.compose.resources.cancel
+import mobi.giza.compose.resources.could_not_ask_the_group_to_send_this
+import mobi.giza.compose.resources.new_message
+import mobi.giza.compose.resources.nothing_signed_by_this_person_is_on_this_device_yet
+import mobi.giza.compose.resources.preparing_the_admins_are_working_out_how_to_write_to_them
+import mobi.giza.compose.resources.send
+import mobi.giza.compose.resources.sending_again
+import mobi.giza.compose.resources.that_is_not_a_nostr_key
+import mobi.giza.compose.resources.the_groups_quorum_has_to_sign_before_anything_is_sent
+import mobi.giza.compose.resources.their_npub
+import mobi.giza.compose.resources.write_a_message
+import mobi.giza.compose.resources.write_to_them
+import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute
+import mobi.giza.compose.ui.composable.widgets.LocalCanSign
+import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab
+import mobi.giza.compose.ui.composable.widgets.rememberNotifier
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.repository.ChatRepository
+import mobi.giza.compose.repository.GroupDmRepository
+import mobi.giza.compose.resources.Res
+import mobi.giza.compose.resources.a_message_this_screen_cant_show_yet
+import mobi.giza.compose.resources.being_signed
+import mobi.giza.compose.resources.declined_by_the_group
+import mobi.giza.compose.resources.group_messages
+import mobi.giza.compose.resources.n_messages_being_opened
+import mobi.giza.compose.resources.n_more_are_queued
+import mobi.giza.compose.resources.n_unread
+import mobi.giza.compose.resources.nobody_has_written_to_the_group_yet
+import mobi.giza.compose.resources.not_yet_answered_by
+import mobi.giza.compose.resources.one_message_being_opened
+import mobi.giza.compose.resources.only_current_admins_see_the_groups_messages
+import mobi.giza.compose.resources.send_again
+import mobi.giza.compose.resources.sent
+import mobi.giza.compose.resources.signed_but_not_sent
+import mobi.giza.compose.resources.signed_not_yet_sent
+import mobi.giza.compose.resources.the_group
+import mobi.giza.compose.resources.waiting_for_n_more_admins_to_open_this
+import mobi.giza.compose.resources.waiting_for_one_more_admin_to_open_this
+import mobi.giza.compose.ui.composable.navigation.routes.GroupDmConversationRoute
+import mobi.giza.compose.ui.composable.navigation.routes.Route
+import mobi.giza.compose.ui.composable.widgets.Decorative
+import mobi.giza.compose.ui.composable.widgets.EmptyState
+import mobi.giza.compose.ui.composable.widgets.ErrorState
+import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
+import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState
+import mobi.giza.compose.ui.composable.widgets.NavigateBackButton
+import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition
+import mobi.giza.compose.ui.theme.readableContent
+import mobi.giza.compose.ui.theme.spacing
+import mobi.giza.compose.ui.view.model.GroupDmConversationViewModel
+import mobi.giza.compose.ui.view.model.GroupDmListViewModel
+import mobi.giza.compose.ui.view.state.GroupDmConversationUIState
+import mobi.giza.compose.ui.view.state.GroupDmLine
+import mobi.giza.compose.ui.view.state.GroupDmListUIState
+import mobi.giza.compose.ui.view.state.GroupDmOutgoingState
+import mobi.giza.compose.ui.view.state.GroupDmPending
+import org.jetbrains.compose.resources.stringResource
+
+/**
+ * A group's conversations (docs/group-threshold-ecdh.md, Phase 8): who has written, the last
+ * line, what is unread, and what is still being opened, naming the admins it waits on rather
+ * than a count. Nothing here says how the opening works; a person reads "waiting for 1 more
+ * admin", not a protocol.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun GroupDmListScreen(
+ activeUserPublicKey: HexKey,
+ chatRoomId: String,
+ chatRepository: ChatRepository,
+ groupDmRepository: GroupDmRepository,
+ onNavigateToRoute: (Route) -> Unit,
+ onNavigateBack: () -> Unit,
+) {
+ val viewModel: GroupDmListViewModel = viewModel(
+ factory = GroupDmListViewModel.factory(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository)
+ )
+ var writing by remember { mutableStateOf(false) }
+ val canWrite = (viewModel.uiState as? GroupDmListUIState.Loaded)?.isAdmin == true && LocalCanSign.current
+ if (writing) {
+ NewMessageDialog(
+ onDismiss = { writing = false },
+ onRecipient = { recipient ->
+ writing = false
+ onNavigateToRoute(GroupDmConversationRoute(activeUserPublicKey, chatRoomId, conversationId = null, recipients = listOf(recipient)))
+ },
+ )
+ }
+
+ Scaffold(
+ snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
+ topBar = {
+ TopAppBar(
+ title = { Text(stringResource(Res.string.group_messages), maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ navigationIcon = { NavigateBackButton(onNavigateBack) },
+ )
+ },
+ floatingActionButton = {
+ if (canWrite) {
+ ExtendedFab(
+ label = stringResource(Res.string.new_message),
+ icon = { Icon(Icons.Default.Edit, contentDescription = Decorative) },
+ onClick = { writing = true },
+ )
+ }
+ },
+ ) { padding ->
+ ScreenStateTransition(viewModel.uiState) { uiState ->
+ when (val state = uiState) {
+ GroupDmListUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding))
+ // The room came from a navigation argument; reading it again fails the same way.
+ is GroupDmListUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null)
+ is GroupDmListUIState.Loaded -> LazyColumn(
+ modifier = Modifier.padding(padding).readableContent().fillMaxSize()
+ .padding(MaterialTheme.spacing.screenMargin),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ ) {
+ if (!state.isAdmin) {
+ item { EmptyState(message = stringResource(Res.string.only_current_admins_see_the_groups_messages), icon = Icons.Default.Mail) }
+ return@LazyColumn
+ }
+ if (state.pending.waiting > 0 || state.pending.queued > 0) {
+ item { PendingCard(state.pending) }
+ }
+ if (state.conversations.isEmpty()) {
+ item { EmptyState(message = stringResource(Res.string.nobody_has_written_to_the_group_yet), icon = Icons.Default.Mail) }
+ }
+ items(items = state.conversations, key = { it.conversationId }) { conversation ->
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ onClick = {
+ onNavigateToRoute(GroupDmConversationRoute(activeUserPublicKey, chatRoomId, conversation.conversationId))
+ },
+ ) {
+ ListItem(
+ leadingContent = { Icon(Icons.Default.Mail, contentDescription = Decorative) },
+ trailingContent = {
+ if (conversation.unread > 0) {
+ Badge { Text(stringResource(Res.string.n_unread, conversation.unread)) }
+ } else {
+ Icon(Icons.Default.ChevronRight, contentDescription = Decorative)
+ }
+ },
+ headlineContent = { Text(conversation.names.joinToString(", "), maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ supportingContent = {
+ Text(
+ conversation.lastLine ?: stringResource(Res.string.a_message_this_screen_cant_show_yet),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ },
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** What is still being opened, and on whom it waits. */
+@Composable
+internal fun PendingCard(pending: GroupDmPending) {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ ListItem(
+ leadingContent = { Icon(Icons.Default.HourglassTop, contentDescription = Decorative) },
+ headlineContent = {
+ Text(
+ if (pending.waiting == 1) stringResource(Res.string.one_message_being_opened)
+ else stringResource(Res.string.n_messages_being_opened, pending.waiting)
+ )
+ },
+ supportingContent = {
+ Column {
+ when {
+ pending.moreAdminsNeeded == 1 -> Text(stringResource(Res.string.waiting_for_one_more_admin_to_open_this))
+ pending.moreAdminsNeeded > 1 -> Text(stringResource(Res.string.waiting_for_n_more_admins_to_open_this, pending.moreAdminsNeeded))
+ }
+ if (pending.notYetAnsweredBy.isNotEmpty()) {
+ Text(stringResource(Res.string.not_yet_answered_by, pending.notYetAnsweredBy.joinToString(", ")))
+ }
+ if (pending.queued > 0) Text(stringResource(Res.string.n_more_are_queued, pending.queued))
+ }
+ },
+ )
+ }
+}
+
+/**
+ * One of a group's conversations, in and out (Phase 8). A message the group sent shows where it
+ * has got to, and one signed but not on a relay offers Send again (Phase 9).
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun GroupDmConversationScreen(
+ activeUserPublicKey: HexKey,
+ chatRoomId: String,
+ conversationId: HexKey?,
+ recipients: List,
+ chatRepository: ChatRepository,
+ groupDmRepository: GroupDmRepository,
+ onNavigateBack: () -> Unit,
+ onNavigateToRoute: (Route) -> Unit = {},
+) {
+ val notify = rememberNotifier(rememberCoroutineScope())
+ val proposed = stringResource(Res.string.asked_the_group_to_sign_this_message)
+ val noEvidence = stringResource(Res.string.nothing_signed_by_this_person_is_on_this_device_yet)
+ val couldNotSend = stringResource(Res.string.could_not_ask_the_group_to_send_this)
+ val sendingAgain = stringResource(Res.string.sending_again)
+ val canSign = LocalCanSign.current
+ val viewModel: GroupDmConversationViewModel = viewModel(
+ key = "$chatRoomId/$conversationId/${recipients.joinToString(",")}",
+ factory = GroupDmConversationViewModel.factory(chatRoomId, activeUserPublicKey, conversationId, recipients, chatRepository, groupDmRepository)
+ )
+
+ ScreenStateTransition(viewModel.uiState) { uiState ->
+ when (val state = uiState) {
+ GroupDmConversationUIState.Loading -> LoadingDataIndicator()
+ is GroupDmConversationUIState.Error -> ErrorState(message = state.message, onRetry = null)
+ is GroupDmConversationUIState.Loaded -> Scaffold(
+ snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
+ topBar = {
+ TopAppBar(
+ title = { Text(state.names.joinToString(", "), maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ navigationIcon = { NavigateBackButton(onNavigateBack) },
+ )
+ },
+ bottomBar = {
+ if (state.isAdmin && canSign) {
+ Composer(
+ composing = viewModel.composing,
+ onSend = { text, clear ->
+ viewModel.send(
+ text = text,
+ replyTo = state.lines.lastOrNull { !it.outgoing }?.id,
+ onProposed = { sessionId ->
+ clear()
+ notify(proposed)
+ onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId))
+ },
+ onNoEvidence = { notify(noEvidence) },
+ onFailure = { notify(couldNotSend) },
+ )
+ },
+ )
+ }
+ },
+ ) { padding ->
+ LazyColumn(
+ modifier = Modifier.padding(padding).readableContent().fillMaxSize()
+ .padding(MaterialTheme.spacing.screenMargin),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap),
+ ) {
+ if (!state.isAdmin) {
+ item { EmptyState(message = stringResource(Res.string.only_current_admins_see_the_groups_messages), icon = Icons.Default.Mail) }
+ return@LazyColumn
+ }
+ items(items = state.lines, key = { it.id }) { line ->
+ GroupDmBubble(line, onSendAgain = { sessionId -> viewModel.sendAgain(sessionId) { notify(sendingAgain) } })
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun GroupDmBubble(line: GroupDmLine, onSendAgain: ((String) -> Unit)?) {
+ Box(modifier = Modifier.fillMaxWidth(), contentAlignment = if (line.outgoing) Alignment.CenterEnd else Alignment.CenterStart) {
+ Card(
+ colors = if (line.outgoing) CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)
+ else CardDefaults.cardColors(),
+ ) {
+ Column(
+ modifier = Modifier.padding(MaterialTheme.spacing.compactPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap),
+ ) {
+ Text(
+ text = if (line.outgoing) stringResource(Res.string.the_group) else line.senderName,
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Text(text = line.text ?: stringResource(Res.string.a_message_this_screen_cant_show_yet), style = MaterialTheme.typography.bodyLarge)
+ line.outgoingState?.let { state ->
+ Text(
+ text = stringResource(
+ when (state) {
+ GroupDmOutgoingState.BEING_SIGNED -> Res.string.being_signed
+ GroupDmOutgoingState.SIGNED -> Res.string.signed_not_yet_sent
+ GroupDmOutgoingState.SENT -> Res.string.sent
+ GroupDmOutgoingState.NOT_SENT -> Res.string.signed_but_not_sent
+ GroupDmOutgoingState.DECLINED -> Res.string.declined_by_the_group
+ }
+ ),
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ val sessionId = line.signingSessionId
+ val owes = state == GroupDmOutgoingState.NOT_SENT || state == GroupDmOutgoingState.SIGNED
+ if (owes && sessionId != null && onSendAgain != null) {
+ TextButton(onClick = { onSendAgain(sessionId) }) { Text(stringResource(Res.string.send_again)) }
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * What an admin writes as the group, with what sending means said above the button: nothing
+ * goes until the group's quorum has signed (D10).
+ */
+@Composable
+private fun Composer(composing: GroupDmConversationViewModel.Composing, onSend: (String, clear: () -> Unit) -> Unit) {
+ val field = rememberTextFieldState()
+ Column(
+ modifier = Modifier.fillMaxWidth().imePadding().padding(MaterialTheme.spacing.containerPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap),
+ ) {
+ Text(
+ text = when (composing) {
+ GroupDmConversationViewModel.Composing.Preparing -> stringResource(Res.string.preparing_the_admins_are_working_out_how_to_write_to_them)
+ else -> stringResource(Res.string.the_groups_quorum_has_to_sign_before_anything_is_sent)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ OutlinedTextField(
+ state = field,
+ modifier = Modifier.weight(1f),
+ placeholder = { Text(stringResource(Res.string.write_a_message)) },
+ lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 5),
+ )
+ FilledIconButton(
+ enabled = composing == GroupDmConversationViewModel.Composing.Idle && field.text.isNotBlank(),
+ onClick = { onSend(field.text.toString()) { field.clearText() } },
+ ) {
+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(Res.string.send))
+ }
+ }
+ }
+}
+
+/** Starts a conversation: an npub, pasted. */
+@Composable
+internal fun NewMessageDialog(onDismiss: () -> Unit, onRecipient: (HexKey) -> Unit) {
+ val field = rememberTextFieldState()
+ val key = recipientKeyOf(field.text.toString())
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(stringResource(Res.string.new_message)) },
+ text = {
+ OutlinedTextField(
+ state = field,
+ label = { Text(stringResource(Res.string.their_npub)) },
+ isError = field.text.isNotBlank() && key == null,
+ supportingText = if (field.text.isNotBlank() && key == null) {
+ { Text(stringResource(Res.string.that_is_not_a_nostr_key)) }
+ } else null,
+ lineLimits = TextFieldLineLimits.SingleLine,
+ )
+ },
+ confirmButton = {
+ TextButton(enabled = key != null, onClick = { key?.let(onRecipient) }) { Text(stringResource(Res.string.write_to_them)) }
+ },
+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } },
+ )
+}
+
+/** An npub or 64 hex characters, as a key; null for anything else. */
+internal fun recipientKeyOf(text: String): HexKey? {
+ val trimmed = text.trim().removePrefix("nostr:")
+ val hex = when {
+ trimmed.startsWith("npub1") -> runCatching { trimmed.bech32ToHexOrThrow() }.getOrNull()
+ else -> trimmed.lowercase()
+ } ?: return null
+ return hex.takeIf { it.length == 64 && it.all { c -> c in "0123456789abcdef" } && mobi.giza.compose.cryptography.threshold.ThresholdEcdh.pointOf(it) != null }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt
new file mode 100644
index 00000000..b05344da
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmSetupScreen.kt
@@ -0,0 +1,165 @@
+package mobi.giza.compose.ui.composable
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.input.TextFieldLineLimits
+import androidx.compose.foundation.text.input.rememberTextFieldState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Draw
+import androidx.compose.material3.BottomAppBar
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.Text
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.ui.Modifier
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.repository.ChatRepository
+import mobi.giza.compose.repository.GroupDmRepository
+import mobi.giza.compose.resources.Res
+import mobi.giza.compose.resources.anyone_on_nostr_will_be_able_to_write_to_the_group
+import mobi.giza.compose.resources.ask_the_group_to_sign
+import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_its_message_relays
+import mobi.giza.compose.resources.every_relay_has_to_be_a_public_wss_address
+import mobi.giza.compose.resources.message_relays
+import mobi.giza.compose.resources.one_wss_address_per_line
+import mobi.giza.compose.resources.only_a_current_admin_can_open_the_groups_messages
+import mobi.giza.compose.resources.open_the_groups_messages
+import mobi.giza.compose.resources.senders_apps_deliver_to_these_relays
+import mobi.giza.compose.resources.the_group_signs_where_it_receives_messages
+import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute
+import mobi.giza.compose.ui.composable.navigation.routes.Route
+import mobi.giza.compose.ui.composable.widgets.Decorative
+import mobi.giza.compose.ui.composable.widgets.ErrorState
+import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
+import mobi.giza.compose.ui.composable.widgets.LocalCanSign
+import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState
+import mobi.giza.compose.ui.composable.widgets.NavigateBackButton
+import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition
+import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab
+import mobi.giza.compose.ui.composable.widgets.rememberNotifier
+import mobi.giza.compose.ui.theme.readableContent
+import mobi.giza.compose.ui.theme.spacing
+import mobi.giza.compose.ui.view.model.GroupDmSetupViewModel
+import mobi.giza.compose.ui.view.state.GroupDmSetupUIState
+import org.jetbrains.compose.resources.stringResource
+
+/**
+ * Where a group decides to receive direct messages (D8 of docs/group-threshold-ecdh.md): the
+ * relays senders deliver to, and what signing them means, said before the button. The button
+ * proposes; the group's messages open when a quorum has signed, so the screen hands over to
+ * the signing session rather than going back.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun GroupDmSetupScreen(
+ activeUserPublicKey: HexKey,
+ chatRoomId: String,
+ chatRepository: ChatRepository,
+ groupDmRepository: GroupDmRepository,
+ onNavigateToRouteAndPopUpInclusive: (Route) -> Unit,
+ onNavigateBack: () -> Unit,
+) {
+ val viewModel: GroupDmSetupViewModel = viewModel(
+ factory = GroupDmSetupViewModel.factory(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository)
+ )
+ val notify = rememberNotifier(rememberCoroutineScope())
+ val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_its_message_relays)
+ val canSign = LocalCanSign.current
+
+ ScreenStateTransition(viewModel.uiState) { uiState ->
+ when (val state = uiState) {
+ is GroupDmSetupUIState.Loading -> LoadingDataIndicator()
+ // The room came from a navigation argument; reading it again fails the same way.
+ is GroupDmSetupUIState.Error -> ErrorState(message = state.message, onRetry = null)
+ is GroupDmSetupUIState.Loaded -> {
+ val relaysField = rememberTextFieldState(state.relays.joinToString("\n"))
+ val relays = viewModel.relaysOf(relaysField.text.toString())
+ Scaffold(
+ snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
+ modifier = Modifier.imePadding(),
+ topBar = {
+ TopAppBar(
+ title = { Text(stringResource(Res.string.open_the_groups_messages)) },
+ navigationIcon = { NavigateBackButton(onNavigateBack) },
+ )
+ },
+ bottomBar = {
+ BottomAppBar(
+ actions = {},
+ floatingActionButton = {
+ ExtendedFab(
+ label = stringResource(Res.string.ask_the_group_to_sign),
+ icon = { Icon(Icons.Default.Draw, contentDescription = Decorative) },
+ enabled = state.canPropose && canSign && relays != null && !viewModel.isActionPending,
+ onClick = {
+ viewModel.propose(
+ text = relaysField.text.toString(),
+ onSuccess = { sessionId ->
+ onNavigateToRouteAndPopUpInclusive(
+ FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)
+ )
+ },
+ onFailure = { notify(couldNotPropose) },
+ )
+ },
+ )
+ },
+ )
+ },
+ ) { innerPadding ->
+ Column(
+ modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize()
+ .verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ ) {
+ Text(
+ text = stringResource(Res.string.anyone_on_nostr_will_be_able_to_write_to_the_group),
+ style = MaterialTheme.typography.bodyLarge,
+ )
+ Text(
+ text = stringResource(Res.string.the_group_signs_where_it_receives_messages),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ if (!state.canPropose) {
+ Text(
+ text = stringResource(Res.string.only_a_current_admin_can_open_the_groups_messages),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.error,
+ )
+ }
+ OutlinedTextField(
+ state = relaysField,
+ modifier = Modifier.fillMaxWidth(),
+ label = { Text(stringResource(Res.string.message_relays)) },
+ placeholder = { Text(stringResource(Res.string.one_wss_address_per_line)) },
+ lineLimits = TextFieldLineLimits.MultiLine(minHeightInLines = 3),
+ isError = relays == null,
+ supportingText = {
+ Text(
+ stringResource(
+ if (relays == null) Res.string.every_relay_has_to_be_a_public_wss_address
+ else Res.string.senders_apps_deliver_to_these_relays
+ )
+ )
+ },
+ )
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt
index 4f043e50..0e226c81 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt
@@ -202,6 +202,7 @@ fun GizaNavHost(
val databaseDkgRepository = runtime.dkgRepository
val databaseFrostSigningRepository = runtime.frostSigningRepository
val databaseConfederationRepository = runtime.confederationRepository
+ val databaseGroupDmRepository = runtime.groupDmRepository
val databaseGroupInboxRepository = runtime.groupInboxRepository
val databaseMarmotRepository = runtime.marmotRepository
val searchRepository = runtime.searchRepository
@@ -1277,6 +1278,50 @@ fun GizaNavHost(
}
)
}
+ // Where a group receives direct messages: docs/group-threshold-ecdh.md, D8.
+ composable { backStackEntry ->
+ val route = backStackEntry.toRoute()
+
+ mobi.giza.compose.ui.composable.GroupDmSetupScreen(
+ activeUserPublicKey = route.activeUserPublicKey,
+ chatRoomId = route.chatRoomId,
+ chatRepository = databaseChatRepository,
+ groupDmRepository = databaseGroupDmRepository,
+ onNavigateToRouteAndPopUpInclusive = { signingRoute ->
+ navController.navigate(route = signingRoute) {
+ popUpTo(route) { inclusive = true }
+ }
+ },
+ onNavigateBack = { navController.popBackStack() }
+ )
+ }
+ // A group's direct messages: docs/group-threshold-ecdh.md, Phase 8.
+ composable { backStackEntry ->
+ val route = backStackEntry.toRoute()
+
+ mobi.giza.compose.ui.composable.GroupDmListScreen(
+ activeUserPublicKey = route.activeUserPublicKey,
+ chatRoomId = route.chatRoomId,
+ chatRepository = databaseChatRepository,
+ groupDmRepository = databaseGroupDmRepository,
+ onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) },
+ onNavigateBack = { navController.popBackStack() }
+ )
+ }
+ composable { backStackEntry ->
+ val route = backStackEntry.toRoute()
+
+ mobi.giza.compose.ui.composable.GroupDmConversationScreen(
+ activeUserPublicKey = route.activeUserPublicKey,
+ chatRoomId = route.chatRoomId,
+ conversationId = route.conversationId,
+ recipients = route.recipients,
+ chatRepository = databaseChatRepository,
+ groupDmRepository = databaseGroupDmRepository,
+ onNavigateBack = { navController.popBackStack() },
+ onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) },
+ )
+ }
// A group's confederations: docs/confederation.md.
composable { backStackEntry ->
val route = backStackEntry.toRoute()
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt
new file mode 100644
index 00000000..12b6ff4a
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt
@@ -0,0 +1,19 @@
+package mobi.giza.compose.ui.composable.navigation.routes
+
+import kotlinx.serialization.Serializable
+
+/** A group's conversations. docs/group-threshold-ecdh.md, Phase 8. */
+@Serializable
+data class GroupDmListRoute(
+ val activeUserPublicKey: String,
+ val chatRoomId: String,
+): Route()
+
+/** One of a group's conversations, or a new one when [conversationId] is null and [recipients] are given (Phase 9). */
+@Serializable
+data class GroupDmConversationRoute(
+ val activeUserPublicKey: String,
+ val chatRoomId: String,
+ val conversationId: String?,
+ val recipients: List = emptyList(),
+): Route()
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt
new file mode 100644
index 00000000..0bcd6651
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmSetupRoute.kt
@@ -0,0 +1,10 @@
+package mobi.giza.compose.ui.composable.navigation.routes
+
+import kotlinx.serialization.Serializable
+
+/** Where a group chooses the relays it receives messages on. docs/group-threshold-ecdh.md, D8. */
+@Serializable
+data class GroupDmSetupRoute(
+ val activeUserPublicKey: String,
+ val chatRoomId: String,
+): Route()
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt
index fc52203f..f71ca546 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt
@@ -135,6 +135,9 @@ class ChatRoomDetailViewModel(
confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId),
inbox = chatRepository.inboxSummary(localChatRoom),
confederationName = chatRepository.confederationOfRoom(chatRoomId),
+ groupDmRow = runCatching { chatRepository.groupDmRow(chatRoomId, localChatRoom.chatRoom.userPublicKey) }
+ .onFailure { if (it is CancellationException) throw it else logger.w(throwable = it) { "Couldn't read $chatRoomId's messages row" } }
+ .getOrNull(),
canSignAsConfederation = chatRepository.canSignAsConfederation(chatRoomId),
canProposeAsGroup = canSign && roomIsOpen,
subgroupsNeedAWallet = canSign && subgroupsNeedAWallet,
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt
new file mode 100644
index 00000000..fa59b2db
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt
@@ -0,0 +1,113 @@
+package mobi.giza.compose.ui.view.model
+
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.withContext
+import mobi.giza.compose.managers.GroupDmSender
+import mobi.giza.compose.repository.ChatRepository
+import mobi.giza.compose.repository.GroupDmRepository
+import mobi.giza.compose.ui.view.state.GroupDmConversationUIState
+
+/**
+ * One of a group's conversations, watched, and marked read while it is open
+ * (docs/group-threshold-ecdh.md, Phase 8). A new conversation is [recipients] with nothing in it.
+ */
+class GroupDmConversationViewModel(
+ val chatRoomId: String,
+ val activeUserPublicKey: HexKey,
+ val conversationId: HexKey?,
+ val recipients: List,
+ val chatRepository: ChatRepository,
+ val groupDmRepository: GroupDmRepository,
+) : ViewModel() {
+ var uiState: GroupDmConversationUIState by mutableStateOf(GroupDmConversationUIState.Loading)
+ private set
+
+ init {
+ viewModelScope.launch(Dispatchers.IO) {
+ val room = chatRepository.getChatRoomByIdentifier(chatRoomId)
+ if (room == null) {
+ uiState = GroupDmConversationUIState.Error("Couldn't find the chat room")
+ return@launch
+ }
+ val isAdmin = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey)
+ val participants = conversationId?.let { groupDmRepository.participantsOf(chatRoomId, it) }?.takeIf { it.isNotEmpty() } ?: recipients
+ val names = participants.map { groupDmRepository.nameOf(it) }
+ // A new conversation is the one its recipients make: the same id the first message files under.
+ val id = conversationId ?: mobi.giza.compose.nostr.groupdm.GroupDmConversation.idOf(recipients)
+ val lines = if (isAdmin) groupDmRepository.observeConversation(chatRoomId, id) else flowOf(emptyList())
+ lines.collect { current ->
+ if (isAdmin) groupDmRepository.markRead(chatRoomId, id)
+ uiState = GroupDmConversationUIState.Loaded(room, participants, names, current, isAdmin)
+ }
+ }
+ }
+
+ /** Where the composer is: idle, preparing a recipient's key, or sending. */
+ var composing: Composing by mutableStateOf(Composing.Idle)
+ private set
+
+ enum class Composing { Idle, Preparing, Sending }
+
+ /**
+ * Asks the group to send [text] (D10). A recipient whose key is still being computed has
+ * the composer wait and try again, for a few minutes, while the admins' apps answer.
+ */
+ fun send(text: String, replyTo: HexKey?, onProposed: (sessionId: String) -> Unit, onNoEvidence: () -> Unit, onFailure: () -> Unit) {
+ val loaded = uiState as? GroupDmConversationUIState.Loaded ?: return
+ if (composing != Composing.Idle || text.isBlank()) return
+ composing = Composing.Sending
+ viewModelScope.launch(Dispatchers.IO) {
+ var outcome = runCatching { groupDmRepository.send(loaded.localChatRoom, loaded.participants, text, replyTo) }.getOrNull()
+ var tries = 0
+ while (outcome is GroupDmSender.Outcome.Preparing && tries < PREPARING_TRIES) {
+ composing = Composing.Preparing
+ delay(PREPARING_INTERVAL)
+ outcome = runCatching { groupDmRepository.send(loaded.localChatRoom, loaded.participants, text, replyTo) }.getOrNull()
+ tries += 1
+ }
+ withContext(Dispatchers.Main) {
+ composing = Composing.Idle
+ when (outcome) {
+ is GroupDmSender.Outcome.Proposed -> onProposed(outcome.sessionId)
+ is GroupDmSender.Outcome.NoEvidence -> onNoEvidence()
+ else -> onFailure()
+ }
+ }
+ }
+ }
+
+ fun sendAgain(signingSessionId: String, onDone: () -> Unit) {
+ viewModelScope.launch(Dispatchers.IO) {
+ runCatching { groupDmRepository.sendAgain(signingSessionId) }
+ withContext(Dispatchers.Main) { onDone() }
+ }
+ }
+
+ companion object {
+ private const val PREPARING_TRIES = 60
+ private val PREPARING_INTERVAL = kotlin.time.Duration.parse("3s")
+
+ fun factory(
+ chatRoomId: String,
+ activeUserPublicKey: HexKey,
+ conversationId: HexKey?,
+ recipients: List,
+ chatRepository: ChatRepository,
+ groupDmRepository: GroupDmRepository,
+ ): ViewModelProvider.Factory = viewModelFactory {
+ initializer { GroupDmConversationViewModel(chatRoomId, activeUserPublicKey, conversationId, recipients, chatRepository, groupDmRepository) }
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt
new file mode 100644
index 00000000..fcba88af
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt
@@ -0,0 +1,53 @@
+package mobi.giza.compose.ui.view.model
+
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.launch
+import mobi.giza.compose.repository.ChatRepository
+import mobi.giza.compose.repository.GroupDmRepository
+import mobi.giza.compose.ui.view.state.GroupDmListUIState
+
+/** A group's conversations, watched (docs/group-threshold-ecdh.md, Phase 8). */
+class GroupDmListViewModel(
+ val chatRoomId: String,
+ val activeUserPublicKey: HexKey,
+ val chatRepository: ChatRepository,
+ val groupDmRepository: GroupDmRepository,
+) : ViewModel() {
+ var uiState: GroupDmListUIState by mutableStateOf(GroupDmListUIState.Loading)
+ private set
+
+ init {
+ viewModelScope.launch(Dispatchers.IO) {
+ val room = chatRepository.getChatRoomByIdentifier(chatRoomId)
+ if (room == null) {
+ uiState = GroupDmListUIState.Error("Couldn't find the chat room")
+ return@launch
+ }
+ val isAdmin = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey)
+ combine(groupDmRepository.observeConversations(chatRoomId), groupDmRepository.observePending(chatRoomId)) { conversations, pending ->
+ // D12: only a current admin sees anything of the group's mail.
+ GroupDmListUIState.Loaded(
+ localChatRoom = room,
+ conversations = if (isAdmin) conversations else emptyList(),
+ pending = if (isAdmin) pending else mobi.giza.compose.ui.view.state.GroupDmPending(),
+ isAdmin = isAdmin,
+ )
+ }.collect { uiState = it }
+ }
+ }
+
+ companion object {
+ fun factory(chatRoomId: String, activeUserPublicKey: HexKey, chatRepository: ChatRepository, groupDmRepository: GroupDmRepository): ViewModelProvider.Factory =
+ viewModelFactory { initializer { GroupDmListViewModel(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) } }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt
new file mode 100644
index 00000000..1835b240
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmSetupViewModel.kt
@@ -0,0 +1,90 @@
+package mobi.giza.compose.ui.view.model
+
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import mobi.giza.compose.managers.GroupDmRelays
+import mobi.giza.compose.nostr.RelayUrlInput
+import mobi.giza.compose.repository.ChatRepository
+import mobi.giza.compose.repository.GroupDmRepository
+import mobi.giza.compose.ui.view.state.GroupDmSetupUIState
+
+/**
+ * Asks the group to sign where it receives direct messages (D8 of
+ * docs/group-threshold-ecdh.md). Proposing is the whole of it: the group opens its messages
+ * when a quorum signs, not when the button is pressed.
+ */
+class GroupDmSetupViewModel(
+ val chatRoomId: String,
+ val activeUserPublicKey: HexKey,
+ val chatRepository: ChatRepository,
+ val groupDmRepository: GroupDmRepository,
+) : ViewModel() {
+ private val logger = Logger.withTag("GroupDmSetupViewModel")
+
+ var uiState: GroupDmSetupUIState by mutableStateOf(GroupDmSetupUIState.Loading)
+ private set
+
+ var isActionPending: Boolean by mutableStateOf(false)
+ private set
+
+ init {
+ viewModelScope.launch(Dispatchers.IO) {
+ val room = chatRepository.getChatRoomByIdentifier(chatRoomId)
+ uiState = if (room == null) {
+ GroupDmSetupUIState.Error("Couldn't find the chat room")
+ } else {
+ GroupDmSetupUIState.Loaded(
+ localChatRoom = room,
+ relays = groupDmRepository.observeRelays(chatRoomId).first() ?: GroupDmRelays.defaultRelays,
+ canPropose = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey),
+ )
+ }
+ }
+ }
+
+ /** The lines of [text] as relays, or null when any is not a public `wss://` address or there are none. */
+ fun relaysOf(text: String): List? {
+ val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() }
+ if (lines.isEmpty()) return null
+ return lines.map { RelayUrlInput.relayUrlOrNull(it)?.url ?: return null }.distinct()
+ }
+
+ fun propose(text: String, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) {
+ val loaded = uiState as? GroupDmSetupUIState.Loaded ?: return
+ val relays = relaysOf(text) ?: return onFailure()
+ if (isActionPending) return
+ isActionPending = true
+ viewModelScope.launch(Dispatchers.IO) {
+ val session = runCatching { groupDmRepository.proposeRelays(loaded.localChatRoom, activeUserPublicKey, relays) }
+ .onFailure { logger.e("Couldn't propose the group's message relays", it) }
+ .getOrNull()
+ withContext(Dispatchers.Main) {
+ isActionPending = false
+ if (session != null) onSuccess(session.id) else onFailure()
+ }
+ }
+ }
+
+ companion object {
+ fun factory(
+ chatRoomId: String,
+ activeUserPublicKey: HexKey,
+ chatRepository: ChatRepository,
+ groupDmRepository: GroupDmRepository,
+ ): ViewModelProvider.Factory = viewModelFactory {
+ initializer { GroupDmSetupViewModel(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) }
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt
index d7f60b90..bfd26ec8 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt
@@ -74,6 +74,7 @@ class SynchronizationViewModel(
val relayRepository: RelayRepository,
val scope: CoroutineScope,
val confederationRepository: ConfederationRepository? = null,
+ val groupDmRepository: mobi.giza.compose.repository.GroupDmRepository? = null,
val groupInboxRepository: GroupInboxRepository? = null,
): ViewModel() {
@@ -95,6 +96,7 @@ class SynchronizationViewModel(
chatRepository = chatRepository,
holdConnections = AppLifecycle.holdConnections,
confederationRepository = confederationRepository,
+ groupDmRepository = groupDmRepository,
groupInboxRepository = groupInboxRepository,
)
@@ -103,6 +105,11 @@ class SynchronizationViewModel(
ConfederationPublisher(repository = it, transport = relaysSocketManager)
}
+ /** Sends the group's signed 10050s and message wraps (docs/group-threshold-ecdh.md, D8 and D10). */
+ private val groupDmPublisher = groupDmRepository?.let {
+ mobi.giza.compose.managers.GroupDmPublisher(repository = it, transport = relaysSocketManager)
+ }
+
/** Sends what this device owes relays for its groups' inboxes (docs/group-inbox.md, D7). */
private val groupInboxPublisher = groupInboxRepository?.let {
GroupInboxPublisher(repository = it, transport = relaysSocketManager)
@@ -159,6 +166,7 @@ class SynchronizationViewModel(
relayRepository: RelayRepository,
scope: CoroutineScope,
confederationRepository: ConfederationRepository? = null,
+ groupDmRepository: mobi.giza.compose.repository.GroupDmRepository? = null,
groupInboxRepository: GroupInboxRepository? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
@@ -169,6 +177,7 @@ class SynchronizationViewModel(
relayRepository = relayRepository,
scope = scope,
confederationRepository = confederationRepository,
+ groupDmRepository = groupDmRepository,
groupInboxRepository = groupInboxRepository,
)
}
@@ -294,6 +303,17 @@ class SynchronizationViewModel(
}
}
}
+ // What the group's direct messages owe relays.
+ // docs/group-threshold-ecdh.md, D8 and D10.
+ groupDmPublisher?.takeIf { ExperimentalFeatures.groupDirectMessages }?.let { publisher ->
+ launch(Dispatchers.IO) {
+ runCatching { publisher.run() }
+ .onFailure {
+ if (it is CancellationException) throw it
+ logger.e("Publishing the group's direct messages stopped", it)
+ }
+ }
+ }
// The group inbox's announcements and replies this device
// owes relays. docs/group-inbox.md, D7 and D10.
groupInboxPublisher?.takeIf { ExperimentalFeatures.groupInbox }?.let { publisher ->
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt
index 0dd58250..b833998d 100755
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt
@@ -78,6 +78,8 @@ sealed interface ChatRoomDetailUIState {
val inbox: InboxRowSummary? = null,
/** The confederation whose room this is, by name: its membership is fixed until it can sign. */
val confederationName: String? = null,
+ /** What the group's direct messages show here, or nothing. docs/group-threshold-ecdh.md. */
+ val groupDmRow: GroupDmRow? = null,
/** Whether this device holds a role in that confederation, and so can propose what it signs. */
val canSignAsConfederation: Boolean = false,
/**
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt
new file mode 100644
index 00000000..d1c2c238
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmRow.kt
@@ -0,0 +1,16 @@
+package mobi.giza.compose.ui.view.state
+
+/**
+ * What a group's screen says about its direct messages (docs/group-threshold-ecdh.md,
+ * Phases 6 and 8). Null when there is nothing to say: the feature off, or no key.
+ */
+sealed interface GroupDmRow {
+ /** A current admin, and the group has not signed where it receives messages. */
+ data object OpenMessages : GroupDmRow
+
+ /** A current admin of a group that receives messages: the way in, with what is unread. */
+ data class Messages(val unread: Int) : GroupDmRow
+
+ /** Anyone else, where the group's 10050 is signed: it is public, and nothing more is. */
+ data object ReceivesMessages : GroupDmRow
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt
new file mode 100644
index 00000000..15e17e59
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmSetupUIState.kt
@@ -0,0 +1,15 @@
+package mobi.giza.compose.ui.view.state
+
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+
+sealed interface GroupDmSetupUIState {
+ data object Loading : GroupDmSetupUIState
+ data class Error(val message: String) : GroupDmSetupUIState
+ data class Loaded(
+ val localChatRoom: LocalChatRoom,
+ /** What the field starts from: what the group signed, or the app's DM relays. */
+ val relays: List,
+ /** A current admin holding a share: who may ask. */
+ val canPropose: Boolean,
+ ) : GroupDmSetupUIState
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt
new file mode 100644
index 00000000..299c29b4
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt
@@ -0,0 +1,65 @@
+package mobi.giza.compose.ui.view.state
+
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlin.time.Instant
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+
+/** One of the group's conversations, for its list (docs/group-threshold-ecdh.md, Phase 8). */
+data class GroupDmConversationSummary(
+ val conversationId: HexKey,
+ val participants: List,
+ val names: List,
+ /** The newest message's words, or null for one the screen cannot show yet. */
+ val lastLine: String?,
+ val lastAt: Instant,
+ val unread: Int,
+)
+
+/** What the group was sent that its admins have not opened yet, and on whom it waits. */
+data class GroupDmPending(
+ val waiting: Int = 0,
+ val queued: Int = 0,
+ /** How many more admins have to answer the newest waiting message. */
+ val moreAdminsNeeded: Int = 0,
+ /** The current admins who have not answered it, by name. */
+ val notYetAnsweredBy: List = emptyList(),
+)
+
+sealed interface GroupDmListUIState {
+ data object Loading : GroupDmListUIState
+ data class Error(val message: String) : GroupDmListUIState
+ data class Loaded(
+ val localChatRoom: LocalChatRoom,
+ val conversations: List,
+ val pending: GroupDmPending,
+ val isAdmin: Boolean,
+ ) : GroupDmListUIState
+}
+
+/** Where a message the group sends has got to (Phase 9). */
+enum class GroupDmOutgoingState { BEING_SIGNED, SIGNED, SENT, NOT_SENT, DECLINED }
+
+/** One message in a conversation, in or out. */
+data class GroupDmLine(
+ val id: HexKey,
+ /** The words, or null for a kind this screen cannot show yet. */
+ val text: String?,
+ val outgoing: Boolean,
+ val senderName: String,
+ val at: Instant,
+ val outgoingState: GroupDmOutgoingState? = null,
+ /** The signing session a message the group sent went out in, for Send again. */
+ val signingSessionId: String? = null,
+)
+
+sealed interface GroupDmConversationUIState {
+ data object Loading : GroupDmConversationUIState
+ data class Error(val message: String) : GroupDmConversationUIState
+ data class Loaded(
+ val localChatRoom: LocalChatRoom,
+ val participants: List,
+ val names: List,
+ val lines: List,
+ val isAdmin: Boolean,
+ ) : GroupDmConversationUIState
+}
diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt
index 76d84077..1ffd858e 100644
--- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt
+++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt
@@ -124,7 +124,10 @@ class ProposedEventTest {
val relays = ProposedEvent.summarize(event(10050, tags = arrayOf(arrayOf("relay", "wss://inbox.example.com/"))))
assertEquals("Where the group receives private messages", relays.label)
assertEquals("inbox.example.com", relays.detail)
- assertEquals("A private reply from the group's inbox", ProposedEvent.summarize(event(13)).label)
+ // A reply names the inbox key it is sealed from; a seal without that `n` tag is the
+ // group writing by threshold ECDH instead (docs/group-threshold-ecdh.md, D12).
+ assertEquals("A private reply from the group's inbox", ProposedEvent.summarize(event(13, tags = arrayOf(arrayOf("n", "c".repeat(64))))).label)
+ assertEquals("A private message from the group", ProposedEvent.summarize(event(13)).label)
}
private fun event(
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ThresholdEcdhPremiseJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ThresholdEcdhPremiseJvmTest.kt
new file mode 100644
index 00000000..2d5e5781
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ThresholdEcdhPremiseJvmTest.kt
@@ -0,0 +1,205 @@
+package mobi.giza.compose
+
+import com.vitorpamplona.crypto.kdf.Hkdf
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+import fr.acinq.bitcoin.crypto.frost.Frost
+import fr.acinq.bitcoin.crypto.frost.KeyMaterial
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.SharedKeyDerivation
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+
+/**
+ * Phase 0 of docs/group-threshold-ecdh.md: the six facts the plan rests on, checked against
+ * the real libraries before anything is built over them.
+ *
+ * This is the one file allowed to build the group's secret whole. Every key in it is a
+ * throwaway made by `Frost.trustedDealerKeygen` for the test, and building `x` and `d` is the
+ * only way to show that the threshold arithmetic lands where single-key NIP-44 does. The app's
+ * own code never does (shared-key-derivation.md's rule), and Phase 2's test enforces that.
+ */
+class ThresholdEcdhPremiseJvmTest {
+ private val one = scalar(1)
+
+ private fun scalar(v: Int): PrivateKey = PrivateKey(ByteArray(32).also {
+ it[28] = (v ushr 24).toByte(); it[29] = (v ushr 16).toByte(); it[30] = (v ushr 8).toByte(); it[31] = v.toByte()
+ })
+
+ /** `n − 2`, the exponent of Fermat's inverse in the group of order `n`. */
+ private val nMinus2 = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f"
+
+ private fun inverse(v: PrivateKey): PrivateKey {
+ var result = one
+ nMinus2.chunked(2).map { it.toInt(16) }.forEach { byte ->
+ for (bit in 7 downTo 0) {
+ result = result * result
+ if ((byte ushr bit) and 1 == 1) result = result * v
+ }
+ }
+ return result
+ }
+
+ /** λᵢ at zero over the evaluation points [xs], each a holder's id plus one (check 1). */
+ private fun lagrange(xi: Int, xs: List): PrivateKey =
+ xs.filter { it != xi }.fold(one) { acc, xj -> acc * scalar(xj) * inverse(scalar(xj) - scalar(xi)) }
+
+ private fun dealer(seed: Int, n: Int = 5, t: Int = 3): Pair {
+ val secret = PrivateKey(Crypto.sha256("threshold-ecdh-premise/$seed".encodeToByteArray()))
+ return secret to Frost.trustedDealerKeygen(secret, n, t)
+ }
+
+ private fun subsets(ids: List, t: Int): List> =
+ if (t == 0) listOf(emptyList()) else if (ids.size < t) emptyList()
+ else subsets(ids.drop(1), t - 1).map { listOf(ids.first()) + it } + subsets(ids.drop(1), t)
+
+ /** D2, replayed: `(a, b)` with `d = a·x + b`, and the point the replay reaches. */
+ private data class Replay(val aNegative: Boolean, val b: PrivateKey?, val q: PublicKey, val parities: List)
+
+ private fun replay(x: PublicKey, tweaks: List): Replay {
+ var aNegative = false
+ var b: PrivateKey? = null
+ var q = x
+ val parities = mutableListOf()
+ tweaks.forEach { tau ->
+ val even = q.isEven()
+ parities += even
+ val t = PrivateKey(tau)
+ if (!even) {
+ q = -q
+ aNegative = !aNegative
+ b = b?.let { -it }
+ }
+ q += t.publicKey()
+ b = b?.let { it + t } ?: t
+ }
+ return Replay(aNegative, b, q, parities)
+ }
+
+ private fun conversationKey(point: PublicKey): ByteArray =
+ Hkdf().extract(point.value.toByteArray().copyOfRange(1, 33), "nip44-v2".encodeToByteArray())
+
+ @Test
+ fun `check 1 - the Shamir evaluation point is the id plus one`() {
+ val (secret, keys) = dealer(1)
+ subsets((0 until 5).toList(), 3).forEach { ids ->
+ val xs = ids.map { it + 1 }
+ val rebuilt = ids.map { id -> keys.secretShares[id] * lagrange(id + 1, xs) }.reduce { a, b -> a + b }
+ assertEquals(keys.thresholdPublicKey, rebuilt.publicKey(), "subset $ids")
+ assertEquals(secret.publicKey(), rebuilt.publicKey())
+ }
+ // The id itself, unshifted, does not reconstruct: the convention is not a no-op.
+ val wrong = listOf(0, 1, 2).map { id -> keys.secretShares[id] * lagrange(id + 1, listOf(1, 2, 3).map { it + 1 }) }
+ .reduce { a, b -> a + b }
+ assertTrue(wrong.publicKey() != keys.thresholdPublicKey)
+ }
+
+ @Test
+ fun `check 2 - replaying the tweaks with their signs reaches the npub, in every parity case`() {
+ val seen = mutableSetOf>()
+ (1..40).forEach { seed ->
+ val (secret, keys) = dealer(seed)
+ val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex())
+ val r = replay(keys.thresholdPublicKey, derived.tweaks)
+ assertEquals(derived.publicKey, r.q.xOnly(), "seed $seed")
+ // And the scalar side: d = a·x + b has the npub as its public key.
+ val d = (if (r.aNegative) -secret else secret) + r.b!!
+ assertEquals(derived.publicKey, d.publicKey().xOnly(), "seed $seed")
+ r.parities.forEachIndexed { step, even -> seen += step to even }
+ }
+ assertEquals(6, seen.size, "every step met both parities somewhere in the seeds: $seen")
+ }
+
+ @Test
+ fun `check 3 - the combined point gives quartz's own conversation key`() {
+ (1..12).forEach { seed ->
+ val (secret, keys) = dealer(seed)
+ val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex())
+ val r = replay(keys.thresholdPublicKey, derived.tweaks)
+ val d = (if (r.aNegative) -secret else secret) + r.b!!
+
+ val other = PrivateKey(Crypto.sha256("peer/$seed".encodeToByteArray()))
+ val p = other.publicKey()
+ val expected = Nip44v2().computeConversationKey(d.value.toByteArray(), p.xOnly().value.toByteArray())
+ // And from the other side, as a sender's app would compute it.
+ val fromPeer = Nip44v2().computeConversationKey(other.value.toByteArray(), derived.publicKey.value.toByteArray())
+ assertEquals(expected.toHex(), fromPeer.toHex())
+
+ subsets((0 until 5).toList(), 3).forEach { ids ->
+ val xs = ids.map { it + 1 }
+ val xP = ids.map { id -> (p * keys.secretShares[id]) * lagrange(id + 1, xs) }.reduce { a, b -> a + b }
+ val dP = (if (r.aNegative) -xP else xP) + p * r.b!!
+ assertEquals(expected.toHex(), conversationKey(dP).toHex(), "seed $seed, subset $ids")
+ // Either lift of P gives the same x-coordinate.
+ val xPNeg = ids.map { id -> ((-p) * keys.secretShares[id]) * lagrange(id + 1, xs) }.reduce { a, b -> a + b }
+ val dPNeg = (if (r.aNegative) -xPNeg else xPNeg) + (-p) * r.b!!
+ assertEquals(expected.toHex(), conversationKey(dPNeg).toHex())
+ }
+ // The sign inside the sum matters: the wrong a gives a different key.
+ val xP = listOf(0, 1, 2).map { id -> (p * keys.secretShares[id]) * lagrange(id + 1, listOf(1, 2, 3)) }.reduce { a, b -> a + b }
+ val wrongSign = (if (r.aNegative) xP else -xP) + p * r.b!!
+ assertFalse(expected.contentEquals(conversationKey(wrongSign)))
+ }
+ }
+
+ @Test
+ fun `check 4 - scalars reduce mod n, the inverse is Fermat's, and the constructor does not range-check`() {
+ val nMinus1 = -one
+ assertEquals(one, nMinus1 * nMinus1)
+ (2..40).forEach { assertEquals(one, scalar(it) * inverse(scalar(it))) }
+ assertEquals(scalar(5), scalar(2) + scalar(3))
+ // A hash at or above n is NOT rejected by the constructor; isValid() is the check D3 needs.
+ val n = PrivateKey(ByteVector32("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"))
+ assertFalse(n.isValid())
+ assertFalse(PrivateKey(ByteVector32("ff".repeat(32))).isValid())
+ }
+
+ @Test
+ fun `check 6 - a batch of partials fits a relay's event when the payload is encrypted once`() {
+ val nip44 = Nip44v2()
+ val key = ByteArray(32) { 7 }
+ // A wrap of a 1,000-character message, as evidence: rumor, seal and wrap layers.
+ val rumor = """{"kind":14,"content":"${"x".repeat(1000)}","tags":[["p","${"a".repeat(64)}"]],"pubkey":"${"b".repeat(64)}","created_at":1700000000,"id":"${"c".repeat(64)}"}"""
+ val seal = """{"kind":13,"content":"${nip44.encrypt(rumor, key).encodePayload()}","tags":[],"pubkey":"${"b".repeat(64)}","created_at":1700000000,"id":"${"c".repeat(64)}","sig":"${"d".repeat(128)}"}"""
+ val wrap = """{"kind":1059,"content":"${nip44.encrypt(seal, key).encodePayload()}","tags":[["p","${"a".repeat(64)}"]],"pubkey":"${"b".repeat(64)}","created_at":1700000000,"id":"${"c".repeat(64)}","sig":"${"d".repeat(128)}"}"""
+ val item = """{"point":"${"02" + "e".repeat(64)}","purpose":"wrap","evidence":$wrap,"partial":"${"02" + "f".repeat(64)}","proof":"${"1".repeat(128)}"}"""
+ val bare = """{"point":"${"02" + "e".repeat(64)}","purpose":"wrap","partial":"${"02" + "f".repeat(64)}","proof":"${"1".repeat(128)}"}"""
+
+ fun sealedPerAdmin(items: List, admins: Int): Int {
+ val payload = """{"v":1,"generation":1,"from":0,"items":[${items.joinToString(",")}]}"""
+ return admins * nip44.encrypt(payload, key).encodePayload().length
+ }
+
+ fun sealedOnce(items: List, admins: Int): Int {
+ val payload = """{"v":1,"generation":1,"from":0,"items":[${items.joinToString(",")}]}"""
+ return nip44.encrypt(payload, key).encodePayload().length + admins * nip44.encrypt("f".repeat(64), key).encodePayload().length
+ }
+
+ println("wrap as evidence: ${wrap.length} bytes")
+ println("20 items with evidence, 7 admins, per admin: ${sealedPerAdmin(List(20) { item }, 7)}")
+ println("20 items with evidence, 7 admins, once: ${sealedOnce(List(20) { item }, 7)}")
+ println("20 bare items, 7 admins, once: ${sealedOnce(List(20) { bare }, 7)}")
+ // The plan as first written -- each payload sealed per admin, the wrap carried as
+ // evidence -- is fourteen times a relay's 64 KB at this size.
+ assertTrue(sealedPerAdmin(List(20) { item }, 7) > 65_536)
+ // Carried once, evidence still outgrows a relay's event: NIP-44 pads to the next
+ // power of two, and one wrap of a long message is most of 64 KB on its own.
+ assertTrue(sealedOnce(List(20) { item }, 7) > 65_536)
+ // So the payload is encrypted once under a key sealed per admin, and a wrap or a seal
+ // travels by reference (every admin's device subscribes to the same wraps, and opens
+ // the same seals). Twenty bare items for seven admins fit in 16 KB.
+ assertTrue(sealedOnce(List(20) { bare }, 7) < 16_384)
+ }
+
+ @Test
+ fun `check 5 - kinds 30400 and 30401 are free here`() {
+ val retired = mobi.giza.compose.nostr.RetiredKinds.WALLET + mobi.giza.compose.nostr.RetiredKinds.GROUP_LIGHTNING
+ assertFalse(30400 in retired)
+ assertFalse(30401 in retired)
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdhJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdhJvmTest.kt
new file mode 100644
index 00000000..35da0671
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdhJvmTest.kt
@@ -0,0 +1,213 @@
+package mobi.giza.compose.cryptography.threshold
+
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+import fr.acinq.bitcoin.crypto.frost.Frost
+import fr.acinq.bitcoin.crypto.frost.KeyMaterial
+import java.io.File
+import kotlin.test.Test
+import kotlin.test.assertContentEquals
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.SharedKeyDerivation
+
+/**
+ * Phase 2 of docs/group-threshold-ecdh.md: the arithmetic, alone, against quartz's NIP-44.
+ *
+ * The expected key is computed the ordinary way, from a whole `d`, which only a test with a
+ * dealer key made for it may build. The code under test never sees `d` or `x`.
+ */
+class ThresholdEcdhJvmTest {
+ private fun dealer(seed: Int, n: Int = 5, t: Int = 3): Pair {
+ val secret = PrivateKey(Crypto.sha256("threshold-ecdh/$seed".encodeToByteArray()))
+ return secret to Frost.trustedDealerKeygen(secret, n, t)
+ }
+
+ /** The npub's secret, built whole -- here and nowhere else. */
+ private fun npubSecret(x: PrivateKey, keys: KeyMaterial): PrivateKey {
+ val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex())
+ // (a, b) recomputed here, independently of NpubTweak, so the two check each other.
+ var q = keys.thresholdPublicKey
+ var a = false
+ var b: PrivateKey? = null
+ derived.tweaks.forEach { s ->
+ val tau = PrivateKey(s)
+ if (q.isOdd()) { q = -q; a = !a; b = b?.let { -it } }
+ q += tau.publicKey(); b = b?.let { it + tau } ?: tau
+ }
+ val d = (if (a) -x else x) + b!!
+ assertEquals(derived.publicKey, d.publicKey().xOnly())
+ return d
+ }
+
+ private fun subsets(ids: List, t: Int): List> =
+ if (t == 0) listOf(emptyList()) else if (ids.size < t) emptyList()
+ else subsets(ids.drop(1), t - 1).map { listOf(ids.first()) + it } + subsets(ids.drop(1), t)
+
+ private fun peer(seed: Int) = PrivateKey(Crypto.sha256("peer/$seed".encodeToByteArray()))
+
+ private fun partials(keys: KeyMaterial, ids: List, p: PublicKey) =
+ ids.associateWith { EcdhPartial.compute(keys.secretShares[it], p) }
+
+ @Test
+ fun `every t-subset of a 3-of-5 key gives quartz's conversation key, and so does a larger one`() {
+ val (x, keys) = dealer(1)
+ val d = npubSecret(x, keys)
+ val tweak = NpubTweak.of(keys.thresholdPublicKey)
+ val other = peer(1)
+ val p = other.publicKey()
+ val expected = Nip44v2().computeConversationKey(d.value.toByteArray(), p.xOnly().value.toByteArray())
+
+ (subsets((0..4).toList(), 3) + subsets((0..4).toList(), 4) + listOf((0..4).toList())).forEach { ids ->
+ val key = ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, ids, p), tweak, p))
+ assertContentEquals(expected, key, "subset $ids")
+ }
+ // The sender's side, as their own app computes it.
+ val npub = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()).publicKey
+ assertContentEquals(expected, Nip44v2().computeConversationKey(other.value.toByteArray(), npub.value.toByteArray()))
+ }
+
+ @Test
+ fun `t minus one partials give a key that does not match`() {
+ val (x, keys) = dealer(2)
+ val d = npubSecret(x, keys)
+ val tweak = NpubTweak.of(keys.thresholdPublicKey)
+ val p = peer(2).publicKey()
+ val expected = Nip44v2().computeConversationKey(d.value.toByteArray(), p.xOnly().value.toByteArray())
+ subsets((0..4).toList(), 2).forEach { ids ->
+ assertFalse(expected.contentEquals(ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, ids, p), tweak, p))))
+ }
+ }
+
+ @Test
+ fun `the tweak replay matches derive in every parity case`() {
+ val seen = mutableSetOf>()
+ (1..40).forEach { seed ->
+ val (x, keys) = dealer(seed)
+ val tweak = NpubTweak.of(keys.thresholdPublicKey)
+ val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex())
+ assertEquals(derived.hex, tweak.npub)
+ npubSecret(x, keys)
+ var q = keys.thresholdPublicKey
+ derived.tweaks.forEachIndexed { step, s ->
+ seen += step to q.isEven()
+ if (q.isOdd()) q = -q
+ q += PrivateKey(s).publicKey()
+ }
+ // And the combined point lands for this seed too.
+ val p = peer(seed).publicKey()
+ val expected = Nip44v2().computeConversationKey(npubSecret(x, keys).value.toByteArray(), p.xOnly().value.toByteArray())
+ assertContentEquals(expected, ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, listOf(0, 2, 4), p), tweak, p)))
+ }
+ assertEquals(6, seen.size, "both parities at every step: $seen")
+ }
+
+ @Test
+ fun `P given as x-only lifts to the same key whichever parity is chosen`() {
+ val (x, keys) = dealer(3)
+ val tweak = NpubTweak.of(keys.thresholdPublicKey)
+ val p = peer(3).publicKey()
+ val lifted = ThresholdEcdh.pointOf(p.xOnly().value.toHex())!!
+ val even = ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, listOf(0, 1, 2), lifted), tweak, lifted))
+ val odd = ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, listOf(0, 1, 2), -lifted), tweak, -lifted))
+ assertContentEquals(even, odd)
+ assertContentEquals(
+ Nip44v2().computeConversationKey(npubSecret(x, keys).value.toByteArray(), p.xOnly().value.toByteArray()),
+ even,
+ )
+ }
+
+ @Test
+ fun `Lagrange coefficients over shifted ids rebuild the dealer's point`() {
+ val (_, keys) = dealer(4)
+ subsets((0..4).toList(), 3).forEach { ids ->
+ val rebuilt = ids.map { Lagrange.coefficient(it, ids).scale(keys.publicShares[it]) }.reduce { a, b -> a + b }
+ assertEquals(keys.thresholdPublicKey, rebuilt)
+ }
+ assertFailsWith { Lagrange.coefficient(5, listOf(0, 1, 2)) }
+ assertFailsWith { Lagrange.coefficient(1, listOf(1, 1, 2)) }
+ }
+
+ @Test
+ fun `an inverse is an inverse`() {
+ (1..64).forEach { assertEquals(Scalars.ONE, Scalars.of(it) * Scalars.inverse(Scalars.of(it))) }
+ val big = PrivateKey(Crypto.sha256("big".encodeToByteArray()))
+ assertEquals(Scalars.ONE, big * Scalars.inverse(big))
+ }
+
+ // --- D3: the proof
+
+ private val aux = ByteArray(32) { 9 }
+
+ private data class Case(val share: PrivateKey, val y: PublicKey, val p: PublicKey, val d: PublicKey, val context: ByteArray)
+
+ private fun case(): Case {
+ val (_, keys) = dealer(5)
+ val p = peer(5).publicKey()
+ val share = keys.secretShares[1]
+ return Case(share, keys.publicShares[1], p, EcdhPartial.compute(share, p), Dleq.context("a".repeat(64), 3, 1))
+ }
+
+ @Test
+ fun `a proof verifies`() {
+ val c = case()
+ val proof = Dleq.prove(c.share, c.y, c.p, c.d, c.context, aux)
+ assertTrue(Dleq.verify(c.y, c.p, c.d, c.context, proof))
+ assertEquals(proof, Dleq.Proof.fromHex(proof.toHex()))
+ // Fresh aux, another proof, still valid.
+ val again = Dleq.prove(c.share, c.y, c.p, c.d, c.context, ByteArray(32) { 1 })
+ assertFalse(again == proof)
+ assertTrue(Dleq.verify(c.y, c.p, c.d, c.context, again))
+ }
+
+ @Test
+ fun `a proof fails for another point, generation, id, partial, public share, or a changed c or z`() {
+ val c = case()
+ val proof = Dleq.prove(c.share, c.y, c.p, c.d, c.context, aux)
+ val otherP = peer(99).publicKey()
+ assertFalse(Dleq.verify(c.y, otherP, c.d, c.context, proof), "another point")
+ assertFalse(Dleq.verify(c.y, c.p, c.d, Dleq.context("a".repeat(64), 4, 1), proof), "another generation")
+ assertFalse(Dleq.verify(c.y, c.p, c.d, Dleq.context("a".repeat(64), 3, 2), proof), "another id")
+ assertFalse(Dleq.verify(c.y, c.p, c.d, Dleq.context("b".repeat(64), 3, 1), proof), "another room")
+ assertFalse(Dleq.verify(c.y, c.p, c.d + c.p, c.context, proof), "another partial")
+ assertFalse(Dleq.verify(c.y + c.p, c.p, c.d, c.context, proof), "another public share")
+ assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, proof.copy(z = proof.c)), "z swapped")
+ assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, Dleq.Proof(proof.z, proof.c)), "c and z swapped")
+ val flipped = proof.c.toByteArray().also { it[31] = (it[31].toInt() xor 1).toByte() }
+ assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, proof.copy(c = ByteVector32(flipped))), "c changed")
+ assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, proof.copy(z = ByteVector32("ff".repeat(32)))), "z out of range")
+ }
+
+ @Test
+ fun `a wrong partial with an honest-looking proof is caught`() {
+ val c = case()
+ // A holder who answers with another scalar cannot prove it against their public share.
+ val forged = EcdhPartial.compute(PrivateKey(Crypto.sha256("forger".encodeToByteArray())), c.p)
+ val proof = Dleq.prove(c.share, c.y, c.p, forged, c.context, aux)
+ assertFalse(Dleq.verify(c.y, c.p, forged, c.context, proof))
+ }
+
+ // --- shared-key-derivation.md's rule, as a test
+
+ @Test
+ fun `nothing in the package can build the group's secret`() {
+ val root = File("src").takeIf { it.resolve("commonMain").isDirectory } ?: File("composeApp/src")
+ val sources = root.resolve("commonMain/kotlin/mobi/giza/compose/cryptography/threshold")
+ .listFiles { f -> f.extension == "kt" }!!.associate { it.name to it.readText() }
+ assertTrue(sources.isNotEmpty())
+ sources.forEach { (name, text) ->
+ // A list of every share is a dealer's, never a device's.
+ assertFalse("secretShares" in text, "$name reads a list of shares")
+ // A Lagrange coefficient leaves the class only through scale(point).
+ if (name != "Lagrange.kt") assertFalse(Regex("""Coefficient\(""").containsMatchIn(text), "$name builds a coefficient")
+ }
+ // The coefficient's scalar is private: scale(point) is its only use.
+ assertTrue("class Coefficient internal constructor(private val scalar: PrivateKey)" in sources.getValue("Lagrange.kt"))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/GroupDmStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/GroupDmStorageJvmTest.kt
new file mode 100644
index 00000000..1f09247b
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/GroupDmStorageJvmTest.kt
@@ -0,0 +1,74 @@
+package mobi.giza.compose.database.dao
+
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.time.Instant
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.model.GroupConversationKey
+import mobi.giza.compose.database.model.GroupDmMessage
+import mobi.giza.compose.database.model.GroupDmWrap
+import mobi.giza.compose.database.model.GroupEcdhPartial
+import mobi.giza.compose.database.model.GroupEcdhRound
+import mobi.giza.compose.managers.SigningProposalHarness
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+
+/**
+ * Phase 4 of docs/group-threshold-ecdh.md: redelivery of a partial, a wrap or a rumor changes
+ * nothing, and wiping a room takes its kept keys and its mail with it.
+ */
+class GroupDmStorageJvmTest {
+ private val harness = SigningProposalHarness()
+
+ @AfterTest
+ fun close() = harness.close()
+
+ private val roundId = "r".repeat(64).replace('r', '1')
+
+ @Test
+ fun `redelivery is a no-op`() = runBlocking {
+ val db = harness.openDevice(harness.members[0])
+ val dao = db.groupDmDao()
+ val round = GroupEcdhRound(id = roundId, chatRoomId = harness.roomId, generation = 0, point = "a".repeat(64), purpose = EcdhPurpose.WRAP, ref = "b".repeat(64))
+ assertEquals(true, dao.insertRound(round) > 0)
+ assertEquals(-1L, dao.insertRound(round.copy(point = "c".repeat(64))), "the same round, not a second")
+ assertEquals("a".repeat(64), dao.getRound(roundId)?.point)
+
+ val partial = GroupEcdhPartial(roundId, 1, harness.members[1], "02" + "d".repeat(64), "e".repeat(128), verified = true)
+ assertEquals(true, dao.insertPartial(partial) > 0)
+ assertEquals(-1L, dao.insertPartial(partial.copy(partial = "03" + "f".repeat(64))))
+ assertEquals(listOf("02" + "d".repeat(64)), dao.getPartials(roundId).map { it.partial })
+
+ val wrap = GroupDmWrap(id = "b".repeat(64), chatRoomId = harness.roomId, wrapJson = "{}", createdAt = Instant.fromEpochSeconds(1))
+ assertEquals(true, dao.insertWrap(wrap) > 0)
+ assertEquals(-1L, dao.insertWrap(wrap))
+
+ val message = GroupDmMessage("9".repeat(64), harness.roomId, "c".repeat(64), "a".repeat(64), "{}", Instant.fromEpochSeconds(2), outgoing = false, wrapId = wrap.id)
+ assertEquals(true, dao.insertMessage(message) > 0)
+ assertEquals(-1L, dao.insertMessage(message.copy(wrapId = "8".repeat(64))), "the same rumor in another wrap")
+ assertEquals(wrap.id, dao.getMessage(message.rumorId)?.wrapId)
+ }
+
+ @Test
+ fun `wiping a room removes its keys, its mail and its rounds`() = runBlocking {
+ val db = harness.openDevice(harness.members[0])
+ val dao = db.groupDmDao()
+ dao.insertRound(GroupEcdhRound(id = roundId, chatRoomId = harness.roomId, generation = 0, point = "a".repeat(64), purpose = EcdhPurpose.SEAL, ref = "b".repeat(64)))
+ dao.insertPartial(GroupEcdhPartial(roundId, 1, harness.members[1], "02" + "d".repeat(64), "e".repeat(128), verified = true))
+ dao.insertConversationKey(GroupConversationKey(harness.roomId, "a".repeat(64), "5".repeat(64), roundId))
+ dao.insertWrap(GroupDmWrap(id = "b".repeat(64), chatRoomId = harness.roomId, wrapJson = "{}", createdAt = Instant.fromEpochSeconds(1)))
+ dao.insertMessage(GroupDmMessage("9".repeat(64), harness.roomId, "c".repeat(64), "a".repeat(64), "{}", Instant.fromEpochSeconds(2), outgoing = false))
+ assertNotNull(dao.getConversationKey(harness.roomId, "a".repeat(64)))
+ assertEquals(false, dao.getConversationKey(harness.roomId, "a".repeat(64)).toString().contains("5555"), "a kept key never prints")
+
+ dao.wipeRoom(harness.roomId)
+
+ assertNull(dao.getConversationKey(harness.roomId, "a".repeat(64)))
+ assertEquals(emptyList(), dao.getMessages(harness.roomId))
+ assertNull(dao.getWrap("b".repeat(64)))
+ assertNull(dao.getRound(roundId))
+ assertEquals(emptyList(), dao.getPartials(roundId))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt
index 6e0815d2..377e386e 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ReadMarkMigrationJvmTest.kt
@@ -23,11 +23,11 @@ import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ChatRoom
/**
- * 46 -> 47: the read marks start where the history ends, so an upgrade does not make every line the
+ * 47 -> 48: the read marks start where the history ends, so an upgrade does not make every line the
* user has ever had unread. docs/notifications-and-background-sync.md, Phase 3.
*
- * Built from the exported v46 schema, as [ShippedProfileUpgradeJvmTest] builds its v36, so the
- * fixture's tables and identity hash are a v46 install's.
+ * Built from the exported v47 schema, as [ShippedProfileUpgradeJvmTest] builds its v36, so the
+ * fixture's tables and identity hash are a v47 install's.
*/
class ReadMarkMigrationJvmTest {
@@ -53,17 +53,17 @@ class ReadMarkMigrationJvmTest {
private val alsoTalkedIn = "b".repeat(64)
private val quiet = "c".repeat(64)
- private fun writeV46() {
+ private fun writeV47() {
BundledSQLiteDriver().open(file.absolutePath).use { connection ->
- entities(46).forEach { entity ->
+ entities(47).forEach { entity ->
val table = entity["tableName"]!!.jsonPrimitive.content
connection.execSQL(entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table))
entity["indices"]?.jsonArray.orEmpty().forEach { index ->
connection.execSQL(index.jsonObject["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table))
}
}
- schema(46)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) }
- connection.execSQL("PRAGMA user_version = 46")
+ schema(47)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) }
+ connection.execSQL("PRAGMA user_version = 47")
insert(connection, "NostrEvent", mapOf("id" to "e".repeat(64), "pubKey" to user))
insert(connection, "Profile", mapOf("publicKey" to user, "nostrEventId" to "e".repeat(64)))
@@ -88,7 +88,7 @@ class ReadMarkMigrationJvmTest {
/** A row with [values], every other NOT NULL column without a default given a placeholder. */
private fun insert(connection: SQLiteConnection, table: String, values: Map) {
- val entity = entities(46).single { it["tableName"]!!.jsonPrimitive.content == table }
+ val entity = entities(47).single { it["tableName"]!!.jsonPrimitive.content == table }
val filled = LinkedHashMap()
entity["fields"]!!.jsonArray.map { it.jsonObject }.forEach { field ->
val column = field["columnName"]!!.jsonPrimitive.content
@@ -121,7 +121,7 @@ class ReadMarkMigrationJvmTest {
@Test
fun `every room an upgraded install has is read up to its newest line`(): Unit = runBlocking {
- writeV46()
+ writeV47()
val database = getRoomDatabase(Room.databaseBuilder(name = file.absolutePath))
try {
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 f69ac3ec..9cee46e4 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
+ * (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
* notifications' read marks and ledger (docs/notifications-and-background-sync.md, Phase 3), so
- * the upgrade crosses eleven generated migrations and the file has to come out at the last.
+ * 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/GroupDmAdminChangeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmAdminChangeJvmTest.kt
new file mode 100644
index 00000000..5f6fd9c3
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmAdminChangeJvmTest.kt
@@ -0,0 +1,156 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PrivateKey
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.KeyShareGeneration
+import mobi.giza.compose.database.model.KeyShareMember
+import mobi.giza.compose.database.model.types.ShareGenerationState
+import mobi.giza.compose.database.model.types.ShareStanding
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.groupdm.AdminSeal
+import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents
+
+/**
+ * Phase 10 of docs/group-threshold-ecdh.md: admin changes need nothing new. A removed admin is
+ * cut off from new mail at once and forgets what it kept; a promoted one reads the history;
+ * and a share rotation leaves every kept key valid, because the group's key never changed (D1).
+ */
+class GroupDmAdminChangeJvmTest {
+ private val net = GroupDmNetwork(n = 4, t = 2)
+ private val a get() = net.devices[0]
+ private val b get() = net.devices[1]
+ private val c get() = net.devices[2]
+ private val d get() = net.devices[3]
+
+ @BeforeTest
+ fun setUp() = runBlocking {
+ ExperimentalFeatures.groupDirectMessagesOverride = true
+ net.admins = net.members.take(3).toSet()
+ net.install()
+ net.all()
+ net.openMessages()
+ }
+
+ @AfterTest
+ fun tearDown() {
+ net.close()
+ ExperimentalFeatures.groupDirectMessagesOverride = null
+ }
+
+ private val sender = KeyPair()
+
+ private suspend fun texts(device: GroupDmNetwork.Device) =
+ device.db.groupDmDao().getMessages(net.roomId).map { Event.fromJson(it.rumorJson).content }.sorted()
+
+ @Test
+ fun `after C's removal a new message opens on A and B, and C gets no slot, opens nothing, and forgets`(): Unit = runBlocking {
+ net.receive(net.wrapFrom(sender, "before"), a, b, c)
+ net.pump()
+ assertEquals(listOf("before"), texts(c))
+ assertNotNull(c.db.groupDmDao().getConversationKey(net.roomId, sender.pubKey.toHexKey()))
+
+ net.admins = setOf(net.members[0], net.members[1])
+ val after = net.wrapFrom(sender, "after")
+ net.receive(after, a, b, c)
+ val sentBefore = net.outbox(a).map { it.id }.toSet()
+ net.pump()
+ assertEquals(listOf("after", "before"), texts(a))
+ assertEquals(listOf("after", "before"), texts(b))
+ net.outbox(a).filter { it.id !in sentBefore && it.kind == GroupEcdhEvents.PARTIALS }.forEach {
+ assertFalse(net.hostKeys[2] in AdminSeal.parseSlots(it.tags).keys, "no slot for C")
+ }
+
+ // C's device sees itself removed on its next sweep, and forgets.
+ GroupEcdhManager.sweep(c.db, c.publicKey, c.privateKey)
+ assertEquals(emptyList(), texts(c))
+ assertEquals(emptyList(), c.db.groupDmDao().getConversationKeys(net.roomId))
+ val line = c.db.chatMessageDao().getChatMessagesByChatRoomId(net.roomId).map { it.chatMessage }
+ .single { it.messageType == ChatMessage.TYPE_GROUP_DM_FORGOTTEN }
+ assertTrue("forgot" in line.content)
+ // Once: a second sweep has nothing to forget.
+ assertFalse(GroupDmReceiver.forgetIfRemoved(c.db, net.roomId, c.publicKey))
+ }
+
+ @Test
+ fun `after a promotion, the new admin's device answers rounds and reads the history`(): Unit = runBlocking {
+ net.receive(net.wrapFrom(sender, "history"), a, b, c, d)
+ net.pump()
+ assertEquals(emptyList(), texts(d))
+
+ net.admins = net.members.toSet()
+ // D's catch-up brings the old wrap; the others answer it although they combined long ago.
+ net.devices.forEach { device -> device.db.groupDmDao().getWrapsInState(net.roomId, "OPENED").firstOrNull()?.let { net.receive(Event.fromJson(it.wrapJson), d) } }
+ net.pump()
+ assertEquals(listOf("history"), texts(d))
+
+ // And D answers a new round as one of the admins, with A's app closed.
+ val fresh = net.wrapFrom(KeyPair(), "new")
+ net.receive(fresh, b, d)
+ net.pump(between = listOf(b, d))
+ assertEquals(listOf("history", "new"), texts(d))
+ assertEquals(listOf("history", "new"), texts(b))
+ }
+
+ @Test
+ fun `a share rotation after the removal leaves every kept key valid on A and B`(): Unit = runBlocking {
+ net.receive(net.wrapFrom(sender, "one"), a, b, c)
+ net.pump()
+ val keyBefore = a.db.groupDmDao().getConversationKey(net.roomId, sender.pubKey.toHexKey())!!.conversationKey
+
+ net.admins = setOf(net.members[0], net.members[1])
+ rotate(without = c)
+ assertEquals(1, a.context()!!.generation)
+
+ // The kept key opens the next message's seal; only the wrap's round runs, at generation 1.
+ net.receive(net.wrapFrom(sender, "two"), a, b)
+ net.pump(between = listOf(a, b))
+ assertEquals(listOf("one", "two"), texts(a))
+ assertEquals(keyBefore, a.db.groupDmDao().getConversationKey(net.roomId, sender.pubKey.toHexKey())!!.conversationKey)
+
+ // A new correspondent's key, made at generation 1, is the one their own app computes.
+ val newcomer = KeyPair()
+ net.receive(net.wrapFrom(newcomer, "hello"), a, b)
+ net.pump(between = listOf(a, b))
+ val kept = a.db.groupDmDao().getConversationKey(net.roomId, newcomer.pubKey.toHexKey())!!.conversationKey
+ assertEquals(Nip44v2().computeConversationKey(newcomer.privKey!!, net.roomId.hexToByteArray()).toHex(), kept)
+ // C, rotated out and no longer an admin, takes no part.
+ assertNull(c.context())
+ }
+
+ /** Generation 1 on the same key, `s'ᵢ = sᵢ + k·(i+1)`, with [without] withheld, as a rotation would leave it. */
+ private suspend fun rotate(without: GroupDmNetwork.Device) {
+ val k = PrivateKey(Crypto.sha256("rotation".encodeToByteArray()))
+ val shares = net.keyMaterial.secretShares.mapIndexed { id, s -> s + k * PrivateKey(ByteArray(32).also { it[31] = (id + 1).toByte() }) }
+ val publicShares = shares.joinToString(",") { it.publicKey().value.toHex() }
+ net.devices.forEach { device ->
+ val withheld = device === without
+ device.db.keyShareDao().upsert(
+ KeyShareGeneration(
+ dkgSessionId = net.ceremonyId, generation = 1,
+ secretShare = if (withheld) null else shares[net.idOf[device.index]].value.toHex(),
+ publicShares = publicShares, state = ShareGenerationState.ACTIVE, activatedAt = Clock.System.now(),
+ )
+ )
+ device.db.keyShareDao().upsert(net.members.indices.map { i ->
+ KeyShareMember(net.ceremonyId, 1, net.idOf[i], net.members[i], net.hostKeys[i], if (net.devices[i] === without) ShareStanding.RETIRED else ShareStanding.LIVE)
+ })
+ }
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt
new file mode 100644
index 00000000..167fb902
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmNetwork.kt
@@ -0,0 +1,184 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+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.time.Instant
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.DkgParticipantMessage
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.GroupDmWrap
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.database.model.Profile
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.model.types.DkgRitualStage
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.dkg.DkgRitualEvents
+import mobi.giza.compose.nostr.frost.FrostSigningEvents
+import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents
+
+/**
+ * A keyed group whose devices are each their own database, for the group's direct messages
+ * (docs/group-threshold-ecdh.md, Phases 5 to 10): every member a real nostr key, so host keys
+ * derive as the app derives them, and nothing passing between devices but the inner events
+ * [pump] ferries. Who a device sees as admins is [admins], through [RoomAdmins.override].
+ *
+ * Modelled on `ShareRefreshRitualJvmTest`'s devices.
+ */
+class GroupDmNetwork(n: Int = 4, val t: Int = 2, secret: String = "6d0000".padEnd(64, '7')) {
+ val keyPairs: List = List(n) { KeyPair() }
+ val members: List = keyPairs.map { it.pubKey.toHexKey() }
+ val hostKeys: List = keyPairs.map { ChillDkgRitualManager.deriveHostPublicKey(it.privKey!!).value.toHex() }
+
+ /** Participant id of member i: its host key's place in the bytewise sort, as a ceremony orders them. */
+ val idOf: List = hostKeys.map { hostKeys.sorted().indexOf(it) }
+
+ val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen(PrivateKey(ByteVector32(secret)), n, t)
+ val thresholdPublicKey: HexKey = keyMaterial.thresholdPublicKey.value.toHex()
+ val roomId: HexKey = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
+ val ceremonyId = "dmceremony".padEnd(64, '0')
+
+ /** Who every device sees as the room's admins. */
+ var admins: Set = members.toSet()
+
+ val devices = mutableListOf()
+
+ inner class Device(val index: Int, val db: GizaDatabase, val room: LocalChatRoom) {
+ val keyPair: KeyPair get() = keyPairs[index]
+ val publicKey: HexKey get() = members[index]
+ val privateKey: ByteArray get() = keyPair.privKey!!
+ val received = mutableSetOf()
+
+ suspend fun context() = GroupEcdhManager.contextFor(db, room, publicKey, privateKey)
+
+ override fun toString(): String = "Device($index)"
+ }
+
+ fun install() {
+ RoomAdmins.override = { id -> if (id == roomId) RoomAdmins(admins, governed = true) else null }
+ }
+
+ fun close() {
+ devices.forEach { it.db.close() }
+ RoomAdmins.override = null
+ }
+
+ suspend fun device(index: Int): Device {
+ val db = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ members.forEach { member ->
+ val nostrEventId = "e$member".take(64)
+ db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
+ db.profileDao().upsert(Profile(publicKey = member, nostrEventId = nostrEventId))
+ }
+ val chatRoom = ChatRoom(id = roomId, userPublicKey = members[index], subject = "#Ekklesia", description = SharedKeyDerivation.describe("Admins."), mlsGroupState = "00")
+ db.chatRoomDao().upsert(chatRoom)
+ db.dkgSessionDao().upsert(
+ DkgSession(
+ id = ceremonyId,
+ chatRoomId = roomId,
+ coordinatorPublicKey = members.first(),
+ userPublicKey = members[index],
+ threshold = t,
+ participantCount = members.size,
+ stage = DkgRitualStage.COMPLETE,
+ hostPublicKey = hostKeys[index],
+ round1Random = "1".repeat(64),
+ round2AuxRandom = "2".repeat(64),
+ thresholdPublicKey = thresholdPublicKey,
+ secretShare = keyMaterial.secretShares[idOf[index]].value.toHex(),
+ publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() },
+ )
+ )
+ members.forEachIndexed { i, member ->
+ db.dkgSessionDao().upsert(DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[i]))
+ }
+ return Device(index, db, LocalChatRoom(chatRoom = chatRoom)).also { devices += it }
+ }
+
+ suspend fun all(): List = members.indices.map { device(it) }
+
+ // ---- the wire ----------------------------------------------------------------------------------------------
+
+ val ferried: List = (GroupEcdhEvents.ALL + FrostSigningEvents.ALL).toList()
+
+ suspend fun outbox(device: Device, kinds: List = ferried): List =
+ device.db.marmotInnerEventDao()
+ .getByChatRoomAndKinds(chatRoomId = roomId, kinds = kinds)
+ .filter { it.publicKey == device.publicKey }
+ .sortedWith(compareBy({ it.createdAt }, { it.kind }))
+
+ /**
+ * Ferries every device's inner events to every other until nothing moves. [hold] keeps a
+ * message from leaving; [between] is who is online.
+ */
+ suspend fun pump(between: List = devices, hold: (from: Device, MarmotInnerEvent) -> Boolean = { _, _ -> false }) {
+ var moved = true
+ while (moved) {
+ moved = false
+ for (from in between) for (to in between) {
+ if (from === to) continue
+ outbox(from).forEach { queued ->
+ if (queued.id in to.received || hold(from, queued)) return@forEach
+ to.received += queued.id
+ moved = true
+ deliver(queued, to)
+ }
+ }
+ }
+ }
+
+ suspend fun deliver(queued: MarmotInnerEvent, to: Device) {
+ to.db.marmotInnerEventDao().upsert(queued.copy(chatRoomId = roomId))
+ val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, "")
+ if (event.kind in GroupEcdhEvents.ALL) {
+ GroupEcdhManager.process(to.db, to.room, event, to.publicKey, to.privateKey)
+ } else {
+ FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey, to.privateKey)
+ }
+ }
+
+ // ---- the outside world -------------------------------------------------------------------------------------
+
+ /** Someone on a stock NIP-17 app, writing to the group's npub. */
+ suspend fun wrapFrom(sender: KeyPair, text: String): GiftWrapEvent {
+ val rumor = Event("", sender.pubKey.toHexKey(), 1_700_000_000, 14, arrayOf(arrayOf("p", roomId)), text, "")
+ val seal = SealEvent.create(rumor, roomId, NostrSignerInternal(sender))
+ return GiftWrapEvent.create(seal, roomId)
+ }
+
+ /**
+ * The group signs where it receives messages, through the real signing session: [proposer]
+ * proposes, [approver] approves, and the network carries the rest. Every device then holds
+ * the signed 10050.
+ */
+ suspend fun openMessages(proposer: Device = devices[0], approver: Device = devices[1], relays: List = listOf("wss://dm.example.com")) {
+ val session = GroupDmRelays.propose(proposer.db, proposer.room, proposer.publicKey, relays)
+ pump()
+ FrostSigningManager.approve(approver.db, approver.room, session.id)
+ pump()
+ check(devices.all { GroupDmRelays.relaysOf(it.db, roomId) != null }) { "the 10050 did not reach every device" }
+ }
+
+ /** [wrap] reaching [to] on the group's subscription. */
+ suspend fun receive(wrap: Event, vararg to: Device) =
+ to.forEach { GroupDmReceiver.receive(it.db, wrap, it.publicKey, it.privateKey) }
+
+ /** The wrap as the group's subscription would put it in [device]'s ledger. */
+ suspend fun ledger(device: Device, wrap: Event) {
+ device.db.groupDmDao().insertWrap(
+ GroupDmWrap(id = wrap.id, chatRoomId = roomId, wrapJson = wrap.toJson(), createdAt = Instant.fromEpochSeconds(wrap.createdAt))
+ )
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmReceiveJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmReceiveJvmTest.kt
new file mode 100644
index 00000000..1b8b375c
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmReceiveJvmTest.kt
@@ -0,0 +1,173 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.Duration.Companion.hours
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.model.GroupDmWrapState
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+
+/**
+ * Phase 7 of docs/group-threshold-ecdh.md: a person on a stock NIP-17 client writes to the
+ * group's npub, and the admins' devices read it, with a share-holder who is not an admin
+ * reading nothing.
+ */
+class GroupDmReceiveJvmTest {
+ private val net = GroupDmNetwork(n = 4, t = 2)
+ private val a get() = net.devices[0]
+ private val b get() = net.devices[1]
+ private val c get() = net.devices[2]
+ private val d get() = net.devices[3]
+
+ @BeforeTest
+ fun setUp() = runBlocking {
+ ExperimentalFeatures.groupDirectMessagesOverride = true
+ net.admins = net.members.take(3).toSet()
+ net.install()
+ net.all()
+ net.openMessages()
+ }
+
+ @AfterTest
+ fun tearDown() {
+ net.close()
+ ExperimentalFeatures.groupDirectMessagesOverride = null
+ GroupDmReceiver.maxNewWrapRoundsPerHour = 60
+ }
+
+ private val sender = KeyPair()
+ private val holdC = { from: GroupDmNetwork.Device, _: MarmotInnerEvent -> from === c }
+
+ private suspend fun texts(device: GroupDmNetwork.Device) =
+ device.db.groupDmDao().getMessages(net.roomId).sortedBy { it.createdAt }.map { Event.fromJson(it.rumorJson).content }
+
+ @Test
+ fun `a message from an outside identity opens on all three admin devices once two have answered`(): Unit = runBlocking {
+ val wrap = net.wrapFrom(sender, "dumela, group")
+ net.receive(wrap, a, b, c, d)
+ net.pump(hold = holdC)
+
+ listOf(a, b, c).forEach { device ->
+ assertEquals(listOf("dumela, group"), texts(device), "$device")
+ val message = device.db.groupDmDao().getMessages(net.roomId).single()
+ assertEquals(sender.pubKey.toHexKey(), message.senderPublicKey)
+ assertFalse(message.outgoing)
+ assertEquals(GroupDmWrapState.OPENED, device.db.groupDmDao().getWrap(wrap.id)?.state)
+ }
+ }
+
+ @Test
+ fun `a share-holder who is not an admin files nothing, and no NostrEvent or gift wrap row is written`(): Unit = runBlocking {
+ val wrap = net.wrapFrom(sender, "for the admins")
+ net.receive(wrap, a, b, c, d)
+ net.pump()
+
+ assertFalse(GroupDmReceiver.readsFor(d.db, net.roomId, d.publicKey))
+ assertEquals(emptyList(), d.db.groupDmDao().getMessages(net.roomId))
+ assertEquals(null, d.db.groupDmDao().getWrap(wrap.id))
+ // On an admin's device, through storeNostrEvent as the old path would see it.
+ val relay = "wss://dm.example.com"
+ val again = net.wrapFrom(sender, "through the old door")
+ a.db.nostrDao().storeNostrEvent(
+ mobi.giza.compose.database.model.NostrEvent(
+ id = again.id, pubKey = again.pubKey, kind = again.kind, tags = again.tags, content = again.content,
+ sig = again.sig, createdAt = kotlin.time.Instant.fromEpochSeconds(again.createdAt),
+ ),
+ relay, listOf(relay), 0, a.keyPair,
+ )
+ assertEquals(null, a.db.nostrEventDao().getNostrEventById(again.id), "no NostrEvent row")
+ assertEquals(emptyList(), a.db.giftWrapMessageDao().getAllGiftWrapMessages(), "no GiftWrapMessage row")
+ assertTrue(a.db.groupDmDao().getWrap(again.id) != null, "the group's ledger has it")
+ }
+
+ @Test
+ fun `a second message from the same sender takes one round`(): Unit = runBlocking {
+ net.receive(net.wrapFrom(sender, "one"), a, b, c)
+ net.pump()
+ val roundsBefore = a.db.groupDmDao().getAllOpenRounds().size to roundsOn(a)
+
+ net.receive(net.wrapFrom(sender, "two"), a, b, c)
+ net.pump()
+ assertEquals(listOf("one", "two"), texts(a).sorted())
+ assertEquals(roundsBefore.second + 1, roundsOn(a), "the wrap's round only; the seal's key was kept")
+ }
+
+ private suspend fun roundsOn(device: GroupDmNetwork.Device): Int =
+ device.db.groupDmDao().countWrapRoundsSince(net.roomId, kotlin.time.Instant.fromEpochSeconds(0)) +
+ listOf(EcdhPurpose.SEAL).sumOf { 0 } +
+ device.db.groupDmDao().getConversationKeys(net.roomId).size
+
+ @Test
+ fun `the same rumor in two wraps is one message`(): Unit = runBlocking {
+ val rumor = Event("", sender.pubKey.toHexKey(), 1_700_000_000, 14, arrayOf(arrayOf("p", net.roomId)), "once", "")
+ val seal = SealEvent.create(rumor, net.roomId, NostrSignerInternal(sender))
+ net.receive(GiftWrapEvent.create(seal, net.roomId), a, b, c)
+ net.receive(GiftWrapEvent.create(seal, net.roomId), a, b, c)
+ net.pump()
+ listOf(a, b, c).forEach { assertEquals(listOf("once"), texts(it)) }
+ }
+
+ @Test
+ fun `a promoted admin's device opens a wrap from before the promotion`(): Unit = runBlocking {
+ net.admins = setOf(net.members[0], net.members[1])
+ val wrap = net.wrapFrom(sender, "before you were an admin")
+ net.receive(wrap, a, b, c)
+ net.pump()
+ assertEquals(emptyList(), texts(c), "not an admin yet")
+
+ net.admins = net.members.take(3).toSet()
+ net.receive(wrap, c)
+ net.pump()
+ assertEquals(listOf("before you were an admin"), texts(c))
+ }
+
+ @Test
+ fun `the rate cap queues rather than drops`(): Unit = runBlocking {
+ GroupDmReceiver.maxNewWrapRoundsPerHour = 2
+ val wraps = (1..3).map { net.wrapFrom(KeyPair(), "message $it") }
+ wraps.forEach { net.receive(it, a) }
+ val dao = a.db.groupDmDao()
+ assertEquals(1, dao.getWrapsInState(net.roomId, GroupDmWrapState.QUEUED.name).size, "one waits")
+ assertEquals(2, dao.countWrapRoundsSince(net.roomId, Clock.System.now() - 1.hours))
+
+ // An hour on: the queued one opens.
+ dao.getAllOpenRounds().forEach { dao.upsertRound(it.copy(openedAt = Clock.System.now() - 2.hours)) }
+ GroupEcdhManager.advance(a.db, a.context()!!)
+ assertEquals(emptyList(), dao.getWrapsInState(net.roomId, GroupDmWrapState.QUEUED.name))
+ net.receive(wraps[0], b); net.receive(wraps[1], b); net.receive(wraps[2], b)
+ GroupDmReceiver.maxNewWrapRoundsPerHour = 60
+ net.pump(between = listOf(a, b))
+ assertEquals(listOf("message 1", "message 2", "message 3"), texts(a).sorted())
+ }
+
+ @Test
+ fun `live-group-dm asks each relay for the groups that list it, two days before the newest wrap`() {
+ val dm = mobi.giza.compose.nostr.Relays.DefaultDMRelayList.first().url
+ val filters = LiveSubscriptionManager.groupDmFilters(
+ listOf(
+ GroupDmInbox("a".repeat(64), listOf("wss://one.example/"), newestWrapAt = 1_700_000_000),
+ GroupDmInbox("b".repeat(64), listOf("wss://two.example/"), newestWrapAt = null),
+ )
+ )
+ val one = filters.getValue("wss://one.example/").single()
+ assertEquals(listOf(GiftWrapEvent.KIND), one.kinds)
+ assertEquals(listOf("a".repeat(64)), one.tags?.get("p"))
+ assertEquals(1_700_000_000L - 2 * 24 * 60 * 60, one.since)
+ assertEquals(null, filters.getValue("wss://two.example/").single().since, "a room with nothing yet asks from the start")
+ assertEquals(listOf("a".repeat(64), "b".repeat(64)), filters.getValue(dm).single().tags?.get("p"), "the app's own DM relays carry every room")
+ assertEquals(emptyMap(), LiveSubscriptionManager.groupDmFilters(emptyList()))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt
new file mode 100644
index 00000000..d88a2fa0
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmRelaysJvmTest.kt
@@ -0,0 +1,122 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.crypto.verify
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.types.FrostSigningStage
+import mobi.giza.compose.nostr.frost.FrostSigningEvents
+import mobi.giza.compose.text.ProposedEvent
+
+/**
+ * Phase 6 of docs/group-threshold-ecdh.md: the group's decision to receive direct messages, a
+ * kind 10050 it signs, published unchanged by the proposer's device, and refused when it lists
+ * a relay nobody can reach.
+ */
+class GroupDmRelaysJvmTest {
+ private val net = GroupDmNetwork(n = 3, t = 2)
+
+ @AfterTest
+ fun tearDown() = net.close()
+
+ private suspend fun signRelays(relays: List): String {
+ val a = net.devices[0]
+ val b = net.devices[1]
+ val session = GroupDmRelays.propose(a.db, a.room, a.publicKey, relays)
+ net.pump()
+ FrostSigningManager.approve(b.db, b.room, session.id)
+ net.pump()
+ assertEquals(FrostSigningStage.COMPLETE, a.db.frostSigningSessionDao().getSessionById(session.id)?.stage)
+ return session.id
+ }
+
+ @Test
+ fun `a signed 10050 is owed to relays by its proposer alone, unchanged, and writes no NostrEvent row`(): Unit = runBlocking {
+ net.install()
+ net.all()
+ val a = net.devices[0]
+ val sessionId = signRelays(listOf("wss://dm.example.com/", "wss://inbox.example.org"))
+
+ // One publisher for every group-signed 10050, whichever feature proposed it: the group
+ // inbox's (docs/group-inbox.md, D7).
+ val owed = a.db.groupInboxDao().getPublicationsFor(sessionId).single()
+ val signed = Event.fromJson(owed.eventJson)
+ assertEquals(GroupDmRelays.KIND, signed.kind)
+ assertEquals(net.roomId, signed.pubKey)
+ assertTrue(signed.verify(), "the group's own signature")
+ assertEquals(listOf("wss://dm.example.com/", "wss://inbox.example.org/"), GroupDmRelays.relaysIn(signed.tags))
+ assertTrue("wss://dm.example.com/" in owed.relays && "wss://inbox.example.org/" in owed.relays)
+ assertEquals(emptyList(), net.devices[1].db.groupInboxDao().getPublicationsFor(sessionId), "only the proposer owes it")
+
+ net.devices.forEach { device ->
+ assertNull(device.db.nostrEventDao().getNostrEventById(signed.id), "no NostrEvent row on $device")
+ assertEquals(listOf("wss://dm.example.com/", "wss://inbox.example.org/"), GroupDmRelays.relaysOf(device.db, net.roomId))
+ }
+ }
+
+ @Test
+ fun `the transcript says where the group's mail arrives, each time it is signed`(): Unit = runBlocking {
+ net.install()
+ net.all()
+ signRelays(listOf("wss://dm.example.com"))
+ Thread.sleep(1100) // a second 10050 needs a later created_at to be the newer list
+ signRelays(listOf("wss://other.example.com"))
+
+ net.devices.forEach { device ->
+ val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(net.roomId)
+ .map { it.chatMessage }
+ .filter { it.messageType == ChatMessage.TYPE_INBOX_RELAYS_ANNOUNCED }
+ assertEquals(2, lines.size, "$device")
+ assertEquals(listOf("wss://other.example.com/"), GroupDmRelays.relaysOf(device.db, net.roomId))
+ }
+ }
+
+ // --- the refusal, on the proposal harness
+
+ private val harness = SigningProposalHarness()
+
+ @AfterTest
+ fun closeHarness() {
+ RoomAdmins.override = null
+ harness.close()
+ }
+
+ private fun proposeRelayList(relays: List) = runBlocking {
+ harness.propose(harness.members[0]) { db, room ->
+ FrostSigningManager.proposeSigning(db, room, harness.members[0], kind = GroupDmRelays.KIND, tags = relays.map { arrayOf("relay", it) }.toTypedArray(), content = "")
+ }
+ }
+
+ @Test
+ fun `a 10050 listing a relay that is not public wss is declined with its reason`(): Unit = runBlocking {
+ val sent = proposeRelayList(listOf("wss://fine.example.com", "ws://plain.example.com"))
+ harness.deliver(sent, harness.members[1])
+ val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id))
+ assertNotNull(session.signDeclinedAt)
+ // The group inbox's refusal, which reads every 10050 the group is asked to sign.
+ assertEquals(listOf(InboxRefusal.RELAYS_SHAPE), harness.queued(FrostSigningEvents.DECLINE).map { it.content })
+
+ val localhost = proposeRelayList(listOf("wss://localhost:7777"))
+ harness.deliver(localhost, harness.members[1])
+ assertEquals(listOf(InboxRefusal.RELAYS_SHAPE), harness.queued(FrostSigningEvents.DECLINE).map { it.content })
+ }
+
+ @Test
+ fun `a 10050 of public relays is put to the member, named for what it is`(): Unit = runBlocking {
+ val sent = proposeRelayList(listOf("wss://fine.example.com"))
+ harness.deliver(sent, harness.members[1])
+ val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id))
+ assertNull(session.signDeclinedAt)
+ val items = harness.db.frostSigningSessionDao().getItems(session.id)
+ assertTrue(FrostSigningManager.isAwaitingApproval(session, items))
+ val summary = ProposedEvent.summarize(Event.fromJson(items.single().unsignedEventJson))
+ assertEquals("Where the group receives private messages", summary.label)
+ assertEquals("fine.example.com", summary.detail)
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt
new file mode 100644
index 00000000..ab7f0ffc
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt
@@ -0,0 +1,97 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.database.repository.DatabaseChatRepository
+import mobi.giza.compose.database.repository.DatabaseGroupDmRepository
+import mobi.giza.compose.ui.view.state.GroupDmPending
+import mobi.giza.compose.ui.view.state.GroupDmRow
+
+/**
+ * Phase 8 of docs/group-threshold-ecdh.md, read through the repositories the screens read: who
+ * sees which row on the group's screen, what the list says before anybody has written, and
+ * what a message still being opened waits on, by name.
+ */
+class GroupDmScreenJvmTest {
+ private val net = GroupDmNetwork(n = 4, t = 2)
+ private val a get() = net.devices[0]
+ private val b get() = net.devices[1]
+ private val d get() = net.devices[3]
+
+ @BeforeTest
+ fun setUp() = runBlocking {
+ ExperimentalFeatures.groupDirectMessagesOverride = true
+ net.admins = net.members.take(3).toSet()
+ net.install()
+ net.all()
+ Unit
+ }
+
+ @AfterTest
+ fun tearDown() {
+ net.close()
+ ExperimentalFeatures.groupDirectMessagesOverride = null
+ }
+
+ private fun chat(device: GroupDmNetwork.Device) = DatabaseChatRepository(device.db, CoroutineScope(Dispatchers.IO))
+
+ @Test
+ fun `the rows by role, before and after the group opens its messages`(): Unit = runBlocking {
+ assertEquals(GroupDmRow.OpenMessages, chat(a).groupDmRow(net.roomId, a.publicKey), "an admin is offered to open them")
+ assertNull(chat(d).groupDmRow(net.roomId, d.publicKey), "a member who is not an admin sees nothing yet")
+
+ net.openMessages()
+ assertEquals(GroupDmRow.Messages(unread = 0), chat(a).groupDmRow(net.roomId, a.publicKey))
+ assertEquals(GroupDmRow.ReceivesMessages, chat(d).groupDmRow(net.roomId, d.publicKey), "the 10050 is public, and only that")
+
+ ExperimentalFeatures.groupDirectMessagesOverride = false
+ assertNull(chat(a).groupDmRow(net.roomId, a.publicKey), "off, the feature shows nothing")
+ }
+
+ @Test
+ fun `nobody has written yet, and then one message waits on one more admin, by name`(): Unit = runBlocking {
+ net.openMessages()
+ val repository = DatabaseGroupDmRepository(a.db)
+ assertEquals(emptyList(), repository.observeConversations(net.roomId).first())
+ assertEquals(GroupDmPending(), repository.observePending(net.roomId).first())
+
+ // Only A's app is open: A answers, and the message waits on one more.
+ val wrap = net.wrapFrom(KeyPair(), "dumela")
+ net.receive(wrap, a)
+ val pending = repository.observePending(net.roomId).first()
+ assertEquals(1, pending.waiting)
+ assertEquals(1, pending.moreAdminsNeeded)
+ assertEquals(listOf(b.publicKey, net.devices[2].publicKey).sorted().map { it.take(8) }, pending.notYetAnsweredBy.sorted())
+
+ // B opens the app: the message opens, and is unread.
+ net.receive(wrap, b)
+ net.pump(between = listOf(a, b))
+ assertEquals(GroupDmPending(), repository.observePending(net.roomId).first())
+ val conversation = repository.observeConversations(net.roomId).first().single()
+ assertEquals("dumela", conversation.lastLine)
+ assertEquals(1, conversation.unread)
+ assertEquals(GroupDmRow.Messages(unread = 1), chat(a).groupDmRow(net.roomId, a.publicKey))
+
+ repository.markRead(net.roomId, conversation.conversationId)
+ assertEquals(0, repository.observeConversations(net.roomId).first().single().unread)
+ val lines = repository.observeConversation(net.roomId, conversation.conversationId).first()
+ assertEquals(listOf("dumela"), lines.map { it.text })
+ }
+
+ @Test
+ fun `a member who is not an admin reads no conversation`(): Unit = runBlocking {
+ net.openMessages()
+ assertEquals(false, DatabaseGroupDmRepository(d.db).isCurrentAdmin(net.roomId, d.publicKey))
+ assertEquals(true, DatabaseGroupDmRepository(a.db).isCurrentAdmin(net.roomId, a.publicKey))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmSendJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmSendJvmTest.kt
new file mode 100644
index 00000000..5c6bcdcf
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmSendJvmTest.kt
@@ -0,0 +1,275 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.Instant
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.database.model.types.FrostSigningStage
+import mobi.giza.compose.database.repository.DatabaseGroupDmRepository
+import mobi.giza.compose.network.dto.RelayDTO
+import mobi.giza.compose.network.relays.EventPublishTransport
+import mobi.giza.compose.network.relays.NostrPublishResult
+import mobi.giza.compose.network.sockets.NostrIncomingMessage
+import mobi.giza.compose.nostr.frost.FrostSigningEvents
+import mobi.giza.compose.nostr.groupdm.AdminSeal
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+import mobi.giza.compose.nostr.groupdm.GroupDmManifest
+import mobi.giza.compose.nostr.groupdm.GroupDmSeal
+import mobi.giza.compose.text.ProposedEvent
+import mobi.giza.compose.ui.view.state.GroupDmOutgoingState
+
+/**
+ * Phase 9 of docs/group-threshold-ecdh.md: the group writing to someone. A proposed by A and
+ * signed by B reaches the recipient as stock NIP-17, every admin sees it as outgoing, and every
+ * way a proposal could say something other than what the signers read is declined.
+ */
+class GroupDmSendJvmTest {
+ private val net = GroupDmNetwork(n = 4, t = 2)
+ private val a get() = net.devices[0]
+ private val b get() = net.devices[1]
+ private val c get() = net.devices[2]
+ private val d get() = net.devices[3]
+
+ private val recipient = KeyPair()
+ private val other = KeyPair()
+ private val r get() = recipient.pubKey.toHexKey()
+ private val r2 get() = other.pubKey.toHexKey()
+
+ @BeforeTest
+ fun setUp() = runBlocking {
+ ExperimentalFeatures.groupDirectMessagesOverride = true
+ net.admins = net.members.take(3).toSet()
+ net.install()
+ net.all()
+ net.openMessages()
+ // What every admin's device holds of the people it writes to: their profile, and R's 10050.
+ listOf(recipient, other).forEach { person ->
+ val profile = NostrSignerSync(person).sign(1_700_000_000, 0, emptyArray(), """{"name":"someone"}""")
+ net.devices.forEach { it.db.nostrEventDao().upsert(rowOf(profile)) }
+ }
+ val inbox = NostrSignerSync(recipient).sign(1_700_000_000, 10050, arrayOf(arrayOf("relay", "wss://r.example")), "")
+ net.devices.forEach { it.db.nostrEventDao().upsert(rowOf(inbox)) }
+ }
+
+ @AfterTest
+ fun tearDown() {
+ net.close()
+ ExperimentalFeatures.groupDirectMessagesOverride = null
+ }
+
+ private fun rowOf(e: Event) = NostrEvent(id = e.id, pubKey = e.pubKey, kind = e.kind, tags = e.tags, content = e.content, sig = e.sig, createdAt = Instant.fromEpochSeconds(e.createdAt))
+
+ private suspend fun send(to: List, text: String) = GroupDmSender.send(a.db, a.room, a.publicKey, a.privateKey, to, text)
+
+ /** Sends, letting the admins compute any key it waits on first. */
+ private suspend fun sendWhenReady(to: List, text: String): String {
+ var outcome = send(to, text)
+ if (outcome is GroupDmSender.Outcome.Preparing) {
+ net.pump()
+ outcome = send(to, text)
+ }
+ return assertIs(outcome).sessionId
+ }
+
+ private class Transport : EventPublishTransport {
+ val sent = mutableListOf>>()
+ override suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow {
+ sent += nostrEvent to relays.map { it.url }.toSet()
+ return flowOf(*relays.map { NostrPublishResult(result = NostrIncomingMessage.OkMessage(eventId = nostrEvent.id, success = true), relayUrl = it.url) }.toTypedArray())
+ }
+ }
+
+ @Test
+ fun `a message proposed by A and signed by B reaches the recipient as stock NIP-17`(): Unit = runBlocking {
+ assertIs(send(listOf(r), "hello from the group"), "the admins compute R's key first")
+ net.pump()
+ val sessionId = sendWhenReady(listOf(r), "hello from the group")
+ net.pump()
+ FrostSigningManager.approve(b.db, b.room, sessionId)
+ net.pump()
+ assertEquals(FrostSigningStage.COMPLETE, a.db.frostSigningSessionDao().getSessionById(sessionId)?.stage)
+
+ // The proposer wrapped it, ordinary NIP-59, and owes it to R's relays.
+ val owed = a.db.groupDmDao().getOutbound(sessionId).single()
+ val wrap = Event.fromJson(assertNotNull(owed.wrapJson)) as GiftWrapEvent
+ val opened = assertNotNull(wrap.unwrapAndUnsealOrNull(NostrSignerInternal(recipient)), "a stock client opens it")
+ assertEquals("hello from the group", opened.content)
+ assertEquals(net.roomId, opened.pubKey)
+
+ val transport = Transport()
+ assertTrue(GroupDmPublisher(DatabaseGroupDmRepository(a.db), transport).publish(owed))
+ assertTrue("wss://r.example/" in transport.sent.single().second)
+
+ // C did not sign, and sees it as outgoing.
+ val onC = assertNotNull(c.db.groupDmDao().getMessageBySigningSession(sessionId))
+ assertTrue(onC.outgoing)
+ assertEquals("hello from the group", Event.fromJson(onC.rumorJson).content)
+ val lineOnA = DatabaseGroupDmRepository(a.db).observeConversation(net.roomId, onC.conversationId).first().single()
+ assertEquals(GroupDmOutgoingState.SENT, lineOnA.outgoingState)
+
+ // A recipient written to before needs no round: the next message is proposed at once.
+ val roundsBefore = a.db.groupDmDao().getAllOpenRounds().size
+ assertIs(send(listOf(r), "and again"))
+ assertEquals(roundsBefore, a.db.groupDmDao().getAllOpenRounds().size)
+
+ // R can answer: the reply opens on the admins' devices like any message to the group.
+ val reply = GiftWrapEvent.create(
+ com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.create(
+ Event("", r, 1_700_000_100, 14, arrayOf(arrayOf("p", net.roomId)), "thanks", ""), net.roomId, NostrSignerInternal(recipient)
+ ),
+ net.roomId,
+ )
+ net.receive(reply, a, b)
+ net.pump(between = listOf(a, b))
+ assertTrue(a.db.groupDmDao().getMessages(net.roomId).any { Event.fromJson(it.rumorJson).content == "thanks" })
+ }
+
+ @Test
+ fun `send again wraps from any signer's device`(): Unit = runBlocking {
+ send(listOf(r), "x"); net.pump()
+ val sessionId = sendWhenReady(listOf(r), "x")
+ net.pump()
+ FrostSigningManager.approve(b.db, b.room, sessionId)
+ net.pump()
+ val onB = b.db.groupDmDao().getOutbound(sessionId).single()
+ assertNull(onB.wrapJson, "only the proposer wraps on its own")
+ assertTrue(GroupDmSender.sendAgain(b.db, sessionId))
+ val wrap = Event.fromJson(assertNotNull(b.db.groupDmDao().getOutbound(sessionId).single().wrapJson)) as GiftWrapEvent
+ assertEquals("x", wrap.unwrapAndUnsealOrNull(NostrSignerInternal(recipient))?.content)
+ }
+
+ // --- every refusal on its own
+
+ /** The keys for R and R2, computed honestly first, so a dishonest seal is the only thing wrong. */
+ private suspend fun keysReady() {
+ send(listOf(r, r2), "warm up"); net.pump()
+ listOf(a, b).forEach { device ->
+ assertNotNull(device.db.groupDmDao().getConversationKey(net.roomId, r))
+ assertNotNull(device.db.groupDmDao().getConversationKey(net.roomId, r2))
+ }
+ }
+
+ private suspend fun keyOf(recipient: HexKey) = a.db.groupDmDao().getConversationKey(net.roomId, recipient)!!.conversationKey.hexToByteArray()
+
+ private suspend fun evidenceOf(person: KeyPair): Event = NostrSignerSync(person).sign(1_700_000_000, 0, emptyArray(), "{}")
+
+ private val now get() = Clock.System.now().epochSeconds
+
+ private fun rumorTo(vararg to: HexKey, text: String = "the words") =
+ GroupDmSeal.rumor(net.roomId, now, 14, to.map { arrayOf("p", it) }.toTypedArray(), text)
+
+ /** A proposal from A, built by hand, sealed to the other admins as A's device would. */
+ private suspend fun proposeRaw(seals: List>, manifest: GroupDmManifest, slotsFor: List = listOf(b, c)): String {
+ val sealed = AdminSeal.seal(manifest.encode(), ChillDkgRitualManager.deriveHostSecretKey(a.privateKey), slotsFor.map { net.hostKeys[it.index] })
+ return FrostSigningManager.proposeSigningBatch(a.db, a.room, a.publicKey, seals, proposalTags = manifest.toTags(sealed)).id
+ }
+
+ private suspend fun assertDeclinedBy(device: GroupDmNetwork.Device, sessionId: String, reason: String = GroupDmRefusal.REASON) {
+ net.pump(between = listOf(a, device))
+ val session = assertNotNull(device.db.frostSigningSessionDao().getSessionById(sessionId), "filed on $device")
+ assertNotNull(session.signDeclinedAt, "declined on $device")
+ assertNull(device.db.groupDmDao().getMessageBySigningSession(sessionId), "and not filed as the group's")
+ val declines = a.db.frostSigningSessionDao().getMessagesByKind(sessionId, FrostSigningEvents.DECLINE)
+ assertTrue(declines.any { it.signerPublicKey == device.publicKey }, "the proposer's device shows the decline")
+ val sent = net.outbox(device, listOf(FrostSigningEvents.DECLINE)).map { it.content }
+ assertTrue(reason in sent, "said with its reason: $sent")
+ }
+
+ private fun manifestOf(vararg people: Pair) = GroupDmManifest(people.map { GroupDmManifest.Seal(it.first, it.second) }, null)
+
+ @Test
+ fun `seals that say different things to different people are declined`(): Unit = runBlocking {
+ keysReady()
+ val one = rumorTo(r, r2, text = "the truth")
+ val two = rumorTo(r, r2, text = "something else")
+ val id = proposeRaw(
+ listOf(GroupDmSeal.build(one, keyOf(r), now - 60), GroupDmSeal.build(two, keyOf(r2), now - 60)),
+ manifestOf(r to evidenceOf(recipient), r2 to evidenceOf(other)),
+ )
+ assertDeclinedBy(b, id)
+ }
+
+ @Test
+ fun `a seal to the wrong key is declined`(): Unit = runBlocking {
+ keysReady()
+ val rumor = rumorTo(r)
+ val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r2), now - 60)), manifestOf(r to evidenceOf(recipient)))
+ assertDeclinedBy(b, id)
+ }
+
+ @Test
+ fun `a message naming a recipient the manifest does not is declined`(): Unit = runBlocking {
+ keysReady()
+ val rumor = rumorTo(r, r2)
+ val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient)))
+ assertDeclinedBy(b, id)
+ }
+
+ @Test
+ fun `forged evidence is declined`(): Unit = runBlocking {
+ keysReady()
+ val rumor = rumorTo(r)
+ val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r), now - 60)), manifestOf(r to evidenceOf(KeyPair())))
+ assertDeclinedBy(b, id)
+ }
+
+ @Test
+ fun `a blank message is declined`(): Unit = runBlocking {
+ keysReady()
+ val rumor = rumorTo(r, text = " ")
+ val id = proposeRaw(listOf(GroupDmSeal.build(rumor, keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient)))
+ assertDeclinedBy(b, id)
+ }
+
+ @Test
+ fun `a seal with tags is declined`(): Unit = runBlocking {
+ keysReady()
+ val honest = GroupDmSeal.build(rumorTo(r), keyOf(r), now - 60)
+ val tagged = EventTemplate(honest.createdAt, honest.kind, arrayOf(arrayOf("expiration", "${now + 99}")), honest.content)
+ val id = proposeRaw(listOf(tagged), manifestOf(r to evidenceOf(recipient)))
+ assertDeclinedBy(b, id)
+ }
+
+ @Test
+ fun `a signer outside the current admins declines, and reads it only as a private message from the group`(): Unit = runBlocking {
+ keysReady()
+ val id = proposeRaw(listOf(GroupDmSeal.build(rumorTo(r), keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient)))
+ assertDeclinedBy(d, id, GroupDmRefusal.CANNOT_READ)
+ val item = d.db.frostSigningSessionDao().getItems(id).single()
+ assertEquals("A private message from the group", ProposedEvent.summarize(Event.fromJson(item.unsignedEventJson)).label)
+ assertEquals(emptyList(), d.db.groupDmDao().getMessages(net.roomId), "and learns nothing more")
+ }
+
+ @Test
+ fun `an honest message is put to the signer, who sees its words`(): Unit = runBlocking {
+ keysReady()
+ val id = proposeRaw(listOf(GroupDmSeal.build(rumorTo(r, text = "fine"), keyOf(r), now - 60)), manifestOf(r to evidenceOf(recipient)))
+ net.pump(between = listOf(a, b))
+ val session = assertNotNull(b.db.frostSigningSessionDao().getSessionById(id))
+ assertNull(session.signDeclinedAt)
+ assertTrue(FrostSigningManager.isAwaitingApproval(session, b.db.frostSigningSessionDao().getItems(id)))
+ assertEquals("fine", Event.fromJson(assertNotNull(b.db.groupDmDao().getMessageBySigningSession(id)).rumorJson).content)
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt
new file mode 100644
index 00000000..cde78c28
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmTodayJvmTest.kt
@@ -0,0 +1,125 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import java.io.File
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Instant
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.nostr.frost.FrostSigningEvents
+import mobi.giza.compose.text.ProposedEvent
+
+/**
+ * What Giza does today with a group's direct messages, pinned before docs/group-threshold-ecdh.md
+ * changes it (Phase 1). Each test here is meant to be flipped, on purpose, by the phase named
+ * beside it.
+ */
+class GroupDmTodayJvmTest {
+ private val harness = SigningProposalHarness()
+ private val alice = harness.members[0]
+ private val bob = harness.members[1]
+
+ @BeforeTest
+ fun seeAdmins() {
+ RoomAdmins.override = { id -> if (id == harness.roomId) RoomAdmins(harness.members.toSet(), governed = false) else null }
+ }
+
+ @AfterTest
+ fun close() {
+ RoomAdmins.override = null
+ harness.close()
+ }
+
+ private val relay = "wss://relay.example"
+
+ /** A person on any NIP-17 app, writing to the group's npub. */
+ private fun wrapToGroup(): NostrEvent {
+ val sender = NostrSignerSync(KeyPair())
+ val seal = sender.signNormal(
+ createdAt = 1_700_000_000,
+ kind = SealEvent.KIND,
+ tags = emptyArray(),
+ content = sender.nip44Encrypt("""{"kind":14,"content":"dumela"}""", harness.roomId),
+ )
+ val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = harness.roomId, createdAt = 1_700_000_100)
+ return NostrEvent(
+ id = wrap.id, pubKey = wrap.pubKey, kind = wrap.kind, tags = wrap.tags,
+ content = wrap.content, sig = wrap.sig, createdAt = Instant.fromEpochSeconds(wrap.createdAt),
+ )
+ }
+
+ /** Phase 7 flips this: the group's subscription hands such a wrap to its own pipeline. */
+ @Test
+ fun `a wrap to the group's npub is stored and never opened`() = runBlocking {
+ val db = harness.openDevice(alice)
+ val wrap = wrapToGroup()
+ db.nostrDao().storeNostrEvent(wrap, relay, listOf(relay), 0, KeyPair())
+
+ assertNotNull(db.nostrEventDao().getNostrEventById(wrap.id))
+ assertEquals(listOf(wrap.id), db.giftWrapMessageDao().getAllGiftWrapMessages().map { it.id })
+ assertEquals(emptyList(), db.giftWrapSealDao().getAllGiftWrapSeals(), "nothing on the device can open it")
+ }
+
+ private fun proposeKind(kind: Int, content: String, tags: Array> = emptyArray()) = runBlocking {
+ harness.propose(alice) { db, room ->
+ FrostSigningManager.proposeSigning(db, room, alice, kind = kind, tags = tags, content = content)
+ }
+ }
+
+ private fun assertAskedBlind(sent: SigningProposalHarness.Sent, kind: Int) = runBlocking {
+ harness.deliver(sent, bob)
+ val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id))
+ assertNull(session.signDeclinedAt, "not declined")
+ val items = harness.db.frostSigningSessionDao().getItems(session.id)
+ assertTrue(FrostSigningManager.isAwaitingApproval(session, items), "put to the member")
+ assertEquals(emptyList(), harness.queued(FrostSigningEvents.DECLINE))
+ val event = Event.fromJson(items.single().unsignedEventJson)
+ assertEquals("Event of kind $kind", ProposedEvent.summarize(event).label)
+ }
+
+ /** Flipped by Phase 9: a seal no signer can read is declined out loud (D13, GroupDmSendJvmTest). */
+ @Test
+ fun `a peer's kind 13 is no longer signed blind`() = runBlocking {
+ val sent = proposeKind(SealEvent.KIND, "AqH1ciphertext")
+ harness.deliver(sent, bob)
+ val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id))
+ assertNotNull(session.signDeclinedAt)
+ val reason = harness.queued(FrostSigningEvents.DECLINE).single().content
+ assertTrue(
+ reason in setOf(
+ mobi.giza.compose.managers.GroupDmRefusal.REASON,
+ mobi.giza.compose.managers.GroupDmRefusal.CANNOT_READ,
+ mobi.giza.compose.managers.GroupDmRefusal.FEATURE_OFF,
+ ),
+ reason,
+ )
+ }
+
+ /** Flipped by Phase 6: a 10050 is named for what it is, and declined unless its relays are public (GroupDmRelaysJvmTest). */
+ @Test
+ fun `a peer's kind 10050 is no longer asked as a raw kind`() = runBlocking {
+ val sent = proposeKind(10050, "", arrayOf(arrayOf("relay", "wss://relay.example")))
+ harness.deliver(sent, bob)
+ val items = harness.db.frostSigningSessionDao().getItems(sent.session.id)
+ assertEquals("Where the group receives private messages", ProposedEvent.summarize(Event.fromJson(items.single().unsignedEventJson)).label)
+ }
+
+ /** Flipped by Phase 7: the group's mail has its own subscription. */
+ @Test
+ fun `there is a subscription for a group's mail`() {
+ assertEquals("live-group-dm", LiveSubscriptionManager.GROUP_DM_SUB_ID)
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupEcdhRoundJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupEcdhRoundJvmTest.kt
new file mode 100644
index 00000000..42dded68
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupEcdhRoundJvmTest.kt
@@ -0,0 +1,244 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PrivateKey
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.Instant
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.cryptography.threshold.Dleq
+import mobi.giza.compose.cryptography.threshold.EcdhPartial
+import mobi.giza.compose.cryptography.threshold.ThresholdEcdh
+import mobi.giza.compose.database.model.GroupEcdhRoundState
+import mobi.giza.compose.database.model.KeyShareGeneration
+import mobi.giza.compose.database.model.KeyShareMember
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.database.model.types.ShareGenerationState
+import mobi.giza.compose.database.model.types.ShareStanding
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.groupdm.AdminSeal
+import mobi.giza.compose.nostr.groupdm.EcdhPurpose
+import mobi.giza.compose.nostr.groupdm.GroupEcdhEvents
+import mobi.giza.compose.nostr.groupdm.GroupEcdhPayload
+
+/**
+ * Phase 5 of docs/group-threshold-ecdh.md: three admins at `t = 2` and a share-holder who is
+ * not an admin, answering and combining rounds between devices that share nothing but the
+ * inner events the network ferries.
+ */
+class GroupEcdhRoundJvmTest {
+ private val net = GroupDmNetwork(n = 4, t = 2)
+ private val a get() = net.devices[0]
+ private val b get() = net.devices[1]
+ private val c get() = net.devices[2]
+ private val d get() = net.devices[3]
+
+ @BeforeTest
+ fun setUp() = runBlocking {
+ net.admins = net.members.take(3).toSet()
+ net.install()
+ net.all()
+ Unit
+ }
+
+ @AfterTest
+ fun tearDown() = net.close()
+
+ private val sender = KeyPair()
+
+ private suspend fun wrapEverywhere(text: String = "dumela") =
+ net.wrapFrom(sender, text).also { wrap -> net.devices.forEach { net.ledger(it, wrap) } }
+
+ private fun holdFrom(device: GroupDmNetwork.Device) = { from: GroupDmNetwork.Device, _: MarmotInnerEvent -> from === device }
+
+ /** What the sender's own app computes: the interoperability claim, end to end. */
+ private val expectedWithSender get() = Nip44v2().computeConversationKey(sender.privKey!!, net.roomId.hexToByteArray()).toHex()
+
+ @Test
+ fun `two admins' partials give the same conversation key on all three admin devices`(): Unit = runBlocking {
+ val wrap = wrapEverywhere()
+ GroupEcdhManager.open(a.db, a.context()!!, wrap.pubKey, EcdhPurpose.WRAP, ref = wrap.id)
+ net.pump(hold = holdFrom(c))
+
+ listOf(a, b, c).forEach { device ->
+ val ledger = assertNotNull(device.db.groupDmDao().getWrap(wrap.id))
+ val seal = Event.fromJson(assertNotNull(ledger.sealJson, "$device opened the wrap"))
+ assertEquals(sender.pubKey.toHexKey(), seal.pubKey)
+ }
+
+ // The seal round, carrying the seal by the wrap's id.
+ val seal = Event.fromJson(a.db.groupDmDao().getWrap(wrap.id)!!.sealJson!!)
+ GroupEcdhManager.open(a.db, a.context()!!, seal.pubKey, EcdhPurpose.SEAL, ref = wrap.id)
+ net.pump(hold = holdFrom(c))
+
+ listOf(a, b, c).forEach { device ->
+ val key = assertNotNull(device.db.groupDmDao().getConversationKey(net.roomId, seal.pubKey), "$device kept the key")
+ assertEquals(expectedWithSender, key.conversationKey, "$device's key is the one the sender's app computed")
+ }
+ // The wrap's key is spent, not kept (D6).
+ listOf(a, b, c).forEach { assertNull(it.db.groupDmDao().getConversationKey(net.roomId, wrap.pubKey)) }
+ }
+
+ @Test
+ fun `a share-holder who is not an admin stores nothing it can read and combines nothing`(): Unit = runBlocking {
+ val wrap = wrapEverywhere()
+ GroupEcdhManager.open(a.db, a.context()!!, wrap.pubKey, EcdhPurpose.WRAP, ref = wrap.id)
+ net.pump()
+
+ assertNull(d.context(), "no part to take")
+ assertEquals(emptyList(), d.db.groupDmDao().getAllOpenRounds())
+ assertNull(d.db.groupDmDao().getRound(GroupEcdhPayload.roundId(net.roomId, 0, wrap.pubKey)))
+ // Partials reaching a device that is not an admin make it forget what it held (D14).
+ assertNull(d.db.groupDmDao().getWrap(wrap.id)?.sealJson)
+ assertEquals(emptyList(), net.outbox(d), "and sends nothing")
+ // The slots on every partials message name only the three admins' host keys.
+ val adminHosts = net.hostKeys.take(3).toSet()
+ listOf(a, b, c).flatMap { net.outbox(it) }.filter { it.kind == GroupEcdhEvents.PARTIALS }.forEach { message ->
+ assertTrue(AdminSeal.parseSlots(message.tags).keys.all { it in adminHosts })
+ assertFalse(net.hostKeys[3] in AdminSeal.parseSlots(message.tags).keys)
+ }
+ }
+
+ @Test
+ fun `a removed admin's device gets no slot in partials sent after the removal`(): Unit = runBlocking {
+ net.admins = net.members.take(2).toSet()
+ val wrap = wrapEverywhere()
+ GroupEcdhManager.open(a.db, a.context()!!, wrap.pubKey, EcdhPurpose.WRAP, ref = wrap.id)
+ net.pump()
+
+ assertNotNull(b.db.groupDmDao().getWrap(wrap.id)!!.sealJson, "the two remaining admins read it")
+ assertNull(c.context())
+ assertNull(c.db.groupDmDao().getWrap(wrap.id)?.sealJson, "the removed admin does not, and forgets the wrap")
+ assertEquals(emptyList(), c.db.groupDmDao().getAllOpenRounds())
+ net.outbox(a).filter { it.kind == GroupEcdhEvents.PARTIALS }.forEach {
+ assertFalse(net.hostKeys[2] in AdminSeal.parseSlots(it.tags).keys)
+ }
+ }
+
+ @Test
+ fun `a forged partial is named, and the round completes with the third admin`(): Unit = runBlocking {
+ val wrap = wrapEverywhere()
+ GroupEcdhManager.open(b.db, b.context()!!, wrap.pubKey, EcdhPurpose.WRAP, ref = wrap.id)
+
+ // A partial "from A" made with another scalar, sealed to B as A's device would seal it.
+ val point = ThresholdEcdh.pointOf(wrap.pubKey)!!
+ val aId = net.idOf[0]
+ val forger = PrivateKey(Crypto.sha256("forger".encodeToByteArray()))
+ val forged = EcdhPartial.compute(forger, point)
+ val payload = GroupEcdhPayload(
+ generation = 0, from = aId,
+ items = listOf(
+ GroupEcdhPayload.Item(
+ point = wrap.pubKey, purpose = EcdhPurpose.WRAP, ref = wrap.id, partial = forged,
+ proof = Dleq.prove(forger, net.keyMaterial.publicShares[aId], point, forged, Dleq.context(net.roomId, 0, aId), ByteArray(32)),
+ )
+ ),
+ )
+ val sealed = AdminSeal.seal(payload.encode(), ChillDkgRitualManager.deriveHostSecretKey(a.privateKey), listOf(net.hostKeys[1]))
+ net.deliver(
+ MarmotInnerEvent(
+ id = "f".repeat(64), publicKey = a.publicKey, kind = GroupEcdhEvents.PARTIALS,
+ createdAt = Instant.fromEpochSeconds(Clock.System.now().epochSeconds), tags = GroupEcdhEvents.partialsTags(sealed),
+ content = sealed.content, chatRoomId = net.roomId,
+ ),
+ b,
+ )
+
+ val roundId = GroupEcdhPayload.roundId(net.roomId, 0, wrap.pubKey)
+ val bad = b.db.groupDmDao().getPartials(roundId).single { it.participantId == aId }
+ assertFalse(bad.verified)
+ assertNotNull(bad.blamedAt, "named")
+ val blame = net.outbox(b, listOf(GroupEcdhEvents.FAILURE)).single()
+ assertEquals(roundId to aId, GroupEcdhEvents.parseFailure(blame.tags))
+ assertNull(b.db.groupDmDao().getWrap(wrap.id)!!.sealJson, "one proven partial is not two")
+
+ net.pump(between = listOf(b, c))
+ assertNotNull(b.db.groupDmDao().getWrap(wrap.id)!!.sealJson, "B and C completed it")
+ assertEquals(GroupEcdhRoundState.COMBINED, b.db.groupDmDao().getRound(roundId)!!.state)
+ }
+
+ @Test
+ fun `a point without evidence is never answered`(): Unit = runBlocking {
+ // A recipient whose "evidence" was signed by somebody else.
+ val someone = KeyPair()
+ val impostor = NostrSignerSync(KeyPair()).sign(1_700_000_000, 0, emptyArray(), "{}")
+ GroupEcdhManager.open(a.db, a.context()!!, someone.pubKey.toHexKey(), EcdhPurpose.RECIPIENT, evidence = impostor)
+ // A wrap this device has not seen.
+ val unseen = net.wrapFrom(sender, "unseen")
+ GroupEcdhManager.open(a.db, a.context()!!, unseen.pubKey, EcdhPurpose.WRAP, ref = unseen.id)
+ assertEquals(emptyList(), net.outbox(a), "nothing answered")
+
+ // Once the wrap is in the ledger the sweep answers it.
+ net.ledger(a, unseen)
+ GroupEcdhManager.advance(a.db, a.context()!!)
+ assertEquals(1, net.outbox(a).count { it.kind == GroupEcdhEvents.PARTIALS })
+
+ // B holds A's partial but no wrap: it stores it and does not answer.
+ net.pump(between = listOf(a, b))
+ val roundId = GroupEcdhPayload.roundId(net.roomId, 0, unseen.pubKey)
+ assertEquals(listOf(net.idOf[0]), b.db.groupDmDao().getPartials(roundId).map { it.participantId })
+ assertEquals(emptyList(), net.outbox(b))
+ net.ledger(b, unseen)
+ GroupEcdhManager.advance(b.db, b.context()!!)
+ assertNotNull(b.db.groupDmDao().getWrap(unseen.id)!!.sealJson)
+ }
+
+ // --- a refresh mid-round
+
+ /** Generation 1: the same key on another polynomial, `s'ᵢ = sᵢ + c·(i+1)`, as a refresh would leave it. */
+ private suspend fun refreshAll() {
+ val c = PrivateKey(Crypto.sha256("refresh".encodeToByteArray()))
+ val newShares = net.keyMaterial.secretShares.mapIndexed { id, s -> s + c * PrivateKey(ByteArray(32).also { it[31] = (id + 1).toByte() }) }
+ val publicShares = newShares.joinToString(",") { it.publicKey().value.toHex() }
+ net.devices.forEach { device ->
+ device.db.keyShareDao().upsert(
+ KeyShareGeneration(
+ dkgSessionId = net.ceremonyId, generation = 1, secretShare = newShares[net.idOf[device.index]].value.toHex(),
+ publicShares = publicShares, state = ShareGenerationState.ACTIVE, activatedAt = Clock.System.now(),
+ )
+ )
+ device.db.keyShareDao().upsert(net.members.indices.map { i ->
+ KeyShareMember(net.ceremonyId, 1, net.idOf[i], net.members[i], net.hostKeys[i], ShareStanding.LIVE)
+ })
+ }
+ }
+
+ @Test
+ fun `a refresh mid-round restarts it, and partials of two generations never combine`(): Unit = runBlocking {
+ val wrap = wrapEverywhere()
+ GroupEcdhManager.open(a.db, a.context()!!, wrap.pubKey, EcdhPurpose.WRAP, ref = wrap.id)
+ val stale = net.outbox(a).single { it.kind == GroupEcdhEvents.PARTIALS }
+
+ refreshAll()
+ assertEquals(1, b.context()!!.generation)
+
+ // A generation-0 partial reaches B at generation 1: ignored, not combined with anything.
+ net.deliver(stale, b)
+ b.received += stale.id
+ assertNull(b.db.groupDmDao().getRound(GroupEcdhPayload.roundId(net.roomId, 0, wrap.pubKey)))
+
+ // A's sweep restarts its round at the new generation.
+ GroupEcdhManager.advance(a.db, a.context()!!)
+ assertEquals(GroupEcdhRoundState.FAILED, a.db.groupDmDao().getRound(GroupEcdhPayload.roundId(net.roomId, 0, wrap.pubKey))!!.state)
+ val fresh = assertNotNull(a.db.groupDmDao().getRound(GroupEcdhPayload.roundId(net.roomId, 1, wrap.pubKey)))
+ assertNotNull(fresh.partialSentAt)
+
+ net.pump()
+ listOf(a, b, c).forEach { device ->
+ assertNotNull(device.db.groupDmDao().getWrap(wrap.id)!!.sealJson, "$device opened it at generation 1")
+ }
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSealRoutingJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSealRoutingJvmTest.kt
new file mode 100644
index 00000000..2538b10c
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSealRoutingJvmTest.kt
@@ -0,0 +1,32 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import kotlin.test.Test
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+
+/**
+ * Two features ask the group to sign kind 13 seals: the group inbox's replies
+ * (docs/group-inbox.md, D10) and messages by threshold ECDH (docs/group-threshold-ecdh.md, D10).
+ * Every seal belongs to exactly one refusal, split on whether it names an inbox key, so none is
+ * read by both and none is asked blind.
+ */
+class GroupSealRoutingJvmTest {
+ private fun seal(tags: Array>) = Event("a".repeat(64), "b".repeat(64), 1_700_000_000, 13, tags, "x", "")
+
+ @Test
+ fun `an inbox reply is the inbox's, and everything else is threshold ECDH's`() {
+ val reply = seal(arrayOf(arrayOf("n", "c".repeat(64))))
+ val bare = seal(emptyArray())
+ val malformed = seal(arrayOf(arrayOf("n", "not a key")))
+ val twoKeys = seal(arrayOf(arrayOf("n", "c".repeat(64)), arrayOf("n", "d".repeat(64))))
+
+ assertTrue(InboxRefusal.involves(listOf(reply)))
+ assertFalse(GroupDmRefusal.involves(listOf(reply)))
+
+ listOf(bare, malformed, twoKeys).forEach { other ->
+ assertTrue(GroupDmRefusal.involves(listOf(other)), "claimed by threshold ECDH: ${other.tags.toList().map { it.toList() }}")
+ assertFalse(InboxRefusal.involves(listOf(other)))
+ }
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmWireTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmWireTest.kt
new file mode 100644
index 00000000..1b3fecb6
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/groupdm/GroupDmWireTest.kt
@@ -0,0 +1,188 @@
+package mobi.giza.compose.nostr.groupdm
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import fr.acinq.bitcoin.Crypto
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
+import fr.acinq.bitcoin.crypto.frost.Frost
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.cryptography.threshold.Dleq
+import mobi.giza.compose.cryptography.threshold.EcdhPartial
+import mobi.giza.compose.cryptography.threshold.NpubTweak
+import mobi.giza.compose.cryptography.threshold.ThresholdEcdh
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.SharedKeyDerivation
+
+/**
+ * Phase 3 of docs/group-threshold-ecdh.md: the wire, against quartz's stock NIP-17. A message
+ * from a person opens through the admins' shares, and a message from the group opens in a
+ * stock client with the recipient's own key.
+ */
+class GroupDmWireTest {
+ private val x = PrivateKey(Crypto.sha256("group-dm-wire".encodeToByteArray()))
+ private val keys = Frost.trustedDealerKeygen(x, 5, 3)
+ private val tweak = NpubTweak.of(keys.thresholdPublicKey)
+ private val group = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()).hex
+
+ /** The npub's secret, whole: only to stand in for a FROST signature in a test. */
+ private val d: PrivateKey = run {
+ var q = keys.thresholdPublicKey
+ var negate = false
+ var b: PrivateKey? = null
+ SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()).tweaks.forEach { s ->
+ val tau = PrivateKey(s)
+ if (q.isOdd()) { q = -q; negate = !negate; b = b?.let { -it } }
+ q += tau.publicKey(); b = b?.let { it + tau } ?: tau
+ }
+ (if (negate) -x else x) + b!!
+ }
+
+ /** What three admins' devices would agree on, without any of them holding `d`. */
+ private fun thresholdKey(point: String, ids: List = listOf(0, 2, 4)): ByteArray {
+ val p = ThresholdEcdh.pointOf(point)!!
+ val partials = ids.associateWith { EcdhPartial.compute(keys.secretShares[it], p) }
+ return ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials, tweak, p))
+ }
+
+ @Test
+ fun `a message from a person, wrapped by quartz, opens through the admins' shares`() = runBlocking {
+ val sender = KeyPair()
+ val signer = NostrSignerInternal(sender)
+ val rumor = Event(
+ id = "", pubKey = sender.pubKey.toHexKey(), createdAt = 1_700_000_000, kind = 14,
+ tags = arrayOf(arrayOf("p", group)), content = "dumela", sig = "",
+ )
+ val seal = SealEvent.create(rumor, group, signer)
+ val wrap = GiftWrapEvent.create(seal, group)
+
+ val openedSeal = assertNotNull(GroupDmWrap.open(wrap, thresholdKey(wrap.pubKey)))
+ assertEquals(sender.pubKey.toHexKey(), openedSeal.pubKey)
+ val opened = assertNotNull(GroupDmSeal.open(openedSeal, thresholdKey(openedSeal.pubKey, listOf(1, 2, 3))))
+ assertEquals("dumela", opened.content)
+ assertEquals(sender.pubKey.toHexKey(), opened.pubKey)
+ assertEquals(listOf(sender.pubKey.toHexKey()), GroupDmConversation.participantsOf(opened, group))
+ // The wrong key opens neither.
+ assertNull(GroupDmWrap.open(wrap, thresholdKey(openedSeal.pubKey)))
+ }
+
+ @Test
+ fun `a message from the group opens in quartz's stock unwrap with the recipient's own key`() = runBlocking {
+ val recipient = KeyPair()
+ val r = recipient.pubKey.toHexKey()
+ val rumor = GroupDmSeal.rumor(group, 1_700_000_000, 14, arrayOf(arrayOf("p", r)), "the group says hello")
+ val template = GroupDmSeal.build(rumor, thresholdKey(r), createdAt = 1_699_990_000)
+ // FROST's signature stands in as a signature by d.
+ val signedSeal = NostrSignerSync(KeyPair(privKey = d.value.toByteArray()))
+ .sign(template.createdAt, template.kind, template.tags, template.content)
+ assertEquals(group, signedSeal.pubKey)
+ val wrap = GiftWrapEvent.create(signedSeal, r)
+
+ val opened = assertNotNull(wrap.unwrapAndUnsealOrNull(NostrSignerInternal(recipient)))
+ assertEquals("the group says hello", opened.content)
+ assertEquals(group, opened.pubKey)
+ assertEquals(rumor.id, opened.id)
+ }
+
+ // --- D5
+
+ private fun signedBy(keyPair: KeyPair, kind: Int, tags: Array> = emptyArray()): Event =
+ NostrSignerSync(keyPair).sign(1_700_000_000, kind, tags, "x")
+
+ @Test
+ fun `evidence is refused unless the point signed something of the right shape`() = runBlocking {
+ val person = KeyPair()
+ val p = person.pubKey.toHexKey()
+ val toGroup = GiftWrapEvent.create(signedBy(person, 13), group)
+ assertNull(Evidence.check(EcdhPurpose.WRAP, toGroup.pubKey, toGroup, group))
+
+ val toSomeoneElse = GiftWrapEvent.create(signedBy(person, 13), p)
+ assertEquals(Evidence.Refusal.NOT_TO_GROUP, Evidence.check(EcdhPurpose.WRAP, toSomeoneElse.pubKey, toSomeoneElse, group))
+
+ val seal = signedBy(person, 13)
+ assertNull(Evidence.check(EcdhPurpose.SEAL, p, seal, group))
+ val unsigned = Event(seal.id, seal.pubKey, seal.createdAt, seal.kind, seal.tags, seal.content, "")
+ assertEquals(Evidence.Refusal.BAD_SIGNATURE, Evidence.check(EcdhPurpose.SEAL, p, unsigned, group))
+ assertEquals(Evidence.Refusal.WRONG_KIND, Evidence.check(EcdhPurpose.SEAL, p, signedBy(person, 1), group))
+
+ assertNull(Evidence.check(EcdhPurpose.RECIPIENT, p, signedBy(person, 0), group))
+ assertEquals(Evidence.Refusal.WRONG_KEY, Evidence.check(EcdhPurpose.RECIPIENT, p, signedBy(KeyPair(), 0), group))
+ val groupSigned = NostrSignerSync(KeyPair(privKey = d.value.toByteArray())).sign(1_700_000_000, 0, emptyArray(), "{}")
+ assertEquals(Evidence.Refusal.THE_GROUP_ITSELF, Evidence.check(EcdhPurpose.RECIPIENT, group, groupSigned, group))
+ }
+
+ // --- the payload, the manifest and the admin seal
+
+ private val hostA = PrivateKey(Crypto.sha256("host-a".encodeToByteArray()))
+ private val hostB = PrivateKey(Crypto.sha256("host-b".encodeToByteArray()))
+ private val hostC = PrivateKey(Crypto.sha256("host-c".encodeToByteArray()))
+ private fun hex(k: PrivateKey) = k.publicKey().value.toHex()
+
+ @Test
+ fun `an admin seal opens for the admins it was sealed to and nobody else`() {
+ val sealed = AdminSeal.seal("partials", hostA, listOf(hex(hostA), hex(hostB)))
+ assertEquals("partials", AdminSeal.open(sealed, hostB, hex(hostB), hex(hostA)))
+ assertEquals("partials", AdminSeal.open(sealed, hostA, hex(hostA), hex(hostA)))
+ assertNull(AdminSeal.open(sealed, hostC, hex(hostC), hex(hostA)), "no slot")
+ assertNull(AdminSeal.open(sealed, hostB, hex(hostB), hex(hostC)), "another sender")
+ val roundTrip = AdminSeal.Sealed(sealed.content, AdminSeal.parseSlots(GroupEcdhEvents.partialsTags(sealed)))
+ assertEquals("partials", AdminSeal.open(roundTrip, hostB, hex(hostB), hex(hostA)))
+ }
+
+ @Test
+ fun `a payload round-trips, and only its own encoding decodes`() {
+ val w = KeyPair().pubKey.toHexKey()
+ val p = ThresholdEcdh.pointOf(w)!!
+ val partial = EcdhPartial.compute(keys.secretShares[0], p)
+ val proof = Dleq.prove(keys.secretShares[0], keys.publicShares[0], p, partial, Dleq.context(group, 0, 0), ByteArray(32))
+ val evidence = signedBy(KeyPair(), 0)
+ val payload = GroupEcdhPayload(
+ generation = 0, from = 0,
+ items = listOf(
+ GroupEcdhPayload.Item(w, EcdhPurpose.WRAP, ref = "a".repeat(64), partial = partial, proof = proof),
+ GroupEcdhPayload.Item(evidence.pubKey, EcdhPurpose.RECIPIENT, evidence = evidence, partial = partial, proof = proof),
+ ),
+ )
+ val text = payload.encode()
+ val decoded = assertNotNull(GroupEcdhPayload.decode(text))
+ assertEquals(text, decoded.encode())
+ assertEquals(evidence.id, decoded.items[1].evidence?.id)
+ assertNull(GroupEcdhPayload.decode(text.replace("\"v\":1", "\"v\": 1")), "another spelling")
+ assertNull(GroupEcdhPayload.decode(text.replace("\"purpose\":\"wrap\"", "\"purpose\":\"recipient\"")), "a recipient with a ref")
+ assertNull(GroupEcdhPayload.decode("""{"v":1,"generation":0,"from":0,"items":[]}"""), "nothing in it")
+ }
+
+ @Test
+ fun `a manifest round-trips, and only its own encoding decodes`() {
+ val evidence = signedBy(KeyPair(), 0)
+ val manifest = GroupDmManifest(listOf(GroupDmManifest.Seal(evidence.pubKey, evidence)), replyingTo = null)
+ val text = manifest.encode()
+ assertEquals(text, GroupDmManifest.decode(text)?.encode())
+ assertNull(GroupDmManifest.decode(text.replace("null", "\"zz\"")))
+ val reply = GroupDmManifest(manifest.seals, replyingTo = "b".repeat(64))
+ assertEquals("b".repeat(64), GroupDmManifest.decode(reply.encode())?.replyingTo)
+
+ val sealed = AdminSeal.seal(text, hostA, listOf(hex(hostB)))
+ val tags = manifest.toTags(sealed)
+ val carried = assertNotNull(GroupDmManifest.sealedIn(tags))
+ assertEquals(text, AdminSeal.open(carried, hostB, hex(hostB), hex(hostA)))
+ }
+
+ @Test
+ fun `a conversation is its correspondents, in any order, without the group`() {
+ val a = "a".repeat(64); val b = "b".repeat(64)
+ val one = GroupDmSeal.rumor(a, 1, 14, arrayOf(arrayOf("p", group), arrayOf("p", b)), "hi")
+ val two = GroupDmSeal.rumor(b, 2, 14, arrayOf(arrayOf("p", a), arrayOf("p", group)), "hi")
+ assertEquals(GroupDmConversation.idOf(one, group), GroupDmConversation.idOf(two, group))
+ assertEquals(listOf(a, b), GroupDmConversation.participantsOf(one, group))
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index 140f92d0..bd1bb3ff 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -43,6 +43,7 @@ the [retired](./retired/) notes now.
| [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase |
| [group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md) | bringing back the group's nostr profile and its posts, ported from Curare, phased and built but for its device run: why it is a port and not a revert of `b21f4c4d`, what Giza does today with a peer's kind:0 or kind:1, why relay lists stay out, why the group's lightning address is kept but never offered, why a broadcast never writes a `NostrEvent` row and sends nothing but those two kinds, and declining what no reader would show |
| [group-inbox.md](./group-inbox.md) | a group that can be written to privately: a phased plan, built but for its device run and behind a flag that is off in release, for NIP-4E on a group's npub. A ChillDKG ceremony at threshold 1 leaves every admin holding the same inbox key, the group announces it in a signed 10044, admins read the NIP-17 messages sent to it, and a reply is a batch of seals the quorum signs before the proposer's device wraps and sends them. Covers why the key is its own ceremony and never a signing key, why the proposal hides the reply from members who are not admins, what every signer checks before signing a seal, and the rotation on every admin change with what it cannot undo |
+| [group-threshold-ecdh.md](./group-threshold-ecdh.md) | a group that sends and receives NIP-17 direct messages at its own npub, with stock NIP-17 on the wire: built behind `ExperimentalFeatures.groupDirectMessages` (Phases 0 to 10), not yet run on devices. The admins' shares compute ECDH together, so no device ever holds the group's key and the conversation key is the one any NIP-44 library would derive. Covers the tweak signs the npub's derivation puts into the arithmetic, the proof every partial carries, why partials go only to current admins (so a removed admin is cut off at once), why a device multiplies only by a key whose owner has signed something, why reading asks nobody and writing asks the quorum, and how it compares with a NIP-4E inbox key |
| [giza-app-icon.md](./giza-app-icon.md) | the sphinx icon on iOS, desktop and in the app, phased and built but for the checks on a mac, a phone and Windows — one master SVG and one generator for every raster, why the iOS light icon must carry no alpha channel, why its dark icon is transparent and its tinted one grayscale, the desktop installers and window that show Java's icon today, and why the mark's cutouts need no fill rule |
| [member-admin-promotion.md](./member-admin-promotion.md) | making a member an admin and back, phased and built, promotion with a share and demotion with a refresh under the experimental enrollment, under three rules: every admin holds a share, every commit in a keyed room is a proposal until the group's threshold signature is on it, and a robust group keeps at least three admins. Covers why the commit rides inside the group's signature and the rule inside the group's state, which lets every device refuse an unsigned commit with the libraries as they are, why a member's own leave stays exempt, and why a removed admin comes back as an admin when re-invited today |
| [admin-change-rotation.md](./admin-change-rotation.md) | an admin change carries its rotation with it: a phased plan, built but for its device session, in which the rotation that follows removing an admin, and the one before a first promotion, asks nobody, because the group's signature on the change already decided who is withheld, and in which admin changes and rotations take turns. Covers the five ways the two overlap today, a removed admin who keeps a live share among them, and the one check a device makes to take part unasked |
diff --git a/docs/confederation.md b/docs/confederation.md
index 36dea253..b2a2e23b 100644
--- a/docs/confederation.md
+++ b/docs/confederation.md
@@ -280,6 +280,13 @@ the group in the usual way, because NIP-44's conversation key is an ECDH between
sender's secret and the recipient's pubkey. For the same reason, nothing can be gift-wrapped
*to* a group's npub.
+> **Since** [group-threshold-ecdh.md](./group-threshold-ecdh.md): a group *can* now be written
+> to at its npub, through its admins' shares computing the ECDH together, where it has opened
+> its messages (signed a kind 10050). That needs `t` admins' apps to answer, and a device
+> multiplies only by a key whose owner signed something it can check, so it is no use to this
+> seal: the coordinator's key is not one the group could compute for in a signing session.
+> D5's seal stays as it is.
+
The acceptance uses an ephemeral sender key instead, and makes everything about the
encryption reproducible by the group's members and by nobody else:
diff --git a/docs/group-threshold-ecdh.md b/docs/group-threshold-ecdh.md
new file mode 100644
index 00000000..9dd8b98e
--- /dev/null
+++ b/docs/group-threshold-ecdh.md
@@ -0,0 +1,901 @@
+# The group's direct messages, by threshold ECDH
+
+A plan for a group to send and receive NIP-17 direct messages as its own npub, with
+nothing on the wire that a stock NIP-17 client would not send or expect:
+
+1. **Anyone can write to the group.** A person on any NIP-17 app writes to the group's
+ npub exactly as they would write to a person. They need no app that knows about groups,
+ and no key the group announced.
+2. **The admins read it.** Every current admin's device can read what the group is sent, and
+ nobody else's can: not the group's other members, not a former admin, and not a relay.
+3. **The group writes back, or first.** An admin drafts a message; it is sent only once the
+ group's quorum has signed it, and it arrives as an ordinary NIP-17 message from the
+ group's npub, readable by any NIP-17 app.
+
+The difficulty is that NIP-17 is built on ECDH with the recipient's key, and nobody holds
+the group's key. [confederation.md](./confederation.md#d5-encrypting-the-admin-list-a-seal-every-signer-can-recompute)
+draws the conclusion that "nothing can be gift-wrapped *to* a group's npub". This plan
+removes that conclusion without changing the premise. ECDH, like a signature, can be
+computed by the share-holders together: each multiplies the other party's key by its own
+share, and any `t` of the results combine into the one point the whole key would have
+given. Nobody learns the group's key, and the conversation key that comes out is exactly
+the one a single-key NIP-44 implementation would have derived.
+
+Read [shared-key-derivation.md](./shared-key-derivation.md) first. Its rule (never
+reconstruct a derived key in the clear) is the rule this plan is built around, and its
+tweaks are the one subtle part of the arithmetic (D2). Then read
+[frost-share-refresh.md](./frost-share-refresh.md), for share generations and why the
+group's key outlives every rotation. After those,
+[group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md) shows how a group
+proposes, signs and broadcasts in its own name, and
+[marmot-direct-messages.md](./marmot-direct-messages.md) covers the last time this app
+built a gift wrap by hand.
+
+There is a sibling plan for the same goal by another route: a NIP-4E inbox key, generated
+by its own ceremony and held whole by every admin (`group-inbox.md`, written alongside this
+one and not merged). *Against the NIP-4E plan* below says where the two differ, and how
+they fit together if both are built.
+
+**Built, Phases 0 to 10**, behind `ExperimentalFeatures.groupDirectMessages`; the device run
+(Phase 11) has not been done. *What the plan said, and what it turned out to be* is below the
+phases. Written against `5ac4c053`, on 2026-11-22. Paths starting `K/` are
+under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`, and `B/` is bitcoin-kmp's
+`src/commonMain/kotlin/fr/acinq/bitcoin/`, under
+`lightning-kmp-app/experimental/lightning-kmp/experimental/bitcoin-kmp/`.
+
+---
+
+## The arithmetic
+
+The group's threshold key is `X = x·G`. Nobody holds `x`. Each share-holder `i` of the
+active generation holds a Shamir share `sᵢ`, and for any set `S` of `t` holders,
+`x = Σᵢ∈S λᵢ·sᵢ`, where `λᵢ` are the Lagrange coefficients at zero over the ids in `S`.
+FROST signing relies on exactly this, inside libsecp256k1-zkp.
+
+The group's npub is not `X`. It is the key derived at `m/9420/0/0` by three x-only tweaks
+([shared-key-derivation.md](./shared-key-derivation.md)), and its secret, which nobody
+holds either, is
+
+```
+d = a·x + b where a ∈ {1, −1} and b are public, fixed by replaying the tweaks
+```
+
+NIP-44's conversation key between the group and a nostr key `P` is
+
+```
+convKey = HKDF-extract(salt = "nip44-v2", IKM = x-coordinate of d·P)
+```
+
+and `d·P` can be computed without `d`:
+
+```
+each holder i ∈ S: Dᵢ = sᵢ·P one scalar multiplication
+ πᵢ = DLEQ(Yᵢ = sᵢ·G, Dᵢ = sᵢ·P) a proof that Dᵢ is honest (D3)
+the combiner: x·P = Σ λᵢ·Dᵢ
+ d·P = a·(x·P) + b·P
+```
+
+Three properties do all the work:
+
+- **Every subset gives the same point.** Any `t` honest holders produce `x·P`, so whoever
+ answers first is enough.
+- **A partial alone is useless.** `Dᵢ` reveals nothing about `sᵢ` (it is a Diffie-Hellman
+ value), and fewer than `t` partials reveal nothing about `x·P`.
+- **The sign of the whole does not matter.** NIP-44 reads only the x-coordinate, and
+ `x(Q) = x(−Q)`. So neither `P`'s lifted parity nor the npub's final even-y normalisation
+ needs care. The sign of `a` *inside* the sum does matter, which is D2.
+
+What comes out is the conversation key of the pair (group, `P`), the one any NIP-44 library
+computes from `d` and `P`. That is the whole interoperability argument: a sender's app
+cannot tell the group's key apart from a person's.
+
+---
+
+## What NIP-17 asks of the group
+
+A message to the group arrives as:
+
+```
+gift wrap (1059) pubkey W, a fresh random key p = the group's npub
+ content = nip44(seal, conv(w, group))
+seal (13) pubkey S, the sender signed by S
+ content = nip44(rumor, conv(s, group))
+rumor (14) pubkey S, the message
+```
+
+So reading one message takes two group ECDHs. **`d·W` is new on every message**, because the
+wrap key is fresh. **`d·S` is the same for every message from that sender**, and once
+computed it can be kept (D6).
+
+A message from the group is:
+
+```
+rumor (14) pubkey = the group's npub, unsigned
+seal (13) pubkey = the group's npub, signed by FROST
+ content = nip44(rumor, conv(group, R)) one group ECDH per recipient R, kept
+gift wrap pubkey = a fresh key this device holds ordinary: no group secret involved
+ content = nip44(seal, conv(w, R))
+```
+
+So writing takes one group ECDH per recipient (kept afterwards) and one FROST signature
+per recipient's seal. The signature is the existing signing session; the ECDH is this plan.
+
+---
+
+## What Giza does today
+
+Traced through the code at `5ac4c053`. Phase 1 pins them.
+
+| event | where it lands | what happens |
+|---|---|---|
+| a kind 1059 `#p`-tagged to a group's npub | nowhere: `LiveSubscriptionManager` subscribes to `#p` = the active identity, on `Relays.DefaultDMRelayList` | never fetched. If one arrived another way, `NostrDao.indexNostrEvent` stores a `GiftWrapMessage` and never opens it, because only the active identity's key is tried |
+| a peer proposes a kind 13 for the group to sign | `FrostSigningManager.acceptProposal` | no refusal fires, because the signer has no allowlist. It is asked as "Event of kind 13" and can be signed: a ciphertext the signer cannot read, which is the rubber stamp [giza-wallet-removal.md](./giza-wallet-removal.md) says a Giza device must never be |
+| a peer proposes a kind 10050 | same | "Event of kind 10050", signable. Signing it leaves nothing behind |
+| either completes | `ChatMessage.applyInnerEvent` | `unsupported()`: a raw-JSON bubble |
+| the user's own NIP-17 send | `NostrNip17Dao.persistAndBroadcastGiftWrap` | to `DefaultDMRelayList` only. The recipient's 10050 is looked up, and the block that would use it is commented out (`:186-218`) |
+
+What already exists and is reused:
+
+- **The share, the public shares and the ids.** `ShareGenerations.active(database, key)`
+ returns this device's `secretShare` (a `PrivateKey`), every holder's `publicShares`, the
+ `signerIds` by member, and the `roster` with each holder's **host key**. That is every
+ input the arithmetic needs, and none of it leaves the device.
+- **The point and scalar operations.** bitcoin-kmp's `PublicKey.plus`, `unaryMinus` and
+ `times(PrivateKey)`, and `PrivateKey.plus`, `times` and `unaryMinus` (`B/PublicKey.kt:48-60`,
+ `B/PrivateKey.kt:47-53`). Each is a libsecp256k1 call, so **every operation on a secret
+ stays inside libsecp256k1's constant-time code**. Kotlin only handles public values.
+- **The tweaks.** `SharedKeyDerivation.Derived.tweaks` carries the three scalars `derive`
+ applied. The confederation already replays them by hand to reach the same key
+ ([confederation.md](./confederation.md) Phase 1, `ConfederationRoomKeyJvmTest`).
+- **The pairwise channel.** `ShareRepairManager.seal`/`open` (`:414-421`) NIP-44-encrypts
+ between two host keys, so that only those two devices can read what passes inside an MLS
+ room every member receives. D4 uses the same channel.
+- **The signing session, the refusals, and the owed-publisher.** `proposeSigningBatch` with
+ hidden `proposalTags`, the four places a refusal sits, and `ConfederationPublisher`'s
+ pattern for sending a signed event with backoff.
+
+---
+
+## Decisions
+
+### D1. The group's own key, not a second one
+
+The group reads and writes with the key it already has. There is no new ceremony, no
+announcement, no second secret on any device, and nothing to rotate. The shares already
+rotate ([frost-share-refresh.md](./frost-share-refresh.md)), and a refresh changes every
+`sᵢ` without changing `x`. So the conversation keys stay the same across rotations, while
+the shares a former admin holds stop combining with anyone's.
+
+### D2. The tweaks are replayed in Kotlin, with their signs
+
+The npub is `X` walked through three x-only tweaks. For an x-only tweak, BIP 327 (which
+FROST's tweak cache follows) negates the key first when its y is odd:
+
+```
+a₀ = 1, b₀ = 0, Q₀ = X
+for each tweak τ:
+ g = 1 if Qₖ has even y, else −1
+ Qₖ₊₁ = g·Qₖ + τ·G
+ aₖ₊₁ = g·aₖ
+ bₖ₊₁ = g·bₖ + τ
+npub = x-only(Q₃), d = a₃·x + b₃
+```
+
+`a` and `b` are public, computed by every device from `X` and the tweak list. Getting `a`
+wrong gives `−x·P + b·P` instead of `x·P + b·P`: a different point whose x-coordinate does
+not match, so every decryption fails. That is why Phase 0 checks it against the library's
+own tweak cache, and against a NIP-44 key derived the ordinary way from a test key. Only in
+the test is `d` built whole, from a dealer key made for the test.
+
+`TweakCache` is opaque bytes from libsecp256k1-zkp (`B/crypto/frost/Frost.kt:60`), so the
+replay cannot read `a` and `b` out of it. It recomputes them, and checks that its `Q₃`
+equals `Derived.publicKey`.
+
+### D3. Every partial carries a proof, and a bad one is named
+
+A holder who sends a wrong `Dᵢ` would make the combined point wrong. NIP-44's MAC would
+catch that, but not say whose partial it was. So every partial carries a Chaum-Pedersen
+proof that `log_G(Yᵢ) = log_P(Dᵢ)`, where `Yᵢ` is the holder's public share at the stated
+generation:
+
+```
+k = TaggedHash("mantra/threshold-ecdh/dleq-nonce/v1", sᵢ || P || Dᵢ || aux) mod n
+R₁ = k·G, R₂ = k·P
+c = TaggedHash("mantra/threshold-ecdh/dleq/v1", room || generation || i || Yᵢ || P || Dᵢ || R₁ || R₂) mod n
+z = k + c·sᵢ
+proof = (c, z)
+
+verify: R₁ = z·G − c·Yᵢ, R₂ = z·P − c·Dᵢ, and c recomputes
+```
+
+`aux` is 32 fresh random bytes, so a fault in one run cannot repeat a nonce across two.
+The challenge binds the room, the generation and the id, so a proof cannot be replayed into
+another round. A hash that lands at or above `n` fails the proof rather than being reduced,
+which happens with probability about 2⁻¹²⁸. bitcoin-kmp's `PrivateKey` constructor does not
+range-check (Phase 0, check 4), so the proof calls `isValid()` on every hash it reads as a
+scalar. The tags are hash inputs, spelled `mantra/` as
+every protocol tag is ([giza-rebrand.md](./giza-rebrand.md)).
+
+A partial whose proof fails is dropped, its sender is named in the inbox's diagnostics
+once per round, and the round waits for another holder. This is the only cryptography the
+plan writes by hand. It is about forty lines over libsecp256k1 calls, and Phase 2 tests it
+against published Chaum-Pedersen vectors where they exist and against itself where they
+do not.
+
+### D4. Partials go to the current admins, sealed to their host keys
+
+Partials travel as MLS inner events in the group's Marmot room, the room its key lives in,
+which every member receives. A member who is not an admin must not be able to combine
+them, so each partial message's payload is NIP-44-encrypted once per current admin, to that
+admin's host key from the roster (the share-repair channel). Phase 0 (check 6) changed how:
+the payload is NIP-44-encrypted **once**, under a fresh 32-byte key, and only that key is
+sealed per admin. Sealing the whole payload per admin multiplied it by the number of admins.
+
+**Current admin** means `RoomAdmins.of(room)` intersected with the holders of the active
+generation. A device sends its partials only if its own member is in that set, and seals
+them only to the others in it. That one rule gives the plan its strongest property:
+
+- **A removed admin stops being able to read new messages the moment their removal lands.**
+ Nobody sends them partials any more, even before the share rotation that follows takes
+ their share away.
+
+A share-holder who is no longer an admin (possible while share refresh is experimental)
+neither sends nor receives partials.
+
+### D5. A device multiplies only by a key whose owner has signed something it can check
+
+Answering partials makes the group a "multiply by `x`" service for its admins. The known
+weakness of such a service is the static Diffie-Hellman oracle (Brown–Gallant, Cheon): fed
+chosen points that are themselves powers of the secret, `x·G`, `x²·G`, and so on, enough
+answers wear the secret's security margin down. That needs points whose discrete log the
+requester does not know.
+
+So a device computes `sᵢ·P` only when it holds a **Schnorr signature by `P`** that it has
+verified, on an event of the right shape for the purpose:
+
+| purpose | `P` | the signed evidence |
+|---|---|---|
+| open a wrap | the wrap's pubkey `W` | the kind 1059 itself, `p`-tagged to the group's npub |
+| open a seal | the seal's pubkey `S` | the kind 13 itself, out of a wrap this round opened |
+| write to someone | the recipient `R` | any event signed by `R` (a kind 0, 10050 or 14 the device has, or one the proposer carries) |
+
+A signature by `P` proves its signer knows `log_G(P)`, so no point can be `x^k·G`. The rule
+also keeps out the group's own npub (`x²·G` is exactly the dangerous query), so the group
+never encrypts to itself. D10 is shaped around that.
+
+### D6. Wrap points are spent once; sender and recipient points are kept
+
+`d·W` opens one wrap and is not kept; the opened message is. `d·S` and `d·R` give a
+conversation key that is the same for every message with that person. It is kept in
+`GroupConversationKey`, so after the first message from or to someone, reading their next
+message costs one round instead of two, and writing to them costs none.
+
+A kept key is only as safe as the device it is on. A stolen admin phone gives up the kept
+conversation keys, but not the means to open new wraps, which still take `t` holders, and
+the phone is not sent partials once its owner is removed (D4). This trade is stated in
+*Risks*.
+
+### D7. Nobody is asked to read; the group is asked to write
+
+An admin's device answers partials **without asking**, whenever the app is open and the
+evidence checks out (D5). Being an admin is the decision to read the group's mail. A person
+cannot add anything to "should my phone help open a message the group was sent", and one
+who could say no would only be holding the group's mail shut.
+
+Writing is different. Every message the group sends is a FROST signing session over its
+seals, asked of `t` holders like any statement in the group's name. Proposing is the
+proposer's approval, as always.
+
+The group's decision to *receive* direct messages at all is its signature on a kind 10050
+(D8). Until it signs one, devices do not subscribe for the group's mail.
+
+### D8. The group's DM relays: a group-signed 10050
+
+A sender's app sends NIP-17 to the recipient's 10050 relays, and many send nothing when
+there are none. **Open the group's messages** proposes a kind 10050 for the group to sign,
+filled with `Relays.DefaultDMRelayList`, which the member can edit first. Its approval
+screen says, in plain words, that anyone on nostr will be able to write to the group and
+every admin will be able to read it.
+
+A refusal, `GroupDmRelayRefusal`, declines a 10050 whose relays are not all public `wss://`
+URLs (the profile plan's `relayUrlOrNull`). Once signed, the proposer's device publishes it
+through an owed-publisher, with backoff. `BROADCASTABLE_KINDS` gains 10050 so any member can
+send it again. It writes no `NostrEvent` row, for the same reasons as the profile (D7 of
+that plan).
+
+This brings back one of the four relay lists that
+[group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md#d1-profile-and-posts-only-relay-lists-stay-out)
+left out, and only that one.
+
+### D9. Reading is its own pipeline, never the personal one
+
+The personal DM path is built around one identity, and it files what it opens into rooms
+keyed by participants. The group's mail would mix the group's correspondents into the
+admin's own DM list. So the group's mail has its own path, and writes no `GiftWrapMessage`,
+`GiftWrapPayload` or `NostrEvent` row.
+
+1. **Subscribe.** `LiveSubscriptionManager` holds `live-group-dm` while the flag is on: kind
+ 1059, `#p` = the npub of every room where this device's member is a current admin and
+ the group has signed a 10050, on those 10050s' relays and the app's DM relays. Catch-up
+ uses `since` = the newest wrap seen minus two days, since NIP-59 back-dates wraps.
+2. **Ledger.** Every wrap goes into `GroupDmWrap`, keyed by id, with its state. Redelivery
+ is a no-op.
+3. **Wrap round.** For a new wrap, the device opens a round for `W` (D11) and sends its own
+ partial at once. The partial names the wrap by its id rather than carrying it (Phase 0,
+ check 6): every admin's device subscribes to the same wraps, and one wrap of a long
+ message is most of a relay's event on its own. A device that has not seen the wrap yet
+ holds the partial and answers when the wrap arrives.
+4. **Open the wrap.** At `t` valid partials: `d·W`, the conversation key, the seal. Verify
+ the seal's signature.
+5. **Seal round.** If `conv(group, S)` is kept, use it. Otherwise open a round for `S`,
+ carrying the seal as evidence.
+6. **Open the seal.** Check the rumor's pubkey is `S`, and file it in `GroupDmMessage`:
+ rumor id (unique), wrap id, sender, the rumor JSON, its time, and a conversation id (the
+ sorted set of the sender and the rumor's `p` tags, without the group, as NIP-17 defines
+ a chat). A rumor that is not kind 14 is filed as one this screen cannot show yet, not
+ dropped.
+
+Every admin's device runs all six steps and combines for itself, since each receives every
+partial. Nothing is decrypted once and passed round, so nothing but partials ever crosses
+the room.
+
+**History comes with the role.** `x` never changes. So a newly promoted admin's device can
+open any wrap still on the relays, by asking the other admins for partials like any other
+round. Unlike the NIP-4E plan, a promoted admin reads the group's past mail. Whether that is
+right is a decision, and D14 makes it.
+
+### D10. Writing: one seal per recipient, signed by the group, wrapped by the proposer
+
+An admin writing to a conversation, or to someone new, builds:
+
+```
+rumor kind 14, pubkey = the group's npub (the room id), unsigned
+ tags: ["p", ] …, and ["e", , , "reply"] for a reply
+ content: the text
+
+for each recipient R:
+ seal kind 13, pubkey = the group's npub, tags = []
+ content = nip44(rumor, conv(group, R)) conv from a kept key, or a round for R
+ created_at = now minus up to two days, at random (NIP-59)
+```
+
+The seals go to the quorum in one batch through `proposeSigningBatch`. Once the session
+completes, the proposer's device wraps each seal under a fresh key of its own, `p` = `R`,
+encrypted to `R`, and sends it to `R`'s 10050 relays, falling back to the publish set. That
+wrap is ordinary NIP-59: no group secret is involved. It is filed as owed and sent with
+backoff by a `GroupDmPublisher`. If the proposer's device is gone, any admin can **Send
+again**, since the signed seals are `GroupSignedEvent` rows on every signer's device.
+
+There is **no copy to the group itself**. NIP-17 suggests a sender wrap a copy to their own
+key so their other devices see it. Here that would mean ECDH with the group's own npub,
+which D5 forbids. It is not needed either: the signing session reaches every admin's device
+through the room, and that is where the group's sent messages are read from (D12).
+
+### D11. Rounds are keyed by the point, and settle themselves
+
+A round is `(room, generation, P)`. Its id is a hash of those three, so two devices that
+open a round for the same wrap open the same round. A partial message carries, per item,
+the round's point, the purpose, the evidence's reference, `Dᵢ` and the proof. A wrap and a
+seal are referenced by the wrap's id: every admin's device holds the wrap, and opens the
+same seal from it. Only a recipient's evidence (D10) is carried, since it is a small event
+no other device need have. Each device:
+
+- **batches**: every point it owes a partial for goes into one message per sync pass, not
+ one message per point, up to 16,000 bytes of plaintext (about thirty items) per message;
+- **answers** a round it has evidence for and has not answered, once (keyed by round and
+ participant id, as `DkgParticipantMessage` absorbs redelivery);
+- **combines** as soon as it holds `t` verified partials of the same generation;
+- **restarts at the new generation** a round a share refresh overtook. Partials of
+ different generations never combine, and a device answers only with its active share.
+
+There are no transcript lines for rounds. One per message the group is sent would bury the
+room. The inbox screen shows what is waiting, and on whom.
+
+### D12. Only admins see anything, including what the group sends
+
+A signing proposal reaches every member of the room. Its content is the unsigned seals,
+which are ciphertext. What the signers also need is which seal is for whom, and the
+evidence for each recipient's key. That rides as a proposal tag, NIP-44-encrypted once per
+current admin's host key (D4's channel):
+
+```
+["dm_manifest", , ] one per admin
+
+manifest:
+{"v":1,"seals":[{"recipient":"","evidence":}, …],
+ "replying_to":""}
+```
+
+A member who is not an admin sees that the group is signing so many seals, which is how
+many people the message goes to, and nothing else. An admin's device decrypts the manifest,
+opens each seal with the kept `conv(group, R)`, and files the message as outgoing in its
+conversation. That is how every admin sees what the group sent, whether or not they signed
+it.
+
+### D13. Every signer reads the message before signing it
+
+`GroupDmRefusal` joins `WalletRefusal`, `GroupStatementRefusal`, `GovernanceManager.refusalOf`
+and `ConfederationRefusal` in the four places: `acceptProposal`, the `approve` backstop,
+`publishDecline`'s reason, and the unshowable-session check. A signer:
+
+1. decrypts the manifest addressed to its host key. A signer that has none, or is not a
+ current admin, **declines** out loud ("This device can't read what the group would be
+ sending"). It is a share-holder outside D4's set, and signing what it cannot read is the
+ rubber stamp;
+2. checks every item is kind 13, authored by the room, with no tags;
+3. checks each recipient's evidence is validly signed by that recipient;
+4. gets `conv(group, R)` for each recipient, from its kept keys or by joining the
+ proposer's round for `R`. **Until it has them, the approval waits rather than
+ declining**, and the screen says it is waiting for the admins to compute the key;
+5. opens every seal and checks they hold the **same** rumor, byte for byte: kind 14,
+ pubkey the room, no signature, non-blank content, and `p` tags exactly the manifest's
+ recipients;
+6. checks each `created_at` is within two days before now and not in the future.
+
+A proposer who wrote one thing to one recipient and another thing to another, sealed to a
+key that is not the recipient's, or named a recipient the rumor does not, is declined by
+every honest signer. The approval screen shows the message, what it answers, and its
+recipients by name.
+
+### D14. Admin changes need nothing new, and a promoted admin reads the past
+
+- **A removal or demotion** takes effect for reading at once (D4), and for signing when the
+ share rotation the change already owes completes
+ ([admin-change-rotation.md](./admin-change-rotation.md)). When a device sees itself
+ removed, it wipes its kept conversation keys and opened messages for the room, and writes
+ a transcript line saying so. That is cooperation, not enforcement: what a removed admin
+ already read, they keep.
+- **A promotion** gives the new admin a share at an id (member-admin-promotion), and with it
+ the ability to answer and combine. Their device fetches the wraps still on the group's
+ relays and opens them like any others, so the group's history comes with the role.
+ **Recommended:** keep it that way. The admins are the group's correspondents, and an
+ admin who cannot see a conversation already under way cannot answer it. If the group
+ wants otherwise, D4's rule can be narrowed to "answer only for wraps created after the
+ requester's promotion". That is a policy every device can check, and it is listed under
+ *Out of scope* rather than built.
+
+### D15. Behind a flag
+
+`ExperimentalFeatures.groupDirectMessages`, `override ?: isDevelopmentBuild()`, as
+`confederation` and `shareRefresh` are. Since a group's admins hold shares only in a keyed
+room, and refresh is itself experimental, the flag stays off in release until the device
+run (Phase 11) has passed. The refusals in D8 and D13 run whatever the flag says, as every
+refusal does. A release build declines a peer's kind 13 proposal out loud rather than
+signing it blind.
+
+---
+
+## Against the NIP-4E plan
+
+| | threshold ECDH (this plan) | NIP-4E inbox key (`group-inbox.md`) |
+|---|---|---|
+| a sender on a stock NIP-17 app | **reaches the group** | does not: encrypts to the npub, which only this plan can open |
+| a recipient on a stock NIP-17 app | **reads the group's message** | may not: it has to read the seal's `n` tag |
+| reading a new message | when `t` admin devices have answered: they answer unasked, but only while their apps are open | at once, by any one admin |
+| one stolen admin phone | kept conversation keys only; no new message opens without `t` holders | the whole inbox, until the next rotation |
+| a removed admin | cut off from new mail at once | until the rotation's ceremony and announcement complete |
+| a promoted admin | reads the past (D14) | starts empty |
+| rotation | none: share refresh already does it | a ceremony and a signed 10044 per admin change |
+| spec | NIP-17 and NIP-44 as published | two open draft pull requests |
+| new cryptography | partials, a DLEQ proof, tweak replay | none (ChillDKG at `t = 1`) |
+
+The two compose. If both are built, a group that announces a 10044 reads 4E senders at once
+through the inbox key, and everyone else through this plan. Each pipeline subscribes to the
+same `#p`, so the ledger has to try the inbox key first and open a round only for what that
+key cannot open. This plan does not depend on the other and is written to stand alone.
+
+---
+
+## Who is asked what
+
+| step | who | asked? |
+|---|---|---|
+| open the group's messages (propose the 10050) | any admin | the button |
+| sign the 10050 | `t` holders | **yes: the group's decision to receive** (D7, D8) |
+| publish it | the proposer's device | no |
+| answer a partial | every admin's device, while open | no (D7) |
+| combine and read | every admin's device | no |
+| propose a message | any admin | the Send button |
+| answer the recipient's round | every admin's device | no |
+| sign the message's seals | `t` holders | **yes: each message** (D13) |
+| wrap and send it | the proposer's device | no |
+
+---
+
+## Phases
+
+One commit per phase, in the repository's style
+(`feat: … (group-threshold-ecdh, Phase n)`). Every phase leaves
+`./gradlew :composeApp:jvmTest` and `:composeApp:m3Audit` green, and `check`'s brand and
+wallet audits at budget.
+
+### Phase 0: this document, and six checks (done)
+
+`ThresholdEcdhPremiseJvmTest` keeps all six. What they found:
+
+| check | result |
+|---|---|
+| 1. ids | the evaluation point is the id plus one, as BIP 445 says; every 3-subset of a 3-of-5 dealer key rebuilds `x`, and the unshifted ids do not |
+| 2. tweaks | D2's replay reaches `Derived.publicKey` for forty dealer seeds, which between them meet both parities at all three steps |
+| 3. the conversation key | **holds.** Every 3-subset, either lift of `P`, gives quartz's `computeConversationKey(d, P)`, which equals the sender's side; the wrong sign of `a` gives another key |
+| 4. scalars | `times` and `plus` reduce mod `n`; Fermat's inverse works; **the `PrivateKey` constructor does not range-check**, so D3 calls `isValid()` |
+| 5. kinds | 30400 and 30401 are free in the NIP README, quartz, Bennu's tree, this one and `RetiredKinds` (30402 and 30403 are NIP-99's) |
+| 6. size | **D4 and D11 changed.** Sealing each payload per admin with the wrap as evidence was 918 KB for 20 items and 7 admins. The payload is now encrypted once under a key sealed per admin, and wraps and seals travel by reference: 20 items for 7 admins is 10.9 KB |
+
+The original text of the checks:
+
+This document and its row in [README.md](./README.md). Then, before code, as scratch
+jvmTests against bitcoin-kmp's `Frost.trustedDealerKeygen` (`B/crypto/frost/Frost.kt:313`),
+which gives a known `x` to check against:
+
+1. **Ids.** `KeyMaterial.publicSharesOf` indexes by a 0-based id
+ (`B/crypto/frost/Frost.kt:48`). Confirm the Shamir evaluation point is `id + 1`, as BIP
+ 445 specifies, by reconstructing the dealer's `x` from every `t`-subset with
+ Kotlin-computed `λᵢ`. If not, record the convention the library uses.
+2. **Tweaks** (D2). Replaying `Derived.tweaks` from `X` with D2's signs gives
+ `Derived.publicKey`, for a key where every step's `Qₖ` parity case occurs. Search dealer
+ seeds until one does, and pin that seed.
+3. **The conversation key.** For a dealer key, D2's `d`, and a random `P`:
+ `HKDF-extract("nip44-v2", x(a·Σλᵢsᵢ·P + b·P))` equals quartz's
+ `Nip44v2.computeConversationKey(d, P)`. This is the interoperability claim, tested in the
+ one place `d` may exist: a test with a throwaway key.
+4. **Scalars.** `PrivateKey.times` and `plus` reduce mod `n`. The inverse `λᵢ` needs is
+ computed as `v^(n−2)` by square-and-multiply over `times`. A hash at or above `n` is
+ rejected by the `PrivateKey` constructor rather than reduced, which is what D3 wants.
+5. **Kinds.** Two new kinds, candidates **30400** (partials) and **30401** (a round's
+ failure, for D3's blame). 30388 is reserved by the confederation
+ (`ConfederationRitualEvents.kt:34`), and the sibling plan proposes 30390–30396. Check the
+ candidates against the NIP README's table, quartz, Curare, Bennu and `RetiredKinds`, and
+ record the result.
+6. **Size.** A partial message for a batch of 20 points, sealed to 7 admins, fits an MLS
+ application message on the relays the app uses. If it does not, D11's batch is capped.
+
+If check 3 fails, stop. Every message would be unreadable, and the arithmetic needs
+another look before anything else.
+
+### Phase 1: pin today
+
+`GroupDmTodayJvmTest`, written to pass now and flipped on purpose:
+
+- a kind 1059 `p`-tagged to a group's npub is stored by `storeNostrEvent` and never opened
+ (Phase 7 flips it: the subscription hands it to the new pipeline, and the old path skips
+ it);
+- a peer's kind 13 and kind 10050 proposals reach the owner's approval prompt as "Event of
+ kind N" (Phases 6 and 10 turn them into declines unless they check out);
+- `live-group-dm` does not exist.
+
+### Phase 2: the arithmetic, alone
+
+No database, no wire. `K/crypto/threshold/`:
+
+- `Lagrange.coefficient(id, ids)` over the confirmed convention, with `inverse` by Fermat.
+- `NpubTweak.of(thresholdPublicKey, path)`: D2's `(a, b)`, checked against
+ `SharedKeyDerivation.derive`.
+- `EcdhPartial.compute(share, P)`, `Dleq.prove(share, Yᵢ, P, Dᵢ, context)` and
+ `Dleq.verify(...)`: D3.
+- `ThresholdEcdh.combine(partials, ids, tweak, P)`, which gives `d·P`, and
+ `ThresholdEcdh.conversationKey(point)`, which gives NIP-44's key.
+
+Tests (`ThresholdEcdhTest`, pure):
+
+- every `t`-subset of a 3-of-5 dealer key gives quartz's conversation key, and so does a
+ subset larger than `t`;
+- `t − 1` partials give a key that does not match;
+- a proof verifies, and fails for another point, another generation, another id, another
+ `Dᵢ`, and a swapped `c` or `z`;
+- the tweak replay matches `derive` in all parity cases;
+- `P` given as x-only lifts to the same key whichever parity is chosen.
+
+Nothing in `K/crypto/threshold/` may build `x` or `d`. A test reads the package's sources and
+fails on a call that sums `λᵢ·sᵢ` as scalars. It is crude, and it is the rule from
+[shared-key-derivation.md](./shared-key-derivation.md) made into a test.
+
+### Phase 3: the wire
+
+`K/nostr/groupdm/`:
+
+- `GroupEcdhEvents`: kind 30400, whose payload maps each admin's host key to a NIP-44
+ ciphertext of
+ `{"v":1,"generation":g,"from":id,"items":[{"point","purpose","evidence"?,"partial","proof"}]}`;
+ and kind 30401, a round's failure naming a participant whose proof failed.
+- `GroupDmWrap.open(wrap, convKey)`, `GroupDmSeal.open(seal, convKey)`, and
+ `GroupDmSeal.build(rumor, convKey, createdAt)`, unsigned.
+- `GroupDmManifest`: D12's JSON, sealed per admin, with a decoder that accepts only its own
+ encoding.
+- `GroupDmConversation.idOf(rumor)`.
+- `Evidence.check(purpose, P, event, groupNpub)`: D5's table, in one function, so the
+ answering device and the signer check the same thing.
+
+Tests (`GroupDmWireTest`, pure):
+
+- a wrap and seal built by quartz's stock `GiftWrapEvent.create` and `SealEvent.create`,
+ from a person to a dealer-key group, open through `ThresholdEcdh`;
+- a seal built here opens in quartz's stock `unsealOrNull` with the recipient's own key.
+ This is the claim that a stock app reads the group's messages;
+- evidence: a wrap not `p`-tagged to the group, an unsigned seal, the group's own npub as a
+ recipient, and an event signed by someone else are each refused.
+
+### Phase 4: storage, schema 44 → 45 (shipped as 46 → 47, below)
+
+Additive: an `AutoMigration(44, 45)` with its comment, the exported
+`composeApp/schemas/…/45.json`, and `ShippedProfileUpgradeJvmTest`'s `current` moved to 45.
+
+| table | key | holds |
+|---|---|---|
+| `GroupEcdhRound` | round id | room, generation, point, purpose, the evidence's JSON, state (`OPEN`, `COMBINED`, `FAILED`), opened at |
+| `GroupEcdhPartial` | `(round, participant id)` | `Dᵢ`, the proof, verified or not, received at |
+| `GroupConversationKey` | `(room, peer)` | the NIP-44 conversation key, computed at, the round it came from |
+| `GroupDmWrap` | wrap id | room, received at, state (`WAITING`, `OPENED`, `UNREADABLE`), the round |
+| `GroupDmMessage` | rumor id | room, wrap id or signing session, conversation id, sender, rumor JSON, created at, outgoing or not |
+| `GroupDmOutbound` | `(signing session, seal id)` | recipient, relays, the wrap once built, `publishedAt`, the backoff |
+
+`GroupConversationKey` holds secrets and is wiped as shares are. `GroupDmStorageJvmTest`:
+redelivery of a partial, wrap or rumor is a no-op, and wiping a room removes its keys and
+messages.
+
+### Phase 5: answering and combining (D3, D4, D5, D11)
+
+- `GroupEcdhManager`:
+ - `open(room, P, purpose, evidence)`: makes the round and owes this device's partial;
+ - `process(message)`: decrypts this device's slot, verifies each item's evidence and
+ proof, stores it, owes a partial for any round this device has not answered, and
+ combines where it can;
+ - `flush(room)`: sends every owed partial in one 30400;
+ - `onCombined`: hands the point to whoever opened the round (D9 or D10).
+- Inbound dispatch in `NostrDao.fileGroupEventResult`, beside the share refresh's arm.
+- The sweep: `SynchronizationViewModel` flushes and combines on each pass, as it resumes
+ ceremonies.
+- Generations: a refresh that completes marks open rounds of the old generation for restart.
+- Blame: a failed proof publishes a 30401 once per round and participant, and is shown in
+ the inbox's diagnostics.
+- Tests (`GroupEcdhRoundJvmTest`, the ritual harness with three admins at `t = 2` and a
+ member):
+ - two admins' partials give the same conversation key on all three admin devices;
+ - the member's device stores nothing it can read and combines nothing;
+ - a removed admin's device gets no slot in partials sent after the removal;
+ - a forged partial is named and the round completes with the third admin;
+ - a point without evidence is never answered;
+ - a refresh mid-round restarts it, and partials of two generations never combine.
+
+### Phase 6: the group's DM relays (D8)
+
+- `GroupDmRelayRefusal` in the four places. `ProposedEvent`'s 10050 arm: "Where the group
+ receives messages", with the relays.
+- The "Open the group's messages" row on the group's screen, for an admin of a keyed room
+ with no 10050. A setup screen shows the relays to edit, explains the decision, and
+ proposes. After that, a "Messages" row.
+- `ChatMessage.applyInnerEvent`'s 10050 arm: "The group can now receive messages" the first
+ time, and "The group changed where it receives messages" after.
+- `GroupDmRelayPublisher`, owed and with backoff. `BROADCASTABLE_KINDS` gains 10050.
+- Tests: `GroupDmRelaysJvmTest`. A signed 10050 is published unchanged and writes no
+ `NostrEvent` row; a 10050 listing a non-`wss` relay is declined with its reason. The
+ Phase 1 pin flips.
+
+### Phase 7: receiving (D9)
+
+- `live-group-dm` in `LiveSubscriptionManager`, re-sent as rooms gain or lose a 10050 or
+ this device's member gains or loses admin. Catch-up uses the two-day margin.
+ `indexNostrEvent` skips a wrap `p`-tagged to a room this device reads for.
+- `GroupDmReceiver`: the ledger, the wrap round, the seal round or kept key, and filing.
+- `DirectMessagePeerSync` fetches the 10050 and kind 0 of each correspondent, for D10's
+ relays, D5's evidence, and names on the screen.
+- **Rate.** Anyone can make the group's admins do work by sending wraps. The receiver opens
+ at most 60 new wrap rounds per room per hour, two batches' worth at Phase 0's size. Beyond that, wraps wait in the ledger, newest first, and the inbox says some
+ are queued. The group's 10050 relays are its first line here, which the setup screen says.
+- Tests (`GroupDmReceiveJvmTest`):
+ - a message from an outside identity, wrapped by quartz's stock code, opens on all three
+ admin devices once two have answered;
+ - a second message from the same sender takes one round;
+ - the same rumor in two wraps is one message;
+ - the member's device files nothing;
+ - a promoted admin's device opens a wrap from before their promotion;
+ - the rate cap queues rather than drops.
+ The Phase 1 wrap pin flips.
+
+### Phase 8: the messages, seen
+
+Routes and screens, each with a back button, `readableContent()`, the four states and
+`ScreenStateTransition`:
+
+- `GroupDmListScreen`: conversations, with names, the last line and an unread mark. A
+ "being opened" line for wraps waiting on admins, naming who has not answered yet. The
+ empty state says nobody has written yet. A queued count when the rate cap is reached.
+- `GroupDmConversationScreen`: messages in and out. Outgoing ones show their state: being
+ signed, signed, sent, or signed but not sent (with **Send again**).
+- The group's screen: the "Messages" row with its unread count, only where this device's
+ member is a current admin (D12). Members who are not admins see that the group receives
+ messages, since the 10050 is public, and nothing else.
+- Strings in sentence case from the catalogue, and nothing says "ECDH" to a person. The
+ waiting line reads "Waiting for 1 more admin to open this", not a protocol name.
+- Tests (`GroupDmScreenJvmTest`): the rows' presence by role, the empty and waiting states,
+ and Send again.
+
+### Phase 9: writing (D10, D12, D13)
+
+- `GroupDmDraft.build(room, recipients, text, replyTo)`: the rumor, the manifest, and a seal
+ per recipient from kept keys. A recipient without a kept key opens a round first, and the
+ composer shows "Preparing" until it combines.
+- The composer, under a conversation and from **New message** (paste or pick an npub; the
+ recipient's evidence is fetched, and the composer says when none can be found). It
+ proposes through `proposeSigningBatch` with the manifest tags, and says above the button
+ that the group's quorum has to sign before anything is sent.
+- `GroupDmRefusal` in the four places, with D13's checks, and the waiting-not-declining
+ behaviour for a signer still computing a key.
+- `ProposedEvent` for a batch of seals: on an admin's device, "A message from the group" with
+ the text and recipients; elsewhere, "A private message from the group".
+ `FrostSigningScreen` shows the text, what it answers, and the recipients.
+- `ChatMessage.applyInnerEvent`: a room-signed kind 13 draws nothing in the transcript. The
+ session's own lines already say the group signed, and naming the message would tell
+ members who are not admins.
+- `GroupDmPublisher`: on completion, on the proposer's device, wrap and send with backoff.
+ Every admin's device files the message as outgoing from the manifest.
+- Tests (`GroupDmSendJvmTest`):
+ - a message proposed by A and signed by B reaches the recipient's 10050 as stock NIP-17,
+ and opens with quartz's stock `unwrapAndUnsealOrNull` under the recipient's key;
+ - C sees it as outgoing;
+ - each D13 refusal on its own: mismatched seals, a seal to the wrong key, an extra
+ recipient, forged evidence, a blank message, a seal with tags, and a signer outside D4's
+ set. Each is declined with its reason, and the proposer's device shows the decline;
+ - a member's device reads the proposal as "A private message from the group" and learns
+ nothing more;
+ - a recipient written to before needs no round.
+ The Phase 1 kind 13 pin flips.
+
+### Phase 10: admin changes (D14)
+
+- The wipe on seeing oneself removed, with its transcript line.
+- `RoomAdmins` changes re-send the subscription and re-key D4's slot list at the next flush.
+- Tests (`GroupDmAdminChangeJvmTest`):
+ - after C's removal lands, a new message opens on A and B, and C's device gets no slot and
+ opens nothing;
+ - C's kept keys are wiped on C's device;
+ - after a promotion, the new admin's device answers rounds and reads the history;
+ - a share rotation after the removal leaves every kept key valid on A and B (D1).
+
+### Phase 11: the record, and devices
+
+- Mark this plan built, with a *what the plan said / what it turned out to be* table, and
+ update the README row.
+- A *since* note on [confederation.md](./confederation.md) D5: a group can now be written to
+ at its npub, through its admins' shares, where it has opened its messages. D5's seal stays
+ as it is.
+- Device run, three desktop clients or emulators in one keyed group at `t = 2`, a fourth
+ member who is not an admin, and an outside identity on a stock NIP-17 client (one that
+ knows nothing of Giza):
+ 1. A opens the group's messages; A and B sign the 10050; a public client shows it.
+ 2. The outside identity writes to the group's npub. With two of the three admin apps open,
+ the message appears on all three; D sees no messages row.
+ 3. B replies; A signs; the outside client shows the reply from the group's npub, and can
+ answer it.
+ 4. Close all but one admin app: a new message shows "Waiting for 1 more admin". Open a
+ second: it opens.
+ 5. Remove C as admin: the next message does not open on C's device; C's kept keys are gone.
+ 6. Promote D: D's device opens the conversation's history.
+ 7. The group writes first to a new npub; the outside client receives it.
+
+---
+
+## What the plan said, and what it turned out to be
+
+Built in eleven commits on top of `5ac4c053`, one or two per phase. The tests named in each
+phase exist and pass; `ThresholdEcdhPremiseJvmTest` keeps Phase 0's six checks.
+
+| the plan said | what was built | why |
+|---|---|---|
+| `K/crypto/threshold/` | `K/cryptography/threshold/` | the app already had a `cryptography` package |
+| D3: the `PrivateKey` constructor rejects a hash at or above `n` | it does not; `Dleq` calls `isValid()` on every hash it reads as a scalar | Phase 0, check 4 |
+| D4: each partial message's payload sealed once per admin | the payload is encrypted once under a fresh key, and only that key is sealed per admin (`AdminSeal`) | Phase 0, check 6: 918 KB for twenty items and seven admins |
+| D9, D11: the first partial carries the wrap as evidence | wraps and seals are named by the wrap's id; only a recipient's evidence travels | Phase 0, check 6: one wrap of a long message is most of a relay's event |
+| D11: a device answers a round once | a device answers once, and sends its partial *again* to an admin whose message shows it lacks it (each item lists the partials its sender holds, `have`) | Phase 7: an admin promoted after a round combined was never answered, because nobody answers a combined round |
+| D12: one `dm_manifest` tag per admin | one `dm_manifest` ciphertext and a `dm_slot` per admin, the same shape as the partials | `AdminSeal`, for the size reason above |
+| D13, check 4: the approval waits, and the signing screen says it is waiting for a key | the proposal is held unfiled and handed to the signing manager again when the recipient's round combines (`GroupDmSender.retryHeld`); nothing shows on the signer's device while it is held | the arrival check needs this device's nostr key to open the manifest, and a session filed as asked could be approved before it was read |
+| D13: a decline says which check failed | three reasons: `REASON` for any of D13's checks, `CANNOT_READ` for a device that is not a current admin or a batch with no manifest, `FEATURE_OFF` with the flag off. A decline published later, without the key to hand, gives the general one for an admin | `publishDecline` has no nostr key; the specific reason is in the log |
+| Phase 4: `GroupDmOutbound` for a message's wraps | it also carries the group's signed 10050, owed by the proposer (`recipient` is the group) | one publisher, `GroupDmPublisher`, for everything the group's mail owes relays |
+| Phase 6: the setup screen shows the relays to edit | one field, one `wss://` address per line, refused until every line is a public relay | |
+| Phase 7: `DirectMessagePeerSync` fetches each correspondent's 10050 and kind 0 | not built. Evidence and relays come from what the device already holds: a seal the person sent the group, or their kind 0, 10050, 10002 or 1 in the `NostrEvent` table. The composer says when there is none | the profile sync the app already runs fills the table for anyone the device has looked at |
+| Phase 7: the rate cap set from the batch size | 60 new wrap rounds per room per hour, two batches' worth | |
+| Phase 8: outgoing states and Send again | built in Phase 9, with the data they read: being signed, signed and not yet sent, sent, signed but not sent, declined. Send again is offered on any admin's device for the two unsent states | only the proposer's device wraps on its own, so another admin's cannot tell sent from not |
+| Phase 9: the signing screen shows the text, what it answers and the recipients | as notes under the seals, beside the confederation's (`DatabaseFrostSigningRepository.confederationNotes`) | the screen already had the slot |
+| Phase 10: the wipe on seeing oneself removed | on every sweep, and whenever partials still reach the device: keys, messages, wraps and rounds, the freed pages scrubbed, and one line in the room | |
+
+### Merged beside the group inbox
+
+The NIP-4E plan (`group-inbox.md`) was built on `giza` at the same time and merged first. The
+two now share the wire where they meet, as *Against the NIP-4E plan* said they would:
+
+| where they meet | what the merge settled |
+|---|---|
+| the schema | the inbox took versions 45 and 46 (with the confederation's signing); this plan's tables are **v47**, `AutoMigration(46, 47)` |
+| the group's 10050 | one event, whichever feature proposes it. `InboxRefusal` declines a relay list a stranger could not reach (`RELAYS_SHAPE`), `InboxAnnouncements.onSigned` publishes it from the proposer's device, and the transcript line and the signing screen's label are the inbox's. `GroupDmRelayRefusal` and this plan's own 10050 publishing were removed rather than run twice |
+| a batch of kind 13s | split on the seal's `n` tag, by the inbox's own reading of it: a seal naming one inbox key is a reply, for `InboxRefusal` and `InboxReplies`; every other seal is this plan's, for `GroupDmRefusal` and `GroupDmSender`. None is read by both and none is asked blind (`GroupSealRoutingJvmTest`) |
+| a wrap to the group's npub | both subscriptions hear it. `GroupDmReceiver` tries the inbox keys this device holds first and hands what they open to `GroupInboxManager`; a round is opened only for what they cannot. The inbox's count of mail it cannot open leaves out what the admins opened by threshold ECDH |
+
+### Known gaps
+
+- **No device run.** Phase 11's seven steps have not been done; the flag stays off in a release
+ until they have.
+- **A held proposal is invisible.** A signer whose device is still computing a recipient's key
+ sees nothing until it has; in practice the partials arrive before the proposal does.
+- **A device that is not the proposer cannot tell whether the message reached its recipients**,
+ only that the group signed it. Send again is how it makes sure.
+- **The rounds move only in the foreground**, as every ritual here does.
+- **A promoted admin reads the past** (D14), and narrowing that is out of scope.
+
+---
+
+## Risks
+
+| risk | what to do |
+|---|---|
+| D2's signs are wrong, and every key is wrong | Phase 0, check 3, against quartz's own key derivation; Phase 2 covers every parity case |
+| D3's proof is hand-written cryptography | about forty lines over libsecp256k1 calls, with no secret arithmetic outside it; tested for every way a proof can be wrong; reviewed before Phase 5 builds on it |
+| reading waits for `t` admin apps to be open | the cost of never putting the group's key in one place. The screen names who it waits on. Background sync is a separate plan for the whole app ([long-running-sync.md](./long-running-sync.md)) |
+| anyone can make the admins' devices work, and fill the room with partials, by sending wraps | D11's batching, Phase 7's rate cap, and the group's choice of relays in its 10050 |
+| the static Diffie-Hellman oracle | D5: only keys whose owner signed something, so no `x^k·G` can be asked for, and never the group's own npub |
+| a kept conversation key leaks with a stolen phone | it opens no new wrap without `t` holders (D6), and the phone is cut off once its owner is removed (D4). Not keeping keys would cost a round per message from known senders; keeping them is recommended |
+| members who are not admins see how many seals a message has, so how many recipients | stated in D12; padding with decoy seals is possible and not planned |
+| a promoted admin reads the past (D14) | a decision, made explicitly in D14 and reversible by policy |
+| a recipient's relays drop gift wraps from unknown keys | the wrap is stock NIP-59, so it fares like any NIP-17 message; Send again exists |
+| a Bennu admin answers nothing | the group still reads with `t` Giza admins; the waiting line names who has not answered |
+| NIP-17's sender copy is skipped (D10) | the group's sent messages live in its signing sessions, which reach every admin; a non-Giza client holding the group's key does not exist, so no other device misses the copy |
+
+---
+
+## Out of scope
+
+- **NIP-4E.** The sibling plan. *Against the NIP-4E plan* says how the two would meet.
+- **Narrowing a promoted admin's view to after their promotion** (D14).
+- **Kind 15 (files), reactions and edits.** Filed, and shown as a message this screen
+ cannot show yet.
+- **Notifications** for the group's new messages.
+- **Answering rounds in the background.** The app's sync runs in the foreground; this plan
+ inherits that.
+- **Decoy seals** to hide the number of recipients from members who are not admins.
+- **Threshold ECDH for anything else.** The confederation's seal, NIP-44 content for other
+ kinds, NIP-46. Each would widen D5's table, and each needs its own argument.
+- **The personal path's ignored 10050** (`NostrNip17Dao.kt:186-218`). Noticed, not fixed
+ here.
+
+---
+
+## Order and size
+
+| phase | rough size | depends on |
+|---|---|---|
+| 0 checks | scratch tests, this document | — |
+| 1 pin | ~150 test | 0 |
+| 2 arithmetic | ~350 main, ~500 test | 0 |
+| 3 wire | ~500 main, ~450 test | 2 |
+| 4 storage | ~400 main, ~200 test | 3 |
+| 5 rounds | ~900 main, ~700 test | 4 |
+| 6 relays | ~600 main, ~300 test | 1 |
+| 7 receiving | ~700 main, ~600 test | 5 and 6 |
+| 8 screens | ~1,200 main, ~300 test | 7 |
+| 9 writing | ~1,100 main, ~800 test | 5, 7 and 8 |
+| 10 admin changes | ~250 main, ~400 test | 9 |
+| 11 record | docs and a device session | all |
+
+Phase 6 touches none of Phases 2 to 5's files and can be built beside them. Everything else
+is in order: the arithmetic before anything rests on it, rounds before either direction,
+and reading before writing, because writing reuses the rounds and keys reading leaves
+behind.
+
+---
+
+## Checking the work
+
+```bash
+./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest
+```
+
+```bash
+./gradlew :composeApp:m3Audit
+```
+
+```bash
+./gradlew check
+```
+
+`wallet-audit.sh` greps for retired kinds and sats. None of 13, 14, 1059, 10050, 30400 or
+30401 is retired. `brand-audit.sh` fails on a Bennu name outside a comment, which the
+waiting line for a Bennu admin must not use: it names the admin, not their app.
diff --git a/docs/notifications-and-background-sync.md b/docs/notifications-and-background-sync.md
index 16da63b8..aa968de0 100644
--- a/docs/notifications-and-background-sync.md
+++ b/docs/notifications-and-background-sync.md
@@ -25,7 +25,7 @@ restart, which is why the background sync serves one profile (D6).
2026-11-22, one commit per phase (`5683199c` to the commit that adds this header; Phase 10 is two).
The background half is behind `ExperimentalFeatures.backgroundSync`, on in development builds and
off in release; read state and notifications while the app runs are not flagged. jvmTest 1,774, all
-passing; `m3Audit`, `brandAudit` and `walletAudit` at their budgets; `compileDebugKotlinAndroid`
+passing (1,837 after merging `giza`); `m3Audit`, `brandAudit` and `walletAudit` at their budgets; `compileDebugKotlinAndroid`
builds and the debug manifest merges; `./gradlew check` passes. The phases are kept as written, because they are the
reasoning. Where the build chose differently:
@@ -34,8 +34,8 @@ reasoning. Where the build chose differently:
| Phase 2: `SyncEngine` and `OutboundEngine` moved out of their view models | **the view models stay, built once by `GizaRuntime`.** Neither ever used `viewModelScope` -- both run on the scope they are given -- so constructing them outside a `ViewModelStore` changed nothing about how they run, and a 950-line move bought nothing. `GizaRuntime.synchronization` and `.notary` are them |
| (not in the plan) | **`SovereignWalletViewModel` resets the identity to null when it is created.** The flow it writes is the runtime's now and outlives an activity, so an activity recreated over a living process would otherwise start with the last one's identity set and skip the startup that chooses it |
| Phase 2: `IdentityStore`, extracted from `listIdentities` | `DefaultIdentity.load` (Phase 9), the reading half only: no key-file migration and no credential repair, which belong to a launch somebody is watching. A seed missing its credential is still found by derivation |
-| Phase 3: a manual `Migration(46, 47)` | an `AutoMigration` with `ReadMarkMigrationSpec`, whose `onPostMigrate` runs the `UPDATE`. Room generates the shape |
-| Phase 5: the switches in the identity's `UserPrefs` | **on `NotificationLedger`**, folded into schema 47 (which has not shipped) in Phase 5. `UserPrefs` lives in the wallet library's submodule. Before an identity is armed there is no row, and the settings screen says why there is nothing to set |
+| Phase 3: a manual `Migration(46, 47)` | an `AutoMigration` with `ReadMarkMigrationSpec`, whose `onPostMigrate` runs the `UPDATE`. Room generates the shape. **47 → 48** since the merge: the group's direct messages (docs/group-threshold-ecdh.md) took 47 on `giza` first, as the phase said might happen |
+| Phase 5: the switches in the identity's `UserPrefs` | **on `NotificationLedger`**, folded into the notifications schema (47 when built, 48 since the merge; neither has shipped) in Phase 5. `UserPrefs` lives in the wallet library's submodule. Before an identity is armed there is no row, and the settings screen says why there is nothing to set |
| D7: approval lines are someone else's | **they are written as the user's own** (`isUserMessage = true`, from `announce`'s actor), so the classifier exempts Needs you from the own-line rule, and the policy never drops one as already read. `NotificationClassifierJvmTest` pins both |
| D9: hide every line's text when Show message text is off | only a message's. A Needs you or Group activity line is the app's own sentence, never what anybody wrote |
| D3: armed after the first sync settles | armed once the identity's negentropy queue has been empty for **30 seconds without a break** -- the only signal that a first sync is over. Arming also marks every room read up to its newest line, so a new device starts with nothing unread |
@@ -53,6 +53,7 @@ reasoning. Where the build chose differently:
| Phase 12: Open Giza, Mute all for an hour, Quit | **Open window** and **Quit**. `m3-title-case.py` reads "Open Giza" as title case; muting everything for an hour is the master switch already |
| Phase 13: a reply runs the outbound engine | through `BackgroundSyncPass.withProfile`, under the pass's own lock so a reply and a sync never activate and deactivate the profile under each other. A reply for a profile other than the default, or than the one open, is refused, not sent as somebody else |
| Phase 15 | not built |
+| (not in the plan) | merging `giza` brought `TYPE_GROUP_DM_FORGOTTEN`, which `NotificationClassifierJvmTest` refused until it was placed: silent, as `TYPE_INBOX_FORGOTTEN` is. The test doing what it was written for |
| (not in the plan) | the worktree's build needed `lightning-kmp-app` and its nested submodules initialised from the main checkout's copies, with their `local.properties` and the prebuilt native secp256k1 |
**Not done:**