diff --git a/CLAUDE.md b/CLAUDE.md index de0cd4b0..cbac2c8e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,7 +81,7 @@ say — marks itself once at the top: ``` **Budget: 0 title-case strings.** Literals in composables are reported without a budget — -39 remain, all of them terms of a `+` concatenation. +19 remain, all of them terms of a `+` concatenation. ## Every target is 48dp, and every icon has a decided description diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json index ab7e8977..21f24e7b 100644 --- a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 27, - "identityHash": "daabaf0818bccb5c97f884214e88674b", + "identityHash": "b3d7bf2b5f251ad1f39aeb01c7ab316d", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -1986,221 +1986,6 @@ } ] }, - { - "tableName": "IcebergKeySession", - "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 NOT NULL, `onchainDkgSessionId` TEXT NOT NULL, `stage` TEXT NOT NULL, `root` TEXT, `share` TEXT, `groupPublicKey` TEXT, `publicShares` TEXT, `joinApprovedAt` INTEGER, `revealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `failureReason` 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": "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", - "notNull": true - }, - { - "fieldPath": "onchainDkgSessionId", - "columnName": "onchainDkgSessionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "stage", - "columnName": "stage", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "root", - "columnName": "root", - "affinity": "TEXT" - }, - { - "fieldPath": "share", - "columnName": "share", - "affinity": "TEXT" - }, - { - "fieldPath": "groupPublicKey", - "columnName": "groupPublicKey", - "affinity": "TEXT" - }, - { - "fieldPath": "publicShares", - "columnName": "publicShares", - "affinity": "TEXT" - }, - { - "fieldPath": "joinApprovedAt", - "columnName": "joinApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "revealApprovedAt", - "columnName": "revealApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "confirmApprovedAt", - "columnName": "confirmApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "approvalRequestedThrough", - "columnName": "approvalRequestedThrough", - "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_IcebergKeySession_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergKeySession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "IcebergParticipantMessage", - "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 `IcebergKeySession`(`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_IcebergParticipantMessage_sessionId", - "unique": false, - "columnNames": [ - "sessionId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" - } - ], - "foreignKeys": [ - { - "table": "IcebergKeySession", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "sessionId" - ], - "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 )", @@ -2326,1407 +2111,6 @@ } ] }, - { - "tableName": "MantraArtifact", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `visibility` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `license` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "url", - "columnName": "url", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `versionLabel` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactId`) REFERENCES `MantraArtifact`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactId", - "columnName": "artifactId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "versionLabel", - "columnName": "versionLabel", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifact", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `originalText` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "originalText", - "columnName": "originalText", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraDialect", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `country` TEXT NOT NULL, `language` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` 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": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "country", - "columnName": "country", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "language", - "columnName": "language", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslation", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChunkId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `text` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChunkId`) REFERENCES `MantraTranslationChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChunkId", - "columnName": "translationChunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `name` TEXT NOT NULL, `visibility` TEXT NOT NULL, `license` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersionContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `editorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersionContributor`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "editorPublicKey", - "columnName": "editorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersionContributor", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapterContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `role` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "role", - "columnName": "role", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chunkId` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chunkId`) REFERENCES `MantraChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chunkId", - "columnName": "chunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dTag` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationId`) REFERENCES `MantraTranslation`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "dTag", - "columnName": "dTag", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationId", - "columnName": "translationId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslation", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "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`))", @@ -3926,7 +2310,7 @@ }, { "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, `payloadEventId` 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 )", + "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", @@ -3969,11 +2353,6 @@ "columnName": "quotedEventId", "affinity": "TEXT" }, - { - "fieldPath": "payloadEventId", - "columnName": "payloadEventId", - "affinity": "TEXT" - }, { "fieldPath": "marmotGroupEventId", "columnName": "marmotGroupEventId", @@ -6179,7 +4558,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, 'daabaf0818bccb5c97f884214e88674b')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'b3d7bf2b5f251ad1f39aeb01c7ab316d')" ] } } \ No newline at end of file diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/28.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/28.json index 821326a4..cd7b208f 100644 --- a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/28.json +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/28.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 28, - "identityHash": "d654728642ae147f8a1128ac3dfeb50b", + "identityHash": "b81b7b97c63fabcda1c21865b7b8c0e7", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -1739,85 +1739,6 @@ } ] }, - { - "tableName": "GroupLightningSeed", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `nodeId` TEXT NOT NULL, `chain` TEXT NOT NULL, `wallet` INTEGER NOT NULL, `seed` TEXT NOT NULL, `sentBy` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `nodeId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", - "fields": [ - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "nodeId", - "columnName": "nodeId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chain", - "columnName": "chain", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "seed", - "columnName": "seed", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "sentBy", - "columnName": "sentBy", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "receivedAt", - "columnName": "receivedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "chatRoomId", - "nodeId" - ] - }, - "indices": [ - { - "name": "index_GroupLightningSeed_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupLightningSeed_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "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 )", @@ -1944,7 +1865,7 @@ }, { "tableName": "GroupTransaction", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `guardedChatRoomId` TEXT, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "frostSigningSessionId", @@ -1970,6 +1891,11 @@ "affinity": "INTEGER", "notNull": true }, + { + "fieldPath": "guardedChatRoomId", + "columnName": "guardedChatRoomId", + "affinity": "TEXT" + }, { "fieldPath": "psbt", "columnName": "psbt", @@ -2065,221 +1991,6 @@ } ] }, - { - "tableName": "IcebergKeySession", - "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 NOT NULL, `onchainDkgSessionId` TEXT NOT NULL, `stage` TEXT NOT NULL, `root` TEXT, `share` TEXT, `groupPublicKey` TEXT, `publicShares` TEXT, `joinApprovedAt` INTEGER, `revealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `failureReason` 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": "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", - "notNull": true - }, - { - "fieldPath": "onchainDkgSessionId", - "columnName": "onchainDkgSessionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "stage", - "columnName": "stage", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "root", - "columnName": "root", - "affinity": "TEXT" - }, - { - "fieldPath": "share", - "columnName": "share", - "affinity": "TEXT" - }, - { - "fieldPath": "groupPublicKey", - "columnName": "groupPublicKey", - "affinity": "TEXT" - }, - { - "fieldPath": "publicShares", - "columnName": "publicShares", - "affinity": "TEXT" - }, - { - "fieldPath": "joinApprovedAt", - "columnName": "joinApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "revealApprovedAt", - "columnName": "revealApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "confirmApprovedAt", - "columnName": "confirmApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "approvalRequestedThrough", - "columnName": "approvalRequestedThrough", - "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_IcebergKeySession_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergKeySession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "IcebergParticipantMessage", - "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 `IcebergKeySession`(`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_IcebergParticipantMessage_sessionId", - "unique": false, - "columnNames": [ - "sessionId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" - } - ], - "foreignKeys": [ - { - "table": "IcebergKeySession", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "sessionId" - ], - "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 )", @@ -2405,1407 +2116,6 @@ } ] }, - { - "tableName": "MantraArtifact", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `visibility` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `license` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "url", - "columnName": "url", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `versionLabel` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactId`) REFERENCES `MantraArtifact`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactId", - "columnName": "artifactId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "versionLabel", - "columnName": "versionLabel", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifact", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `originalText` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "originalText", - "columnName": "originalText", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraDialect", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `country` TEXT NOT NULL, `language` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` 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": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "country", - "columnName": "country", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "language", - "columnName": "language", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslation", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChunkId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `text` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChunkId`) REFERENCES `MantraTranslationChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChunkId", - "columnName": "translationChunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `name` TEXT NOT NULL, `visibility` TEXT NOT NULL, `license` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersionContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `editorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersionContributor`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "editorPublicKey", - "columnName": "editorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersionContributor", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapterContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `role` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "role", - "columnName": "role", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chunkId` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chunkId`) REFERENCES `MantraChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chunkId", - "columnName": "chunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dTag` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationId`) REFERENCES `MantraTranslation`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "dTag", - "columnName": "dTag", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationId", - "columnName": "translationId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslation", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "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`))", @@ -4005,7 +2315,7 @@ }, { "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, `payloadEventId` 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 )", + "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", @@ -4048,11 +2358,6 @@ "columnName": "quotedEventId", "affinity": "TEXT" }, - { - "fieldPath": "payloadEventId", - "columnName": "payloadEventId", - "affinity": "TEXT" - }, { "fieldPath": "marmotGroupEventId", "columnName": "marmotGroupEventId", @@ -6258,7 +4563,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, 'd654728642ae147f8a1128ac3dfeb50b')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'b81b7b97c63fabcda1c21865b7b8c0e7')" ] } } \ No newline at end of file diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/29.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/29.json index 709631c2..eedb09be 100644 --- a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/29.json +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/29.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 29, - "identityHash": "3d7cecc660080662defcb7612d40e230", + "identityHash": "9fb0ffd54bd2d67d1790f97b8bd644b0", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -855,7 +855,7 @@ }, { "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, `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 )", + "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", @@ -903,6 +903,11 @@ "columnName": "subject", "affinity": "TEXT" }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, { "fieldPath": "stage", "columnName": "stage", @@ -1739,85 +1744,6 @@ } ] }, - { - "tableName": "GroupLightningSeed", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `nodeId` TEXT NOT NULL, `chain` TEXT NOT NULL, `wallet` INTEGER NOT NULL, `seed` TEXT NOT NULL, `sentBy` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `nodeId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", - "fields": [ - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "nodeId", - "columnName": "nodeId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chain", - "columnName": "chain", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "seed", - "columnName": "seed", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "sentBy", - "columnName": "sentBy", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "receivedAt", - "columnName": "receivedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "chatRoomId", - "nodeId" - ] - }, - "indices": [ - { - "name": "index_GroupLightningSeed_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupLightningSeed_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "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 )", @@ -1944,7 +1870,7 @@ }, { "tableName": "GroupTransaction", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `guardedChatRoomId` TEXT, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "frostSigningSessionId", @@ -1970,6 +1896,11 @@ "affinity": "INTEGER", "notNull": true }, + { + "fieldPath": "guardedChatRoomId", + "columnName": "guardedChatRoomId", + "affinity": "TEXT" + }, { "fieldPath": "psbt", "columnName": "psbt", @@ -2065,518 +1996,6 @@ } ] }, - { - "tableName": "IcebergBudgetSpend", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `paymentHash` TEXT NOT NULL, `consumedMsat` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `paymentHash`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "paymentHash", - "columnName": "paymentHash", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "consumedMsat", - "columnName": "consumedMsat", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "paymentHash" - ] - } - }, - { - "tableName": "IcebergChannelLedger", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `channelId` TEXT NOT NULL, `fundingOutPoint` TEXT NOT NULL, `remoteFundingPubKey` TEXT NOT NULL, `ledger` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `channelId`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "channelId", - "columnName": "channelId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "fundingOutPoint", - "columnName": "fundingOutPoint", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "remoteFundingPubKey", - "columnName": "remoteFundingPubKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "ledger", - "columnName": "ledger", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "updatedAt", - "columnName": "updatedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "channelId" - ] - } - }, - { - "tableName": "IcebergEchoRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `label` TEXT NOT NULL, `participant` TEXT NOT NULL, `messageHash` TEXT NOT NULL, PRIMARY KEY(`wallet`, `label`, `participant`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "label", - "columnName": "label", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "participant", - "columnName": "participant", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "messageHash", - "columnName": "messageHash", - "affinity": "TEXT", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "label", - "participant" - ] - } - }, - { - "tableName": "IcebergKeySession", - "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 NOT NULL, `onchainDkgSessionId` TEXT NOT NULL, `stage` TEXT NOT NULL, `root` TEXT, `share` TEXT, `groupPublicKey` TEXT, `publicShares` TEXT, `joinApprovedAt` INTEGER, `revealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `failureReason` 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": "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", - "notNull": true - }, - { - "fieldPath": "onchainDkgSessionId", - "columnName": "onchainDkgSessionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "stage", - "columnName": "stage", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "root", - "columnName": "root", - "affinity": "TEXT" - }, - { - "fieldPath": "share", - "columnName": "share", - "affinity": "TEXT" - }, - { - "fieldPath": "groupPublicKey", - "columnName": "groupPublicKey", - "affinity": "TEXT" - }, - { - "fieldPath": "publicShares", - "columnName": "publicShares", - "affinity": "TEXT" - }, - { - "fieldPath": "joinApprovedAt", - "columnName": "joinApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "revealApprovedAt", - "columnName": "revealApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "confirmApprovedAt", - "columnName": "confirmApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "approvalRequestedThrough", - "columnName": "approvalRequestedThrough", - "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_IcebergKeySession_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergKeySession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "IcebergLabelAssignment", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `counter` INTEGER NOT NULL, `label` TEXT NOT NULL, `purpose` TEXT NOT NULL, `assignedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `counter`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "counter", - "columnName": "counter", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "label", - "columnName": "label", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "purpose", - "columnName": "purpose", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "assignedAt", - "columnName": "assignedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "counter" - ] - }, - "indices": [ - { - "name": "index_IcebergLabelAssignment_wallet_purpose", - "unique": false, - "columnNames": [ - "wallet", - "purpose" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergLabelAssignment_wallet_purpose` ON `${TABLE_NAME}` (`wallet`, `purpose`)" - } - ] - }, - { - "tableName": "IcebergLabelLedger", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `label` TEXT NOT NULL, `requestId` TEXT NOT NULL, `messageHash` TEXT NOT NULL, `echoedAt` INTEGER NOT NULL, `signedAt` INTEGER, PRIMARY KEY(`wallet`, `label`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "label", - "columnName": "label", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "requestId", - "columnName": "requestId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "messageHash", - "columnName": "messageHash", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "echoedAt", - "columnName": "echoedAt", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signedAt", - "columnName": "signedAt", - "affinity": "INTEGER" - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "label" - ] - } - }, - { - "tableName": "IcebergNonceRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `counter` INTEGER NOT NULL, `participant` TEXT NOT NULL, `contribution` TEXT NOT NULL, PRIMARY KEY(`wallet`, `counter`, `participant`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "counter", - "columnName": "counter", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "participant", - "columnName": "participant", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "contribution", - "columnName": "contribution", - "affinity": "TEXT", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "counter", - "participant" - ] - } - }, - { - "tableName": "IcebergParticipantMessage", - "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 `IcebergKeySession`(`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_IcebergParticipantMessage_sessionId", - "unique": false, - "columnNames": [ - "sessionId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" - } - ], - "foreignKeys": [ - { - "table": "IcebergKeySession", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "sessionId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "IcebergShareRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `requestId` TEXT NOT NULL, `participant` TEXT NOT NULL, `share` TEXT NOT NULL, PRIMARY KEY(`wallet`, `requestId`, `participant`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "requestId", - "columnName": "requestId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "participant", - "columnName": "participant", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "share", - "columnName": "share", - "affinity": "TEXT", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "requestId", - "participant" - ] - } - }, { "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 )", @@ -2702,1407 +2121,6 @@ } ] }, - { - "tableName": "MantraArtifact", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `visibility` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `license` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "url", - "columnName": "url", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `versionLabel` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactId`) REFERENCES `MantraArtifact`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactId", - "columnName": "artifactId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "versionLabel", - "columnName": "versionLabel", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifact", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `originalText` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "originalText", - "columnName": "originalText", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraDialect", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `country` TEXT NOT NULL, `language` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` 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": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "country", - "columnName": "country", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "language", - "columnName": "language", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslation", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChunkId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `text` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChunkId`) REFERENCES `MantraTranslationChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChunkId", - "columnName": "translationChunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `name` TEXT NOT NULL, `visibility` TEXT NOT NULL, `license` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersionContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `editorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersionContributor`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "editorPublicKey", - "columnName": "editorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersionContributor", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapterContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `role` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "role", - "columnName": "role", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chunkId` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chunkId`) REFERENCES `MantraChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chunkId", - "columnName": "chunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dTag` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationId`) REFERENCES `MantraTranslation`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "dTag", - "columnName": "dTag", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationId", - "columnName": "translationId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslation", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "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`))", @@ -4302,7 +2320,7 @@ }, { "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, `payloadEventId` 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 )", + "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", @@ -4345,11 +2363,6 @@ "columnName": "quotedEventId", "affinity": "TEXT" }, - { - "fieldPath": "payloadEventId", - "columnName": "payloadEventId", - "affinity": "TEXT" - }, { "fieldPath": "marmotGroupEventId", "columnName": "marmotGroupEventId", @@ -6555,7 +4568,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, '3d7cecc660080662defcb7612d40e230')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '9fb0ffd54bd2d67d1790f97b8bd644b0')" ] } } \ No newline at end of file diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/30.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/30.json index b56b58d5..de9606ce 100644 --- a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/30.json +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/30.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 30, - "identityHash": "1c1d38fb933b34767085c3d595c09815", + "identityHash": "47aa631ec4032d9b2c00bf0b38689864", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -855,7 +855,7 @@ }, { "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, `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 )", + "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", @@ -903,6 +903,11 @@ "columnName": "subject", "affinity": "TEXT" }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, { "fieldPath": "stage", "columnName": "stage", @@ -1739,234 +1744,6 @@ } ] }, - { - "tableName": "GroupLightningInvoiceRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `requestId` TEXT NOT NULL, `bolt11` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `requestId`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "requestId", - "columnName": "requestId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "bolt11", - "columnName": "bolt11", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "receivedAt", - "columnName": "receivedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "requestId" - ] - } - }, - { - "tableName": "GroupLightningPaymentRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `id` TEXT NOT NULL, `incoming` INTEGER NOT NULL, `amountMsat` INTEGER NOT NULL, `feesMsat` INTEGER NOT NULL, `paymentHash` TEXT, `description` TEXT, `completedAt` INTEGER, `succeeded` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `id`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "id", - "columnName": "id", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "incoming", - "columnName": "incoming", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "amountMsat", - "columnName": "amountMsat", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "feesMsat", - "columnName": "feesMsat", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "paymentHash", - "columnName": "paymentHash", - "affinity": "TEXT" - }, - { - "fieldPath": "description", - "columnName": "description", - "affinity": "TEXT" - }, - { - "fieldPath": "completedAt", - "columnName": "completedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "succeeded", - "columnName": "succeeded", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "id" - ] - } - }, - { - "tableName": "GroupLightningSeed", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `nodeId` TEXT NOT NULL, `chain` TEXT NOT NULL, `wallet` INTEGER NOT NULL, `seed` TEXT NOT NULL, `sentBy` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `nodeId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", - "fields": [ - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "nodeId", - "columnName": "nodeId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chain", - "columnName": "chain", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "seed", - "columnName": "seed", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "sentBy", - "columnName": "sentBy", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "receivedAt", - "columnName": "receivedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "chatRoomId", - "nodeId" - ] - }, - "indices": [ - { - "name": "index_GroupLightningSeed_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupLightningSeed_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "GroupLightningSnapshotRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `sentBy` TEXT NOT NULL, `term` INTEGER NOT NULL, `content` TEXT NOT NULL, `sentAt` INTEGER NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "sentBy", - "columnName": "sentBy", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "term", - "columnName": "term", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "content", - "columnName": "content", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "sentAt", - "columnName": "sentAt", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "receivedAt", - "columnName": "receivedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet" - ] - } - }, { "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 )", @@ -2093,7 +1870,7 @@ }, { "tableName": "GroupTransaction", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `guardedChatRoomId` TEXT, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "frostSigningSessionId", @@ -2119,6 +1896,11 @@ "affinity": "INTEGER", "notNull": true }, + { + "fieldPath": "guardedChatRoomId", + "columnName": "guardedChatRoomId", + "affinity": "TEXT" + }, { "fieldPath": "psbt", "columnName": "psbt", @@ -2214,518 +1996,6 @@ } ] }, - { - "tableName": "IcebergBudgetSpend", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `paymentHash` TEXT NOT NULL, `consumedMsat` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `paymentHash`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "paymentHash", - "columnName": "paymentHash", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "consumedMsat", - "columnName": "consumedMsat", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "paymentHash" - ] - } - }, - { - "tableName": "IcebergChannelLedger", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `channelId` TEXT NOT NULL, `fundingOutPoint` TEXT NOT NULL, `remoteFundingPubKey` TEXT NOT NULL, `ledger` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `channelId`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "channelId", - "columnName": "channelId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "fundingOutPoint", - "columnName": "fundingOutPoint", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "remoteFundingPubKey", - "columnName": "remoteFundingPubKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "ledger", - "columnName": "ledger", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "updatedAt", - "columnName": "updatedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "channelId" - ] - } - }, - { - "tableName": "IcebergEchoRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `label` TEXT NOT NULL, `participant` TEXT NOT NULL, `messageHash` TEXT NOT NULL, PRIMARY KEY(`wallet`, `label`, `participant`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "label", - "columnName": "label", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "participant", - "columnName": "participant", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "messageHash", - "columnName": "messageHash", - "affinity": "TEXT", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "label", - "participant" - ] - } - }, - { - "tableName": "IcebergKeySession", - "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 NOT NULL, `onchainDkgSessionId` TEXT NOT NULL, `stage` TEXT NOT NULL, `root` TEXT, `share` TEXT, `groupPublicKey` TEXT, `publicShares` TEXT, `joinApprovedAt` INTEGER, `revealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `failureReason` 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": "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", - "notNull": true - }, - { - "fieldPath": "onchainDkgSessionId", - "columnName": "onchainDkgSessionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "stage", - "columnName": "stage", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "root", - "columnName": "root", - "affinity": "TEXT" - }, - { - "fieldPath": "share", - "columnName": "share", - "affinity": "TEXT" - }, - { - "fieldPath": "groupPublicKey", - "columnName": "groupPublicKey", - "affinity": "TEXT" - }, - { - "fieldPath": "publicShares", - "columnName": "publicShares", - "affinity": "TEXT" - }, - { - "fieldPath": "joinApprovedAt", - "columnName": "joinApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "revealApprovedAt", - "columnName": "revealApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "confirmApprovedAt", - "columnName": "confirmApprovedAt", - "affinity": "INTEGER" - }, - { - "fieldPath": "approvalRequestedThrough", - "columnName": "approvalRequestedThrough", - "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_IcebergKeySession_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergKeySession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - } - ], - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "IcebergLabelAssignment", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `counter` INTEGER NOT NULL, `label` TEXT NOT NULL, `purpose` TEXT NOT NULL, `assignedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `counter`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "counter", - "columnName": "counter", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "label", - "columnName": "label", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "purpose", - "columnName": "purpose", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "assignedAt", - "columnName": "assignedAt", - "affinity": "INTEGER", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "counter" - ] - }, - "indices": [ - { - "name": "index_IcebergLabelAssignment_wallet_purpose", - "unique": false, - "columnNames": [ - "wallet", - "purpose" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergLabelAssignment_wallet_purpose` ON `${TABLE_NAME}` (`wallet`, `purpose`)" - } - ] - }, - { - "tableName": "IcebergLabelLedger", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `label` TEXT NOT NULL, `requestId` TEXT NOT NULL, `messageHash` TEXT NOT NULL, `echoedAt` INTEGER NOT NULL, `signedAt` INTEGER, PRIMARY KEY(`wallet`, `label`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "label", - "columnName": "label", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "requestId", - "columnName": "requestId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "messageHash", - "columnName": "messageHash", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "echoedAt", - "columnName": "echoedAt", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signedAt", - "columnName": "signedAt", - "affinity": "INTEGER" - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "label" - ] - } - }, - { - "tableName": "IcebergNonceRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `counter` INTEGER NOT NULL, `participant` TEXT NOT NULL, `contribution` TEXT NOT NULL, PRIMARY KEY(`wallet`, `counter`, `participant`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "counter", - "columnName": "counter", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "participant", - "columnName": "participant", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "contribution", - "columnName": "contribution", - "affinity": "TEXT", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "counter", - "participant" - ] - } - }, - { - "tableName": "IcebergParticipantMessage", - "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 `IcebergKeySession`(`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_IcebergParticipantMessage_sessionId", - "unique": false, - "columnNames": [ - "sessionId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" - } - ], - "foreignKeys": [ - { - "table": "IcebergKeySession", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "sessionId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "IcebergShareRow", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `requestId` TEXT NOT NULL, `participant` TEXT NOT NULL, `share` TEXT NOT NULL, PRIMARY KEY(`wallet`, `requestId`, `participant`))", - "fields": [ - { - "fieldPath": "wallet", - "columnName": "wallet", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "requestId", - "columnName": "requestId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "participant", - "columnName": "participant", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "share", - "columnName": "share", - "affinity": "TEXT", - "notNull": true - } - ], - "primaryKey": { - "autoGenerate": false, - "columnNames": [ - "wallet", - "requestId", - "participant" - ] - } - }, { "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 )", @@ -2851,1407 +2121,6 @@ } ] }, - { - "tableName": "MantraArtifact", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `visibility` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `license` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "url", - "columnName": "url", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `versionLabel` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactId`) REFERENCES `MantraArtifact`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactId", - "columnName": "artifactId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "versionLabel", - "columnName": "versionLabel", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifact", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `originalText` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "originalText", - "columnName": "originalText", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "wordCount", - "columnName": "wordCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "characterCount", - "columnName": "characterCount", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraDialect", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `country` TEXT NOT NULL, `language` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` 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": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "country", - "columnName": "country", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "language", - "columnName": "language", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslation", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChunkId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `text` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChunkId`) REFERENCES `MantraTranslationChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChunkId", - "columnName": "translationChunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersion", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `name` TEXT NOT NULL, `visibility` TEXT NOT NULL, `license` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "artifactVersionId", - "columnName": "artifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "dialectId", - "columnName": "dialectId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "name", - "columnName": "name", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "visibility", - "columnName": "visibility", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "license", - "columnName": "license", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "artifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraDialect", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "dialectId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationArtifactVersionContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `editorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersionContributor`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "editorPublicKey", - "columnName": "editorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersionContributor", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapter", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chapterId", - "columnName": "chapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationArtifactVersionId", - "columnName": "translationArtifactVersionId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationArtifactVersion", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationArtifactVersionId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChapterContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `role` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "role", - "columnName": "role", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationChunk", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chunkId` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chunkId`) REFERENCES `MantraChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chunkId", - "columnName": "chunkId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationChapterId", - "columnName": "translationChapterId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "text", - "columnName": "text", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "index", - "columnName": "index", - "affinity": "INTEGER", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraChunk", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chunkId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "MantraTranslationChapter", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationChapterId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } - ] - }, - { - "tableName": "MantraTranslationContributor", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dTag` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationId`) REFERENCES `MantraTranslation`(`id`) 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": "TEXT", - "notNull": true - }, - { - "fieldPath": "dTag", - "columnName": "dTag", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "publicKey", - "columnName": "publicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translationId", - "columnName": "translationId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "translatorPublicKey", - "columnName": "translatorPublicKey", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "signature", - "columnName": "signature", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, - { - "fieldPath": "relayHint", - "columnName": "relayHint", - "affinity": "TEXT" - }, - { - "fieldPath": "marmotGroupEventId", - "columnName": "marmotGroupEventId", - "affinity": "TEXT" - }, - { - "fieldPath": "groupSignedEventId", - "columnName": "groupSignedEventId", - "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" - ] - }, - "foreignKeys": [ - { - "table": "MantraTranslation", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "translationId" - ], - "referencedColumns": [ - "id" - ] - }, - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "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`))", @@ -4451,7 +2320,7 @@ }, { "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, `payloadEventId` 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 )", + "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", @@ -4494,11 +2363,6 @@ "columnName": "quotedEventId", "affinity": "TEXT" }, - { - "fieldPath": "payloadEventId", - "columnName": "payloadEventId", - "affinity": "TEXT" - }, { "fieldPath": "marmotGroupEventId", "columnName": "marmotGroupEventId", @@ -4930,6 +2794,158 @@ } ] }, + { + "tableName": "MemberWallet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` TEXT NOT NULL, `ownerPublicKey` TEXT NOT NULL, `guardingChatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `walletPrivateKey` TEXT NOT NULL, `label` TEXT, `requestJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "guardingChatRoomId", + "columnName": "guardingChatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletPrivateKey", + "columnName": "walletPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT" + }, + { + "fieldPath": "requestJson", + "columnName": "requestJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_MemberWallet_ownerPublicKey", + "unique": false, + "columnNames": [ + "ownerPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWallet_ownerPublicKey` ON `${TABLE_NAME}` (`ownerPublicKey`)" + }, + { + "name": "index_MemberWallet_guardingChatRoomId", + "unique": false, + "columnNames": [ + "guardingChatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWallet_guardingChatRoomId` ON `${TABLE_NAME}` (`guardingChatRoomId`)" + } + ] + }, + { + "tableName": "MemberWalletSpend", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`txid` TEXT NOT NULL, `walletId` TEXT NOT NULL, `psbt` TEXT NOT NULL, `signedTransaction` TEXT NOT NULL, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`txid`))", + "fields": [ + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "psbt", + "columnName": "psbt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedTransaction", + "columnName": "signedTransaction", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "broadcastAt", + "columnName": "broadcastAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "seenAt", + "columnName": "seenAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "replacedByTxid", + "columnName": "replacedByTxid", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "txid" + ] + }, + "indices": [ + { + "name": "index_MemberWalletSpend_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWalletSpend_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, { "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 )", @@ -6704,7 +4720,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, '1c1d38fb933b34767085c3d595c09815')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '47aa631ec4032d9b2c00bf0b38689864')" ] } } \ No newline at end of file diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/31.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/31.json new file mode 100644 index 00000000..0d3f097d --- /dev/null +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/31.json @@ -0,0 +1,4731 @@ +{ + "formatVersion": 1, + "database": { + "version": 31, + "identityHash": "63d1cbf5fb6fb297117d1e7a0d45766d", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `guardianDelay` INTEGER, `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": "guardianDelay", + "columnName": "guardianDelay", + "affinity": "INTEGER" + }, + { + "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, `inputIndex` INTEGER, 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" + }, + { + "fieldPath": "inputIndex", + "columnName": "inputIndex", + "affinity": "INTEGER" + } + ], + "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, `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": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `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": "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": "GroupTransaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `guardedChatRoomId` TEXT, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "account", + "columnName": "account", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "guardedChatRoomId", + "columnName": "guardedChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "psbt", + "columnName": "psbt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedTransaction", + "columnName": "signedTransaction", + "affinity": "TEXT" + }, + { + "fieldPath": "broadcastAt", + "columnName": "broadcastAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "seenAt", + "columnName": "seenAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "replacedByTxid", + "columnName": "replacedByTxid", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "frostSigningSessionId" + ] + }, + "indices": [ + { + "name": "index_GroupTransaction_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupTransaction_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupTransaction_txid", + "unique": false, + "columnNames": [ + "txid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupTransaction_txid` ON `${TABLE_NAME}` (`txid`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "frostSigningSessionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "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": "MemberWallet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` TEXT NOT NULL, `ownerPublicKey` TEXT NOT NULL, `guardingChatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `walletPrivateKey` TEXT NOT NULL, `label` TEXT, `requestJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "guardingChatRoomId", + "columnName": "guardingChatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletPrivateKey", + "columnName": "walletPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT" + }, + { + "fieldPath": "requestJson", + "columnName": "requestJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_MemberWallet_ownerPublicKey", + "unique": false, + "columnNames": [ + "ownerPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWallet_ownerPublicKey` ON `${TABLE_NAME}` (`ownerPublicKey`)" + }, + { + "name": "index_MemberWallet_guardingChatRoomId", + "unique": false, + "columnNames": [ + "guardingChatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWallet_guardingChatRoomId` ON `${TABLE_NAME}` (`guardingChatRoomId`)" + } + ] + }, + { + "tableName": "MemberWalletSpend", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`txid` TEXT NOT NULL, `walletId` TEXT NOT NULL, `psbt` TEXT NOT NULL, `signedTransaction` TEXT NOT NULL, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`txid`))", + "fields": [ + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "psbt", + "columnName": "psbt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedTransaction", + "columnName": "signedTransaction", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "broadcastAt", + "columnName": "broadcastAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "seenAt", + "columnName": "seenAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "replacedByTxid", + "columnName": "replacedByTxid", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "txid" + ] + }, + "indices": [ + { + "name": "index_MemberWalletSpend_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWalletSpend_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '63d1cbf5fb6fb297117d1e7a0d45766d')" + ] + } +} \ No newline at end of file diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/32.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/32.json new file mode 100644 index 00000000..df42641a --- /dev/null +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/32.json @@ -0,0 +1,5471 @@ +{ + "formatVersion": 1, + "database": { + "version": 32, + "identityHash": "6272f3e8e60bff8f0692fe9061ed56dc", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `guardianDelay` INTEGER, `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": "guardianDelay", + "columnName": "guardianDelay", + "affinity": "INTEGER" + }, + { + "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, `inputIndex` INTEGER, 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" + }, + { + "fieldPath": "inputIndex", + "columnName": "inputIndex", + "affinity": "INTEGER" + } + ], + "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, `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": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `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": "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": "GroupLightningInvoiceRow", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `requestId` TEXT NOT NULL, `bolt11` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `requestId`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bolt11", + "columnName": "bolt11", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "requestId" + ] + } + }, + { + "tableName": "GroupLightningPaymentRow", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `id` TEXT NOT NULL, `incoming` INTEGER NOT NULL, `amountMsat` INTEGER NOT NULL, `feesMsat` INTEGER NOT NULL, `paymentHash` TEXT, `description` TEXT, `completedAt` INTEGER, `succeeded` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `id`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "incoming", + "columnName": "incoming", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amountMsat", + "columnName": "amountMsat", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "feesMsat", + "columnName": "feesMsat", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "paymentHash", + "columnName": "paymentHash", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "completedAt", + "columnName": "completedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "succeeded", + "columnName": "succeeded", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "id" + ] + } + }, + { + "tableName": "GroupLightningSeed", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `nodeId` TEXT NOT NULL, `chain` TEXT NOT NULL, `wallet` INTEGER NOT NULL, `seed` TEXT NOT NULL, `sentBy` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `nodeId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nodeId", + "columnName": "nodeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "seed", + "columnName": "seed", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sentBy", + "columnName": "sentBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "nodeId" + ] + }, + "indices": [ + { + "name": "index_GroupLightningSeed_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupLightningSeed_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupLightningSnapshotRow", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `sentBy` TEXT NOT NULL, `term` INTEGER NOT NULL, `content` TEXT NOT NULL, `sentAt` INTEGER NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sentBy", + "columnName": "sentBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "term", + "columnName": "term", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sentAt", + "columnName": "sentAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet" + ] + } + }, + { + "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": "GroupTransaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `guardedChatRoomId` TEXT, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "account", + "columnName": "account", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "guardedChatRoomId", + "columnName": "guardedChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "psbt", + "columnName": "psbt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedTransaction", + "columnName": "signedTransaction", + "affinity": "TEXT" + }, + { + "fieldPath": "broadcastAt", + "columnName": "broadcastAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "seenAt", + "columnName": "seenAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "replacedByTxid", + "columnName": "replacedByTxid", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "frostSigningSessionId" + ] + }, + "indices": [ + { + "name": "index_GroupTransaction_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupTransaction_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupTransaction_txid", + "unique": false, + "columnNames": [ + "txid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupTransaction_txid` ON `${TABLE_NAME}` (`txid`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "frostSigningSessionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "IcebergBudgetSpend", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `paymentHash` TEXT NOT NULL, `consumedMsat` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `paymentHash`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "paymentHash", + "columnName": "paymentHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "consumedMsat", + "columnName": "consumedMsat", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "paymentHash" + ] + } + }, + { + "tableName": "IcebergChannelLedger", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `channelId` TEXT NOT NULL, `fundingOutPoint` TEXT NOT NULL, `remoteFundingPubKey` TEXT NOT NULL, `ledger` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `channelId`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelId", + "columnName": "channelId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fundingOutPoint", + "columnName": "fundingOutPoint", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "remoteFundingPubKey", + "columnName": "remoteFundingPubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ledger", + "columnName": "ledger", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "channelId" + ] + } + }, + { + "tableName": "IcebergEchoRow", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `label` TEXT NOT NULL, `participant` TEXT NOT NULL, `messageHash` TEXT NOT NULL, PRIMARY KEY(`wallet`, `label`, `participant`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participant", + "columnName": "participant", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageHash", + "columnName": "messageHash", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "label", + "participant" + ] + } + }, + { + "tableName": "IcebergKeySession", + "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 NOT NULL, `onchainDkgSessionId` TEXT NOT NULL, `stage` TEXT NOT NULL, `root` TEXT, `share` TEXT, `groupPublicKey` TEXT, `publicShares` TEXT, `joinApprovedAt` INTEGER, `revealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `failureReason` 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": "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", + "notNull": true + }, + { + "fieldPath": "onchainDkgSessionId", + "columnName": "onchainDkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "root", + "columnName": "root", + "affinity": "TEXT" + }, + { + "fieldPath": "share", + "columnName": "share", + "affinity": "TEXT" + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "joinApprovedAt", + "columnName": "joinApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "revealApprovedAt", + "columnName": "revealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "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_IcebergKeySession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergKeySession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "IcebergLabelAssignment", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `counter` INTEGER NOT NULL, `label` TEXT NOT NULL, `purpose` TEXT NOT NULL, `assignedAt` INTEGER NOT NULL, PRIMARY KEY(`wallet`, `counter`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "counter", + "columnName": "counter", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAt", + "columnName": "assignedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "counter" + ] + }, + "indices": [ + { + "name": "index_IcebergLabelAssignment_wallet_purpose", + "unique": false, + "columnNames": [ + "wallet", + "purpose" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergLabelAssignment_wallet_purpose` ON `${TABLE_NAME}` (`wallet`, `purpose`)" + } + ] + }, + { + "tableName": "IcebergLabelLedger", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `label` TEXT NOT NULL, `requestId` TEXT NOT NULL, `messageHash` TEXT NOT NULL, `echoedAt` INTEGER NOT NULL, `signedAt` INTEGER, PRIMARY KEY(`wallet`, `label`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageHash", + "columnName": "messageHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "echoedAt", + "columnName": "echoedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "label" + ] + } + }, + { + "tableName": "IcebergNonceRow", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `counter` INTEGER NOT NULL, `participant` TEXT NOT NULL, `contribution` TEXT NOT NULL, PRIMARY KEY(`wallet`, `counter`, `participant`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "counter", + "columnName": "counter", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participant", + "columnName": "participant", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "contribution", + "columnName": "contribution", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "counter", + "participant" + ] + } + }, + { + "tableName": "IcebergParticipantMessage", + "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 `IcebergKeySession`(`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_IcebergParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_IcebergParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "IcebergKeySession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "IcebergShareRow", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`wallet` TEXT NOT NULL, `requestId` TEXT NOT NULL, `participant` TEXT NOT NULL, `share` TEXT NOT NULL, PRIMARY KEY(`wallet`, `requestId`, `participant`))", + "fields": [ + { + "fieldPath": "wallet", + "columnName": "wallet", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participant", + "columnName": "participant", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "share", + "columnName": "share", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "wallet", + "requestId", + "participant" + ] + } + }, + { + "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": "MemberWallet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` TEXT NOT NULL, `ownerPublicKey` TEXT NOT NULL, `guardingChatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `walletPrivateKey` TEXT NOT NULL, `label` TEXT, `requestJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "guardingChatRoomId", + "columnName": "guardingChatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletPrivateKey", + "columnName": "walletPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT" + }, + { + "fieldPath": "requestJson", + "columnName": "requestJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_MemberWallet_ownerPublicKey", + "unique": false, + "columnNames": [ + "ownerPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWallet_ownerPublicKey` ON `${TABLE_NAME}` (`ownerPublicKey`)" + }, + { + "name": "index_MemberWallet_guardingChatRoomId", + "unique": false, + "columnNames": [ + "guardingChatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWallet_guardingChatRoomId` ON `${TABLE_NAME}` (`guardingChatRoomId`)" + } + ] + }, + { + "tableName": "MemberWalletSpend", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`txid` TEXT NOT NULL, `walletId` TEXT NOT NULL, `psbt` TEXT NOT NULL, `signedTransaction` TEXT NOT NULL, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`txid`))", + "fields": [ + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "psbt", + "columnName": "psbt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedTransaction", + "columnName": "signedTransaction", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "broadcastAt", + "columnName": "broadcastAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "seenAt", + "columnName": "seenAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "replacedByTxid", + "columnName": "replacedByTxid", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "txid" + ] + }, + "indices": [ + { + "name": "index_MemberWalletSpend_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MemberWalletSpend_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '6272f3e8e60bff8f0692fe9061ed56dc')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/composeResources/drawable/compose-multiplatform.xml b/composeApp/src/commonMain/composeResources/drawable/compose-multiplatform.xml index 1ffc948c..601df181 100644 --- a/composeApp/src/commonMain/composeResources/drawable/compose-multiplatform.xml +++ b/composeApp/src/commonMain/composeResources/drawable/compose-multiplatform.xml @@ -1,44 +1,13 @@ - + + + android:fillColor="#FF3A1A" + android:pathData="M0,0 L512,0 L512,512 L0,512 Z"/> - - - - - - - - - - - - - - - - - - \ No newline at end of file + android:fillColor="#000000" + android:pathData="M246.31,26.00 C244.88,25.74 243.39,26.79 241.55,28.54 C239.71,30.29 236.15,33.14 235.20,36.48 C234.24,39.82 237.67,41.82 235.83,48.55 C233.99,55.29 227.25,68.63 224.08,76.83 C220.90,85.02 218.77,91.18 216.77,97.79 C214.77,104.40 213.21,110.56 212.00,116.54 C210.80,122.51 209.94,131.37 209.46,133.69 C208.99,136.01 209.62,131.47 209.15,130.51 C208.67,129.56 207.02,130.04 206.60,127.97 C206.19,125.91 206.38,121.30 206.60,118.12 C206.83,114.95 206.99,113.20 207.87,108.91 C208.76,104.62 209.37,99.95 212.00,92.39 C214.64,84.83 221.63,69.74 223.76,63.48 C225.89,57.22 224.97,57.29 224.71,54.91 C224.46,52.52 223.06,50.52 222.17,49.19 C221.28,47.85 220.36,47.50 219.31,46.96 C218.26,46.42 217.31,45.95 215.82,46.01 C214.32,46.07 211.91,46.33 210.42,47.28 C208.92,48.23 207.49,50.24 206.92,51.73 C206.35,53.22 206.70,55.16 206.92,56.18 C207.14,57.19 207.49,57.76 208.19,57.76 C208.89,57.76 210.42,55.86 211.05,56.18 C211.69,56.49 213.59,55.92 212.00,59.67 C210.42,63.42 204.63,72.54 201.52,78.73 C198.41,84.93 195.23,92.07 193.26,96.84 C191.29,101.60 191.04,102.33 189.77,107.32 C188.50,112.31 186.18,123.30 185.64,126.70 C185.10,130.10 184.11,127.43 186.59,127.65 C189.07,127.88 197.71,127.65 200.57,127.97 C203.43,128.29 202.57,128.67 203.74,129.56 C204.92,130.45 206.60,132.10 207.56,133.37 C208.51,134.64 209.78,136.14 209.46,137.18 C209.15,138.23 207.08,138.30 205.65,139.73 C204.22,141.16 213.12,143.70 200.89,145.76 C188.66,147.83 147.13,150.46 132.27,152.12 C117.40,153.77 99.16,154.43 111.62,155.61 C124.07,156.79 190.50,158.21 206.92,159.10 C223.35,159.99 208.29,160.37 210.10,161.01 C211.91,161.65 212.39,162.54 217.72,162.92 C223.06,163.30 237.26,162.82 242.18,163.23 C247.11,163.65 245.84,164.25 247.27,165.46 C248.70,166.67 250.28,168.89 250.76,170.54 C251.24,172.19 251.17,173.72 250.13,175.31 C249.08,176.89 246.16,179.05 244.41,180.07 C242.66,181.09 244.63,181.09 239.64,181.34 C234.66,181.60 219.79,181.28 214.55,181.66 C209.30,182.04 210.42,182.61 208.19,183.57 C205.97,184.52 203.49,185.69 201.20,187.38 C198.92,189.06 196.34,191.44 194.53,193.73 C192.72,196.02 191.36,198.88 190.40,201.04 C189.45,203.20 189.13,204.53 188.81,206.76 C188.50,208.98 188.27,211.84 188.50,214.38 C188.72,216.92 189.07,219.30 190.08,222.00 C191.10,224.71 190.50,225.56 194.53,230.58 C198.57,235.60 208.29,244.56 214.23,252.18 C220.17,259.81 224.97,269.50 230.11,276.33 C235.26,283.16 240.98,287.70 245.04,293.17 C249.11,298.63 249.87,302.38 254.57,309.05 C259.28,315.72 270.14,328.59 273.32,333.19 C276.49,337.80 273.86,334.40 273.63,336.69 C273.41,338.97 275.64,334.08 272.05,346.85 C268.46,359.62 257.05,397.14 252.03,413.25 C247.01,429.35 244.63,436.06 241.87,443.43 C239.10,450.80 237.20,454.45 235.51,457.41 C233.83,460.36 233.51,460.11 231.70,461.22 C229.89,462.33 227.09,463.54 224.71,464.08 C222.33,464.62 219.47,464.55 217.41,464.39 C215.34,464.24 214.13,463.35 212.32,463.12 C210.51,462.90 208.03,462.87 206.60,463.12 C205.17,463.38 204.48,464.08 203.74,464.71 C203.01,465.35 203.81,466.36 202.16,466.94 C200.50,467.51 196.03,467.19 193.90,468.21 C191.77,469.22 189.35,472.59 189.45,472.97 C189.54,473.35 193.10,470.84 194.53,470.43 C195.96,470.02 197.55,470.05 198.03,470.43 C198.50,470.81 197.33,472.11 197.39,472.65 C197.45,473.19 197.71,473.45 198.34,473.61 C198.98,473.77 200.41,473.83 201.20,473.61 C202.00,473.39 200.73,472.65 203.11,472.34 C205.49,472.02 213.97,471.07 215.50,471.70 C217.02,472.34 212.96,474.66 212.32,476.15 C211.69,477.64 210.99,480.69 211.69,480.60 C212.39,480.50 214.93,476.21 216.45,475.51 C217.98,474.81 219.79,476.63 220.90,476.47 C222.01,476.31 220.17,475.58 223.12,474.56 C226.08,473.54 233.45,470.91 238.69,470.43 C243.93,469.95 251.56,471.29 254.57,471.70 C257.59,472.11 256.00,472.75 256.80,472.97 C257.59,473.19 258.64,473.19 259.34,472.97 C260.04,472.75 260.67,472.18 260.93,471.70 C261.18,471.22 260.45,470.37 260.93,470.11 C261.40,469.86 262.67,469.64 263.79,470.11 C264.90,470.59 267.22,473.23 267.60,472.97 C267.98,472.72 266.71,469.64 266.01,468.52 C265.31,467.41 264.64,466.71 263.47,466.30 C262.29,465.89 259.97,466.24 259.02,465.98 C258.07,465.73 258.39,464.78 257.75,464.71 C257.12,464.65 256.54,465.67 255.21,465.67 C253.87,465.67 251.30,465.19 249.81,464.71 C248.32,464.24 247.20,463.60 246.31,462.81 C245.42,462.01 244.57,461.76 244.41,459.95 C244.25,458.14 243.84,457.88 245.36,452.01 C246.89,446.13 248.12,441.59 253.62,424.68 C259.12,407.78 273.54,364.71 278.40,350.67 C283.26,336.62 282.15,343.20 282.85,340.50 C283.55,337.80 283.07,336.31 282.53,334.46 C281.99,332.62 280.94,332.88 279.67,329.38 C278.40,325.89 276.72,317.56 274.91,313.50 C273.09,309.43 270.24,307.24 268.87,304.92 C267.50,302.60 264.10,297.04 266.65,299.52 C269.19,302.00 278.34,313.66 284.12,319.85 C289.90,326.05 298.35,332.81 301.27,336.69 C304.20,340.56 301.18,341.07 301.59,343.04 C302.00,345.01 302.64,342.79 303.81,348.44 C304.99,354.10 306.13,359.81 308.58,377.03 C311.03,394.25 317.06,437.77 318.43,451.69 C319.79,465.60 317.70,458.52 316.84,460.58 C315.98,462.65 315.00,463.22 313.34,464.08 C311.69,464.93 309.53,465.57 306.99,465.67 C304.45,465.76 300.26,464.65 298.10,464.71 C295.94,464.78 295.01,465.41 293.97,465.98 C292.92,466.55 293.39,467.79 291.74,468.21 C290.09,468.62 286.12,467.95 284.12,468.52 C282.12,469.10 280.72,470.49 279.67,471.70 C278.62,472.91 277.54,475.67 277.76,475.83 C277.99,475.99 279.61,473.39 280.94,472.65 C282.28,471.92 284.85,471.29 285.71,471.38 C286.56,471.48 285.61,472.88 286.02,473.29 C286.44,473.70 288.41,473.13 288.25,473.93 C288.09,474.72 285.64,476.69 285.07,478.05 C284.50,479.42 284.50,482.12 284.75,482.18 C285.01,482.25 285.77,479.39 286.66,478.37 C287.55,477.36 289.20,476.24 290.15,476.15 C291.11,476.05 291.65,477.48 292.38,477.74 C293.11,477.99 292.38,478.44 294.60,477.74 C296.83,477.04 302.23,474.56 305.72,473.61 C309.21,472.65 313.92,472.11 315.57,472.02 C317.22,471.92 315.95,472.65 315.57,472.97 C315.19,473.29 314.08,473.04 313.34,473.93 C312.61,474.81 311.53,476.40 311.12,478.37 C310.71,480.34 310.42,485.30 310.80,485.68 C311.18,486.06 312.45,481.39 313.34,480.60 C314.23,479.80 314.62,481.61 316.20,480.91 C317.79,480.22 321.13,477.17 322.87,476.47 C324.62,475.77 325.51,476.15 326.69,476.78 C327.86,477.42 328.97,479.64 329.86,480.28 C330.75,480.91 331.45,479.80 332.09,480.60 C332.72,481.39 333.29,485.04 333.68,485.04 C334.06,485.04 334.37,482.41 334.31,480.60 C334.25,478.79 334.06,475.77 333.36,474.24 C332.66,472.72 329.48,471.70 330.18,471.38 C330.88,471.07 335.96,472.27 337.49,472.34 C339.01,472.40 338.85,472.24 339.39,471.70 C339.93,471.16 340.03,469.41 340.66,469.16 C341.30,468.91 342.41,469.54 343.21,470.11 C344.00,470.68 345.21,472.91 345.43,472.65 C345.65,472.40 345.27,469.73 344.48,468.52 C343.68,467.32 341.68,465.89 340.66,465.35 C339.65,464.81 339.01,465.57 338.44,465.35 C337.87,465.13 337.96,464.14 337.17,464.08 C336.38,464.01 334.79,465.09 333.68,465.03 C332.56,464.97 331.52,464.55 330.50,463.76 C329.48,462.97 328.50,462.01 327.64,460.26 C326.78,458.52 327.58,467.03 325.42,453.28 C323.26,439.52 316.93,394.98 314.62,377.67 C312.30,360.35 312.01,355.97 311.44,349.39 C310.87,342.82 311.37,340.82 311.12,338.28 C310.87,335.73 310.58,335.48 309.85,334.15 C309.12,332.81 308.01,332.46 306.67,330.33 C305.34,328.21 298.32,321.50 301.91,321.44 C305.50,321.38 319.22,327.95 328.28,330.02 C337.33,332.08 351.21,333.03 356.23,333.83 C361.25,334.62 356.80,333.35 358.45,334.78 C360.11,336.21 363.95,340.56 366.08,342.41 C368.21,344.25 370.37,345.74 371.16,345.90 C371.96,346.06 370.05,343.10 370.84,343.36 C371.64,343.61 375.13,347.11 375.93,347.49 C376.72,347.87 375.04,345.42 375.61,345.58 C376.18,345.74 378.88,348.35 379.42,348.44 C379.96,348.54 378.25,346.15 378.79,346.22 C379.33,346.28 382.12,348.51 382.60,348.76 C383.08,349.01 381.71,348.03 381.65,347.81 C381.58,347.58 381.11,347.08 382.28,347.49 C383.46,347.90 388.00,350.35 388.63,350.35 C389.27,350.35 385.78,347.65 386.09,347.49 C386.41,347.33 389.81,349.33 390.54,349.39 C391.27,349.46 389.81,347.49 390.54,347.81 C391.27,348.12 394.45,351.21 394.99,351.30 C395.53,351.40 393.50,348.70 393.72,348.44 C393.94,348.19 395.78,349.62 396.26,349.71 C396.74,349.81 396.26,348.92 396.58,349.08 C396.89,349.24 398.23,351.84 398.16,350.67 C398.10,349.49 395.94,342.88 396.26,342.09 C396.58,341.29 399.91,346.00 400.07,345.90 C400.23,345.80 397.59,342.31 397.21,341.45 C396.83,340.59 397.43,340.56 397.85,340.82 C398.26,341.07 400.01,344.15 399.75,343.04 C399.50,341.93 396.80,335.73 396.26,334.15 C395.72,332.56 396.10,333.26 396.58,333.51 C397.05,333.76 399.50,336.69 399.12,335.73 C398.74,334.78 395.08,329.22 394.35,327.79 C393.62,326.36 394.42,327.09 394.67,327.16 C394.92,327.22 397.78,331.06 395.94,328.11 C394.10,325.16 391.40,319.91 383.55,309.37 C375.70,298.82 359.09,276.96 348.92,264.89 C338.76,252.82 330.88,244.78 322.56,236.94 C314.23,229.09 306.61,223.18 299.05,217.88 C291.49,212.57 282.75,208.03 277.13,205.17 C271.51,202.31 268.87,201.77 265.37,200.72 C261.88,199.67 259.08,199.20 256.16,198.81 C253.24,198.43 250.86,198.18 247.90,198.50 C244.95,198.81 240.85,199.86 238.37,200.72 C235.89,201.58 235.29,201.93 232.97,203.58 C230.65,205.23 226.68,209.04 224.39,210.57 C222.11,212.09 220.74,212.41 219.31,212.79 C217.88,213.17 216.93,213.01 215.82,212.79 C214.70,212.57 213.66,212.38 212.64,211.52 C211.62,210.66 210.26,209.04 209.78,207.71 C209.30,206.38 209.53,204.85 209.78,203.58 C210.03,202.31 210.57,201.20 211.37,200.08 C212.16,198.97 213.34,197.80 214.55,196.91 C215.75,196.02 216.93,195.32 218.68,194.68 C220.42,194.05 221.28,193.41 225.03,193.10 C228.78,192.78 237.10,193.10 241.23,192.78 C245.36,192.46 246.89,192.14 249.81,191.19 C252.73,190.24 256.23,188.81 258.70,187.06 C261.18,185.31 263.31,183.09 264.74,180.71 C266.17,178.32 267.06,175.56 267.28,172.76 C267.50,169.97 267.03,166.82 266.01,163.87 C264.99,160.92 263.72,158.31 261.24,154.97 C258.77,151.64 249.08,145.51 251.08,143.86 C253.08,142.20 265.44,144.33 273.32,145.13 C281.20,145.92 290.85,147.25 298.41,148.62 C305.97,149.99 311.60,151.32 318.74,153.39 C325.89,155.45 341.36,161.11 341.30,161.01 C341.24,160.92 325.48,154.97 318.43,152.75 C311.37,150.53 307.09,149.26 299.05,147.67 C291.01,146.08 278.40,144.24 270.14,143.22 C261.88,142.20 253.30,142.04 249.49,141.63 C245.68,141.22 244.73,140.90 247.27,140.68 C249.81,140.46 254.41,139.82 264.74,140.36 C275.06,140.90 297.78,142.68 309.21,143.86 C320.65,145.03 326.85,146.17 333.36,147.35 C339.87,148.53 348.99,151.07 348.29,150.84 C347.59,150.62 335.36,147.41 329.23,146.08 C323.10,144.75 319.79,144.01 311.44,142.90 C303.08,141.79 290.63,140.30 279.03,139.41 C267.44,138.52 248.54,138.07 241.87,137.50 C235.20,136.93 238.59,136.87 239.01,135.91 C239.42,134.96 242.41,132.96 244.41,131.78 C246.41,130.61 247.33,129.78 251.08,128.92 C254.83,128.07 264.52,135.34 266.96,126.70 C269.41,118.06 265.79,87.69 265.69,77.14 C265.60,66.60 265.79,66.28 266.33,63.48 C266.87,60.69 268.23,60.85 268.87,60.31 C269.50,59.77 269.76,59.99 270.14,60.31 C270.52,60.62 270.52,62.05 271.09,62.21 C271.66,62.37 272.78,62.28 273.63,61.26 C274.49,60.24 275.86,57.67 276.18,56.18 C276.49,54.68 276.02,53.48 275.54,52.36 C275.06,51.25 274.27,50.24 273.32,49.50 C272.36,48.77 271.16,48.17 269.82,47.92 C268.49,47.66 267.28,47.28 265.37,47.92 C263.47,48.55 260.36,49.89 258.39,51.73 C256.42,53.57 254.80,56.33 253.62,59.04 C252.45,61.74 252.10,61.58 251.40,67.93 C250.70,74.28 250.22,88.83 249.49,97.16 C248.76,105.48 247.81,112.66 246.95,117.81 C246.09,122.95 245.46,126.00 244.41,127.97 C243.36,129.94 240.60,133.75 240.60,129.56 C240.60,125.37 243.23,115.96 244.41,102.87 C245.58,89.79 246.85,60.46 247.58,51.09 C248.32,41.72 248.06,48.33 248.86,46.65 C249.65,44.96 252.13,43.69 252.35,40.93 C252.57,38.16 251.14,32.60 250.13,30.13 C249.11,27.65 247.74,26.25 246.31,26.00 Z"/> + diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index c1fbb96b..83c4127f 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -21,21 +21,18 @@ "XML file ... is not valid. Check the file content." --> Abandoned + Abandon + Abandon ceremony + Abandon this key ceremony? + It ends for everyone in it. No key is created, and the ceremony can be started again. Abandoned. Nothing was signed. All Bennu - Add a dialect the group can translate into - Add artifact to library - Add artifact to the group library - Add chapter - Add dialect Add to group - Add translation After this there is no turning back. All broadcasts are queued so that we can manage data usage on metered connections. Any amount ARTICLE - Artifact detail As long as you control your keys there can be no dispute about who YOU actually is. Back Backup confirmation @@ -46,16 +43,11 @@ BIP39 seed with the standard BIP84 derivation path. The profile\'s nostr key comes off the same seed, so these 12 words restore both. Block user Cancel - Chapter detail - Chapter name - Chapter translation - Chapters Choose who to chat with Close Cloud backup Copy URL Could not unlock your phrase. Please try again. - Country Create chat Create new chat Create profile @@ -71,9 +63,6 @@ Currently no messages have been shared.\nBreak the ice. Declined to sign Delete group - Details - Dialect name - Dialects Direct message detail Direct message functionality will be here. Direct message via npub @@ -82,20 +71,12 @@ Download Download and securely store everything needed to recover this profile and the coins it holds. Edit profile - eg. Chapter 1 — The Beginning - eg. First Edition - eg. https://harper.com/2-kill-Bird - eg. Lesotho - eg. Sesotho - eg. st - eg. To Kill a Mocking Bird Emergency kit ENDED Encrypt and back your recovery information up to your Google Drive or iCloud. Enough members took part without you. Enter the name you want to use for your group Enter the name you want to use for your profile - Enter the translation for this chunk Events are indexed so that we can deliver a premium local first experience. Everything else Everything is cryptographical sound. Just announcing your profile to the world. @@ -113,7 +94,6 @@ I have saved my recovery phrase somewhere safe. I understand that if I lose this phone and my recovery phrase, I lose this profile and the funds in its wallet. If you are new to Bennu or just want to create a fresh profile - Initial version label Input npub... or nip05 Introduce yourself Invite @@ -126,7 +106,6 @@ Key Key package management Key recovery - Language Learn more Leave group Remove from group @@ -156,7 +135,6 @@ Name Name (eg. Alan Turing) Name (eg. Group Discussions) - Name of artifact Needs you Needs your review. Network relays @@ -166,29 +144,17 @@ Not backed up yet New chat Next - No artifacts exists in this groups library. - No chapters. - No chapters yet. No chat message relays were found for this user. - No chunks. - No dialects have been defined in this group yet. Add one from the group's detail screen first. - No dialects have been defined in this group. No messages. Go to a profile and send them a message. No one selected yet No one to add yet. No projects exists in this group. No proposal has been abandoned. - No translations yet. - No versions. Not now Nothing is waiting for your signature. Nothing was created and no key exists. It is safe to run it again. Open chat - Original - Original text - Original text (markdown) ✓ Paid - Paste the chapter's markdown. Blank lines separate paragraphs into chunks. Pay Pay now Post @@ -201,11 +167,6 @@ Profiles Projects Proposals - Propose - Propose artifact - Propose chapter - Propose dialect - Propose translation Publish new key package Re-broadcast Asked the members who have not answered to take another look @@ -261,11 +222,15 @@ Something went wrong and we were unable to sign in to your provided profile. Please try again later. Something went wrong and we were unable to sign you up. Please try again later. Something went wrong and we were unable to write a new note. Please try again later. - Source dialect Start Start a group chat Start chat via npub or nip05 Start key ceremony + This room was made from a key the group already holds, so it can't run a key ceremony of its own. A subgroup's ceremony is started from the group's details. + A shared key needs at least %1$s members to split it between. + Couldn't load this group. + Couldn't read your keys. + Couldn't start the key ceremony. Startup error Taking part with these members Tap to load @@ -277,12 +242,8 @@ The group has a shared key. The recovery phrase (sometimes called a seed) is a list of 12 English words. It is the only way back to this profile: the key that signs as you, and the wallet that holds your coins, are both derived from it.\n\nOnly you have this phrase. Keep it private — nobody from Bennu will ever ask you for it.\n\nDo not lose it. Write it down and keep it somewhere safe that is not this phone. If you lose both the phone and the phrase, this profile and its funds are gone for good. These are your keys. Keep them safe so they can keep unlocking this profile and its coins, even when you lose or change your phone. - This artifact has no version for a translation to be of. - This artifact has no version for a chapter to attach to. - This chapter has no chunks. This device holds no phrase for the profile that is signed in. This decides who can change the group later. You can't switch afterwards. - This group has no shared key, so it cannot sign them in. This group has not been asked to sign anything yet. This group has not signed anything yet. This is fixed once the ceremony runs. Changing it later means generating a new key. @@ -300,12 +261,6 @@ Could not sign out. Please try again. This will give you write access to the profile. Bennu broadcasts what you publish to a distributed set of relays, so it stays decentralised. - Translate chunk - Translate into which dialect? - Translated text - Translation - Translation detail - Translations Transmit note Trending notes functionality coming soon. In the meantime search for what you are looking for. Try again @@ -314,9 +269,6 @@ Unlocking your phrase… Unsupported event kind Untitled article - Url - Version - Versions View and accept invites you may have received to stay connected with others. View invites Waiting for you @@ -348,15 +300,9 @@ Your profile is almost ready... just getting it's first cryptographic signature together. Your share of it is on this device only. Your wallet backup restores it — nobody else's share can. - Add chapter to %1$s Add people to %1$s Ask all %1$s again Asked again about all %1$s proposals - Chapter %1$s - Chapter %1$s · %2$s words · %3$s characters - Chunk %1$s - Chunks (%1$s) - %1$s/%2$s chunks translated %1$s event(s) still unreadable%2$s %1$s events, signed together Everyone has to be online at the same time — the ceremony can only finish once all %1$s of you have taken part. @@ -385,11 +331,9 @@ %1$s sent a private message to %2$s Shared key for %1$s to join the %1$s chat room. - Translate %1$s Unsupported event kind: %1$s %1$s was created, but %2$s couldn't be added yet. Invite them again from the chat once they're on Bennu. %1$s was created, but its shared key ceremony couldn't be started. Open the chat and start it from the group's details — until then the group has no key of its own. - %1$s words · %2$s characters #%1$s You and %1$s others You aren't following anyone yet. @@ -434,104 +378,7 @@ Check the combined result and confirm it The group has its key — finish setting it up Open - Nostr profile - This group hasn't said anything about itself on Nostr yet. - - Not described yet - Edit Nostr profile - Propose Nostr profile - What the group says about itself on Nostr - The group signs this, so it takes a quorum. An empty field unsays what the group had said. - This group has no shared key, so it cannot sign a profile. Run a shared key ceremony first. - Signed by the group on %1$s - No name on this profile - About - Picture url - Website - Nostr address - Lightning address - eg. Translation collective - eg. A group translating hard books into Sesotho - eg. https://example.com/group.png - eg. https://example.com - eg. group@example.com - eg. group@getalby.com - Couldn't ask the group to sign this profile. - Relays - Edit relays - Not set yet - No relays in this list - - %1$s of %2$s lists agreed - Where the group lives on Nostr - The group signs each list, so it takes a quorum. Only the lists you change are proposed. - This group has no shared key, so it cannot sign a relay list. Run a shared key ceremony first. - Relay url - eg. wss://relay.example.com - Add relay - That isn't a relay address. Relays start with wss:// and cannot be on this device. - That relay is already in this list. - Propose relays - Nothing has changed, so there is nothing to propose. - Couldn't ask the group to sign these relays. - Read - Write - General - Messages - Search - Blocked - Where the group publishes, and where a reader should look for it. - Where a message addressed to the group should be sent. - The relays a search of the group's work runs against. - Relays the group will not talk to. - A group signs and cannot decrypt, so every list here is public — including the blocked one, which most clients keep private. - Signed %1$s - Posts - Add post - Propose post - This group hasn't posted anything yet. - - No posts yet - 1 post - %1$s posts - What should the group say? - The group signs a post, so it takes a quorum. It goes out in the group's name, not yours. - This group has no shared key, so it cannot sign a post. Run a shared key ceremony first. - A post needs something to say. - Couldn't ask the group to sign this post. - Posted %1$s - A reply - Propose event - Paste an unsigned Nostr event for the group to sign. It is filed by kind: a profile (kind 0), a post (kind 1) or a relay list. - The group signs it, so it takes a quorum. The author is the group and the time is now, whatever the paste says about either. - This group has no shared key, so it cannot sign an event. Run a shared key ceremony first. - Couldn't ask the group to sign this event. - Unsigned event - {"kind": 1, "tags": [], "content": "…"} - What the group would sign - Kind %1$s - That isn't JSON. - An event is a JSON object with a kind, tags and content. - An event needs a kind. - Kind %1$s has nowhere to go on the group's screen. It can file kinds %2$s. - Tags must be a list of lists of strings. - Content must be text. - The content isn't a profile. A kind 0 carries a JSON object of profile fields. Ask again - - Broadcast - Sends the event to each relay below, exactly as the group signed it. Any member holding it can send it: the signature is the group's, not yours. - Where the group has said it lives is filled in. Add or remove relays before sending. - No relays to broadcast to. Add one above. - Add a relay to broadcast to. - Sending… - Accepted - Rejected: %1$s - Couldn't send: %1$s - No answer - Accepted by %1$s of %2$s relays. - Copy raw JSON - Copied the raw JSON A password-protected key (ncryptsec) is not supported yet. Decrypt it in the app it came from and paste the nsec. Enter a recovery phrase or an nsec to sign in. @@ -611,6 +458,8 @@ Group onchain wallet Group onchain wallet on %1$s + + %1$s onchain wallet Open a group onchain wallet Not opened yet Open on %1$s @@ -618,6 +467,28 @@ Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone. Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share. Couldn't ask the group to open a wallet. + The groups above this one have agreed to guard its wallet. In a guarded wallet each of them can spend any coin that has waited as long as its own delay, without this group agreeing: + Open a guarded wallet + Open without guardians + Guarded wallets + Spend + Spend from %1$s's guarded wallet + Wallets of groups below this one. This group can spend a coin in each once the coin has waited as long as the delay that wallet gives this group. + %1$s sats within this group's reach + Fund + Fund %1$s's guarded wallet + %1$s sats arriving + To + %1$s's guarded wallet + This group can spend these coins again once they have waited %1$s. + Finding an address in %1$s's wallet… + Wait for this group's open payments to %1$s to confirm. + Tell the groups above + Not yet shared with the groups above that you're in + Share + Shared with the groups above + Couldn't share the wallet + Guarded: the groups above this one can spend any coin here that has waited as long as their own delay: Balance %1$s sats %1$s sats on the way @@ -664,6 +535,7 @@ Fee rate in sats per byte Ask the group to send Sends %1$s sats, with a fee of %2$s sats. + Sends %1$s sats to %2$s's guarded wallet, with a fee of %3$s sats. %1$s sats come back to the group as change. That isn't an address on %1$s. The group has nothing confirmed to spend yet. @@ -682,7 +554,7 @@ Signed, sending it to the network Sent, waiting for a confirmation Confirmed - Replaced by a later spend + Replaced by another spend of the same coins Send again Bump the fee Sent again @@ -707,7 +579,6 @@ Each contribution is encrypted to the members who will hold it. Your randomness starts shaping the key here. Confirming publishes your public share and a hash of every commitment you saw, so the group can check it agrees. %1$s of 3 steps - Couldn't start the key ceremony. Couldn't approve this step. Your share of this key is stored unencrypted on this device, as the onchain wallet's is. Lightning wallet @@ -779,4 +650,171 @@ Anyone can pay this offer, as often as they like, without asking for an invoice first. It pays the group's node, the one the group signed for. Copy offer Offer copied + + + The subgroup's wallet + Guarded wallet + Unguarded wallet + This group can spend any coin in it once it has waited as long as the delay below. + This group, after the delay below, and the %1$d above it, after the delays they chose, can spend any coin in it. + Only the subgroup can spend from its wallet. Groups above it can't reach it or anything beneath it. + This group is guarded, so its subgroups are too. + This group's own guardian keys can't be read, so it can't guard a subgroup. + The subgroup's wallet will be guarded: this group can spend any coin in it once it has waited %1$s, and each group above it after the delay it chose. + The subgroup's wallet will not be guarded: only the subgroup can spend from it. + The group above this one decided this group's wallet is guarded. Each group above it can spend any coin in it that has waited as long as its own delay, without this group agreeing: + The group above this one decided this group's wallet is not guarded. Only this group can spend from it. + + + %1$s, %2$s + %1$s: after %2$s + How long before this group can spend a coin + 1 hour + 2 hours + 1 day + 1 week + 1 month + 6 months + Longest + Custom + Delay in blocks + A coin the subgroup moves starts waiting again, so a long delay lets it keep its coins out of reach by moving them. + A group above this one + This group can spend a coin here after %1$s + Guarded wallet, after %1$s + Only coins that have waited %1$s can be spent from this guarded wallet. + + %1$s block + %1$s blocks + + + about %1$d minute + about %1$d minutes + + + about %1$d hour + about %1$d hours + + + about %1$d day + about %1$d days + + + about %1$d month + about %1$d months + + + about %1$d year + about %1$d years + + + + New guarded wallet + A group + Choose a group to guard it + None of your groups guards members' wallets yet. A group's signers can turn it on from the group's page. + A wallet only you can spend from, guarded by %1$s + %1$s can take any coin in it that has waited %2$s, without asking you. + %1$s can take any coin in it that has waited %2$s, and the group above it any coin that has waited %3$s, without asking you. + %1$s can take any coin in it that has waited %2$s, and each of the %3$d groups above it after the delay it chose, the shortest %4$s, without asking you. + Members of the groups that guard it will see its balance, and that it's yours. + If you lose this device, those groups can still move your coins for you. + Label (optional) + Ask %1$s + Asked %1$s to guard a wallet. + Couldn't ask the group to guard a wallet. + This profile can only look, so it can't sign a request. + Only a group with a shared key can guard a wallet. + This device doesn't know what this group signs with yet, so it can't work out the group's leaves. + Ask the group for its key + Asked. A member who holds the group's key will answer when their device next reads the room. + This group's guardian keys can't be read by this version of the app. + Guarded wallets for members aren't offered on this network yet. + This profile has no wallet of its own to watch the chain with, so it couldn't see its own coins. + %1$s would refuse this request: it was asked before the group said it guards members' wallets. Asking again makes a new one. + %1$s has changed its delay since you asked. Asking again makes a new request at the new delay. + %1$s has stopped guarding members' wallets, so this request won't be signed. You can discard it. + %1$s would refuse this request. Asking again makes a new one. + Guards members' wallets + Doesn't guard members' wallets + Stopped guarding new members' wallets + After %1$s + Guard members' wallets + How long before this group can take a coin from a member's wallet + A coin the member moves starts waiting again, so a long delay lets them keep their coins out of reach by moving them. + Wallets already guarded keep the delay they were guarded at. + Members whose app is older than this one can only be guarded at 12 blocks, and don't know this group can close. + Ask the group + Stop guarding new wallets + Stop guarding new members' wallets? + Wallets already guarded stay guarded, and this group can still take their coins after their delay. + Stop + Couldn't ask the group. + This group doesn't guard members' wallets. + This group has stopped guarding members' wallets. + You have no guarded wallets. + Waiting for someone in %1$s to put it to the group + %1$s is signing + %1$s didn't sign. Ask again, or discard it. + Key on another device + You're no longer in %1$s. It still guards this wallet. + Guarded by %1$s + Guarded by %1$s, below %2$s + this group + a group below %1$s + a group below this one + another group + the wallet guarded by %1$s + Spend from %1$s as %2$s + Members' wallets + %1$s, %2$s + + %1$d wallet + %1$d wallets + + + guarded by %1$d group + guarded by %1$d groups + + Fund %1$s's guarded wallet “%2$s” + Spend from %1$s's guarded wallet “%2$s” + Fund %1$s's wallet guarded by %2$s + Spend from %1$s's wallet guarded by %2$s + Discard + Discard this wallet? + Its key is forgotten. No address of it was ever offered, so nothing can have been paid to it. + Export key + Export this wallet's key? + Whoever holds these descriptors can spend every coin in this wallet. Keep them where only you can reach them. + Show key + Receive descriptor + Change descriptor + Copied. + Copy + Finding your coins… + %1$s took %2$s sats through its guardian leaf, in %3$s. + Taken by guardians + This wallet's key is on another of your devices, so it can be watched here but not spent from. + Couldn't ask again. + Couldn't discard the wallet. + %1$s sats come back to this wallet as change. + This wallet has nothing confirmed to spend. + This wallet doesn't have that much confirmed. + Send from your guarded wallet + You sign this alone, and it is sent as soon as you press the button. + Sending needs this wallet's key on this device, a group's certificate for it, and a wallet of this profile's own to watch the chain with. + Sign and send + Sent. + Couldn't send. + Your spends + Sent, waiting for the network to report it + In the mempool + @%1$s + Members' guarded wallets + Ask this group to guard a wallet for you + Asked by %1$s, not yet signed + Put to the group + Couldn't put it to the group. + Wallets your groups guard + This device tells the groups above about these on its own when it can. Share now if a group above hasn't heard. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt index 540db2c3..0be9bae1 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt @@ -19,6 +19,7 @@ import com.machankura.bennu.compose.database.model.IcebergParticipantMessage import com.machankura.bennu.compose.database.model.IcebergKeySession import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.database.dao.GroupTransactionDao +import com.machankura.bennu.compose.database.dao.MemberWalletDao import androidx.room3.ColumnTypeConverters import androidx.room3.AutoMigration import androidx.room3.ConstructedBy @@ -43,19 +44,6 @@ import com.machankura.bennu.compose.database.dao.GiftWrapSealDao import com.machankura.bennu.compose.database.dao.GroupKeyStateDao import com.machankura.bennu.compose.database.dao.GroupSignedEventDao import com.machankura.bennu.compose.database.dao.InReplyToRelationDao -import com.machankura.bennu.compose.database.dao.MantraArtifactDao -import com.machankura.bennu.compose.database.dao.MantraArtifactVersionDao -import com.machankura.bennu.compose.database.dao.MantraChapterDao -import com.machankura.bennu.compose.database.dao.MantraChunkDao -import com.machankura.bennu.compose.database.dao.MantraDao -import com.machankura.bennu.compose.database.dao.MantraDialectDao -import com.machankura.bennu.compose.database.dao.MantraTranslationArtifactVersionDao -import com.machankura.bennu.compose.database.dao.MantraTranslationArtifactVersionContributorDao -import com.machankura.bennu.compose.database.dao.MantraTranslationChapterDao -import com.machankura.bennu.compose.database.dao.MantraTranslationChapterContributorDao -import com.machankura.bennu.compose.database.dao.MantraTranslationChunkDao -import com.machankura.bennu.compose.database.dao.MantraTranslationDao -import com.machankura.bennu.compose.database.dao.MantraTranslationContributorDao import com.machankura.bennu.compose.database.dao.MarmotCommitResultDao import com.machankura.bennu.compose.database.dao.MarmotOutboundDao import com.machankura.bennu.compose.database.dao.MarmotGroupEventDao @@ -98,18 +86,6 @@ import com.machankura.bennu.compose.database.model.GiftWrapSeal import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.InReplyToRelation -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MantraTranslation -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersionContributor -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChapterContributor -import com.machankura.bennu.compose.database.model.MantraTranslationChunk -import com.machankura.bennu.compose.database.model.MantraTranslationContributor import com.machankura.bennu.compose.database.model.MarmotCommitResult import com.machankura.bennu.compose.database.model.MarmotGroupEvent import com.machankura.bennu.compose.database.model.MarmotInnerEvent @@ -120,6 +96,8 @@ import com.machankura.bennu.compose.database.model.MarmotPublishObligation import com.machankura.bennu.compose.database.model.MarmotOutboundGate import com.machankura.bennu.compose.managers.MarmotEngine import com.machankura.bennu.compose.database.model.MarmotRetainedEpochSecret +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.database.model.MemberWalletSpend import com.machankura.bennu.compose.database.model.Mention import com.machankura.bennu.compose.database.model.NegentropySynchronizeRequest import com.machankura.bennu.compose.database.model.NegentropySynchronizeResult @@ -181,18 +159,6 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) IcebergParticipantMessage::class, IcebergShareRow::class, InReplyToRelation::class, - MantraArtifact::class, - MantraArtifactVersion::class, - MantraChapter::class, - MantraChunk::class, - MantraDialect::class, - MantraTranslation::class, - MantraTranslationArtifactVersion::class, - MantraTranslationArtifactVersionContributor::class, - MantraTranslationChapter::class, - MantraTranslationChapterContributor::class, - MantraTranslationChunk::class, - MantraTranslationContributor::class, MarmotCommitResult::class, MarmotGroupEvent::class, MarmotInnerEvent::class, @@ -202,6 +168,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) MarmotPublishObligation::class, MarmotOutboundGate::class, MarmotRetainedEpochSecret::class, + MemberWallet::class, + MemberWalletSpend::class, Mention::class, NegentropySynchronizeRequest::class, NegentropySynchronizeResult::class, @@ -220,7 +188,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 30, + version = 32, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -408,19 +376,38 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // nothing is rebuilt; a rebuild of either signing table would fire the // cascades from FrostSigningSession, see docs/frost-batch-signing.md. AutoMigration(from = 25, to = 26), - // v27 is the group Lightning wallet's key ceremony (docs/group-lightning-wallet.md, - // Phase 5): the IcebergKeySession and IcebergParticipantMessage tables. Two new - // tables and nothing else, which Room migrates itself. - AutoMigration(from = 26, to = 27), - // v28 is the Lightning wallet's node seed (docs/group-lightning-wallet.md, Phase 6): - // the GroupLightningSeed table, keyed by the node id each seed produces. + // v27 drops the nip30303 document tables and MarmotInnerEvent's + // payloadEventId, and deletes the chat lines nothing renders any more + // (docs/ceremony-creation.md, Phase 8). Manual -- it deletes rows -- + // so it is MIGRATION_26_27 in `getRoomDatabase`, not an entry here. + // + // v28 adds the nullable GroupTransaction.guardedChatRoomId: the descendant + // whose guarded wallet a guardian's spend draws from + // (docs/group-wallet-guardians.md, Phase 7). Every spend before it was the + // room's own, which is what null means. AutoMigration(from = 27, to = 28), - // v29 is the co-signing protocol (docs/group-lightning-wallet.md, Phase 9): seven new - // tables, from the round-one pool to the per-channel ledger. Nothing existing changes. + // v29 adds the nullable DkgSession.walletPolicy: the wallet policy a + // subgroup's ceremony was proposed under (docs/subgroup-wallet-policy.md, + // Phase 2). Every ceremony before it chose none, which is what null means. AutoMigration(from = 28, to = 29), - // v30 is what members keep of the operator's reports (docs/group-lightning-wallet.md, - // Phases 10 and 11): the newest snapshot, the payments, the invoices. Three new tables. + // v30 adds MemberWallet and MemberWalletSpend: the random key of a + // guarded wallet one member holds and a group guards, and the spends the + // member signed alone from it (docs/member-guarded-wallets.md, Phase 5). + // New tables, and no foreign keys -- deleting a group's room must never + // delete a key coins may sit behind. AutoMigration(from = 29, to = 30), + // v31 adds the nullable DkgSession.guardianDelay: the delay a guarded + // subgroup's ceremony was proposed under for the parent's own leaf + // (docs/guardian-delay.md, Phase 4). Null for every ceremony before it. + AutoMigration(from = 30, to = 31), + // v32 is the group Lightning wallet (docs/group-lightning-wallet.md): the Iceberg key + // ceremony (IcebergKeySession, IcebergParticipantMessage), the node seed + // (GroupLightningSeed), the co-signing protocol (seven Iceberg tables, from the round-one + // pool to the per-channel ledger), and what members keep of the operator's reports + // (GroupLightningSnapshotRow, GroupLightningPaymentRow, GroupLightningInvoiceRow). New + // tables and nothing else. They were four versions on the branch that built them, before + // it merged after v31; no installed database ever had those, so they are one step here. + AutoMigration(from = 31, to = 32), ] ) @ConstructedBy(BennuDatabaseConstructor::class) @@ -457,6 +444,8 @@ abstract class BennuDatabase: RoomDatabase() { abstract fun groupTransactionDao(): GroupTransactionDao + abstract fun memberWalletDao(): MemberWalletDao + abstract fun connectionDao(): ConnectionDao abstract fun giftWrapMessageDao(): GiftWrapMessageDao @@ -467,31 +456,6 @@ abstract class BennuDatabase: RoomDatabase() { abstract fun inReplyToRelationDao(): InReplyToRelationDao - abstract fun mantraDao(): MantraDao - - abstract fun mantraArtifactDao(): MantraArtifactDao - - abstract fun mantraArtifactVersionDao(): MantraArtifactVersionDao - - abstract fun mantraChapterDao(): MantraChapterDao - - abstract fun mantraChunkDao(): MantraChunkDao - - abstract fun mantraDialectDao(): MantraDialectDao - - abstract fun mantraTranslationArtifactVersionDao(): MantraTranslationArtifactVersionDao - - abstract fun mantraTranslationArtifactVersionContributorDao(): MantraTranslationArtifactVersionContributorDao - - abstract fun mantraTranslationChapterDao(): MantraTranslationChapterDao - - abstract fun mantraTranslationChapterContributorDao(): MantraTranslationChapterContributorDao - - abstract fun mantraTranslationChunkDao(): MantraTranslationChunkDao - - abstract fun mantraTranslationDao(): MantraTranslationDao - - abstract fun mantraTranslationContributorDao(): MantraTranslationContributorDao abstract fun icebergKeySessionDao(): IcebergKeySessionDao @@ -558,6 +522,11 @@ abstract class BennuDatabase: RoomDatabase() { useWriterConnection { transactor -> transactor.immediateTransaction { // TODO: Actually delete the data... + // + // When this does: MemberWallet holds the only copy of keys that + // coins may sit behind (docs/member-guarded-wallets.md, D6). A + // caller wiping a profile that holds an open member wallet has to + // say so first and offer the key's export, before anything goes. } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/builder/PlatformDatabaseBuilder.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/builder/PlatformDatabaseBuilder.kt index 13e5f002..6c4ae40e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/builder/PlatformDatabaseBuilder.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/builder/PlatformDatabaseBuilder.kt @@ -6,6 +6,7 @@ import com.machankura.bennu.compose.database.migrations.MIGRATION_3_4 import com.machankura.bennu.compose.database.migrations.MIGRATION_9_10 import com.machankura.bennu.compose.database.migrations.MIGRATION_13_14 import com.machankura.bennu.compose.database.migrations.MIGRATION_14_15 +import com.machankura.bennu.compose.database.migrations.MIGRATION_26_27 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO @@ -19,13 +20,15 @@ fun getRoomDatabase( builder: RoomDatabase.Builder ): com.machankura.bennu.compose.database.BennuDatabase { return builder - // Everything else Room generates itself. These four move data rather than + // Everything else Room generates itself. These five move data rather than // only changing shape, which an AutoMigration cannot express: 3->4 rewrites // chat rows, 9->10 copies a session's per-event columns onto the items // table before dropping them, 13->14 renames a column and rewrites the - // chat rows that named it the old way, and 14->15 adds a column and deletes - // the chat rows written for messages from before this device joined. - .addMigrations(MIGRATION_3_4, MIGRATION_9_10, MIGRATION_13_14, MIGRATION_14_15) + // chat rows that named it the old way, 14->15 adds a column and deletes + // the chat rows written for messages from before this device joined, and + // 26->27 drops the document tables and deletes the chat rows nothing + // renders any more. + .addMigrations(MIGRATION_3_4, MIGRATION_9_10, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_26_27) .setDriver(BundledSQLiteDriver()) .setQueryCoroutineContext(Dispatchers.IO) .build() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraArtifactDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraArtifactDao.kt deleted file mode 100644 index 9fb30e42..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraArtifactDao.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraArtifact - -@Dao -interface MantraArtifactDao { - @Upsert - suspend fun upsert(mantraArtifact: MantraArtifact) - - @Query("SELECT * FROM MantraArtifact WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") - suspend fun getArtifactsByChatRoomId(chatRoomId: String): List - - @Query("SELECT * FROM MantraArtifact WHERE id = :id") - suspend fun getArtifactById(id: String): MantraArtifact? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraArtifactVersionDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraArtifactVersionDao.kt deleted file mode 100644 index 845c191d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraArtifactVersionDao.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraArtifactVersion - -@Dao -interface MantraArtifactVersionDao { - @Upsert - suspend fun upsert(mantraArtifactVersion: MantraArtifactVersion) - - @Query("SELECT * FROM MantraArtifactVersion WHERE artifactId = :artifactId ORDER BY createdAt DESC") - suspend fun getArtifactVersionsByArtifactId(artifactId: String): List - - @Query("SELECT * FROM MantraArtifactVersion WHERE id = :id") - suspend fun getArtifactVersionById(id: String): MantraArtifactVersion? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraChapterDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraChapterDao.kt deleted file mode 100644 index c25108e6..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraChapterDao.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraChapter - -@Dao -interface MantraChapterDao { - @Upsert - suspend fun upsert(mantraChapter: MantraChapter) - - /** Chapters across all versions of an artifact, ordered by their in-book index. */ - @Query( - """ - SELECT MantraChapter.* FROM MantraChapter - INNER JOIN MantraArtifactVersion - ON MantraChapter.artifactVersionId = MantraArtifactVersion.id - WHERE MantraArtifactVersion.artifactId = :artifactId - ORDER BY MantraChapter.`index` ASC - """ - ) - suspend fun getChaptersByArtifactId(artifactId: String): List - - @Query("SELECT * FROM MantraChapter WHERE artifactVersionId = :artifactVersionId ORDER BY `index` ASC") - suspend fun getChaptersByArtifactVersionId(artifactVersionId: String): List - - @Query("SELECT * FROM MantraChapter WHERE id = :id") - suspend fun getChapterById(id: String): MantraChapter? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraChunkDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraChunkDao.kt deleted file mode 100644 index e0913038..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraChunkDao.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraChunk - -@Dao -interface MantraChunkDao { - @Upsert - suspend fun upsert(mantraChunk: MantraChunk) - - @Query("SELECT * FROM MantraChunk WHERE chapterId = :chapterId ORDER BY `index` ASC") - suspend fun getChunksByChapterId(chapterId: String): List - - @Query("SELECT * FROM MantraChunk WHERE id = :id") - suspend fun getChunkById(id: String): MantraChunk? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraDao.kt deleted file mode 100644 index 5cf51b92..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraDao.kt +++ /dev/null @@ -1,216 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Transaction -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.model.ChatMessage -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MarmotInnerEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactIdTag -import com.machankura.bennu.compose.repository.MantraRepository.Companion.DEFAULT_LICENSE -import com.machankura.bennu.compose.repository.MantraRepository.Companion.DEFAULT_VISIBILITY -import kotlin.time.Instant - -@Dao -abstract class MantraDao( - private val database: BennuDatabase, -) { - val logger = Logger.withTag("NostrDao") - - /** - * The unsigned nip30303 event [template] describes, authored by [publicKey]. - * - * Its id is computed the same way the matching Mantra* entity computes - * its own, so the row on disk and the payload on the wire are the same - * event rather than two copies of one. - */ - private fun rumorOf( - template: EventTemplate, - publicKey: HexKey, - ): Event = Event( - id = EventHasher.hashId( - pubKey = publicKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - ), - pubKey = publicKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - // A rumor. What signs for this reaching the group is the kind:445 the - // outbound pipeline wraps it in, not the payload itself. - sig = "", - ) - - /** - * Queue [payload] for the group inside a [SubmissionEvent] that - * [submitterPublicKey] authors. - * - * nip30303 events are never sent on their own. Wrapping them means the - * payload keeps whoever wrote it as its author while the group still knows - * which member put it there -- see [SubmissionEvent] for why the two are - * worth telling apart. - * - * The submission is stored as an unprocessed rumor (null marmotGroupEventId), - * which is what the outbound pipeline picks up and encrypts into a kind:445 - * group event for the chat room. - */ - private suspend fun submitToGroup( - chatRoomId: String, - submitterPublicKey: HexKey, - payload: Event, - text: String, - ): MarmotInnerEvent { - val submissionTemplate = SubmissionEvent.build(payload = payload) - - val submissionInnerEvent = MarmotInnerEvent( - id = EventHasher.hashId( - pubKey = submitterPublicKey, - createdAt = submissionTemplate.createdAt, - kind = submissionTemplate.kind, - tags = submissionTemplate.tags, - content = submissionTemplate.content, - ), - publicKey = submitterPublicKey, - kind = SubmissionEvent.KIND, - createdAt = Instant.fromEpochSeconds(submissionTemplate.createdAt), - tags = submissionTemplate.tags, - content = submissionTemplate.content, - payloadEventId = payload.id, - chatRoomId = chatRoomId, - ) - - sendMarmotInnerEvent( - chatRoomId = chatRoomId, - userPublicKey = submitterPublicKey, - text = text, - marmotInnerEvent = submissionInnerEvent, - ) - - return submissionInnerEvent - } - - @Transaction - open suspend fun addDialect( - localChatRoom: LocalChatRoom, - name: String, - country: String, - language: String, - userPublicKey: HexKey, - ): MantraDialect? { - logger.d("addDialect: $name") - - val dialectEventTemplate = DialectEvent.build( - name = name, - country = country, - language = language, - ) - - val mantraDialect = MantraDialect.fromDialectEventTemplate( - dialectEventTemplate = dialectEventTemplate, - chatRoomId = localChatRoom.chatRoom.id, - userPublicKey = userPublicKey, - ) ?: return null - - return try { - database.mantraDialectDao().upsert(mantraDialect) - - submitToGroup( - chatRoomId = mantraDialect.chatRoomId, - submitterPublicKey = userPublicKey, - payload = rumorOf(dialectEventTemplate, userPublicKey), - text = "Added $name as a dialect", - ) - - mantraDialect - } catch (error: Throwable) { - logger.e("Failed to add dialect \"$name\" to chat room ${localChatRoom.chatRoom.id}", error) - null - } - - } - - @Transaction - open suspend fun addArtifactVersion( - localChatRoom: LocalChatRoom, - artifactId: HexKey, - versionLabel: String, - userPublicKey: HexKey, - ): MantraArtifactVersion? { - return addArtifactVersionInternal( - localChatRoom = localChatRoom, - artifactId = artifactId, - versionLabel = versionLabel, - userPublicKey = userPublicKey - ) - } - - private suspend fun addArtifactVersionInternal( - localChatRoom: LocalChatRoom, - artifactId: HexKey, - versionLabel: String, - userPublicKey: HexKey, - ): MantraArtifactVersion? { - // The version label is carried in the event content (see - // MantraArtifactVersion.fromArtifactVersionEvent). - val artifactVersionEventTemplate = ArtifactVersionEvent.build( - content = versionLabel, - ) { - addUnique(ArtifactIdTag.assemble(artifactId)) - } - - val mantraArtifactVersion = MantraArtifactVersion.fromArtifactVersionEventTemplate( - artifactVersionEventTemplate = artifactVersionEventTemplate, - chatRoomId = localChatRoom.chatRoom.id, - userPublicKey = userPublicKey, - ) ?: return null - - database.mantraArtifactVersionDao().upsert(mantraArtifactVersion) - - submitToGroup( - chatRoomId = mantraArtifactVersion.chatRoomId, - submitterPublicKey = userPublicKey, - payload = rumorOf(artifactVersionEventTemplate, userPublicKey), - text = "Add the ${artifactVersionEventTemplate.content} version", - ) - - return mantraArtifactVersion - } - - private suspend fun sendMarmotInnerEvent( - chatRoomId: String, - userPublicKey: HexKey, - text: String, - marmotInnerEvent: MarmotInnerEvent - ) { - database.marmotInnerEventDao().upsert( - marmotInnerEvent - ) - - database.chatMessageDao().upsert( - ChatMessage( - content = text, - chatRoomId = chatRoomId, - senderPublicKey = userPublicKey, - isUserMessage = true, - giftWrapPayloadId = null, - marmotGroupEventId = null, - marmotInnerEventId = marmotInnerEvent.id, - ) - ) - // TODO: Depending on visibility (if signature is non-empty) might want to queue this event for broadcasting... - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraDialectDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraDialectDao.kt deleted file mode 100644 index 1d4b7f40..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraDialectDao.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraDialect - -@Dao -interface MantraDialectDao { - @Upsert - suspend fun upsert(mantraDialect: MantraDialect) - - @Query("SELECT * FROM MantraDialect WHERE chatRoomId = :chatRoomId ORDER BY name") - suspend fun getDialectsByChatRoomId(chatRoomId: String): List - - @Query("SELECT * FROM MantraDialect WHERE id = :id") - suspend fun getDialectById(id: String): MantraDialect? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationArtifactVersionContributorDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationArtifactVersionContributorDao.kt deleted file mode 100644 index b15910d7..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationArtifactVersionContributorDao.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersionContributor - -@Dao -interface MantraTranslationArtifactVersionContributorDao { - @Upsert - suspend fun upsert(mantraTranslationArtifactVersionContributor: MantraTranslationArtifactVersionContributor) -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationArtifactVersionDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationArtifactVersionDao.kt deleted file mode 100644 index ca26aca6..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationArtifactVersionDao.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion - -@Dao -interface MantraTranslationArtifactVersionDao { - @Upsert - suspend fun upsert(mantraTranslationArtifactVersion: MantraTranslationArtifactVersion) - - /** Translations targeting any version of an artifact. */ - @Query( - """ - SELECT MantraTranslationArtifactVersion.* FROM MantraTranslationArtifactVersion - INNER JOIN MantraArtifactVersion - ON MantraTranslationArtifactVersion.artifactVersionId = MantraArtifactVersion.id - WHERE MantraArtifactVersion.artifactId = :artifactId - ORDER BY MantraTranslationArtifactVersion.createdAt DESC - """ - ) - suspend fun getTranslationsByArtifactId(artifactId: String): List - - /** - * Translations of one version, which is what a chapter of that version has - * to be scaffolded into. Narrower than [getTranslationsByArtifactId]: a - * chapter belongs to a version, and a translation of an older version is - * not a translation the chapter is in. - */ - @Query( - """ - SELECT * FROM MantraTranslationArtifactVersion - WHERE artifactVersionId = :artifactVersionId - ORDER BY createdAt DESC - """ - ) - suspend fun getTranslationsByArtifactVersionId(artifactVersionId: String): List - - @Query("SELECT * FROM MantraTranslationArtifactVersion WHERE id = :id") - suspend fun getTranslationById(id: String): MantraTranslationArtifactVersion? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChapterContributorDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChapterContributorDao.kt deleted file mode 100644 index f5826cb7..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChapterContributorDao.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChapterContributor - -@Dao -interface MantraTranslationChapterContributorDao { - @Upsert - suspend fun upsert(mantraTranslationChapterContributor: MantraTranslationChapterContributor) -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChapterDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChapterDao.kt deleted file mode 100644 index 9cb71940..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChapterDao.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslationChapter - -@Dao -interface MantraTranslationChapterDao { - @Upsert - suspend fun upsert(mantraTranslationChapter: MantraTranslationChapter) - - @Query("SELECT * FROM MantraTranslationChapter WHERE translationArtifactVersionId = :translationArtifactVersionId ORDER BY `index` ASC") - suspend fun getTranslationChaptersByTranslationArtifactVersionId(translationArtifactVersionId: String): List - - @Query("SELECT * FROM MantraTranslationChapter WHERE id = :id") - suspend fun getTranslationChapterById(id: String): MantraTranslationChapter? -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChunkDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChunkDao.kt deleted file mode 100644 index a80eca2d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationChunkDao.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Query -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslationChunk - -@Dao -interface MantraTranslationChunkDao { - @Upsert - suspend fun upsert(mantraTranslationChunk: MantraTranslationChunk) - - @Query("SELECT * FROM MantraTranslationChunk WHERE translationChapterId = :translationChapterId ORDER BY `index` ASC") - suspend fun getTranslationChunksByTranslationChapterId(translationChapterId: String): List - - /** - * Every translation this chapter holds of one source chunk. - * - * There should only ever be one, and this is how that is kept true: a - * retranslation is a new event with a new id rather than an edit, so the - * row it replaces has to be found and dropped. - */ - @Query("SELECT * FROM MantraTranslationChunk WHERE translationChapterId = :translationChapterId AND chunkId = :chunkId") - suspend fun getTranslationChunksByChunkId( - translationChapterId: String, - chunkId: String - ): List - - @Query("DELETE FROM MantraTranslationChunk WHERE id = :id") - suspend fun deleteById(id: String) -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationContributorDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationContributorDao.kt deleted file mode 100644 index da5ce79e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationContributorDao.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslationContributor - -@Dao -interface MantraTranslationContributorDao { - @Upsert - suspend fun upsert(mantraTranslationContributor: MantraTranslationContributor) -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationDao.kt deleted file mode 100644 index 0c13bb3f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MantraTranslationDao.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy.Companion.IGNORE -import androidx.room3.Upsert -import com.machankura.bennu.compose.database.model.MantraTranslation - -@Dao -interface MantraTranslationDao { - @Upsert - suspend fun upsert(mantraTranslation: MantraTranslation) -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotInnerEventDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotInnerEventDao.kt index 8867b41c..55e790a6 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotInnerEventDao.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotInnerEventDao.kt @@ -65,12 +65,4 @@ interface MarmotInnerEventDao { @Query("DELETE FROM MarmotInnerEvent WHERE id = :id") suspend fun deleteById(id: String) - /** - * Drop the submissions carrying [payloadEventId]. - * - * A submission's id is the envelope's, not the payload's, so a superseded - * nip30303 event cannot be un-queued by its own id. - */ - @Query("DELETE FROM MarmotInnerEvent WHERE payloadEventId = :payloadEventId") - suspend fun deleteByPayloadEventId(payloadEventId: String) } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MemberWalletDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MemberWalletDao.kt new file mode 100644 index 00000000..fc279727 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MemberWalletDao.kt @@ -0,0 +1,46 @@ +package com.machankura.bennu.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Query +import androidx.room3.Upsert +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import kotlinx.coroutines.flow.Flow + +@Dao +abstract class MemberWalletDao { + @Query("SELECT * FROM MemberWallet WHERE ownerPublicKey = :ownerPublicKey ORDER BY createdAt DESC") + abstract suspend fun getByOwner(ownerPublicKey: String): List + + @Query("SELECT * FROM MemberWallet WHERE ownerPublicKey = :ownerPublicKey ORDER BY createdAt DESC") + abstract fun observeByOwner(ownerPublicKey: String): Flow> + + @Query("SELECT * FROM MemberWallet WHERE walletId = :walletId") + abstract suspend fun getById(walletId: String): MemberWallet? + + @Query("SELECT * FROM MemberWallet WHERE guardingChatRoomId = :chatRoomId ORDER BY createdAt DESC") + abstract suspend fun getByGuardingChatRoomId(chatRoomId: String): List + + @Upsert + abstract suspend fun upsert(wallet: MemberWallet) + + /** + * Deletes a wallet's key. `MemberWalletManager.discard` is the only caller, + * and only for a wallet no group has certified: before then no address was + * ever offered, so no coin can be behind the key. + */ + @Query("DELETE FROM MemberWallet WHERE walletId = :walletId") + abstract suspend fun delete(walletId: String) + + @Query("SELECT * FROM MemberWalletSpend WHERE walletId = :walletId ORDER BY createdAt DESC") + abstract suspend fun getSpends(walletId: String): List + + @Query("SELECT * FROM MemberWalletSpend WHERE walletId = :walletId ORDER BY createdAt DESC") + abstract fun observeSpends(walletId: String): Flow> + + @Query("SELECT * FROM MemberWalletSpend WHERE txid = :txid") + abstract suspend fun getSpend(txid: String): MemberWalletSpend? + + @Upsert + abstract suspend fun upsertSpend(spend: MemberWalletSpend) +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt index 8d792e4f..c538144a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt @@ -1536,8 +1536,12 @@ abstract class NostrDao( is GroupEventResult.ProposalStaged -> { database.marmotOutboundDao().commitStagedProposals(localChatRoom) } + // Every application message lands here -- chat, documents, and the + // ceremony and signing messages handled just below. Debug, because at + // info it read like a failure on each of them and sent at least one + // investigation the wrong way. else -> { - logger.i("No app logic to handle: $groupEventResult") + logger.d("No membership change to file for: $groupEventResult") } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/migrations/RemoveDocumentsMigration.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/migrations/RemoveDocumentsMigration.kt new file mode 100644 index 00000000..c936df0b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/migrations/RemoveDocumentsMigration.kt @@ -0,0 +1,80 @@ +package com.machankura.bennu.compose.database.migrations + +import androidx.room3.migration.Migration +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.execSQL + +/** + * Drops the nip30303 document tables, and the chat lines nothing can show any more. + * + * The artifact, chapter, dialect and translation screens were unreachable, and + * their kinds shared numbers with the key ceremony's: a subgroup's round 1 (30312) + * was read as a document submission and landed in the parent's chat as raw hex. + * See docs/ceremony-creation.md, Phases 7 and 8. + * + * Manual rather than an `AutoMigration`, because it deletes chat rows as well as + * changing shape: + * + * - the lines the removed document arms wrote (`artifact`, `chapter`, `dialect`, + * `translationArtifactVersion`, `translation`), which nothing renders now; + * - the `unsupported` lines written for a ceremony's own messages. They are the + * raw-hex bubbles above, found by the kind of the inner event behind them, and + * only those: an `unsupported` line over any other kind is still the only trace + * an unrecognised payload leaves, and stays. + * + * Then the twelve tables, children before parents. No kept table has a foreign key + * into any of them, so nothing outside them cascades; the order is so the drops + * hold if foreign keys are ever enforced during a migration. And + * `MarmotInnerEvent.payloadEventId`, which only a submission ever set. + * + * `DROP COLUMN` is safe for the reason `ChronicleRenameMigration` gives for + * `RENAME COLUMN`: `getRoomDatabase` pins `BundledSQLiteDriver` on every platform, + * so the SQLite underneath is one this app chose. The column has no index and is + * in no foreign key, either of which SQLite would refuse to drop it from. + * + * `GroupSignedEvent` keeps any rows of the document kinds. The table is generic + * and keyed by kind, nothing reads those kinds any more, and deleting what a group + * signed is not this migration's call. The chronicle's column and its lines stay + * too: the chronicle is kept, carrying nothing. + */ +val MIGRATION_26_27 = object : Migration(26, 27) { + override suspend fun migrate(connection: SQLiteConnection) { + connection.execSQL( + "DELETE FROM `ChatMessage` WHERE `messageType` IN " + + "('artifact', 'chapter', 'dialect', 'translationArtifactVersion', 'translation')" + ) + connection.execSQL( + "DELETE FROM `ChatMessage` WHERE `messageType` = 'unsupported' " + + "AND `marmotInnerEventId` IN (" + + "SELECT `id` FROM `MarmotInnerEvent` WHERE `kind` BETWEEN $FIRST_CEREMONY_KIND AND $LAST_CEREMONY_KIND)" + ) + + DOCUMENT_TABLES.forEach { table -> connection.execSQL("DROP TABLE IF EXISTS `$table`") } + + connection.execSQL("ALTER TABLE `MarmotInnerEvent` DROP COLUMN `payloadEventId`") + } +} + +/** + * The ceremony's kinds, written out rather than read from `DkgRitualEvents`: a + * migration has to keep meaning what it meant when it shipped, whatever the + * constants later say. + */ +private const val FIRST_CEREMONY_KIND = 30310 +private const val LAST_CEREMONY_KIND = 30316 + +/** Children before parents. */ +internal val DOCUMENT_TABLES = listOf( + "MantraTranslationContributor", + "MantraTranslation", + "MantraTranslationArtifactVersionContributor", + "MantraTranslationChapterContributor", + "MantraTranslationChunk", + "MantraTranslationChapter", + "MantraTranslationArtifactVersion", + "MantraChunk", + "MantraChapter", + "MantraArtifactVersion", + "MantraArtifact", + "MantraDialect", +) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 561bb0a8..b37c1cbc 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -6,6 +6,9 @@ import com.machankura.bennu.compose.text.grouped import fr.acinq.bitcoin.Satoshi import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent +import com.machankura.bennu.compose.text.describe +import com.machankura.bennu.compose.text.BlockDuration +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Index @@ -18,8 +21,13 @@ import com.machankura.bennu.compose.database.model.traits.TimestampedEntity import com.machankura.bennu.compose.database.model.traits.UserViewableEntity import com.machankura.bennu.compose.exceptions.MarmotUnprocessableInnerEventException import com.machankura.bennu.compose.managers.ChronicleManager +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.extensions.toHex import com.vitorpamplona.quartz.marmot.GroupEventResult @@ -29,9 +37,10 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupRelaySet +import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent +import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent +import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import com.vitorpamplona.quartz.nipC7Chats.ChatEvent import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents @@ -39,20 +48,9 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent import com.machankura.bennu.compose.nostr.chronicle.ChronicleRequestEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.firstTagValue import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent @@ -471,53 +469,6 @@ data class ChatMessage( */ const val TYPE_SUBGROUP_CERTIFIED = "subgroupCertified" - /** - * The group signed what it says about itself on nostr. - * - * A system line rather than a bubble, for the reason every group-signed - * line is one: nobody said it, the group signed it. Whoever filled the - * form in proposed it and a quorum agreed, and the transcript of that - * happening is the signing session's own -- this is the line saying what - * the group now is, which is worth having in the room because a rename is - * the kind of thing members should not have to go looking for. - * - * Written only for a profile the *room* signed. A kind:0 authored by - * anybody else that reaches this room is a member's own profile - * travelling as a rumor, which is not the group saying anything. - */ - const val TYPE_GROUP_PROFILE_SIGNED = "groupProfileSigned" - - /** - * The group signed where it lives on nostr. - * - * One line per list, so a session that changed three of them writes three. - * They are not three accounts of one thing -- each names which list was - * agreed, which is the part a reader needs -- and `applyInnerEvent` is - * handed one event at a time with no way to know it was in a batch anyway. - */ - const val TYPE_GROUP_RELAYS_SIGNED = "groupRelaysSigned" - - /** - * Every line about the group's own nostr identity, for the one check the - * transcript dispatches on. - * - * The profile and the relay lists together, because they are the same kind - * of statement -- the group's account of itself, signed by the group -- and - * the transcript does the same thing with both. A type missing from here - * renders as a chat bubble, silently, looking exactly like somebody having - * said "The group is now called Translation collective". - */ - /** - * The group signed something to say publicly, in its own name. - * - * A system line rather than a bubble, like the other two -- nobody said it, - * the group signed it -- and the line names the post rather than repeating - * it, because the post itself is on the group's screen where it can be read - * whole. A quote here would be the same words twice with the second copy - * unable to say who agreed to them. - */ - const val TYPE_GROUP_POST_SIGNED = "groupPostSigned" - /** * Lines the curated-lists feature wrote: the group signing a list's schema, * and an entry into one. The feature is gone and nothing writes either any @@ -528,6 +479,15 @@ data class ChatMessage( private const val TYPE_LEGACY_GROUP_SCHEMA_SIGNED = "groupSchemaSigned" private const val TYPE_LEGACY_GROUP_ENTRY_CURATED = "groupEntryCurated" + /** + * Lines the group's nostr profile, relay lists and posts wrote. Those + * features are gone too, and these stay for the same reason: rows already + * in a transcript carry them and have to stay system lines. + */ + private const val TYPE_LEGACY_GROUP_PROFILE_SIGNED = "groupProfileSigned" + private const val TYPE_LEGACY_GROUP_RELAYS_SIGNED = "groupRelaysSigned" + private const val TYPE_LEGACY_GROUP_POST_SIGNED = "groupPostSigned" + /** * The group opened a wallet. * @@ -548,10 +508,47 @@ data class ChatMessage( */ const val TYPE_GROUP_TRANSACTION_CONFIRMED = "groupTransactionConfirmed" + /** + * A member told this group about a descendant's guarded wallet -- a + * `GuardedWalletNoticeEvent` this device checked and believes. Written + * from the notice, attributed to the member who forwarded it. See + * `docs/group-wallet-guardians.md`. + */ + const val TYPE_GUARDED_WALLET_SHARED = "guardedWalletShared" + + /** + * One of this group's guardians spent from its guarded wallet through its + * leaf. Read off the chain by `GuardianManager.takenIn`, and the child's + * only notice of it: nobody in this room signed it. + */ + const val TYPE_GUARDIAN_SPEND = "guardianSpend" + + /** + * A member asked this group to guard a wallet only they can spend from -- + * a `MemberWalletRequestEvent` this device checked. A request, not a + * decision: the group decides when a signer puts it to the quorum. See + * `docs/member-guarded-wallets.md`. + */ + const val TYPE_MEMBER_WALLET_REQUESTED = "memberWalletRequested" + + /** The group signed a member wallet certificate: it now guards that member's wallet. */ + const val TYPE_MEMBER_WALLET_GUARDED = "memberWalletGuarded" + + /** + * The group signed a policy on its members' wallets: it guards them, at a + * delay, or it has stopped. See `docs/member-wallet-delay.md`. + */ + const val TYPE_MEMBER_WALLET_POLICY = "memberWalletPolicy" + + /** + * Every line the group signed, for the one check the transcript + * dispatches on. A type missing from here renders as a chat bubble, + * silently, looking exactly like somebody having said it. + */ val GROUP_IDENTITY_TYPES = setOf( - TYPE_GROUP_PROFILE_SIGNED, - TYPE_GROUP_RELAYS_SIGNED, - TYPE_GROUP_POST_SIGNED, + TYPE_LEGACY_GROUP_PROFILE_SIGNED, + TYPE_LEGACY_GROUP_RELAYS_SIGNED, + TYPE_LEGACY_GROUP_POST_SIGNED, TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_GROUP_WALLET_OPENED, @@ -559,6 +556,11 @@ data class ChatMessage( TYPE_GROUP_LIGHTNING_WALLET_OPENED, TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED, TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED, + TYPE_GUARDED_WALLET_SHARED, + TYPE_GUARDIAN_SPEND, + TYPE_MEMBER_WALLET_REQUESTED, + TYPE_MEMBER_WALLET_GUARDED, + TYPE_MEMBER_WALLET_POLICY, ) /** @@ -926,24 +928,25 @@ data class ChatMessage( val event = Event.fromJsonOrNull(groupEventResult.innerEventJson) ?: throw MarmotUnprocessableInnerEventException("Can't process ${groupEventResult.innerEventJson}") - // A submission is an envelope: the nip30303 event it delivers - // is in its content, written by whoever wrote it. Everything - // else on the wire is the nip30303 event itself. Either way the - // row on disk is the outer event -- that is what the group sent - // and what the chat line is attributed to. - val submission = if (event.kind == SubmissionEvent.KIND) { - SubmissionEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - } else { - null - } - val payload = submission?.payload() + // A key ceremony's or a signing session's own message. Decided + // first: 30310-30312 were nip30303 document kinds too, and round + // 1 of a subgroup's ceremony (30312) was read as a document + // submission, failed to parse, and landed in the parent's chat + // as raw hex -- see docs/ceremony-creation.md, finding F11. Stored like + // every inner event, so a ceremony can replay what arrived + // before its proposal; acted on by the managers + // `NostrDao.fileGroupEventResult` dispatches to, which write + // their own transcript lines. + // + // Except a direct message's envelope. It shares 30330 with a + // signing session's decline, and is told apart by what it + // carries: an envelope holds a gift wrap, a decline does not. + // Treating every 30330 as a decline dropped every direct + // message in a current-profile room. + val isDirectMessageEnvelope = MarmotDirectMessage.wrapInside(event) != null + val isProtocolMessage = !isDirectMessageEnvelope && ( + event.kind in DkgRitualEvents.ALL || event.kind in FrostSigningEvents.ALL + ) database.marmotInnerEventDao().upsert( MarmotInnerEvent( @@ -954,12 +957,13 @@ data class ChatMessage( content = event.content, chatRoomId = groupEventResult.groupId, kind = event.kind, - payloadEventId = payload?.id, createdAt = Instant.fromEpochSeconds(event.createdAt) ) ) - // A direct message is not a nip30303 payload to apply. It is + if (isProtocolMessage) return null + + // A direct message is not a payload to apply. It is // gift wrapped for one member, and what this device does with it // depends only on whether its key opens it. A legacy room carries // the wrap itself; a current-profile room carries it inside an @@ -1017,6 +1021,33 @@ data class ChatMessage( return null } + // A descendant's guarded wallet, carried up by a member who is in + // both rooms. The row above is the whole record of it -- there is + // no table -- so all that is left is the line, and only for a + // notice this room can actually believe. + if (event.kind == GuardedWalletNoticeEvent.KIND) { + // And on, a generation further: the statement inside, to + // the groups above this one that this device is in. Any + // device that believes it can, whether or not it holds this + // room's key. docs/guarded-wallet-forwarding.md. + GuardedWalletNoticeEvent.statementOf(event)?.let { + GuardianManager.forwardOnArrival(database, it, groupEventResult.groupId) + } + val content = GuardianManager.describeNotice(database, groupEventResult.groupId, event) + ?: return null + return ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_GUARDED_WALLET_SHARED, + marmotGroupEventId = groupEvent.id, + marmotInnerEventId = event.id, + senderPublicKey = senderIdentity ?: event.pubKey, + isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), + chatRoomId = groupEventResult.groupId, + createdAt = Instant.fromEpochSeconds(event.createdAt), + content = content, + ) + } + // Somebody in the room holds none of its signed work and is // asking. Any member may answer and none is elected to: a // duplicate answer costs bandwidth and nothing else, since @@ -1037,33 +1068,34 @@ data class ChatMessage( return null } - // A submission whose payload will not parse, or which carries - // another submission, is kept but not applied: there is nothing - // here we can turn into a row. - if (submission != null && (payload == null || payload.kind == SubmissionEvent.KIND)) { - ChatMessage( - giftWrapPayloadId = null, - messageType = "unsupported", - marmotGroupEventId = groupEvent.id, - marmotInnerEventId = event.id, - senderPublicKey = event.pubKey, - isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), - chatRoomId = groupEventResult.groupId, - createdAt = Instant.fromEpochSeconds(event.createdAt), - content = event.content, - ) - } else { - applyInnerEvent( + // A member asking what the group signs with, so their device + // can work out a guarded wallet's leaves, or a member + // answering. Plumbing, so no line either way: the row above + // is the record, and an answer is checked each time it is + // read. Answered like the chronicle's request -- by any + // member holding the key state, none elected. + // docs/member-guarded-wallets.md, Phase 2. + if (event.kind == GroupKeyNoticeEvent.KIND) { + MemberWalletManager.answerKeyRequest( database = database, - groupId = groupEventResult.groupId, - event = payload ?: event, - marmotGroupEventId = groupEvent.id, - marmotInnerEventId = event.id, - senderPublicKey = event.pubKey, - isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), - createdAt = Instant.fromEpochSeconds(event.createdAt), + chatRoomId = groupEventResult.groupId, + request = event, + userPublicKey = activeKeyPair.pubKey.toHex(), ) + + return null } + + applyInnerEvent( + database = database, + groupId = groupEventResult.groupId, + event = event, + marmotGroupEventId = groupEvent.id, + marmotInnerEventId = event.id, + senderPublicKey = event.pubKey, + isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), + createdAt = Instant.fromEpochSeconds(event.createdAt), + ) } is GroupEventResult.CommitPending -> { ChatMessage( @@ -1157,16 +1189,12 @@ data class ChatMessage( } /** - * Apply one nip30303 [event] the group delivered, and describe it for - * the transcript. + * Apply one [event] the group delivered, and describe it for the + * transcript. * * [event] is what is being applied; the other parameters are how it - * arrived. They come apart for submissions: the payload is written by - * whoever wrote it -- possibly nobody in this group -- while - * [marmotInnerEventId], [senderPublicKey] and [createdAt] all belong to - * the envelope a member actually sent. Entity rows take their author - * from [event], so the chat line says who added it and the row says who - * wrote it. + * arrived -- [marmotInnerEventId], [senderPublicKey] and [createdAt] + * belong to the message a member actually sent. * * [groupSignedEventId] is the third way in, and the one with no * envelope at all: a `GroupSignedEvent` the group put its own signature @@ -1176,6 +1204,10 @@ data class ChatMessage( * which is why they need an id of their own, and why every row this * writes carries it. */ + /** A member as a transcript line names them: their profile's name, or the start of their key. */ + private suspend fun memberName(database: BennuDatabase, publicKey: HexKey): String = + database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() ?: publicKey.take(8) + internal suspend fun applyInnerEvent( database: BennuDatabase, groupId: String, @@ -1187,10 +1219,8 @@ data class ChatMessage( createdAt: Instant, groupSignedEventId: HexKey? = null, ): ChatMessage? { - // The last resort, named because one arm reaches it deliberately rather - // than by falling off the end: a kind:1 the room did not sign is a - // member's own note travelling through the room, and it has always - // rendered as this. See the `TextNoteEvent` arm. + // The last resort: raw JSON in a bubble, the only trace an + // unrecognised payload leaves. fun unsupported() = ChatMessage( giftWrapPayloadId = null, messageType = "unsupported", @@ -1204,327 +1234,11 @@ data class ChatMessage( ) return when (event.kind) { - ChatEvent.KIND -> { - ChatMessage( - giftWrapPayloadId = null, - messageType = "message", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = event.content, // TODO: Figure out what to do here... - ) - } - ArtifactEvent.KIND -> { - val artifactEvent = ArtifactEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - - MantraArtifact.fromArtifactEvent( - artifactEvent = artifactEvent, - chatRoomId = groupId, - )?.let { mantraArtifact -> - database.mantraArtifactDao().upsert( - mantraArtifact.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - // The version the artifact starts life with is its own - // event, signed in the same batch and applied after this - // one -- see AddArtifactViewModel.addArtifact. It used to - // be derived here instead; deriving it now as well would - // stand a second, unsigned version row against the same - // artifact, since the two hash differently. - - ChatMessage( - giftWrapPayloadId = null, - messageType = "artifact", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraArtifact.name} to artifacts" - ) - } - } - ArtifactVersionEvent.KIND -> { - MantraArtifactVersion.fromArtifactVersionEvent( - artifactVersionEvent = ArtifactVersionEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraArtifactVersion -> - database.mantraArtifactVersionDao().upsert( - mantraArtifactVersion.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - // No line of its own. A version arrives as the second - // item of the batch that carries its artifact, and the - // artifact has already said so -- the same reason a - // chunk writes no line beside its chapter. While the - // version was derived here rather than signed it wrote - // none either, so this is the transcript standing still - // rather than losing something. - } - null - } - ChapterEvent.KIND -> { - // The chunks the chapter splits into are their own events, - // signed in the same session and applied after it -- see - // AddChapterViewModel.addChapter. Nothing to do here but the - // chapter itself. - MantraChapter.fromChapterEvent( - chapterEvent = ChapterEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraChapter -> - database.mantraChapterDao().upsert( - mantraChapter.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - ChatMessage( - giftWrapPayloadId = null, - messageType = "chapter", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraChapter.name} to chapters" // TODO: Use artifact name... - ) - } - } - - ChunkEvent.KIND -> { - MantraChunk.fromChunkEvent( - chunkEvent = ChunkEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraChunk -> - database.mantraChunkDao().upsert( - mantraChunk.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - // TODO: Chunks might be too noisy to show in chat... - } - null - } - DialectEvent.KIND -> { - MantraDialect.fromDialectEvent( - dialectEvent = DialectEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraDialect -> - database.mantraDialectDao().upsert( - mantraDialect.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - - ChatMessage( - giftWrapPayloadId = null, - messageType = "dialect", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraDialect.name} to dialects" // TODO: Use artifact name... - ) - } - } - TranslationArtifactVersionEvent.KIND -> { - MantraTranslationArtifactVersion.fromTranslationArtifactVersionEvent( - translationArtifactVersionEvent = TranslationArtifactVersionEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslationArtifactVersion -> - database.mantraTranslationArtifactVersionDao().upsert( - mantraTranslationArtifactVersion.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - ChatMessage( - giftWrapPayloadId = null, - messageType = "translationArtifactVersion", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraTranslationArtifactVersion.name} to translation artifact versions" // TODO: Use artifact name... - ) - } - } - TranslationArtifactVersionContributorListEvent.KIND -> { - // TODO: Consume contributors... - null - } - TranslationChapterEvent.KIND -> { - MantraTranslationChapter.fromTranslationChapterEvent( - translationChapterEvent = TranslationChapterEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslationChapter -> - database.mantraTranslationChapterDao().upsert( - mantraTranslationChapter.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - // TODO: translation chapter might be too noisy for chat updates - } - null - } - TranslationChunkEvent.KIND -> { - MantraTranslationChunk.fromTranslationChunkEvent( - translationChunkEvent = TranslationChunkEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslationChunk -> - // One translation per source chunk. Retranslating changes - // the text and so the event's id, which makes it a new - // event rather than an edit of the old one -- so the one - // it supersedes is dropped here, or a passage would have - // two answers to what it says and the reader would be - // shown whichever the query happened to reach first. - // - // Newest wins by the timestamp the group signed at, not by - // when it arrived, with the id breaking a tie. Two devices - // catching up read the same events in whatever order the - // relay hands them over, and they have to end up holding - // the same translation either way. - val existing = database.mantraTranslationChunkDao() - .getTranslationChunksByChunkId( - translationChapterId = mantraTranslationChunk.translationChapterId, - chunkId = mantraTranslationChunk.chunkId, - ) - .filterNot { it.id == mantraTranslationChunk.id } - - val isNewest = existing.none { - it.createdAt > mantraTranslationChunk.createdAt || - (it.createdAt == mantraTranslationChunk.createdAt && - it.id > mantraTranslationChunk.id) - } - - if (isNewest) { - existing.forEach { - database.mantraTranslationChunkDao().deleteById(it.id) - } - - database.mantraTranslationChunkDao().upsert( - mantraTranslationChunk.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - } - } - null - } - TranslationContributorListEvent.KIND -> { - // TODO: Consume contributors... - null - } - TranslationEvent.KIND -> { - MantraTranslation.fromTranslationEvent( - translationEvent = TranslationEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslation -> - database.mantraTranslationDao().upsert( - mantraTranslation.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - ChatMessage( - giftWrapPayloadId = null, - messageType = "translation", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraTranslation.text} to translations" // TODO: Reference original text - ) - } - } + // First, above every content kind: protocol kinds are never + // content, whatever else might share their number, and a `when` + // takes the first arm that matches. The ceremony's 30310 and 30311 + // once reached document arms that sat above this one. + // // A signing session's own protocol messages. FrostSigningManager // applies them and writes its own transcript lines naming who did // what, so an "unsupported" row here would be a second, worse @@ -1546,6 +1260,19 @@ data class ChatMessage( // none of their business. in DkgRitualEvents.ALL -> null + ChatEvent.KIND -> { + ChatMessage( + giftWrapPayloadId = null, + messageType = "message", + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = event.content, // TODO: Figure out what to do here... + ) + } // The group saying what key one of its rooms signs with, arriving // here the way every group-signed event does: applied by // `FrostSigningManager` once a quorum has signed the proposal it @@ -1615,103 +1342,78 @@ data class ChatMessage( ) } - // The group saying who it is on nostr. A room's id is the pubkey - // it signs as, so a group has an identity from the moment it has a - // key; this is the kind:0 describing it, signed by the group's own - // quorum like everything else it says. - // - // **Only when the room itself signed it.** This arm is reached both - // from a completed signing session, where the author is the room by - // construction, and from an arriving inner event, where any member - // could have sent a rumor of this kind -- and it cannot tell which. - // A member's own kind:0 travelling through a room is their profile, - // not the group's, and gets no line here. - // - // No row is written. The event is already on file as a - // `GroupSignedEvent` -- `FrostSigningManager.complete` records the - // batch before it applies it -- and `GroupNostrProfile` reads the - // group's profile straight off those. A `Profile` row is not an - // option anyway: it hangs off `NostrEvent` by foreign key, and a - // group-signed event is not one. - MetadataEvent.KIND -> { - if (!event.pubKey.equals(groupId, ignoreCase = true)) return null - - val profile = GroupNostrProfile.of( - signedEvent = GroupSignedEvent.fromEvent(event, chatRoomId = groupId), - chatRoomId = groupId, - ) ?: return null + // A member asking the group to guard a wallet of theirs. The + // inner event carries the signed request whole; only a request + // that checks out and asks this room gets a line, and it is a + // line and nothing more -- the group decides when a signer puts + // it to the quorum. docs/member-guarded-wallets.md. + MemberWalletRequestEvent.KIND -> { + val request = MemberWalletRequestEvent.carried(event) ?: return null + val reading = MemberWalletRequestEvent.verified(request)?.reading ?: return null + if (!reading.groupChatRoomId.equals(groupId, ignoreCase = true)) return null ChatMessage( giftWrapPayloadId = null, - messageType = TYPE_GROUP_PROFILE_SIGNED, + messageType = TYPE_MEMBER_WALLET_REQUESTED, marmotGroupEventId = marmotGroupEventId, marmotInnerEventId = marmotInnerEventId, senderPublicKey = senderPublicKey, isUserMessage = isUserMessage, chatRoomId = groupId, createdAt = createdAt, - content = profile.name()?.let { "The group is now called $it" } - ?: "The group signed a new profile for itself" + content = "@${memberName(database, reading.memberPublicKey)} asked this group to guard a wallet", ) } - // The group saying something publicly, in its own name -- which - // is a different thing from a member saying something in the room. - // A room's messages are `ChatEvent`s; this is a kind:1 authored by - // the room's own key, so any reader can check the group said it and - // that no single member could have. - // - // Verified like the arms below and for the same reason: a rumor - // carries an empty signature and any pubkey its sender likes, so an - // author check alone would let one member put words in the group's - // mouth in its own transcript. - // - // **Unlike those arms, a kind:1 that fails falls through to - // `unsupported` rather than vanishing.** A member's kind:0 or relay - // list passing through a room is identity plumbing nobody sent on - // purpose and silence is the right treatment; a kind:1 is content, - // somebody meant it, and it has rendered as an unsupported event - // since before any of this existed. Dropping it here would be this - // change quietly deleting messages it has no business touching. - TextNoteEvent.KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return unsupported() + // The group agreeing to guard a member's wallet. Checked whole -- + // the room's signature and the request inside -- because the line + // says the group made a promise about somebody's money. It is + // filed as a `GroupSignedEvent` either way, and every reader + // checks it there again. + MemberWalletCertificateEvent.KIND -> { + val verified = MemberWalletCertificateEvent.verify(event, groupId) ?: return null + // The groups above this one guard the wallet too, and learn + // of it only by being told. docs/guarded-wallet-forwarding.md. + GuardianManager.forwardOnArrival(database, event, groupId) ChatMessage( giftWrapPayloadId = null, - messageType = TYPE_GROUP_POST_SIGNED, + messageType = TYPE_MEMBER_WALLET_GUARDED, marmotGroupEventId = marmotGroupEventId, marmotInnerEventId = marmotInnerEventId, senderPublicKey = senderPublicKey, isUserMessage = isUserMessage, chatRoomId = groupId, createdAt = createdAt, - content = "The group posted in its own name" + content = "This group now guards a wallet for @${memberName(database, verified.memberPublicKey)}", + ) + } + + // The group saying whether it guards its members' wallets, and at + // what delay. Checked as the room's own signature, which is all a + // policy needs; one that does not verify gets no line, and is + // ignored where it is filed too. docs/member-wallet-delay.md. + MemberWalletPolicyEvent.KIND -> { + val policy = MemberWalletPolicyEvent.verify(event, groupId) ?: return null + + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_MEMBER_WALLET_POLICY, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = when (policy) { + is MemberWalletPolicyEvent.Policy.Open -> + "The group guards members' wallets, after ${BlockDuration.describe(policy.delay)}" + is MemberWalletPolicyEvent.Policy.Closed -> + "The group has stopped guarding new members' wallets" + }, ) } - // The group saying where it lives on nostr: which relays carry - // its work, take its messages, answer a search of it, and which it - // will not talk to. - // - // **Verified, not just attributed.** This arm is reached from a - // completed signing session, where the author is the room by - // construction, and from an arriving inner event, where it is - // whatever the sender wrote -- and it cannot tell which. A rumor - // carries an empty signature and any pubkey its sender likes, so an - // author check alone would let one member put "the group signed its - // general relay list" in the transcript. `verifies` is what makes - // the line mean what it says: the room's key over these tags. - // - // A member's own relay list travelling through the room fails the - // author half and gets no line, which is right -- it is their list, - // not the group's. - // - // No row is written, and nothing is parsed beyond the check. The - // events are already on file as `GroupSignedEvent` and - // `GroupRelayList` reads the lists straight off those; this arm - // exists so a signed relay list is a line in the transcript rather - // than raw JSON in a bubble. // The group opening a wallet. Checked the whole way -- the room's // signature, and the statement rederiving from the room's own key -- // because a line saying "the group opened a wallet" is a line people @@ -1723,6 +1425,9 @@ data class ChatMessage( val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, groupId) ?: return null val wallet = GroupWallet.of(signed, thresholdPublicKey) ?: return null + // A guarded wallet is one the groups above can find only by + // being told of it. docs/guarded-wallet-forwarding.md. + if (wallet.account.isGuarded) GuardianManager.forwardOnArrival(database, event, groupId) ChatMessage( giftWrapPayloadId = null, @@ -1801,25 +1506,17 @@ data class ChatMessage( ) } - in GroupRelaySet.KINDS -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return null - - val set = GroupRelaySet.entries.firstOrNull { it.kind == event.kind } - ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_RELAYS_SIGNED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "The group signed its ${set.name.lowercase()} relay list" - ) - } + // A profile or a relay list -- the group's or a member's own -- + // travelling through the room. The app no longer reads either as + // the group's, and both are identity plumbing nobody sends into a + // room on purpose, so neither is a line nor a raw-JSON bubble: a + // signing session an older build opened for one ends in silence. + // A kind:1 is content, and keeps the bubble it always had. + MetadataEvent.KIND, + AdvertisedRelayListEvent.KIND, + ChatMessageRelayListEvent.KIND, + SearchRelayListEvent.KIND, + BlockedRelayListEvent.KIND -> null // v2's two non-chat kinds. A kind:1210 that arrives is one member's // assertion about what the group's state became, and this device diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/DkgSession.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/DkgSession.kt index 8f71c1fe..46477ccd 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/DkgSession.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/DkgSession.kt @@ -8,6 +8,7 @@ import com.machankura.bennu.compose.database.model.traits.LocalStoreEntity import com.machankura.bennu.compose.database.model.traits.TimestampedEntity import com.machankura.bennu.compose.database.model.types.DkgApprovalStep import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import fr.acinq.bitcoin.ByteVector @@ -99,6 +100,33 @@ data class DkgSession( */ val subject: String? = null, + /** + * The wallet policy the coordinator chose for the subgroup this ceremony + * makes, as `SubgroupWalletPolicy.tagValue` -- or null for a ceremony that + * makes no subgroup, or one proposed by a build from before policies. + * `docs/subgroup-wallet-policy.md`. + * + * A claim on a proposal, like [subject], and read for two things only: the + * join screen, which tells an admin what they are agreeing to, and the + * certificate rung, which proposes the certificate under it. What makes it + * binding is the parent's quorum signing it into the certificate, and every + * child signer then refusing a key state whose certificate says otherwise. + */ + val walletPolicy: String? = null, + + /** + * The delay, in blocks, the coordinator chose for the parent's own leaf in + * the guarded subgroup this ceremony makes -- or null for an unguarded one, + * one that makes no subgroup, or one from a build before parents chose. + * `docs/guardian-delay.md`. + * + * A claim on a proposal like [walletPolicy], read for the join screen and for + * the certificate rung. A guarded ceremony with none is certified at + * `GuardianDerivation.DEFAULT_DELAY`, which is what its build would have + * written. + */ + val guardianDelay: Long? = null, + val stage: DkgRitualStage = DkgRitualStage.COLLECTING_HOST_KEYS, /** This device's ChillDKG host public key (33-byte compressed, hex). */ @@ -232,3 +260,7 @@ data class DkgSession( publicKeys.takeIf { it.isNotEmpty() }?.sorted()?.joinToString(",") } } + +/** [DkgSession.walletPolicy], read; null for none or one this build does not know. */ +val DkgSession.subgroupWalletPolicy: SubgroupWalletPolicy? + get() = walletPolicy?.let(SubgroupWalletPolicy::fromTagValue) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt index e53667de..6a229ee4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt @@ -36,12 +36,6 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent * columns are `NostrEvent`'s so that what is stored is an event rather than a * summary of one, which is what makes [verifies] answerable from the row alone. * - * The one way one reaches a relay is a member sending it there by hand -- from - * `BroadcastGroupSignedEventScreen`, or every accepted entry at once from the - * entries screen -- and that path serialises the row straight to the pool - * without ever making a `NostrEvent` of it -- see - * `BroadcastGroupSignedEventViewModel` for why a row would be the wrong shape. - * * ### The derivation path * * [publicKey] is the group's threshold key walked to [derivationPath], and for a diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt index b0960854..0e3c7ba3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt @@ -48,6 +48,18 @@ data class GroupTransaction( /** The wallet account the inputs are under. From the room's statement, never from the proposal. */ val account: Long, + /** + * The descendant whose guarded wallet this spend draws from, through this + * room's guardian leaf -- or null for a spend from the room's own wallet. + * [account] is then the descendant's, from the statement this room was told. + * + * A descendant is a subgroup's room id or, since + * `docs/member-guarded-wallets.md`, a member wallet's `W`: either is what the + * line of descent ends in. The column keeps its name, because a rename is a + * migration for a word. + */ + val guardedChatRoomId: String? = null, + /** * The PSBT as proposed, base64. Write-once: it is what every item's sighash * was computed from, and a second proposal under the same session id that diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraArtifact.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraArtifact.kt deleted file mode 100644 index db1cdfb4..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraArtifact.kt +++ /dev/null @@ -1,163 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionMetadataTag -import com.machankura.bennu.compose.nostr.nip30303.tags.DialectIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.LicenseTag -import com.machankura.bennu.compose.nostr.nip30303.tags.UrlTag -import com.machankura.bennu.compose.nostr.nip30303.tags.VisibilityTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30300 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraDialect::class, - parentColumns = ["id"], - childColumns = ["dialectId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ] -) -data class MantraArtifact( - @PrimaryKey - val id: HexKey, - val publicKey: String, - val name: String, - val url: String, // Hash this to get the dTag... - val visibility: String, // public, private, permissioned (public, but only members can contribute) - val dialectId: String, - val license: String, -// val artifactApprovalId: String, - - val chatRoomId: String, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val relayHint: String? = null, - - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - /** - * The event the group signed, rebuilt from this row. - * - * [versionLabel] is a parameter because it is not on this row and cannot be. - * `fromArtifactEvent` reads the artifact's own fields and drops the version - * metadata, which `ChatMessage.applyInnerEvent` has by then turned into the - * artifact's first `MantraArtifactVersion`. It was still part of what the - * group put its signature to, so a rebuild without it hashes to a different - * id and produces an event the signature does not cover -- which a receiver - * reads as a forgery, silently. Recover it from the initial version: the one - * whose `createdAt` is this artifact's, since `initialVersionOf` derives it - * from the same event. - * - * Tag order matches [ArtifactEvent.build] exactly -- alt first -- for the - * same reason, and `ChronicleRoundTripTest` is what says so. Both of those were - * wrong here until a chronicle needed to rebuild an artifact and nothing had - * ever called this. - */ - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toArtifactEvent(versionLabel: String): ArtifactEvent { - return ArtifactEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches ArtifactEvent.build so the event id round-trips. - tags = TagArrayBuilder() - .addUnique( - AltTag.assemble(ArtifactEvent.ALT_DESCRIPTION) - ) - .addUnique(UrlTag.assemble(url)) - .addUnique(VisibilityTag.assemble(visibility)) - .addUnique(LicenseTag.assemble(license)) - .addUnique( - DialectIdTag.assemble(dialectId) - ) - .addUnique( - ArtifactVersionMetadataTag.assemble(versionLabel) - ) - .build(), - content = name, - sig = signature - ) - } - - companion object { - fun fromArtifactEventTemplate(artifactEventTemplate: EventTemplate, chatRoomId: HexKey, userPublicKey: HexKey): MantraArtifact? { - return fromArtifactEvent( - ArtifactEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, // TODO: get pub key... - tags = artifactEventTemplate.tags, - content = artifactEventTemplate.content, - createdAt = artifactEventTemplate.createdAt, - kind = artifactEventTemplate.kind - ), - content = artifactEventTemplate.content, - tags = artifactEventTemplate.tags, - createdAt = artifactEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "" // Unsigned.... - ), - chatRoomId = chatRoomId - ) - } - fun fromArtifactEvent(artifactEvent: ArtifactEvent, chatRoomId: HexKey, ): MantraArtifact? { - return artifactEvent.url()?.let { url -> - artifactEvent.visibility()?.let { visibility -> - artifactEvent.license()?.let { license -> - artifactEvent.dialectId()?.let { dialectId -> - MantraArtifact( - id = artifactEvent.id, - publicKey = artifactEvent.pubKey, - dialectId = dialectId, - createdAt = Instant.fromEpochSeconds(artifactEvent.createdAt), - url = url, - license = license, - visibility = visibility, - name = artifactEvent.content, - signature = artifactEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraArtifactVersion.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraArtifactVersion.kt deleted file mode 100644 index b73ccb1e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraArtifactVersion.kt +++ /dev/null @@ -1,135 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30301 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraArtifact::class, - parentColumns = ["id"], - childColumns = ["artifactId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraArtifactVersion( - @PrimaryKey - val id: HexKey, - val artifactId: HexKey, - val publicKey: HexKey, - - /** - * Version Tag... - */ - val versionLabel: String, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toArtifactVersionEvent(): ArtifactVersionEvent { - return ArtifactVersionEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches ArtifactVersionEvent.initialVersionOf, which puts - // the alt first because `build` does, or the event id does not - // round-trip. It was the other way round here for as long as nothing - // called this -- see ChronicleRoundTripTest, which is what calls it now. - tags = TagArrayBuilder() - .addUnique( - AltTag.assemble(ArtifactVersionEvent.ALT_DESCRIPTION) - ) - .addUnique( - ArtifactIdTag.assemble(artifactId) - ) - .build(), - content = versionLabel, - sig = signature - ) - } - - companion object { - fun fromArtifactVersionEventTemplate( - artifactVersionEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraArtifactVersion? { - return fromArtifactVersionEvent( - ArtifactVersionEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = artifactVersionEventTemplate.tags, - content = artifactVersionEventTemplate.content, - createdAt = artifactVersionEventTemplate.createdAt, - kind = artifactVersionEventTemplate.kind, - ), - content = artifactVersionEventTemplate.content, - tags = artifactVersionEventTemplate.tags, - createdAt = artifactVersionEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromArtifactVersionEvent(artifactVersionEvent: ArtifactVersionEvent, chatRoomId: HexKey, ): MantraArtifactVersion? { - return artifactVersionEvent.artifactId()?.let { artifactId -> - MantraArtifactVersion( - id = artifactVersionEvent.id, - publicKey = artifactVersionEvent.pubKey, - createdAt = Instant.fromEpochSeconds(artifactVersionEvent.createdAt), - artifactId = artifactId, - versionLabel = artifactVersionEvent.content, - signature = artifactVersionEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraChapter.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraChapter.kt deleted file mode 100644 index 4d86b31c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraChapter.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.NameTag -import com.machankura.bennu.compose.nostr.nip30303.tags.OriginalTextTag -import com.machankura.bennu.compose.nostr.nip30303.tags.WordStatisticsTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30302 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraArtifactVersion::class, - parentColumns = ["id"], - childColumns = ["artifactVersionId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraChapter( - @PrimaryKey - val id: HexKey, - val artifactVersionId: HexKey, - val publicKey: HexKey, - val name: String, - val originalText: String, - val index: Int, - val wordCount: Int, - val characterCount: Int, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toChapterEvent(): ChapterEvent { - return ChapterEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches ChapterEvent.build so the event id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(ChapterEvent.ALT_DESCRIPTION)) - .addUnique( - ArtifactVersionIdTag.assemble(artifactVersionId) - ) - .addUnique(NameTag.assemble(name)) - .addUnique(OriginalTextTag.assemble(originalText)) - .addUnique( - IndexTag.assemble( - index - ) - ) - .addUnique( - WordStatisticsTag.assemble(wordCount, characterCount) - ) - .build(), - content = "", - sig = signature - ) - } - - companion object { - fun fromChapterEventTemplate( - chapterEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraChapter? { - return fromChapterEvent( - ChapterEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = chapterEventTemplate.tags, - content = chapterEventTemplate.content, - createdAt = chapterEventTemplate.createdAt, - kind = chapterEventTemplate.kind, - ), - content = chapterEventTemplate.content, - tags = chapterEventTemplate.tags, - createdAt = chapterEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromChapterEvent(chapterEvent: ChapterEvent, chatRoomId: HexKey): MantraChapter? { - return chapterEvent.name()?.let { name -> - chapterEvent.originalText()?.let { originalText -> - chapterEvent.wordStatisticsTag?.let { wordStatisticsTag -> - chapterEvent.artifactVersionId()?.let { artifactId -> - chapterEvent.index()?.let { index -> - MantraChapter( - id = chapterEvent.id, - publicKey = chapterEvent.pubKey, - createdAt = Instant.fromEpochSeconds(chapterEvent.createdAt), - artifactVersionId = artifactId, - name = name, - originalText = originalText, - index = index, - wordCount = wordStatisticsTag.wordCount, - characterCount = wordStatisticsTag.characterCount, - signature = chapterEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraChunk.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraChunk.kt deleted file mode 100644 index f71f451d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraChunk.kt +++ /dev/null @@ -1,147 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ChapterIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.WordStatisticsTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30303 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraChapter::class, - parentColumns = ["id"], - childColumns = ["chapterId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraChunk( - @PrimaryKey - val id: HexKey, - val chapterId: HexKey, - val publicKey: HexKey, - val text: String, - val index: Int, - val wordCount: Int, - val characterCount: Int, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toChunkEvent(): ChunkEvent { - return ChunkEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches ChunkEvent.build so the event id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(ChunkEvent.ALT_DESCRIPTION)) - .addUnique( - ChapterIdTag.assemble(chapterId) - ) - .addUnique( - IndexTag.assemble( - index - ) - ) - .addUnique( - WordStatisticsTag.assemble(wordCount, characterCount) - ) - .build(), - content = text, - sig = signature - ) - } - - companion object { - fun fromChunkEventTemplate( - chunkEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraChunk? { - return fromChunkEvent( - ChunkEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = chunkEventTemplate.tags, - content = chunkEventTemplate.content, - createdAt = chunkEventTemplate.createdAt, - kind = chunkEventTemplate.kind, - ), - content = chunkEventTemplate.content, - tags = chunkEventTemplate.tags, - createdAt = chunkEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromChunkEvent(chunkEvent: ChunkEvent, chatRoomId: HexKey): MantraChunk? { - return chunkEvent.wordStatisticsTag?.let { wordStatisticsTag -> - chunkEvent.index()?.let { index -> - chunkEvent.chapterId()?.let { chapterId -> - MantraChunk( - id = chunkEvent.id, - publicKey = chunkEvent.pubKey, - createdAt = Instant.fromEpochSeconds(chunkEvent.createdAt), - index = index, - wordCount = wordStatisticsTag.wordCount, - characterCount = wordStatisticsTag.characterCount, - chapterId = chapterId, - text = chunkEvent.content, - signature = chunkEvent.sig, - chatRoomId = chatRoomId - ) - } - - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraDialect.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraDialect.kt deleted file mode 100644 index 113b4b99..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraDialect.kt +++ /dev/null @@ -1,126 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.CountryTag -import com.machankura.bennu.compose.nostr.nip30303.tags.LanguageTag -import com.machankura.bennu.compose.nostr.nip30303.tags.NameTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30304 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ] -) -data class MantraDialect( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val name: String, - val country: String, - val language: String, - - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toDialectEvent(): DialectEvent { - return DialectEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches DialectEvent.build so the event id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(DialectEvent.ALT_DESCRIPTION)) - .addUnique(NameTag.assemble(name)) - .addUnique(CountryTag.assemble(country)) - .addUnique(LanguageTag.assemble(language)) - .build(), - content = language, // TODO: Consider using the isoCode... as content? - sig = signature - ) - } - - companion object { - fun fromDialectEventTemplate( - dialectEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraDialect? { - return fromDialectEvent( - DialectEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = dialectEventTemplate.tags, - content = dialectEventTemplate.content, - createdAt = dialectEventTemplate.createdAt, - kind = dialectEventTemplate.kind, - ), - content = dialectEventTemplate.content, - tags = dialectEventTemplate.tags, - createdAt = dialectEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromDialectEvent(dialectEvent: DialectEvent, chatRoomId: HexKey): MantraDialect? { - return dialectEvent.name()?.let { name -> - dialectEvent.language()?.let { language -> - dialectEvent.country()?.let { country -> - - MantraDialect( - id = dialectEvent.id, - publicKey = dialectEvent.pubKey, - createdAt = Instant.fromEpochSeconds(dialectEvent.createdAt), - name = name, - language = language, - country = country, - signature = dialectEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslation.kt deleted file mode 100644 index 31983b4f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslation.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.utils.ensure -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChunkIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30305 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraTranslationChunk::class, - parentColumns = ["id"], - childColumns = ["translationChunkId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = MantraTranslationArtifactVersion::class, - parentColumns = ["id"], - childColumns = ["translationArtifactVersionId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslation( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val translationChunkId: HexKey, - val translationArtifactVersionId: HexKey, - val text: String, - - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - fun toTranslationEvent(): TranslationEvent { - return TranslationEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - tags = TagArrayBuilder() - .addUnique( - TranslationArtifactVersionIdTag.assemble(translationArtifactVersionId) - ) - .addUnique( - TranslationChunkIdTag.assemble(translationChunkId) - ) - .build(), - content = text, - sig = signature - ) - } - - companion object { - fun fromTranslationEvent(translationEvent: TranslationEvent, chatRoomId: HexKey): MantraTranslation? { - ensure(translationEvent.translationChunkId() != null) { return null} - ensure(translationEvent.translationArtifactVersionId() != null) { return null} - - return translationEvent.translationChunkId()?.let { translationChunkId -> - translationEvent.translationArtifactVersionId()?.let { translationArtifactVersionId -> - MantraTranslation( - id = translationEvent.id, - publicKey = translationEvent.pubKey, - createdAt = Instant.fromEpochSeconds(translationEvent.createdAt), - text = translationEvent.content, - translationChunkId = translationChunkId, - translationArtifactVersionId = translationArtifactVersionId, - signature = translationEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationArtifactVersion.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationArtifactVersion.kt deleted file mode 100644 index 8f7c45e5..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationArtifactVersion.kt +++ /dev/null @@ -1,158 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.DialectIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.LicenseTag -import com.machankura.bennu.compose.nostr.nip30303.tags.NameTag -import com.machankura.bennu.compose.nostr.nip30303.tags.VisibilityTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30306 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraArtifactVersion::class, - parentColumns = ["id"], - childColumns = ["artifactVersionId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = MantraDialect::class, - parentColumns = ["id"], - childColumns = ["dialectId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationArtifactVersion( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val artifactVersionId: HexKey, - val dialectId: HexKey, - val name: String, - val visibility: String, - val license: String, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toTranslationArtifactVersionEvent(): TranslationArtifactVersionEvent { - return TranslationArtifactVersionEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches TranslationArtifactVersionEvent.build so the id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(TranslationArtifactVersionEvent.ALT_DESCRIPTION)) - .addUnique( - ArtifactVersionIdTag.assemble(artifactVersionId) - ) - .addUnique( - DialectIdTag.assemble(dialectId) - ) - .addUnique(NameTag.assemble(name)) - .addUnique(VisibilityTag.assemble(visibility)) - .addUnique(LicenseTag.assemble(license)) - .build(), - content = "", - sig = signature - ) - } - - companion object { - fun fromTranslationArtifactVersionEventTemplate( - translationArtifactVersionEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraTranslationArtifactVersion? { - return fromTranslationArtifactVersionEvent( - TranslationArtifactVersionEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = translationArtifactVersionEventTemplate.tags, - content = translationArtifactVersionEventTemplate.content, - createdAt = translationArtifactVersionEventTemplate.createdAt, - kind = translationArtifactVersionEventTemplate.kind, - ), - content = translationArtifactVersionEventTemplate.content, - tags = translationArtifactVersionEventTemplate.tags, - createdAt = translationArtifactVersionEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromTranslationArtifactVersionEvent(translationArtifactVersionEvent: TranslationArtifactVersionEvent, chatRoomId: HexKey): MantraTranslationArtifactVersion? { - - return translationArtifactVersionEvent.artifactVersionId()?.let { artifactVersionId -> - translationArtifactVersionEvent.dialectId()?.let { dialectId -> - translationArtifactVersionEvent.name()?.let { name -> - translationArtifactVersionEvent.visibility()?.let { visibility -> - translationArtifactVersionEvent.license()?.let { license -> - MantraTranslationArtifactVersion( - id = translationArtifactVersionEvent.id, - publicKey = translationArtifactVersionEvent.pubKey, - createdAt = Instant.fromEpochSeconds(translationArtifactVersionEvent.createdAt), - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = name, - visibility = visibility, - license = license, - signature = translationArtifactVersionEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } - } - } -} - diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationArtifactVersionContributor.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationArtifactVersionContributor.kt deleted file mode 100644 index ae958bed..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationArtifactVersionContributor.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ContributorTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30307 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraTranslationArtifactVersionContributor::class, - parentColumns = ["id"], - childColumns = ["translationArtifactVersionId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationArtifactVersionContributor( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val translationArtifactVersionId: HexKey, - val editorPublicKey: HexKey, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - companion object { - fun toTranslationChapterProofReaderListEvent(chatRoomId: HexKey, mantraTranslationChapterProofReaders: List): TranslationArtifactVersionContributorListEvent { - // TODO: create TranslationChapterProofReaderListEvent from mantraTranslationChapterProofReaders - return TranslationArtifactVersionContributorListEvent( - id = "", - pubKey = "", - createdAt = TimeUtils.now(), - tags = TagArrayBuilder() - - .addUnique( - TranslationArtifactVersionIdTag.assemble("") // TODO: use actual value.. - ) - // TODO: Add tag for editorPublicKey - .addUnique( - ContributorTag.assemble( - "", - ContributorTag.ROLE_EDITOR - ) - ) - .build(), - content = "", - sig = "" - ) - } - } -} - diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChapter.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChapter.kt deleted file mode 100644 index 5aa9475e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChapter.kt +++ /dev/null @@ -1,146 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ChapterIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30308 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraTranslationArtifactVersion::class, - parentColumns = ["id"], - childColumns = ["translationArtifactVersionId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = MantraChapter::class, - parentColumns = ["id"], - childColumns = ["chapterId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationChapter( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val chapterId: HexKey, - val translationArtifactVersionId: HexKey, - val index: Int, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toTranslationChapterEvent(): TranslationChapterEvent { - return TranslationChapterEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches TranslationChapterEvent.build so the id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(TranslationChapterEvent.ALT_DESCRIPTION)) - .addUnique( - TranslationArtifactVersionIdTag.assemble(translationArtifactVersionId) - ) - .addUnique( - ChapterIdTag.assemble(chapterId) - ) - .addUnique( - IndexTag.assemble(index) - ) - .build(), - content = "", - sig = signature - ) - } - - companion object { - fun fromTranslationChapterEventTemplate( - translationChapterEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraTranslationChapter? { - return fromTranslationChapterEvent( - TranslationChapterEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = translationChapterEventTemplate.tags, - content = translationChapterEventTemplate.content, - createdAt = translationChapterEventTemplate.createdAt, - kind = translationChapterEventTemplate.kind, - ), - content = translationChapterEventTemplate.content, - tags = translationChapterEventTemplate.tags, - createdAt = translationChapterEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromTranslationChapterEvent(translationChapterEvent: TranslationChapterEvent, chatRoomId: HexKey): MantraTranslationChapter? { - return translationChapterEvent.chapterId()?.let { chapterId -> - translationChapterEvent.translationArtifactVersionId()?.let { translationArtifactVersionId -> - translationChapterEvent.index()?.let { index -> - MantraTranslationChapter( - id = translationChapterEvent.id, - publicKey = translationChapterEvent.pubKey, - createdAt = Instant.fromEpochSeconds(translationChapterEvent.createdAt), - chapterId = chapterId, - translationArtifactVersionId = translationArtifactVersionId, - index = index, - signature = translationChapterEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } -} - diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChapterContributor.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChapterContributor.kt deleted file mode 100644 index 8a776a53..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChapterContributor.kt +++ /dev/null @@ -1,87 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nipF4Podcasts.metadata.tags.AuthorTag -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ContributorTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChapterIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30310 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraTranslationChapter::class, - parentColumns = ["id"], - childColumns = ["translationChapterId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationChapterContributor( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val translationChapterId: HexKey, - val translatorPublicKey: HexKey, - - val role: String, - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - companion object { - fun toTranslationChapterTranslatorListEvent(mantraTranslationChapterTranslators: List): TranslationChapterContributorListEvent { - // TODO: create TranslationChapterProofReaderListEvent from mantraTranslationChapterProofReaders - return TranslationChapterContributorListEvent( - id = "", - pubKey = "", - createdAt = TimeUtils.now(), - tags = TagArrayBuilder() - .addUnique( - TranslationChapterIdTag.assemble("") - ) - .addUnique( - ContributorTag.assemble("", ContributorTag.ROLE_TRANSLATOR) - ) - .build(), - content = "", - sig = "" - ) - } - } -} - diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChunk.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChunk.kt deleted file mode 100644 index ac090b51..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChunk.kt +++ /dev/null @@ -1,148 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ChunkIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChapterIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30311 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraChunk::class, - parentColumns = ["id"], - childColumns = ["chunkId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = MantraTranslationChapter::class, - parentColumns = ["id"], - childColumns = ["translationChapterId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationChunk( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val chunkId: HexKey, - val translationChapterId: HexKey, - val text: String, - val index: Int, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. Read the " + - "event off that table instead; this rebuild goes when the last pre-v13 install " + - "does -- see the removal checklist in docs/member-chronicle.md." - ) - fun toTranslationChunkEvent(): TranslationChunkEvent { - return TranslationChunkEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches TranslationChunkEvent.build so the id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(TranslationChunkEvent.ALT_DESCRIPTION)) - .addUnique( - TranslationChapterIdTag.assemble(translationChapterId) - ) - .addUnique( - ChunkIdTag.assemble(chunkId) - ) - .addUnique( - IndexTag.assemble(index) - ) - .build(), - content = text, - sig = signature - ) - } - - companion object { - fun fromTranslationChunkEventTemplate( - translationChunkEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraTranslationChunk? { - return fromTranslationChunkEvent( - TranslationChunkEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = translationChunkEventTemplate.tags, - content = translationChunkEventTemplate.content, - createdAt = translationChunkEventTemplate.createdAt, - kind = translationChunkEventTemplate.kind, - ), - content = translationChunkEventTemplate.content, - tags = translationChunkEventTemplate.tags, - createdAt = translationChunkEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromTranslationChunkEvent(translationChunkEvent: TranslationChunkEvent, chatRoomId: HexKey): MantraTranslationChunk? { - return translationChunkEvent.translationChapterId()?.let { translationChapterId -> - translationChunkEvent.chunkId()?.let { chunkId -> - translationChunkEvent.index()?.let { index -> - MantraTranslationChunk( - id = translationChunkEvent.id, - publicKey = translationChunkEvent.pubKey, - createdAt = Instant.fromEpochSeconds(translationChunkEvent.createdAt), - translationChapterId = translationChapterId, - chunkId = chunkId, - index = index, - text = translationChunkEvent.content, - signature = translationChunkEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChunkProposal.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChunkProposal.kt deleted file mode 100644 index 68c63b74..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationChunkProposal.kt +++ /dev/null @@ -1,140 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip31Alts.AltTag -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ChunkIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChapterIdTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30311 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraChunk::class, - parentColumns = ["id"], - childColumns = ["chunkId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = MantraTranslationChapter::class, - parentColumns = ["id"], - childColumns = ["translationChapterId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationChunkProposal( - @PrimaryKey - val id: HexKey, - val publicKey: HexKey, - val chunkId: HexKey, - val translationChapterId: HexKey, - val text: String, - val index: Int, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - fun toTranslationChunkEvent(): TranslationChunkEvent { - return TranslationChunkEvent( - id = id, - pubKey = publicKey, - createdAt = createdAt.epochSeconds, - // Tag order matches TranslationChunkEvent.build so the id round-trips. - tags = TagArrayBuilder() - .addUnique(AltTag.assemble(TranslationChunkEvent.ALT_DESCRIPTION)) - .addUnique( - TranslationChapterIdTag.assemble(translationChapterId) - ) - .addUnique( - ChunkIdTag.assemble(chunkId) - ) - .addUnique( - IndexTag.assemble(index) - ) - .build(), - content = text, - sig = signature - ) - } - - companion object { - fun fromTranslationChunkEventTemplate( - translationChunkEventTemplate: EventTemplate, - chatRoomId: HexKey, - userPublicKey: HexKey, - ): MantraTranslationChunkProposal? { - return fromTranslationChunkEvent( - TranslationChunkEvent( - id = EventHasher.hashId( - pubKey = userPublicKey, - tags = translationChunkEventTemplate.tags, - content = translationChunkEventTemplate.content, - createdAt = translationChunkEventTemplate.createdAt, - kind = translationChunkEventTemplate.kind, - ), - content = translationChunkEventTemplate.content, - tags = translationChunkEventTemplate.tags, - createdAt = translationChunkEventTemplate.createdAt, - pubKey = userPublicKey, - sig = "", // Unsigned rumor - ), - chatRoomId = chatRoomId, - ) - } - - fun fromTranslationChunkEvent(translationChunkEvent: TranslationChunkEvent, chatRoomId: HexKey): MantraTranslationChunkProposal? { - return translationChunkEvent.translationChapterId()?.let { translationChapterId -> - translationChunkEvent.chunkId()?.let { chunkId -> - translationChunkEvent.index()?.let { index -> - MantraTranslationChunkProposal( - id = translationChunkEvent.id, - publicKey = translationChunkEvent.pubKey, - createdAt = Instant.fromEpochSeconds(translationChunkEvent.createdAt), - translationChapterId = translationChapterId, - chunkId = chunkId, - index = index, - text = translationChunkEvent.content, - signature = translationChunkEvent.sig, - chatRoomId = chatRoomId - ) - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationContributor.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationContributor.kt deleted file mode 100644 index 56ef346f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MantraTranslationContributor.kt +++ /dev/null @@ -1,116 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Entity -import androidx.room3.ForeignKey -import androidx.room3.PrimaryKey -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag -import com.vitorpamplona.quartz.nip31Alts.alt -import com.machankura.bennu.compose.database.model.traits.OptionalNostrEventEntity -import com.machankura.bennu.compose.database.model.traits.TimestampedEntity -import com.machankura.bennu.compose.nostr.nip30303.TranslationContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ContributorTag -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * 30312 - */ -@Entity( - foreignKeys = [ - ForeignKey( - entity = MantraTranslation::class, - parentColumns = ["id"], - childColumns = ["translationId"], - onDelete = ForeignKey.CASCADE, - ), - ForeignKey( - entity = ChatRoom::class, - parentColumns = ["id"], - childColumns = ["chatRoomId"], - onDelete = ForeignKey.CASCADE, - ), - ], -) -data class MantraTranslationContributor( - @PrimaryKey - val id: HexKey, - val dTag: String, - val publicKey: HexKey, - val translationId: HexKey, - val translatorPublicKey: HexKey, - - /** - * Signature will be an empty string if this is a rumor - */ - val signature: String, - - val chatRoomId: String, - - val relayHint: String? = null, - val marmotGroupEventId: HexKey? = null, - - /** The [GroupSignedEvent] this row was made from, when the group signed it. */ - val groupSignedEventId: HexKey? = null, - /** - * Related nostrEventId if this is not a rumor... - */ - override val nostrEventId: HexKey? = null, - override val createdAt: Instant = Clock.System.now(), - override val updatedAt: Instant = createdAt -): OptionalNostrEventEntity, TimestampedEntity { - - companion object { - fun toTranslationChapterProofReaderListEvent(mantraTranslationContributors: List): TranslationContributorListEvent? { - mantraTranslationContributors.firstOrNull()?.let { firstMantraTranslationTranslator -> - val allFromSameEvent = mantraTranslationContributors.all { - it.publicKey == firstMantraTranslationTranslator.publicKey - && it.createdAt == firstMantraTranslationTranslator.createdAt - && it.dTag == firstMantraTranslationTranslator.dTag - } - - if (allFromSameEvent) { - val translatorPublicKeys = mantraTranslationContributors.map { - ContributorTag.assemble( - pubKey = it.publicKey, - role = ContributorTag.ROLE_TRANSLATOR - ) - } - val template = eventTemplate( - kind = TranslationContributorListEvent.KIND, - description = "", - createdAt = firstMantraTranslationTranslator.createdAt.epochSeconds - ) { - addUnique( - DTag.assemble( - firstMantraTranslationTranslator.dTag - ) - ) - alt(TranslationContributorListEvent.ALT_DESCRIPTION) - - } - - - return TranslationContributorListEvent( - id = EventHasher.hashId( - pubKey = firstMantraTranslationTranslator.publicKey, - tags = template.tags, - createdAt = template.createdAt, - content = template.content, - kind = template.kind - ), - pubKey = firstMantraTranslationTranslator.publicKey, - createdAt = firstMantraTranslationTranslator.createdAt.epochSeconds, - tags = translatorPublicKeys.toTypedArray(), - content = template.content, - sig = firstMantraTranslationTranslator.signature - ) - } - } - return null - } - } -} - diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MarmotInnerEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MarmotInnerEvent.kt index 00ead353..568724a9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MarmotInnerEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MarmotInnerEvent.kt @@ -64,14 +64,6 @@ data class MarmotInnerEvent( // TODO: Rename this to GiftWrapPayload... val content: String, val quotedEventId: String? = null, - /** - * For a SubmissionEvent rumor, the id of the nip30303 event it carries. - * - * The submission's own id is derived from the envelope, so it is the only - * handle the queue has on what is actually being submitted. Null for every - * other kind, where the row *is* the event. - */ - val payloadEventId: HexKey? = null, /** * Associated MarmotGroupEvent @@ -140,7 +132,6 @@ data class MarmotInnerEvent( // TODO: Rename this to GiftWrapPayload... if (!tags.contentDeepEquals(other.tags)) return false if (content != other.content) return false if (quotedEventId != other.quotedEventId) return false - if (payloadEventId != other.payloadEventId) return false if (marmotGroupEventId != other.marmotGroupEventId) return false if (directMessageRecipientPublicKey != other.directMessageRecipientPublicKey) return false if (createdAt != other.createdAt) return false @@ -161,7 +152,6 @@ data class MarmotInnerEvent( // TODO: Rename this to GiftWrapPayload... result = 31 * result + tags.contentDeepHashCode() result = 31 * result + content.hashCode() result = 31 * result + (quotedEventId?.hashCode() ?: 0) - result = 31 * result + (payloadEventId?.hashCode() ?: 0) result = 31 * result + (marmotGroupEventId?.hashCode() ?: 0) result = 31 * result + (directMessageRecipientPublicKey?.hashCode() ?: 0) result = 31 * result + createdAt.hashCode() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MemberWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MemberWallet.kt new file mode 100644 index 00000000..68850128 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MemberWallet.kt @@ -0,0 +1,68 @@ +package com.machankura.bennu.compose.database.model + +import androidx.room3.Entity +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * A guarded wallet this device holds the key of: one member's random key, and + * the request that asked a group to guard it. `docs/member-guarded-wallets.md`. + * + * The key is why there is a table at all. Everything else about a member's + * wallet is read off signed events -- whether it is certified is whether the + * group's room holds a 30334 for [walletId] that verifies, read again each time + * the way `GroupWallet` reads statements -- so there is no *certified* column to + * disagree with the signature. + * + * ### `guardingChatRoomId` is a plain column, never a foreign key + * + * The argument `docs/subgroups.md` makes against cascading `parentChatRoomId`, + * with money at the end of it. Deleting the group's room on this device must + * never delete a private key that coins may sit behind; and a member who leaves + * the group keeps a wallet the group still guards. + * + * ### One database holds every profile + * + * So every read is scoped by [ownerPublicKey], the profile the key belongs to. + */ +@Entity( + indices = [ + Index("ownerPublicKey"), + Index("guardingChatRoomId"), + ], +) +data class MemberWallet( + /** `W`: `MemberWalletDerivation.walletId` of the wallet key. */ + @PrimaryKey + val walletId: String, + + /** The profile the wallet belongs to: the npub that signed the request. */ + val ownerPublicKey: HexKey, + + /** The group asked to guard it. */ + val guardingChatRoomId: String, + + /** The network, as `GroupWalletStatementEvent.chainName` writes it. */ + val chain: String, + + /** + * `k`, hex. Stored as `DkgSession.secretShare` is, in the profile's database; + * never logged, never sent. Lost with the device unless exported -- and then + * the guardians can still move the coins after 12 blocks. + */ + val walletPrivateKey: HexKey, + + /** The member's name for it, as the request carries it. */ + val label: String? = null, + + /** The signed 30335, whole: kept so a request the group did not sign can be asked again, unchanged. */ + val requestJson: String, + + val createdAt: Instant = Clock.System.now(), +) { + override fun toString(): String = + "MemberWallet(walletId=$walletId, owner=$ownerPublicKey, guardedBy=$guardingChatRoomId, chain=$chain, key=)" +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MemberWalletSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MemberWalletSpend.kt new file mode 100644 index 00000000..18307bb9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/MemberWalletSpend.kt @@ -0,0 +1,53 @@ +package com.machankura.bennu.compose.database.model + +import androidx.room3.Entity +import androidx.room3.Index +import androidx.room3.PrimaryKey +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * One transaction a member signed alone from their guarded wallet. + * + * The subset of [GroupTransaction] a spend with no signing session needs. + * `GroupTransaction` cannot hold it: its foreign keys are to a session and a + * room, and a member's own spend has neither. Written whole when it is signed, + * then filled in as the chain answers. + * + * No foreign key to [MemberWallet] either. A spend is a fact about the chain, + * and a row that cascaded away with its wallet would take the record of where + * the coins went with it. + */ +@Entity( + indices = [ + Index("walletId"), + ], +) +data class MemberWalletSpend( + /** The transaction's id, which a segwit spend fixes before it is signed. */ + @PrimaryKey + val txid: String, + + /** `W`, the wallet the inputs are under. */ + val walletId: String, + + /** The PSBT as built, base64: what every input's sighash was computed from. */ + val psbt: String, + + /** The finished transaction, hex, once it has passed `correctlySpends`. */ + val signedTransaction: String, + + /** When this device last handed it to Electrum -- which reports success whatever the server said. */ + val broadcastAt: Instant? = null, + + /** When this device's wallet first saw the transaction, in the mempool or in a block. */ + val seenAt: Instant? = null, + + /** When its first confirmation was seen. */ + val confirmedAt: Instant? = null, + + /** The txid of a later spend of the same coins that confirmed instead, if one did. */ + val replacedByTxid: String? = null, + + val createdAt: Instant = Clock.System.now(), +) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index ed14be7d..a1ca6635 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -1,8 +1,11 @@ package com.machankura.bennu.compose.database.repository +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.managers.GroupLightningWalletManager import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.GENESIS_AT @@ -20,10 +23,6 @@ import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SubgroupManager -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload @@ -40,8 +39,6 @@ import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync @@ -144,48 +141,21 @@ class DatabaseChatRepository( null } - override suspend fun groupNostrProfile(chatRoomId: String): GroupNostrProfile? = try { - GroupNostrProfile.newestAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, MetadataEvent.KIND), - chatRoomId = chatRoomId, - ) + override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = try { + SubgroupManager.walletPolicyOf(database, chatRoomId) } catch (e: Throwable) { - // Reading one parses content off the wire and checks a signature, and a - // room that shows no profile is wrong and survivable where one that will - // not open is neither -- the same trade the readings above make. - logger.e("Error reading the nostr profile of $chatRoomId", e) + logger.e("Error reading the wallet policy of $chatRoomId", e) null } - override suspend fun groupRelayLists(chatRoomId: String): List = try { - // One query per set rather than one for the room: the four kinds are - // indexed and a room's whole signed history is every artifact, chunk and - // translation it has ever agreed. - GroupRelaySet.entries.map { set -> - GroupRelayList.newestAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, set.kind), - chatRoomId = chatRoomId, - set = set, - ) - } + // Null on a failure, which reads as keys this build cannot read: the picker + // then refuses a guarded subgroup rather than promising a grant it could not + // check. + override suspend fun guardiansOf(chatRoomId: String): List? = try { + SubgroupManager.guardiansOf(database, chatRoomId) } catch (e: Throwable) { - logger.e("Error reading the relay lists of $chatRoomId", e) - // Four unsigned, empty sets: the screen draws "not set yet" rather than - // failing to draw, which is the trade every reading above makes. - GroupRelayList.allAmong(emptyList(), chatRoomId) - } - - override suspend fun groupPosts(chatRoomId: String): List = try { - GroupPost.newestFirstAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, TextNoteEvent.KIND), - chatRoomId = chatRoomId, - ) - } catch (e: Throwable) { - logger.e("Error reading the posts of $chatRoomId", e) - emptyList() + logger.e("Error reading the guardians of $chatRoomId", e) + null } override suspend fun lightningParticipants(chatRoomId: String, chain: Chain): Set = @@ -205,13 +175,50 @@ class DatabaseChatRepository( null } - override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { - database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } + override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? = try { + GroupWalletManager.guardedAccountFor(database, chatRoomId, chain) } catch (e: Throwable) { - logger.e("Error reading the signed event $id of $chatRoomId", e) + logger.e("Error deriving the guarded wallet account of $chatRoomId", e) null } + override suspend fun guardedWallets(chatRoomId: String): List = try { + GuardianManager.guardedWalletsOf(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading the guarded wallets $chatRoomId was told about", e) + emptyList() + } + + override suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List = try { + GuardianManager.shareableFrom(database, chatRoomId, chain) + } catch (e: Throwable) { + logger.e("Error reading what $chatRoomId can tell the groups above it", e) + emptyList() + } + + override suspend fun forwardGuardedWallets(chatRoomId: String): Int = try { + GuardianManager.forwardAll(database, chatRoomId) + } catch (e: Throwable) { + // A room that opens without telling the groups above is wrong and + // survivable, and the button is still there. + logger.e("Error forwarding $chatRoomId's guarded wallets upward", e) + 0 + } + + override suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int = try { + GuardianManager.share(database, shareable.statement, shareable.rooms, userPublicKey, certificate = shareable.certificate) + } catch (e: Throwable) { + logger.e("Error telling the groups above about ${shareable.statement.pubKey}'s guarded wallet", e) + 0 + } + + override suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int = try { + GuardianManager.recordTaken(database, chatRoomId, taken) + } catch (e: Throwable) { + logger.e("Error recording guardian spends from $chatRoomId's wallet", e) + 0 + } + override suspend fun canSign(chatRoomId: String): Boolean = try { FrostSigningManager.canSign(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseDkgRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseDkgRepository.kt index 16015f4b..77dbb6c4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseDkgRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseDkgRepository.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.database.repository +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.DkgParticipantMessage import com.machankura.bennu.compose.database.model.DkgSession @@ -64,7 +65,9 @@ class DatabaseDkgRepository( threshold: Int, parentChatRoomId: HexKey?, participantPublicKeys: Set?, - subject: String? + subject: String?, + walletPolicy: SubgroupWalletPolicy?, + guardianDelay: Long? ): DkgSession? = try { ChillDkgRitualManager.proposeRitual( database = database, @@ -74,7 +77,9 @@ class DatabaseDkgRepository( threshold = threshold, parentChatRoomId = parentChatRoomId, participantPublicKeys = participantPublicKeys, - subject = subject + subject = subject, + walletPolicy = walletPolicy, + guardianDelay = guardianDelay ) } catch (e: Throwable) { logger.e("Error proposing DKG ritual for ${localChatRoom.chatRoom.id}", e) @@ -214,6 +219,17 @@ class DatabaseDkgRepository( null } + override suspend fun abandon(localChatRoom: LocalChatRoom, sessionId: String): Boolean = try { + ChillDkgRitualManager.abandon( + database = database, + localChatRoom = localChatRoom, + sessionId = sessionId, + ) + } catch (e: Throwable) { + logger.e("Error abandoning DKG ritual $sessionId", e) + false + } + override suspend fun approve( localChatRoom: LocalChatRoom, sessionId: String, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt index b90a59f8..a7badb0c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -149,6 +149,23 @@ class DatabaseFrostSigningRepository( ) } + override suspend fun proposeGuardianSpend( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + ): FrostSigningSession? = proposing(localChatRoom) { + FrostSigningManager.proposeGuardianSpend( + database = database, + localChatRoom = localChatRoom, + userPublicKey = userPublicKey, + psbt = psbt, + descendantChatRoomId = descendantChatRoomId, + chain = chain, + ) + } + override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = try { FrostSigningManager.checkedSpend(database, sessionId) } catch (e: Throwable) { @@ -177,6 +194,13 @@ class DatabaseFrostSigningRepository( emptySet() } + override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = try { + FrostSigningManager.reservedFundingIndices(database, chatRoomId, account) + } catch (e: Throwable) { + logger.e("Error reading the funding addresses reserved in $chatRoomId", e) + emptySet() + } + override fun observeGroupTransactions(chatRoomId: String): Flow> = database.groupTransactionDao().observeByChatRoomId(chatRoomId) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt deleted file mode 100644 index 28bd0e10..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMantraRepository.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.machankura.bennu.compose.database.repository - -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.CoroutineScope -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChunk -import com.machankura.bennu.compose.database.model.MarmotInnerEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.MantraRepository - -class DatabaseMantraRepository( - val database: BennuDatabase, - val scope: CoroutineScope -): MantraRepository { - - private val logger = Logger.withTag(TAG) - - override suspend fun getArtifacts(chatRoomId: String): List = - database.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId) - - override suspend fun getArtifact(id: String): MantraArtifact? = - database.mantraArtifactDao().getArtifactById(id) - - override suspend fun getArtifactVersions(artifactId: String): List = - database.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(artifactId) - - override suspend fun getArtifactVersion(id: String): MantraArtifactVersion? = - database.mantraArtifactVersionDao().getArtifactVersionById(id) - - override suspend fun getChaptersForArtifact(artifactId: String): List = - database.mantraChapterDao().getChaptersByArtifactId(artifactId) - - override suspend fun getChaptersForArtifactVersion(artifactVersionId: String): List = - database.mantraChapterDao().getChaptersByArtifactVersionId(artifactVersionId) - - override suspend fun getChapter(id: String): MantraChapter? = - database.mantraChapterDao().getChapterById(id) - - override suspend fun getChunksForChapter(chapterId: String): List = - database.mantraChunkDao().getChunksByChapterId(chapterId) - - override suspend fun getChunk(id: String): MantraChunk? = - database.mantraChunkDao().getChunkById(id) - - override suspend fun getTranslationsForArtifact(artifactId: String): List = - database.mantraTranslationArtifactVersionDao().getTranslationsByArtifactId(artifactId) - - override suspend fun getTranslation(id: String): MantraTranslationArtifactVersion? = - database.mantraTranslationArtifactVersionDao().getTranslationById(id) - - override suspend fun getTranslationsForArtifactVersion(artifactVersionId: String): List = - database.mantraTranslationArtifactVersionDao().getTranslationsByArtifactVersionId(artifactVersionId) - - override suspend fun getTranslationChapter(id: String): MantraTranslationChapter? = - database.mantraTranslationChapterDao().getTranslationChapterById(id) - - override suspend fun getTranslationChapters(translationArtifactVersionId: String): List = - database.mantraTranslationChapterDao().getTranslationChaptersByTranslationArtifactVersionId(translationArtifactVersionId) - - override suspend fun getTranslationChunks(translationChapterId: String): List = - database.mantraTranslationChunkDao().getTranslationChunksByTranslationChapterId(translationChapterId) - - override suspend fun getDialects(chatRoomId: String): List = - database.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - - override suspend fun getDialect(id: String): MantraDialect? = - database.mantraDialectDao().getDialectById(id) - - override suspend fun addArtifactVersion( - localChatRoom: LocalChatRoom, - artifactId: HexKey, - versionLabel: String, - userPublicKey: HexKey, - ): MantraArtifactVersion? { - return database.mantraDao().addArtifactVersion( - localChatRoom = localChatRoom, - artifactId = artifactId, - versionLabel = versionLabel, - userPublicKey = userPublicKey - ) - } - - companion object { - private const val TAG = "DatabaseMantraRepository" - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt new file mode 100644 index 00000000..cd2f7701 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt @@ -0,0 +1,153 @@ +package com.machankura.bennu.compose.database.repository + +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.managers.GuardianManager +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.psbt.Psbt +import kotlinx.coroutines.flow.Flow +import kotlin.time.Instant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +class DatabaseMemberWalletRepository( + private val database: BennuDatabase, + private val activeIdentity: StateFlow = MutableStateFlow(null), +) : MemberWalletRepository { + private val logger = Logger.withTag(TAG) + + override suspend fun groupsOf(ownerPublicKey: HexKey): List = try { + MemberWalletManager.groupsOf(database, ownerPublicKey) + } catch (e: Throwable) { + logger.e("Error reading the groups that could guard a wallet", e) + emptyList() + } + + override suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? = try { + MemberWalletManager.refusal(database, chatRoomId, canSign = activeIdentity.value?.canSign == true, chain = chain) + } catch (e: Throwable) { + logger.e("Error reading whether $chatRoomId can guard a wallet", e) + MemberWalletManager.Refusal.KEY_UNKNOWN + } + + override suspend fun reachOf(chatRoomId: String): Int? = try { + MemberWalletManager.reachOf(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading how far $chatRoomId's guard reaches", e) + null + } + + override suspend fun delaysOf(chatRoomId: String): List? = try { + MemberWalletManager.delaysOf(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading how far $chatRoomId's guard reaches", e) + null + } + + override suspend fun askForGroupKey(chatRoomId: String): Boolean { + val identity = activeIdentity.value ?: return false + return MemberWalletManager.askForGroupKey(database, chatRoomId, identity.nostrPublicKey) + } + + override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet { + val key = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This profile cannot sign") + return MemberWalletManager.request(database, chatRoomId, key, chain, label) + } + + override suspend fun walletsOf(ownerPublicKey: HexKey): List = try { + MemberWalletManager.walletsOf(database, ownerPublicKey) + } catch (e: Throwable) { + // A profile that lists no wallets is wrong and survivable; one that will + // not open because reading them threw is neither. + logger.e("Error reading $ownerPublicKey's guarded wallets", e) + emptyList() + } + + override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = try { + MemberWalletManager.walletOf(database, ownerPublicKey, walletId) + } catch (e: Throwable) { + logger.e("Error reading guarded wallet $walletId", e) + null + } + + override suspend fun askAgain(walletId: String): String { + val wallet = database.memberWalletDao().getById(walletId) ?: throw IllegalStateException("No key for $walletId here") + check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" } + val key = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This profile cannot sign") + return MemberWalletManager.askAgain(database, wallet, key).walletId + } + + override suspend fun discard(walletId: String) { + val wallet = database.memberWalletDao().getById(walletId) ?: return + check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" } + MemberWalletManager.discard(database, walletId) + } + + override suspend fun exportKey(walletId: String): Pair? { + val owner = activeIdentity.value?.nostrPublicKey ?: return null + return MemberWalletManager.exportKey(database, owner, walletId) + } + + override suspend fun roomName(chatRoomId: String): String? = + database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.subject?.takeIf { it.isNotBlank() } + + override suspend fun signSpend(walletId: String, psbt: Psbt): Transaction { + val owner = activeIdentity.value?.nostrPublicKey ?: throw IllegalStateException("No profile is active") + return MemberWalletManager.signSpend(database, owner, walletId, psbt) + } + + override suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant?) = + MemberWalletManager.recordChain(database, txid, confirmations, broadcastAt) + + override fun observeSpends(walletId: String): Flow> = database.memberWalletDao().observeSpends(walletId) + + override suspend fun couldGuard(chatRoomId: String): Boolean = try { + database.chatRoomDao().findChatRoomById(chatRoomId)?.let { MemberWalletManager.couldGuard(database, it) } == true + } catch (e: Throwable) { + logger.e("Error reading whether $chatRoomId could guard a wallet", e) + false + } + + override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = try { + MemberWalletManager.policyFor(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading $chatRoomId's member-wallet policy", e) + null + } + + override suspend fun memberWalletsOf(chatRoomId: String): List = try { + MemberWalletManager.memberWalletsOf(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading the member wallets $chatRoomId guards", e) + emptyList() + } + + override suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession { + val identity = activeIdentity.value ?: throw IllegalStateException("No profile is active") + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: throw IllegalStateException("No such group here") + return MemberWalletManager.putToGroup(database, room, identity.nostrPublicKey, request) + } + + override suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List = try { + val viewer = activeIdentity.value?.nostrPublicKey ?: return emptyList() + MemberWalletManager.guardedByGroupsHere(database, viewer, ownerPublicKey) + } catch (e: Throwable) { + logger.e("Error reading the wallets of $ownerPublicKey this profile's groups guard", e) + emptyList() + } + + companion object { + private const val TAG = "DatabaseMemberWalletRepository" + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChillDkgRitualManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChillDkgRitualManager.kt index 28cd7985..3c79f61d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChillDkgRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChillDkgRitualManager.kt @@ -1,5 +1,9 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianDelayTag +import com.machankura.bennu.compose.database.model.subgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.DkgParticipantMessage @@ -106,6 +110,9 @@ object ChillDkgRitualManager { */ const val MINIMUM_PARTICIPANTS = 2 + /** Why a ceremony a participant walked away from ended, as every device records it. */ + private const val ABANDONED = "Abandoned by a participant" + /** * This device's long-term ChillDKG host secret key. * @@ -138,6 +145,14 @@ object ChillDkgRitualManager { fun canRunRitual(localChatRoom: LocalChatRoom): Boolean = memberPublicKeys(localChatRoom).size >= MINIMUM_PARTICIPANTS + /** + * Whether [localChatRoom] is a Marmot room, and so can host a subgroup's + * ceremony but never one of its own. The same reading [broadcast] makes to + * pick a transport. + */ + fun isMarmotRoom(localChatRoom: LocalChatRoom): Boolean = + localChatRoom.chatRoom.mlsGroupState != null + /** * Everyone a ceremony is being run with — which is not the same question as * who is in the room it runs in. @@ -171,6 +186,17 @@ object ChillDkgRitualManager { * and is carried to the other admins on the proposal because there is no * longer a room of its own for them to read it off. * + * [walletPolicy] is what the subgroup's wallet is to be, as the coordinator + * chose it on the picker -- carried on the proposal so every admin is told + * before joining, and on the session so whoever proposes the birth + * certificate proposes it under the same one. Only a subgroup's ceremony has + * one. See `docs/subgroup-wallet-policy.md`. + * + * [guardianDelay] is the delay, in blocks, the coordinator chose for the + * parent's own leaf in a guarded subgroup's wallet, carried the same way and + * for the same reasons. Only a guarded ceremony has one, and it is in + * `GuardianDerivation.DELAY_RANGE`. See `docs/guardian-delay.md`. + * * Throws when the group or the threshold cannot support one; the UI checks * both before offering the button, so reaching either is a bug rather than a * user error. @@ -183,8 +209,25 @@ object ChillDkgRitualManager { threshold: Int, parentChatRoomId: HexKey? = null, participantPublicKeys: Set? = null, - subject: String? = null + subject: String? = null, + walletPolicy: SubgroupWalletPolicy? = null, + guardianDelay: Long? = null ): DkgSession { + // A policy is for a subgroup's wallet, and a ceremony with no parent makes + // no subgroup. `acceptProposal` drops the same thing on the way in. + // Before the running check, which would otherwise hand back a ceremony + // for a question this one should never have asked. + require(walletPolicy == null || parentChatRoomId != null) { + "Only a subgroup's ceremony carries a wallet policy" + } + // A delay is a guarded wallet's, and within what a leaf can carry. + require(guardianDelay == null || walletPolicy == SubgroupWalletPolicy.GUARDED) { + "Only a guarded subgroup's ceremony carries a guardian delay" + } + require(guardianDelay == null || guardianDelay in GuardianDerivation.DELAY_RANGE) { + "A guardian's delay is ${GuardianDerivation.MIN_DELAY} to ${GuardianDerivation.MAX_DELAY} blocks, not $guardianDelay" + } + // Built the way a receiver rebuilds it from the proposal — the p-tags // `broadcast` writes, plus this device — so both sides count the same `n` // even if the room's own rows have drifted. @@ -245,6 +288,15 @@ object ChillDkgRitualManager { "${(members - room).joinToString { it.take(8) }}, who are not in it" } + // A Marmot room's id is derived from the key it already has, so a ceremony + // of its own would make a key the room could never answer to. It hosts its + // subgroups' ceremonies and nothing else. The screens stopped offering one + // here, and this is what makes that a rule rather than a screen not drawing + // a button -- see docs/ceremony-creation.md. + require(parentChatRoomId != null || !isMarmotRoom(localChatRoom)) { + "${localChatRoom.chatRoom.id} is a Marmot room; it can only host a subgroup's ceremony" + } + require(members.size >= MINIMUM_PARTICIPANTS) { "A shared key needs at least $MINIMUM_PARTICIPANTS members, this ceremony has ${members.size}" } @@ -273,6 +325,8 @@ object ChillDkgRitualManager { // subgroup's ceremony runs in the parent's room over a subset of it. participantPublicKeys = DkgSession.formatParticipants(members), subject = ceremonySubject, + walletPolicy = walletPolicy?.tagValue, + guardianDelay = guardianDelay, hostPublicKey = deriveHostPublicKey(nostrPrivateKey).value.toHex(), // Fresh per session. Persisted because participantStep1/2 are pure in // it, which is what makes the whole ritual restart-safe. @@ -375,7 +429,7 @@ object ChillDkgRitualManager { return } - if (!record(database, session, innerEvent)) return + if (!record(database, localChatRoom, session, innerEvent)) return advance( database = database, @@ -399,6 +453,20 @@ object ChillDkgRitualManager { ): DkgSession? { database.dkgSessionDao().getSessionById(sessionId)?.let { return it } + // The receiving half of `proposeRitual`'s refusal. A build from before it + // can still put a group's own ceremony on the wire in a Marmot room, and + // recording it would show every member a ceremony whose key the room can + // never use -- which is how a second ceremony ended up beside a subgroup's. + if (isMarmotRoom(localChatRoom) && + DkgRitualEvents.parseParentChatRoomId(innerEvent.tags) == null + ) { + logger.w( + "DKG proposal $sessionId names no parent in Marmot room " + + "${localChatRoom.chatRoom.id}; dropping" + ) + return null + } + // The participant set is the proposal's own p-tags plus its sender, NOT // this device's view of the room. `n` is hashed into the session identity, // so two devices that disagree on it cannot complete a ritual together — @@ -437,6 +505,37 @@ object ChillDkgRitualManager { return null } + // A policy is only for a subgroup's wallet, and one that does not read is + // not one to join on the assumption it says nothing: an admin would be + // shown no policy and then asked to sign a key state under one. + val walletPolicy = when (val tag = DkgRitualEvents.parseWalletPolicy(innerEvent.tags)) { + WalletPolicyTag.Result.Absent -> null + WalletPolicyTag.Result.Unreadable -> { + logger.w("DKG proposal $sessionId carries a wallet policy that does not read; dropping") + return null + } + is WalletPolicyTag.Result.Present -> tag.policy + } + if (walletPolicy != null && DkgRitualEvents.parseParentChatRoomId(innerEvent.tags) == null) { + logger.w("DKG proposal $sessionId carries a wallet policy and names no parent; dropping") + return null + } + + // The same for the delay: a guarded subgroup's only, and in range. An + // admin shown no delay must not be asked to sign a certificate under one. + val guardianDelay = when (val tag = DkgRitualEvents.parseGuardianDelay(innerEvent.tags)) { + GuardianDelayTag.Result.Absent -> null + GuardianDelayTag.Result.Unreadable -> { + logger.w("DKG proposal $sessionId carries a guardian delay that does not read; dropping") + return null + } + is GuardianDelayTag.Result.Present -> tag.delay + } + if (guardianDelay != null && walletPolicy != SubgroupWalletPolicy.GUARDED) { + logger.w("DKG proposal $sessionId carries a guardian delay for a subgroup that is not guarded; dropping") + return null + } + val session = DkgSession( id = sessionId, chatRoomId = localChatRoom.chatRoom.id, @@ -461,6 +560,10 @@ object ChillDkgRitualManager { // on it, and the certificate the parent's quorum signs is over this // name, so an admin who dislikes it declines that. subject = DkgRitualEvents.parseSubject(innerEvent.tags), + // What the subgroup's wallet is to be, as claimed -- shown at the join + // gate, so joining is agreeing to it. See the checks above. + walletPolicy = walletPolicy?.tagValue, + guardianDelay = guardianDelay, hostPublicKey = deriveHostPublicKey(nostrPrivateKey).value.toHex(), round1Random = RandomInstance.bytes(32).toHex(), round2AuxRandom = RandomInstance.bytes(32).toHex(), @@ -550,7 +653,7 @@ object ChillDkgRitualManager { logger.i("Replaying ${stored.size} stored message(s) for ritual ${session.id}") stored.forEach { payload -> - if (!record(database, session, payload)) return + if (!record(database, localChatRoom, session, payload)) return } } @@ -564,6 +667,7 @@ object ChillDkgRitualManager { */ private suspend fun record( database: BennuDatabase, + localChatRoom: LocalChatRoom, session: DkgSession, innerEvent: Event ): Boolean { @@ -634,6 +738,18 @@ object ChillDkgRitualManager { } DkgRitualEvents.FAILURE -> { + // Only somebody in the ceremony can end it. In a parent's room every + // member can read a subgroup's proposal, and so could name its + // session -- but a member who was never in it walking away is not + // the ceremony failing. + if (innerEvent.pubKey !in participantsOf(session, localChatRoom)) { + logger.w( + "Ritual ${session.id}: FAILURE from ${innerEvent.pubKey.take(8)}, " + + "who is not in it; ignoring" + ) + return true + } + fail( database = database, session = session, @@ -1088,6 +1204,49 @@ object ChillDkgRitualManager { return null } + /** + * Ends a ceremony this device is in, for everyone in it. + * + * ChillDKG has no "no" short of this: a participant who never approves stalls + * the ceremony for good, and the others are left waiting on a key that will + * not come. Saying so lets them stop. It is the same FAILURE message a fault + * sends, and every device files it the same way -- no key is created, and the + * group can start again. + * + * Returns whether it was ended. Refuses, rather than throws, a ceremony this + * device is not in or one that is already over: a stale screen may ask. + */ + suspend fun abandon( + database: BennuDatabase, + localChatRoom: LocalChatRoom, + sessionId: String, + ): Boolean { + val session = database.dkgSessionDao().getSessionById(sessionId) ?: return false + + if (session.stage == DkgRitualStage.COMPLETE || session.stage == DkgRitualStage.FAILED) { + logger.i("Ritual $sessionId is already over; nothing to abandon") + return false + } + + if (session.userPublicKey !in participantsOf(session, localChatRoom)) { + logger.w("Ritual $sessionId does not include this device; not abandoning it") + return false + } + + logger.i("Abandoning ritual $sessionId") + + fail(database, session, ABANDONED) + broadcast( + database = database, + localChatRoom = localChatRoom, + session = session, + kind = DkgRitualEvents.FAILURE, + content = ABANDONED + ) + + return true + } + /** * Records that this device's owner agreed to [step], then lets the ritual run as * far as the next thing it is waiting on. @@ -1374,7 +1533,10 @@ object ChillDkgRitualManager { sessionId = session.id, threshold = if (includeThreshold) session.threshold else null, parentChatRoomId = if (includeParent) session.parentChatRoomId else null, - subject = subject + subject = subject, + // With the parent, and for the same reason: only on the proposal. + walletPolicy = if (includeParent) session.subgroupWalletPolicy else null, + guardianDelay = if (includeParent) session.guardianDelay else null ) val createdAt = Clock.System.now().epochSeconds diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt index 3fe5838d..39cf6bfb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt @@ -18,7 +18,7 @@ import kotlin.time.Instant import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent import com.machankura.bennu.compose.nostr.chronicle.ChronicleRequestEvent import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent +import com.machankura.bennu.compose.nostr.chronicle.ChronicleKinds /** * Building the group's signed record into pages a member who lacks it can apply. @@ -28,49 +28,39 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent * locally by each device that took part and never goes on the wire. This is how * it gets to them. * - * ### The events are the chronicle, and the rows are the fallback + * ### Carrying nothing, for now + * + * What a chronicle may carry is [ChronicleEvent.KINDS], and that is empty since + * the document kinds it was built for were removed (docs/ceremony-creation.md, + * Phase 7). Every entry point here takes the kinds as a parameter defaulting to + * that list, and with it empty the chronicle is quiet: [requestIfEmpty] asks for + * nothing, [sendTo] sends nothing, and a page from an older build applies + * nothing. The machinery is kept, and tested with a list of the tests' own, for + * the next kind that should join. + * + * ### The events are the chronicle * * `GroupSignedEvent` holds what the group signed, as it signed it, so - * [signedEventsOf] reads it first: no rebuild, no round-trip risk, and nothing - * that depends on a row having kept every field of the event it came from. The - * artifact's version label is the standing example -- it is not on the artifact - * row at all, and [rebuiltEventsOf] has to go and find it on the initial version - * or leave the artifact out. + * [signedEventsOf] reads it: no rebuild, no round-trip risk, and nothing that + * depends on a row having kept every field of the event it came from. * - * A room whose work predates that table has no events on file, so the rebuild - * stays as the fallback for exactly what the table is missing, keyed by id. - * Every payload it produces stands or falls on being byte-identical to what was - * signed; `ChronicleRoundTripTest` is what says it is, per kind, against a real - * quorum, and it found two faults in the artifact's rebuild the first time it - * ran -- both of which would have shipped payloads that every receiver drops as - * forgeries without a word. Both it and everything that exists only to hold it - * up are marked `@Deprecated`; the fallback can go once no install still holds - * pre-v13 work, and docs/member-chronicle.md's "Retiring the rebuild" is the list - * of what goes with it. - * - * **The allowlist does real work on the way out now.** The rebuild could only - * ever produce document kinds; the table holds everything the group has ever - * signed, `GroupKeyStateEvent` included. So [signedEventsOf] filters on - * [ChronicleEvent.isChroniclable] before anything else, which is the same rule - * [applyPage] applies on the way in. Without it `ChronicleEvent.build` would - * refuse the page and take the whole chronicle down with it. - * - * A room's own key state no longer sits in that table under the room -- it is - * signed in the NIP-17 room the ceremony ran in, before the room exists, and - * filed under that room; see `GroupKeyStateManager`. That makes the filter a - * narrower guard than it was and not a redundant one: what it is really stopping + * **The allowlist does real work on the way out.** The table holds everything + * the group has ever signed, `GroupKeyStateEvent` included. So [signedEventsOf] + * filters on the kinds before anything else, which is the same rule [applyPage] + * applies on the way in. Without it `ChronicleEvent.build` would refuse the page + * and take the whole chronicle down with it. What the filter is really stopping * is a member replaying any group-signed statement about the record as though it - * were work, and [applyPage] refuses the same kinds coming the other way. The - * two are a pair and neither is safe to drop on the strength of the other. + * were work, and [applyPage] refuses the same kinds coming the other way. The two + * are a pair and neither is safe to drop on the strength of the other. * * ### Nothing unverifiable leaves * - * Every rebuilt event is checked with [GroupKeyStateEvent.isSignedByRoom] before - * it is packed, against the same room id the recipient will check it with. That - * is not politeness towards the receiver, who checks anyway. It is what keeps an - * chronicle honest about its own size: a row that came from a member's rumor - * cannot be chronicled, and dropping it here rather than letting the recipient - * drop it means the page count says what will actually arrive. + * Every event is checked with [GroupKeyStateEvent.isSignedByRoom] before it is + * packed, against the same room id the recipient will check it with. That is not + * politeness towards the receiver, who checks anyway. It is what keeps a + * chronicle honest about its own size: dropping a payload here rather than + * letting the recipient drop it means the page count says what will actually + * arrive. */ object ChronicleManager { private const val TAG = "ChronicleManager" @@ -93,16 +83,13 @@ object ChronicleManager { recipient: HexKey, chronicleId: String = RandomInstance.bytes(32).toHex(), createdAt: Long = TimeUtils.now(), + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): List> { - val held = signedEventsOf(database, chatRoomId) + val held = signedEventsOf(database, chatRoomId, kinds) - // One rule over both sources: nothing leaves that the recipient could - // not check for themselves. What a drop means depends on where it came - // from, and the two are worth telling apart when reading this log -- - // from the rebuild it is the ordinary case of a member's own rumor - // sitting in the same table as the group's work, and from the record it - // is a row that has drifted from the event it recorded, which nothing - // in this app does on purpose. + // Nothing leaves that the recipient could not check for themselves. A + // drop here is a row that has drifted from the event it recorded, which + // nothing in this app does on purpose. val verified = held.filter { GroupKeyStateEvent.isSignedByRoom(it, chatRoomId) } if (verified.size != held.size) { logger.d( @@ -111,7 +98,7 @@ object ChronicleManager { ) } - val pages = paginate(ChronicleEvent.inApplyOrder(verified)) + val pages = paginate(kinds.inApplyOrder(verified)) if (pages.isEmpty()) { logger.i("Nothing signed to chronicle for room $chatRoomId") return emptyList() @@ -130,6 +117,7 @@ object ChronicleManager { count = pages.size, recipient = recipient, createdAt = createdAt, + kinds = kinds, ) } } @@ -139,9 +127,12 @@ object ChronicleManager { /** * Ask the group for its signed history, if this device holds none of it. * - * Called on entering a room. The condition is deliberately crude -- no - * dialects and no artifacts -- because the three cases it has to catch look - * identical from inside the database and should not be told apart: + * Called on entering a room. Does nothing while [kinds] is empty, which it + * is in this app at the moment -- see the class comment. + * + * The condition is deliberately crude -- nothing of a chroniclable kind on + * file -- because the three cases it has to catch look identical from inside + * the database and should not be told apart: * * - a member added after the work was done, whose invite may be recent; * - a reinstall, whose invite is long past; @@ -162,12 +153,17 @@ object ChronicleManager { database: BennuDatabase, chatRoomId: String, userPublicKey: HexKey, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Boolean { + // Quiet while a chronicle may carry nothing: there is no answer worth + // asking for, and asking would put a request on the wire and a line in + // the transcript on every room the member opens. + if (kinds.isEmpty()) return false + val chatRoom = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom ?: return false if (chatRoom.chronicleRequestedAt != null) return false - val holdsWork = database.mantraDialectDao().getDialectsByChatRoomId(chatRoomId).isNotEmpty() || - database.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).isNotEmpty() + val holdsWork = signedEventsOf(database, chatRoomId, kinds).isNotEmpty() if (holdsWork) return false @@ -217,10 +213,11 @@ object ChronicleManager { chatRoomId: String, userPublicKey: HexKey, recipient: HexKey, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Int { if (recipient.equals(userPublicKey, ignoreCase = true)) return 0 - val pages = assemble(database, chatRoomId, recipient) + val pages = assemble(database, chatRoomId, recipient, kinds = kinds) if (pages.isEmpty()) { logger.i("Nothing signed here to send ${recipient.take(8)} for $chatRoomId") return 0 @@ -373,6 +370,7 @@ object ChronicleManager { chatRoomId: String, userPublicKey: HexKey, page: Event, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Outcome { val recipient = ChronicleEvent( id = page.id, @@ -388,7 +386,7 @@ object ChronicleManager { return Outcome() } - return sweep(database, chatRoomId, userPublicKey) + return sweep(database, chatRoomId, userPublicKey, kinds) } /** @@ -421,6 +419,7 @@ object ChronicleManager { database: BennuDatabase, chatRoomId: String, userPublicKey: HexKey, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Outcome { val pages = database.marmotInnerEventDao() .getByChatRoomAndKinds(chatRoomId, listOf(ChronicleEvent.KIND)) @@ -433,7 +432,7 @@ object ChronicleManager { while (true) { pass = Outcome() - pages.forEach { pass += applyPage(database, chatRoomId, it) } + pages.forEach { pass += applyPage(database, chatRoomId, it, kinds) } if (pass.failed == 0 || pass.failed >= previousFailures) { if (pass.failed > 0) { @@ -513,6 +512,7 @@ object ChronicleManager { database: BennuDatabase, chatRoomId: String, stored: MarmotInnerEvent, + kinds: ChronicleKinds, ): Outcome { val payloads = ChronicleEvent.decodePage(stored.content) if (payloads == null) { @@ -530,13 +530,13 @@ object ChronicleManager { var outcome = Outcome() - ChronicleEvent.inApplyOrder(payloads).forEach { payload -> + kinds.inApplyOrder(payloads).forEach { payload -> // The allowlist first, and it is not a formality. Verification admits // an event to the apply path on the strength of the group's // signature, which makes every kind the group has ever signed // replayable by any member at any time -- a GroupKeyStateEvent from // an earlier epoch passes the signature check perfectly. - if (!ChronicleEvent.isChroniclable(payload.kind)) { + if (!kinds.isChroniclable(payload.kind)) { logger.w( "Chronicle page ${stored.id.take(8)} carries kind ${payload.kind}, " + "which a chronicle may not deliver; dropping ${payload.id.take(8)}" @@ -605,224 +605,31 @@ object ChronicleManager { } /** - * Every chroniclable event this device holds for the room: the ones the group - * signed here or sent here, plus anything only the rows still remember. + * Every chroniclable event this device holds for the room, as the group + * signed it. * - * The record comes first because it is the event rather than a reconstruction - * of one, and the rebuild fills the gap behind it -- keyed by id, so an event - * held both ways travels once. A room that upgraded mid-life has both, and - * neither half is complete on its own. - * - * The two disagree only in one direction worth naming. An id the rebuild - * produces that the record does not hold is either work from before the - * table existed, which is the point of the fallback, or a rebuild that has - * gone wrong -- and a wrong rebuild hashes to an id whose signature does not - * verify, so the filter in [assemble] drops it either way rather than - * shipping a payload every receiver reads as a forgery. - * - * Order does not matter at this point; [ChronicleEvent.inApplyOrder] settles it - * afterwards. It is stable within a rank, so a room holding some of its work - * both ways can order two chapters differently from a member holding one way - * only. That costs nothing: pages are idempotent and applied payload by - * payload, and two members already differed by the order their rows were - * written in. + * Order does not matter at this point; [ChronicleKinds.inApplyOrder] settles + * it afterwards. */ private suspend fun signedEventsOf( database: BennuDatabase, chatRoomId: String, - ): List { - val recorded = database.groupSignedEventDao() - .getByChatRoomId(chatRoomId) - // The allowlist, applied to the source that can actually trip it -- - // see the class comment. A key state on file is the room's own, and - // sending it would be handing every member a validly signed - // statement about what the room signs with, replayable forever. - .filter { ChronicleEvent.isChroniclable(it.kind) } - .map { it.toEvent() } - - val onFile = recorded.mapTo(mutableSetOf()) { it.id } - val rebuilt = rebuiltEventsOf(database, chatRoomId).filterNot { it.id in onFile } - - if (rebuilt.isNotEmpty()) { - logger.d( - "Chronicling $chatRoomId: ${recorded.size} event(s) as the group signed them, " + - "${rebuilt.size} rebuilt from rows that predate the record" - ) - } - - return currentTranslationsOnly(recorded + rebuilt) - } - - /** - * Drops every translation of a passage but the one that stands. - * - * The record keeps every event the group ever signed, deliberately -- a - * signature is the group's statement and discarding one is not this table's - * business. The rows do not: `ChatMessage.applyInnerEvent` supersedes a - * translation chunk, deleting the one it replaces, so a passage translated - * three times leaves one row and three events. - * - * That difference reaches the chronicle the moment it is read from the record - * rather than rebuilt from rows, and it compounds: every draft a group ever - * signed would travel in every chronicle it ever sends, for as long as the room - * exists. A chronicle exists to catch a member up on where the group has got - * to, not to hand them its drafting history. - * - * **The rule is the applying arm's, restated rather than approximated**: - * newest by the timestamp the group signed at, id breaking a tie. It has to - * be, or the chronicle would ship one translation as current and the recipient - * would settle on another -- and since both are validly signed, nothing - * downstream would notice the disagreement. - * - * Dropping the drafts is safe precisely because the recipient applies the - * same rule: it is not what keeps them correct, only what stops them being - * sent work they would immediately discard. - * - * A translation naming no passage is left alone rather than grouped with - * others: it is unappliable either way, and letting one stand in for a whole - * passage would let a malformed event suppress a good one. - */ - private fun currentTranslationsOnly(events: List): List { - val translations = events.filter { it.kind == TranslationChunkEvent.KIND } - if (translations.size < 2) return events - - val current = translations - .groupBy { event -> - val translation = TranslationChunkEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - - val chapterId = translation.translationChapterId() - val chunkId = translation.chunkId() - - if (chapterId == null || chunkId == null) event.id else "$chapterId/$chunkId" - } - .values - .mapNotNull { candidates -> - candidates.maxWithOrNull(compareBy({ it.createdAt }, { it.id })) - } - .mapTo(mutableSetOf()) { it.id } - - if (current.size != translations.size) { - logger.d( - "Leaving ${translations.size - current.size} superseded translation(s) " + - "out of the chronicle" - ) - } - - return events.filter { it.kind != TranslationChunkEvent.KIND || it.id in current } - } - - /** - * The room's rows, rebuilt into the events they came from. - * - * Walked down the tree rather than queried per kind, because only dialects - * and artifacts have a by-room query and the rest hang off a parent. The walk - * is also what makes an artifact's version label reachable: it is not on the - * artifact row -- see `MantraArtifact.toArtifactEvent` -- and the version it - * went into is one step away here. - * - * Still walked on every chronicle, and by now it contributes nothing in most - * rooms: everything signed or applied since `GroupSignedEvent` existed is on - * file as an event, and [signedEventsOf] discards whatever this rebuilds of - * it. The walk is a handful of indexed queries against a room's own rows, - * and it is what makes a half-upgraded room whole, so it runs rather than - * being skipped when the record looks complete -- there is no way to tell a - * complete record from a partial one without doing it. - * - * It returns everything it can rebuild and lets [signedEventsOf] and the - * verify filter decide what can travel. - * - * Deprecated rather than merely legacy: it is a whole mechanism kept alive - * for a shrinking set of rows, and it takes eight `toXEvent()` methods and a - * ten-case round-trip suite with it. **docs/member-chronicle.md, "Retiring the - * rebuild", is the checklist** -- what goes, what only looks like it goes, - * and the one thing that has to be true before any of it can. - */ - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. " + - "Goes when the last pre-v13 install does -- see the removal checklist " + - "in docs/member-chronicle.md." - ) - private suspend fun rebuiltEventsOf( - database: BennuDatabase, - chatRoomId: String, - ): List = buildList { - database.mantraDialectDao().getDialectsByChatRoomId(chatRoomId).forEach { - add(it.toDialectEvent()) - } - - database.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).forEach { artifact -> - val versions = database.mantraArtifactVersionDao() - .getArtifactVersionsByArtifactId(artifact.id) - - // The version an artifact starts life with carries the label the - // artifact was signed with, and `ArtifactVersionEvent.initialVersionOf` - // gives it the artifact's own timestamp. The label is still not on the - // artifact row -- `fromArtifactEvent` drops it -- so this is where it - // comes back from. An artifact with no such version is one this device - // cannot rebuild, which is a gap in the chronicle rather than a reason to - // abandon it. - val versionLabel = versions - .firstOrNull { it.createdAt == artifact.createdAt } - ?.versionLabel - - if (versionLabel == null) { - logger.w("Artifact ${artifact.id} has no initial version; leaving it out") - } else { - add(artifact.toArtifactEvent(versionLabel = versionLabel)) - } - - versions.forEach { version -> - add(version.toArtifactVersionEvent()) - - database.mantraChapterDao() - .getChaptersByArtifactVersionId(version.id) - .forEach { chapter -> - add(chapter.toChapterEvent()) - - database.mantraChunkDao() - .getChunksByChapterId(chapter.id) - .forEach { add(it.toChunkEvent()) } - } - - database.mantraTranslationArtifactVersionDao() - .getTranslationsByArtifactVersionId(version.id) - .forEach { translationVersion -> - add(translationVersion.toTranslationArtifactVersionEvent()) - - database.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId(translationVersion.id) - .forEach { translationChapter -> - add(translationChapter.toTranslationChapterEvent()) - - // Only the translation that survived supersession - // is here to be found: retranslating a passage - // changes the text and so the event id, and the - // arm that applies one drops what it replaces. So - // a chronicle carries a group's current answer to - // each passage rather than its drafts, which is - // the same thing every other member holds. - database.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapter.id) - .forEach { add(it.toTranslationChunkEvent()) } - } - } - } - } - } + kinds: ChronicleKinds, + ): List = database.groupSignedEventDao() + .getByChatRoomId(chatRoomId) + // The allowlist, applied to the source that can actually trip it -- + // see the class comment. A key state on file is the room's own, and + // sending it would be handing every member a validly signed + // statement about what the room signs with, replayable forever. + .filter { kinds.isChroniclable(it.kind) } + .map { it.toEvent() } /** * [events] cut into pages that fit, keeping the order they arrive in. * * Greedy: fill a page until the next event would cross either cap. Both are - * checked because they bind different chronicles -- a room of one-line dialects - * hits the count first and a room of chapters hits the bytes. + * checked because they bind different chronicles -- a room of one-line events + * hits the count first and a room of long ones hits the bytes. * * The bytes are the page's *escaped* bytes -- what it will occupy as the * `content` of the Marmot app event that carries it, which is what a @@ -832,7 +639,7 @@ object ChronicleManager { * * An event too large to share a page with anything is given one of its own. * One too large for even that is dropped with a log rather than failing the - * chronicle: a chapter nobody can chronicle is a hole, and a member who gets + * chronicle: an event nobody can chronicle is a hole, and a member who gets * nothing at all is a bigger one. */ private fun paginate(events: List): List> { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index 0f9b9e63..2da8a5bc 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -1,9 +1,12 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.subgroup.allows +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import fr.acinq.bitcoin.OutPoint import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.database.model.types.FrostSigningSubject import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent import com.machankura.bennu.compose.wallet.GroupSpend import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.Chain @@ -57,6 +60,7 @@ import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent /** * Signs a nostr event with a group's FROST threshold key, in one of its rooms. @@ -565,6 +569,73 @@ object FrostSigningManager { } } + // A birth certificate's guardian keys are a promise by the group signing + // it, so they have to be the keys it grants: recomputed here from the key + // this session signs with and the group's own certificate, never taken + // from the proposer. Its wallet policy has to be one the group may make: + // a guarded group only makes guarded subgroups. Refused before anything is shown, for the reason a + // mismatched id is. + val thresholdPublicKey = key.thresholdPublicKey + unsignedEvents.forEach { rebuilt -> + if (rebuilt.kind != SubgroupBirthCertificateEvent.KIND || thresholdPublicKey == null) return@forEach + SubgroupManager.refuseCertificate(database, rebuilt.pubKey, thresholdPublicKey, rebuilt)?.let { reason -> + logger.w("Signing proposal $sessionId carries a birth certificate that $reason; dropping") + return null + } + } + + // A member wallet's certificate is this group agreeing to guard one + // member's key, so it has to be exactly what that member asked for, asked + // by a member, with exactly the guardian keys this group grants -- the + // list a guarded subgroup of it would get. Recomputed from this device's + // own key state, never taken from the sponsor who proposed it. + // docs/member-guarded-wallets.md, Phase 7. + unsignedEvents.forEach { rebuilt -> + if (rebuilt.kind != MemberWalletCertificateEvent.KIND) return@forEach + val reason = thresholdPublicKey + ?.let { MemberWalletManager.refuseCertificate(database, rebuilt.pubKey, it, rebuilt) } + ?: if (thresholdPublicKey == null) "cannot be checked without the group's key" else null + reason?.let { + logger.w("Signing proposal $sessionId carries a member wallet certificate that $it; dropping") + return null + } + } + + // A subgroup's key state carries its birth certificate, and the + // certificate's wallet policy has to be the one this group was made + // under: every admin was shown it at the join gate, so joining was + // agreeing to it. A certificate proposed later, by a parent admin + // resuming the flow, under another one would be the child signing a + // decision none of its members agreed to. [key] is the child's own + // ceremony here, which is where the policy was filed. + // `docs/subgroup-wallet-policy.md`, Phase 5. + // A wallet statement has to be one the room's parent allows: a subgroup + // decided guarded opens a guarded wallet and nothing else, and one decided + // unguarded a plain one. Read off this device's own certificate for the + // room, never the proposal's, and refused before it is shown -- a member + // should not be asked to approve what their device already knows the + // room has ruled out. docs/subgroup-wallet-policy.md, Phase 7. + unsignedEvents.forEach { rebuilt -> + if (rebuilt.kind != GroupWalletStatementEvent.KIND) return@forEach + val guarded = GroupWalletStatementEvent.read(rebuilt.tags, rebuilt.content)?.guardians?.isNotEmpty() ?: return@forEach + val policy = SubgroupManager.walletPolicyOf(database, rebuilt.pubKey) + if (!policy.allows(guarded)) { + logger.w( + "Signing proposal $sessionId opens ${if (guarded) "a guarded" else "an unguarded"} wallet, " + + "and this group's parent decided otherwise; dropping" + ) + return null + } + } + + unsignedEvents.forEach { rebuilt -> + if (rebuilt.kind != GroupKeyStateEvent.KIND) return@forEach + SubgroupManager.refuseKeyState(key, rebuilt)?.let { reason -> + logger.w("Signing proposal $sessionId carries a key state that $reason; dropping") + return null + } + } + val session = FrostSigningSession( id = sessionId, chatRoomId = localChatRoom.chatRoom.id, @@ -631,7 +702,7 @@ object FrostSigningManager { val wallet = GroupWalletManager.walletFor(database, chatRoomId, thresholdPublicKey, chain, account) ?: throw IllegalStateException("This group has not opened a wallet on ${GroupWalletStatementEvent.chainName(chain)}") - val checked = when (val result = GroupSpend.check(psbt, wallet.account)) { + val checked = when (val result = GroupSpend.check(psbt, wallet.account).withFundings(database, chatRoomId)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") } @@ -675,6 +746,82 @@ object FrostSigningManager { return session } + /** + * Opens a session over one transaction from a *descendant's* guarded wallet, + * signed through this room's guardian leaf -- `docs/group-wallet-guardians.md`. + * + * The same session as [proposeSpend] in every way but three: the wallet is + * the one this room was told about rather than its own, every input is + * signed over BIP342's script-path sighash as the key this group's walk + * reaches, and the proposal names the descendant so every signer reads the + * same wallet from its own copy of the statement. + * + * @throws IllegalArgumentException when the spend fails a check, with the reason + * @throws IllegalStateException when the room has no key, this device holds no + * share of it, or the room holds no guarded wallet of [descendantChatRoomId] on + * [chain] at [account] + */ + suspend fun proposeGuardianSpend( + database: BennuDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + account: Long = 0L, + ): FrostSigningSession { + val chatRoomId = localChatRoom.chatRoom.id + val ceremony = completedKey(database, chatRoomId) + ?: throw IllegalStateException("This group has no shared key to sign with") + val thresholdPublicKey = ceremony.thresholdPublicKey + ?: throw IllegalStateException("Ceremony ${ceremony.id} holds no threshold key") + val signerId = signerIdOf(database, ceremony, userPublicKey) + ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") + val guarded = GuardianManager.guardedWalletFor(database, chatRoomId, descendantChatRoomId, chain, account) + ?: throw IllegalStateException("This group guards no wallet of $descendantChatRoomId on ${GroupWalletStatementEvent.chainName(chain)}") + + val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey)).withFundings(database, chatRoomId)) { + is GroupSpend.Result.Ok -> result.checked + is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") + } + + val session = FrostSigningSession( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = chatRoomId, + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + dkgSessionId = ceremony.id, + threshold = ceremony.threshold, + participantCount = ceremony.participantCount, + signerId = signerId, + derivationPath = null, + subject = FrostSigningSubject.TRANSACTION, + signApprovedAt = Clock.System.now() + ) + writeSpend(database, session, checked, chain, account, guardedChatRoomId = descendantChatRoomId) + announceStarted(database, session) + + logger.i( + "Proposing guardian spend ${session.id} from $descendantChatRoomId: ${checked.inputs.size} input(s), " + + "${checked.amountSent.sat} sats out, ${checked.fee.sat} sats fee, txid ${checked.tx.txid}" + ) + + broadcast( + database = database, + localChatRoom = localChatRoom, + session = session, + kind = FrostSigningEvents.TRANSACTION_PROPOSAL, + content = GroupSpend.encode(psbt), + includeKey = true, + extraTags = FrostSigningEvents.walletTags(GroupWalletStatementEvent.chainName(chain), account) + + FrostSigningEvents.guardedTags(descendantChatRoomId) + ) + + advance(database, localChatRoom, session.id) + + return session + } + /** * Records a proposed spend, after every check [GroupSpend.check] makes. * Returns the session, whether it was just created or already known. @@ -737,14 +884,33 @@ object FrostSigningManager { return null } - // 1. There is a wallet, and it is the room's. - val wallet = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account) - if (wallet == null) { - logger.w("Spend proposal $sessionId spends from a wallet the group has not opened on $chainName; dropping") - return null + // 1. There is a wallet, and it is the room's -- or, for a guardian's + // spend, a descendant's this room was told about and holds a leaf in. + // Either way read from this device's own copy of the statement. + val guardedChatRoomId = FrostSigningEvents.parseGuarded(innerEvent.tags) + val (walletAccount, spender) = if (guardedChatRoomId == null) { + val wallet = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account) + if (wallet == null) { + logger.w("Spend proposal $sessionId spends from a wallet the group has not opened on $chainName; dropping") + return null + } + wallet.account to GroupSpend.Spender.Owner + } else { + // The leaf is the room's, so the key signing it has to be the room's + // own -- not a subgroup ceremony held in this room. + if (GroupWalletManager.thresholdKeyFor(database, localChatRoom.chatRoom.id) != thresholdPublicKey) { + logger.w("Guardian spend proposal $sessionId names a key that is not this room's; dropping") + return null + } + val guarded = GuardianManager.guardedWalletFor(database, localChatRoom.chatRoom.id, guardedChatRoomId, chain, account) + if (guarded == null) { + logger.w("Guardian spend proposal $sessionId spends from a wallet this room guards none of; dropping") + return null + } + guarded.account to guarded.spender(thresholdPublicKey) } - val checked = when (val result = GroupSpend.check(psbt, wallet.account)) { + val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender).withFundings(database, localChatRoom.chatRoom.id)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> { logger.w("Spend proposal $sessionId ${result.reason}; dropping") @@ -764,7 +930,7 @@ object FrostSigningManager { derivationPath = null, subject = FrostSigningSubject.TRANSACTION, ) - writeSpend(database, session, checked, chain, account) + writeSpend(database, session, checked, chain, account, guardedChatRoomId) announceStarted(database, session) logger.i( @@ -788,6 +954,7 @@ object FrostSigningManager { checked: GroupSpend.Checked, chain: Chain, account: Long, + guardedChatRoomId: String? = null, ) { database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems( @@ -809,6 +976,7 @@ object FrostSigningManager { chatRoomId = session.chatRoomId, chain = GroupWalletStatementEvent.chainName(chain), account = account, + guardedChatRoomId = guardedChatRoomId, psbt = GroupSpend.encode(checked.psbt), txid = checked.tx.txid.toString(), ) @@ -826,6 +994,26 @@ object FrostSigningManager { * rebuilt on every pass from the ceremony's key and the transaction row -- * the same rule as a room's path: stored inputs, rederived, never cached. */ + /** + * One cache per input: the address's key path for the room's own spend, read + * off the items as always; the guardian's leaf for a spend through it, read + * off the spend checked again -- the leaf, the walk and the sighash are one + * computation, and a cache taken apart from it could sign for another leaf. + */ + private suspend fun spendCaches( + database: BennuDatabase, + session: FrostSigningSession, + thresholdPublicKey: HexKey, + items: List, + ): List? { + val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null + if (transaction.guardedChatRoomId == null) { + return spendDerivations(database, session, thresholdPublicKey, items)?.map { it.cache } + } + val checked = checkedSpend(database, session.id) ?: return null + return checked.inputs.map { it.cache }.takeIf { it.size == items.size } + } + private suspend fun spendDerivations( database: BennuDatabase, session: FrostSigningSession, @@ -840,6 +1028,30 @@ object FrostSigningManager { } } + /** What a spend session signs under: its transaction row, the account its coins are in, and who signs them. */ + private data class SpendContext( + val transaction: GroupTransaction, + val account: GroupWalletDerivation.Account, + val spender: GroupSpend.Spender, + ) + + /** + * [spendAccount], and for a guardian's spend the descendant's guarded wallet + * as this room holds it, with this group as the spender. + */ + private suspend fun spendContext( + database: BennuDatabase, + session: FrostSigningSession, + thresholdPublicKey: HexKey, + ): SpendContext? { + val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null + val guardedChatRoomId = transaction.guardedChatRoomId + ?: return spendAccount(database, session, thresholdPublicKey)?.let { (row, account) -> SpendContext(row, account, GroupSpend.Spender.Owner) } + val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null + val guarded = GuardianManager.guardedWalletFor(database, transaction.chatRoomId, guardedChatRoomId, chain, transaction.account) ?: return null + return SpendContext(transaction, guarded.account, guarded.spender(thresholdPublicKey)) + } + private suspend fun spendAccount( database: BennuDatabase, session: FrostSigningSession, @@ -847,7 +1059,11 @@ object FrostSigningManager { ): Pair? { val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null - return transaction to GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account) + // The account as the room's statement opened it: a guarded one's + // addresses carry its guardians' leaves, and the bare derivation would be + // a plain account at the same key, whose addresses none of these coins are at. + val opened = GroupWalletManager.walletFor(database, transaction.chatRoomId, thresholdPublicKey, chain, transaction.account) + return transaction to (opened?.account ?: GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account)) } /** @@ -1084,9 +1300,28 @@ object FrostSigningManager { if (session.subject != FrostSigningSubject.TRANSACTION) return null val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey ?: return null - val (transaction, account) = spendAccount(database, session, thresholdPublicKey) ?: return null - val psbt = GroupSpend.decode(transaction.psbt) ?: return null - return (GroupSpend.check(psbt, account) as? GroupSpend.Result.Ok)?.checked + val context = spendContext(database, session, thresholdPublicKey) ?: return null + val psbt = GroupSpend.decode(context.transaction.psbt) ?: return null + return (GroupSpend.check(psbt, context.account, context.spender).withFundings(database, context.transaction.chatRoomId) as? GroupSpend.Result.Ok)?.checked + } + + /** + * A checked spend with its payments into descendants' guarded wallets read + * against the ones [chatRoomId] holds -- `GroupSpend.fundingsOf` -- or + * refused for a claim that does not derive. Every place a spend is checked + * for a member to read or sign reads its fundings here, so the label a + * signer sees is the one every other signer's device derived too. + * + * A spend none of whose payments claims anything -- every spend to a typed + * address -- reads no guarded wallets at all. + */ + private suspend fun GroupSpend.Result.withFundings(database: BennuDatabase, chatRoomId: String): GroupSpend.Result { + val checked = (this as? GroupSpend.Result.Ok)?.checked ?: return this + if (checked.payments.all { checked.psbt.outputs[it.index].taprootDerivationPaths.isEmpty() }) return this + return when (val reading = GroupSpend.fundingsOf(checked, GuardianManager.guardedWalletsOf(database, chatRoomId))) { + is GroupSpend.FundingReading.Ok -> GroupSpend.Result.Ok(checked.copy(fundings = reading.fundings)) + is GroupSpend.FundingReading.Refused -> GroupSpend.Result.Refused(reading.reason) + } } /** @@ -1115,6 +1350,21 @@ object FrostSigningManager { .flatMap { GroupSpend.claimedChangeIndices(it, account) } .toSet() + /** + * The receive addresses of [account] -- a descendant's guarded wallet -- that + * a room's open spends fund, which a new funding should not pay as well. + * Held by the same sessions as [reservedOutPoints], for the reason + * [reservedChangeIndices] gives. + */ + suspend fun reservedFundingIndices( + database: BennuDatabase, + chatRoomId: String, + account: GroupWalletDerivation.Account, + ): Set = + openSpends(database, chatRoomId) + .flatMap { GroupSpend.claimedFundingIndices(it, account) } + .toSet() + /** The PSBT of every spend in the room whose session has not failed. */ private suspend fun openSpends(database: BennuDatabase, chatRoomId: String): List = database.groupTransactionDao().getByChatRoomId(chatRoomId) @@ -1142,28 +1392,7 @@ object FrostSigningManager { database.groupTransactionDao().upsert(confirmed.copy(confirmedAt = at, seenAt = confirmed.seenAt ?: at)) - val coins = coinsOf(confirmed) - database.groupTransactionDao().getByChatRoomId(confirmed.chatRoomId) - .filter { it.frostSigningSessionId != sessionId && (coinsOf(it) intersect coins).isNotEmpty() } - .forEach { other -> - val otherSession = database.frostSigningSessionDao().getSessionById(other.frostSigningSessionId) - ?: return@forEach - when (otherSession.stage) { - FrostSigningStage.COMPLETE -> if (other.confirmedAt == null && other.replacedByTxid == null) { - database.groupTransactionDao().upsert(other.copy(replacedByTxid = confirmed.txid)) - } - - FrostSigningStage.FAILED -> Unit - - else -> fail( - database = database, - session = otherSession, - reason = "Spent by another transaction", - content = "abandoned a spend: another of the group's transactions spent its coins first. " + - "Nothing was signed." - ) - } - } + settleSpendsOf(database, confirmed.chatRoomId, coinsOf(confirmed), byTxid = confirmed.txid, except = sessionId) val sent = checkedSpend(database, sessionId)?.amountSent announce( @@ -1176,6 +1405,67 @@ object FrostSigningManager { ) } + /** + * A spend whose coins a transaction the room never proposed has taken, as + * [conflictTxid] confirmed: marked replaced, and every other spend of the same + * coins settled with it. + * + * A guarded wallet's coins have two kinds of spender. The child's own spend + * can lose a coin to a guardian's, and a guardian's to the child's, and the + * winner is never a row in the loser's room -- so [recordConfirmed] cannot be + * what settles the loser. The watcher is: it asks the chain whether a signed + * spend's coins are still there, and calls this when one was taken by a + * confirmed transaction. Once per spend, by the read of `replacedByTxid`. + */ + suspend fun recordReplaced(database: BennuDatabase, sessionId: String, conflictTxid: String) { + val lost = database.groupTransactionDao().getBySessionId(sessionId) ?: return + if (lost.confirmedAt != null || lost.replacedByTxid != null) return + + database.groupTransactionDao().upsert(lost.copy(replacedByTxid = conflictTxid)) + settleSpendsOf(database, lost.chatRoomId, coinsOf(lost), byTxid = conflictTxid, except = sessionId) + logger.i("Spend $sessionId lost its coins to $conflictTxid") + } + + /** + * Every spend in [chatRoomId] other than [except] that wants any of [coins], + * settled by [byTxid] having taken them: only one spend of a coin can ever + * confirm, so the rest are over whatever stage they are in. One still + * collecting is abandoned -- its signatures, if it ever got them, would be + * over a transaction nobody can mine. One already signed is a transaction + * [byTxid] replaced, a fee bump or a race, and is marked so rather than + * failed: it was signed, and saying otherwise would misreport what the group + * did. + */ + private suspend fun settleSpendsOf( + database: BennuDatabase, + chatRoomId: String, + coins: Set, + byTxid: String, + except: String, + ) { + database.groupTransactionDao().getByChatRoomId(chatRoomId) + .filter { it.frostSigningSessionId != except && (coinsOf(it) intersect coins).isNotEmpty() } + .forEach { other -> + val otherSession = database.frostSigningSessionDao().getSessionById(other.frostSigningSessionId) + ?: return@forEach + when (otherSession.stage) { + FrostSigningStage.COMPLETE -> if (other.confirmedAt == null && other.replacedByTxid == null) { + database.groupTransactionDao().upsert(other.copy(replacedByTxid = byTxid)) + } + + FrostSigningStage.FAILED -> Unit + + else -> fail( + database = database, + session = otherSession, + reason = "Spent by another transaction", + content = "abandoned a spend: another transaction spent its coins first. " + + "Nothing was signed." + ) + } + } + } + private fun coinsOf(transaction: GroupTransaction): Set = GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }?.toSet().orEmpty() @@ -1189,7 +1479,7 @@ object FrostSigningManager { * transaction nobody can mine, and `correctlySpends` is the only check that * asks the question the network will. Nothing is applied and nothing is * filed as a `GroupSignedEvent` -- this is not an event, and the chronicle - * and the broadcast screen read that table. + * reads that table. */ private suspend fun completeSpend( database: BennuDatabase, @@ -1199,11 +1489,11 @@ object FrostSigningManager { val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) val thresholdPublicKey = key?.thresholdPublicKey ?: throw IllegalStateException("The ceremony this spend signs under is gone") - val (transaction, account) = spendAccount(database, session, thresholdPublicKey) + val (transaction, account, spender) = spendContext(database, session, thresholdPublicKey) ?: throw IllegalStateException("This spend has no transaction on file") val psbt = GroupSpend.decode(transaction.psbt) ?: throw IllegalStateException("This spend's PSBT can no longer be read") - val checked = when (val result = GroupSpend.check(psbt, account)) { + val checked = when (val result = GroupSpend.check(psbt, account, spender)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> throw IllegalStateException("This spend ${result.reason}") } @@ -1211,13 +1501,13 @@ object FrostSigningManager { val signatures = items.mapIndexed { index, item -> val input = checked.inputs[index] val signature = ByteVector64(item.signature!!) - if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.derivation.outputKey)) { + if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.signingKey)) { throw IllegalStateException("The aggregated signature for input $index does not verify against its coin") } signature } - val signed = GroupSpend.witnessed(checked.tx, signatures) + val signed = checked.witnessed(signatures) signed.correctlySpends( checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS @@ -1240,8 +1530,11 @@ object FrostSigningManager { database = database, session = session, messageType = ChatMessage.TYPE_FROST_COMPLETE, - content = "The group signed a transaction sending ${checked.amountSent.sat} sats, " + - "with ${checked.fee.sat} sats in fees. It took ${session.threshold} of " + + content = when (val guardian = checked.spender as? GroupSpend.Spender.Guardian) { + null -> "The group signed a transaction sending ${checked.amountSent.sat} sats, " + else -> "The group signed a transaction sending ${checked.amountSent.sat} sats from " + + "${com.machankura.bennu.compose.text.ProposedSpend.guardedWallet(guardian.name, guardian.label)}, " + } + "with ${checked.fee.sat} sats in fees. It took ${session.threshold} of " + "${session.participantCount} members.", actor = session.coordinatorPublicKey ) @@ -1595,8 +1888,7 @@ object FrostSigningManager { .cache .let { cache -> List(items.size) { cache } } - FrostSigningSubject.TRANSACTION -> spendDerivations(database, session, thresholdPublicKey, items) - ?.map { it.cache } + FrostSigningSubject.TRANSACTION -> spendCaches(database, session, thresholdPublicKey, items) ?: throw IllegalStateException("The coins this transaction spends no longer derive under the group's wallet") FrostSigningSubject.SWEEP -> sweepOf(database, session, thresholdPublicKey) @@ -1831,8 +2123,7 @@ object FrostSigningManager { // wire from here: a signed event authored by the threshold key cannot // travel as an inner event anyway, because the outbound pipeline // re-authors rumors as their sender and would strip the group's - // signature off. Sending one to relays is a member's separate act, - // from `BroadcastGroupSignedEventScreen`, off the recorded row. + // signature off. signedEvents.forEach { applySignedEvent(database, session, it, recorded) } announce( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateManager.kt index 181b8fe8..de4bc698 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateManager.kt @@ -423,6 +423,19 @@ object GroupKeyStateManager { return null } + // A wallet policy present and unreadable must never look absent: an + // undecided child is offered both wallets, so a corrupt `guarded` would + // hand it the plain one its parent took away -- the lesson of + // [GroupKeyStateEvent.claimsParentage], one tag further on. + // `docs/subgroup-wallet-policy.md`. + if (SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) == null) { + logger.w( + "Key state for $announced carries a certificate whose wallet policy does not " + + "read, or contradicts its guardian keys; dropping" + ) + return null + } + return Parentage( SubgroupParentage(parentChatRoomId = parentChatRoomId, certificate = certificate) ) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt index 2b3d59c2..a12fe844 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt @@ -18,7 +18,7 @@ import kotlin.time.Instant * What the group has authorised its Lightning wallet to spend, as a co-signer reads it and the operator's * node acts on it (`docs/group-lightning-wallet.md`, Phases 12 and 13). * - * An authorisation is a group-signed event (kind 30346, [GroupLightningAuthorisationEvent]). The group + * An authorisation is a group-signed event (kind 30363, [GroupLightningAuthorisationEvent]). The group * may sign two for one invoice -- once more after the first expired, say. They are one payment: the * budget is the larger, and it is open while either is. A close or force close names one channel, and * lasts [CHANNEL_ACTION_LIFETIME]. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt index 4f302dd4..f8b2b9ee 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt @@ -66,7 +66,7 @@ import kotlinx.coroutines.launch * transport ([GroupIcebergTransport]) reaches the members through the room. It runs only while this * device is the elected operator and has heard from the room recently ([GroupLightningOperatorManager.mayRunNode]), * and it stops itself the moment a newer term names somebody else -- telling the room where its - * channels were as it goes (kind 30349). + * channels were as it goes (kind 30366). * * The node itself is behind [PeerHandle], so the life cycle can be tested without an LSP to connect to. */ diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt index 5ac8991b..3387bde8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt @@ -87,7 +87,7 @@ object GroupLightningOperatorManager { return current(database, chatRoomId, chain, wallet)?.publicKey == userPublicKey } - /** Tells the room this device's node stopped, and where its channels were (kind 30349). */ + /** Tells the room this device's node stopped, and where its channels were (kind 30366). */ suspend fun announceStopped(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long, term: Long, commitmentNumbers: Map) { GroupLightningWalletManager.queue( database, localChatRoom, userPublicKey, GroupLightningEvents.STOPPED, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt index d1d6337b..a74821ff 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt @@ -144,7 +144,7 @@ object GroupLightningWalletManager { /** * Proposes the wallet: makes its node seed, sends it to every other participant encrypted to them - * (kind 30340), and opens a signing session over the statement. The wallet exists once a quorum signs. + * (kind 30357), and opens a signing session over the statement. The wallet exists once a quorum signs. */ suspend fun proposeWallet( database: BennuDatabase, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt index fa49f211..cea9dd47 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt @@ -13,6 +13,7 @@ import fr.acinq.bitcoin.KeyPath import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.PublicKey import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree import fr.acinq.bitcoin.XonlyPublicKey import fr.acinq.bitcoin.crypto.Pack import fr.acinq.bitcoin.crypto.frost.TweakCache @@ -54,6 +55,15 @@ import fr.acinq.bitcoin.utils.Either * key for any address recovers the group's threshold key -- the room, every * address of every account, and every event the group can sign. Nothing here or * anywhere else reconstructs one. The only export is the account xpub. + * + * ### A guarded account + * + * An account opened with guardians -- the keys a subgroup's birth certificate + * grants it, see `GuardianDerivation` -- is the same account with one change at + * the very end: each address commits to a tree of one leaf per guardian, so the + * last tweak is BIP341's script-path tweak over that tree rather than BIP86's + * empty one. The internal key, and so the group's own key-path spend, is + * untouched. `docs/group-wallet-guardians.md` says why. */ object GroupWalletDerivation { /** BIP44's external chain: addresses handed out to be paid. */ @@ -71,7 +81,7 @@ object GroupWalletDerivation { private const val ACCOUNT_TAG = "bennu/group-wallet/account/v1" /** The largest unhardened BIP32 index. Hardened ones cannot be walked here. */ - private const val MAX_INDEX: Long = 0x7FFFFFFFL + internal const val MAX_INDEX: Long = 0x7FFFFFFFL /** * One account of one group on one network: the extended public key every @@ -86,7 +96,16 @@ object GroupWalletDerivation { val extendedPublicKey: DeterministicWallet.ExtendedPublicKey, /** The threshold key tweaked to [extendedPublicKey]'s key: what the account's sessions start from. */ internal val cache: TweakCache, + /** + * The ancestors that can spend from every address of this account, nearest + * first -- empty for an account nobody guards, which is every account a + * group that is nobody's subgroup opens. + */ + val guardians: List = emptyList(), ) { + /** Whether its addresses carry guardian leaves. */ + val isGuarded: Boolean get() = guardians.isNotEmpty() + /** The account key's own fingerprint, as a descriptor's key origin and a PSBT's derivation name it. */ val fingerprint: Long get() = extendedPublicKey.fingerprint() @@ -109,14 +128,20 @@ object GroupWalletDerivation { val changeDescriptor: String get() = descriptor(CHANGE) private fun descriptor(change: Long): String { - val body = "tr([$fingerprintHex]$xpub/$change/*)" + val tree = if (isGuarded) "," + GuardianDerivation.descriptorTree(guardians, chain, account, change) else "" + val body = "tr([$fingerprintHex]$xpub/$change/*$tree)" return "$body#${Descriptor.checksum(body)}" } - override fun equals(other: Any?): Boolean = - other is Account && chain == other.chain && account == other.account && extendedPublicKey == other.extendedPublicKey + /** The same account with [guardians] in every address. */ + fun guardedBy(guardians: List): Account = + Account(chain, account, extendedPublicKey, cache, guardians) - override fun hashCode(): Int = extendedPublicKey.hashCode() + override fun equals(other: Any?): Boolean = + other is Account && chain == other.chain && account == other.account && + extendedPublicKey == other.extendedPublicKey && guardians == other.guardians + + override fun hashCode(): Int = extendedPublicKey.hashCode() * 31 + guardians.hashCode() } /** @@ -134,12 +159,22 @@ object GroupWalletDerivation { /** BIP86's output key `Q`: the key in the output script, and the key a spend's signature verifies against. */ val outputKey: XonlyPublicKey, val cache: TweakCache, + /** The guardian leaves this address commits to, or null for BIP86's empty tree. */ + val tree: ScriptTree? = null, ) { + /** The tweak from [internalKey] to [outputKey]: over [tree] when there is one, BIP86's otherwise. */ + val taprootTweak: Crypto.TaprootTweak + get() = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak + /** `OP_1 `. */ val pubkeyScript: ByteVector - get() = ByteVector(Script.write(Script.pay2tr(internalKey, Crypto.TaprootTweak.KeyPathTweak))) + get() = ByteVector(Script.write(Script.pay2tr(internalKey, taprootTweak))) - fun address(chain: Chain): String = Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + fun address(chain: Chain): String = when (tree) { + null -> Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + else -> Bitcoin.addressFromPublicKeyScript(chain.chainHash, pubkeyScript.toByteArray()).right + ?: throw IllegalStateException("a taproot output always has an address") + } /** The path below the account, as a PSBT's `tap_bip32_derivation` carries it. */ val keyPath: KeyPath get() = KeyPath(listOf(change, index)) @@ -153,22 +188,21 @@ object GroupWalletDerivation { * or the HMAC lands on an invalid scalar -- around 2^-127, and BIP32 throws at * the same place. */ - fun account(thresholdPublicKey: HexKey, chain: Chain, account: Long = 0L): Account { + fun account( + thresholdPublicKey: HexKey, + chain: Chain, + account: Long = 0L, + guardians: List = emptyList(), + ): Account { require(account in 0L..MAX_INDEX) { "account $account is not an unhardened index" } val root = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) require(root.isValid()) { "the threshold key is not a valid point" } - val i = Crypto.hmac512( - ACCOUNT_TAG.encodeToByteArray(), - root.value.toByteArray() + chain.chainHash.value.toByteArray() + Pack.writeInt32BE(account.toInt()) - ) - val tweak = i.copyOfRange(0, 32) - val chainCode = i.copyOfRange(32, 64) - require(Crypto.isPrivKeyValid(tweak)) { "the account step for account $account landed on an invalid scalar" } + val (tweak, chainCode) = accountStep(root, chain, account) val accountKey = root + PrivateKey(tweak).publicKey() - val cache = plainTweak(TweakCache.create(root), ByteVector32(tweak), "the account step") + val cache = plainTweak(TweakCache.create(root), tweak, "the account step") // The cache tracks the full point; the point arithmetic above is the // reference it has to agree with, or every session for this account signs // for a key nobody's coins are at. @@ -179,15 +213,34 @@ object GroupWalletDerivation { account = account, extendedPublicKey = DeterministicWallet.ExtendedPublicKey( publickeybytes = accountKey.value, - chaincode = ByteVector32(chainCode), + chaincode = chainCode, depth = 0, path = KeyPath.empty, parent = 0L, ), cache = cache, + guardians = guardians, ) } + /** + * The account step's tweak and chain code for [root]: `I[0:32]` and + * `I[32:64]` of the tagged HMAC over the key, the network and the account. + * + * Split out for the one holder of a key path who has its private key -- a + * member wallet, `MemberWalletDerivation` -- which adds the same tweak to + * the scalar that [account] adds to the point. + */ + internal fun accountStep(root: PublicKey, chain: Chain, account: Long): Pair { + val i = Crypto.hmac512( + ACCOUNT_TAG.encodeToByteArray(), + root.value.toByteArray() + chain.chainHash.value.toByteArray() + Pack.writeInt32BE(account.toInt()) + ) + val tweak = i.copyOfRange(0, 32) + require(Crypto.isPrivKeyValid(tweak)) { "the account step for account $account landed on an invalid scalar" } + return ByteVector32(tweak) to ByteVector32(i.copyOfRange(32, 64)) + } + /** * The address at `//` under [account]. * @@ -197,19 +250,27 @@ object GroupWalletDerivation { * a parity mistake in the cache and a wallet whose signatures do not verify. */ fun derive(account: Account, change: Long, index: Long): Derived = - deriveBelow(account.extendedPublicKey, account.cache, change, index) + deriveBelow( + account.extendedPublicKey, + account.cache, + change, + index, + tree = GuardianDerivation.treeAt(account.guardians, account.chain, account.account, change, index), + ) /** - * The tail on its own: BIP32 public derivation and the BIP341 key-path tweak, - * from any account-level key and the cache that signs as it. Split out so the - * tail can be tested against BIP86's published vectors, which start from a - * seed's account key rather than from a threshold key. + * The tail on its own: BIP32 public derivation and the BIP341 tweak -- over + * [tree] when there is one, BIP86's key-path tweak otherwise -- from any + * account-level key and the cache that signs as it. Split out so the tail can + * be tested against BIP86's published vectors, which start from a seed's + * account key rather than from a threshold key. */ internal fun deriveBelow( accountKey: DeterministicWallet.ExtendedPublicKey, accountCache: TweakCache, change: Long, index: Long, + tree: ScriptTree? = null, ): Derived { require(change == RECEIVE || change == CHANGE) { "change must be $RECEIVE or $CHANGE, not $change" } require(index in 0L..MAX_INDEX) { "index $index is not an unhardened index" } @@ -224,19 +285,20 @@ object GroupWalletDerivation { val internalKey = childKey.publicKey.xOnly() require(cache.tweakedPublicKey == internalKey) { "the cache does not reach the internal key at $change/$index" } - cache = when (val tweaked = cache.tweak(internalKey.tweak(Crypto.TaprootTweak.KeyPathTweak), isXonly = true)) { - is Either.Left -> throw IllegalArgumentException("Could not apply the key-path tweak at $change/$index", tweaked.value) + val taprootTweak = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak + cache = when (val tweaked = cache.tweak(internalKey.tweak(taprootTweak), isXonly = true)) { + is Either.Left -> throw IllegalArgumentException("Could not apply the taproot tweak at $change/$index", tweaked.value) is Either.Right -> tweaked.value.first } - val outputKey = internalKey.outputKey(Crypto.TaprootTweak.KeyPathTweak).first + val outputKey = internalKey.outputKey(taprootTweak).first require(cache.tweakedPublicKey == outputKey) { "the cache does not reach the output key at $change/$index" } - return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache) + return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache, tree = tree) } /** BIP32's `I_L` for one unhardened step: the scalar CKDpub adds, which a FROST cache takes as a plain tweak. */ - private fun childTweak(parent: DeterministicWallet.ExtendedPublicKey, index: Long): ByteVector32 = + internal fun childTweak(parent: DeterministicWallet.ExtendedPublicKey, index: Long): ByteVector32 = ByteVector32( Crypto.hmac512( parent.chaincode.toByteArray(), @@ -244,7 +306,7 @@ object GroupWalletDerivation { ).copyOfRange(0, 32) ) - private fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = + internal fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = when (val tweaked = cache.tweak(tweak, isXonly = false)) { is Either.Left -> throw IllegalArgumentException("Could not apply $step to the group's key", tweaked.value) is Either.Right -> tweaked.value.first diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt index 37c35462..c9a51fc5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt @@ -1,8 +1,11 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain @@ -35,6 +38,40 @@ object GroupWalletManager { ): GroupWalletDerivation.Account? = thresholdKeyFor(database, chatRoomId)?.let { GroupWalletDerivation.account(it, chain, account) } + /** A guarded account a room could open, and the certificate that granted its guardians, which the statement carries. */ + data class GuardedOpening( + val account: GroupWalletDerivation.Account, + val certificate: Event, + ) + + /** + * The guarded account [chatRoomId] would open on [chain], or null for a room + * whose certificate grants it no guardian keys -- a room nobody's subgroup, + * or one certified before certificates carried them. + * + * Off the verified key state, the one place a certificate this device + * believes is kept. A member who holds no key state cannot open one; that + * member cannot sign, either. + */ + suspend fun guardedAccountFor( + database: BennuDatabase, + chatRoomId: String, + chain: Chain, + account: Long = 0L, + ): GuardedOpening? { + val thresholdPublicKey = thresholdKeyFor(database, chatRoomId) ?: return null + val certificate = GroupKeyStateManager.keyStateFor(database, chatRoomId) + ?.takeIf { it.verifies() } + ?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?: return null + val guardians = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + ?.takeIf { it.isNotEmpty() } + ?: return null + + return GuardedOpening(GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians), certificate) + } + /** * The wallet [chatRoomId] has opened on [chain] under [thresholdPublicKey], or * null when the room signed no statement that key rederives. @@ -54,6 +91,7 @@ object GroupWalletManager { thresholdPublicKey = thresholdPublicKey, chain = chain, account = account, + policy = walletPolicyFor(database, chatRoomId), ) /** The wallet [chatRoomId] has opened on [chain], or null when the group has not opened one. */ @@ -71,6 +109,17 @@ object GroupWalletManager { thresholdPublicKey = thresholdPublicKey, chain = chain, account = account, + policy = walletPolicyFor(database, chatRoomId), ) } + + /** + * What [chatRoomId]'s parent decided about its wallet at its birth, or null + * for a room with no certificate -- `docs/subgroup-wallet-policy.md`. The + * same reading the picker and every parent signer make, through + * `SubgroupManager.walletPolicyOf`, so the wallet a device opens, offers and + * signs for cannot disagree with what the group was made as. + */ + suspend fun walletPolicyFor(database: BennuDatabase, chatRoomId: String): WalletPolicyReading? = + SubgroupManager.walletPolicyOf(database, chatRoomId) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt new file mode 100644 index 00000000..ab5f7ab7 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt @@ -0,0 +1,314 @@ +package com.machankura.bennu.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.DeterministicWallet +import fr.acinq.bitcoin.KeyPath +import fr.acinq.bitcoin.OP_CHECKSEQUENCEVERIFY +import fr.acinq.bitcoin.OP_CHECKSIGVERIFY +import fr.acinq.bitcoin.OP_PUSHDATA +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptElt +import fr.acinq.bitcoin.ScriptEltMapping +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.Pack +import fr.acinq.bitcoin.crypto.frost.TweakCache + +/** + * The keys an ancestor group holds in a subgroup's wallet, and the leaves they + * sit in. + * + * Every group has one guardian root, a tagged HMAC away from its threshold key, + * which it never hands out. What a parent writes into a child's birth + * certificate is that root one public BIP32 step further, at an index taken + * from the child's room id -- and, behind it, every key the parent's own + * ancestors gave the parent, each one step further at the same index: + * + * ``` + * I = HMAC-SHA512("bennu/group-wallet/guardian/v1", serP(K_A)) + * R_A = K_A + I[0:32]·G, chain code I[32:64] A's guardian root + * i(C) = taggedHash("bennu/group-wallet/guardian/child/v1", C)[0:4] & 0x7fffffff + * grant(C) = [R_A/i(C)] ++ [g/i(C) for g in grant(A)] nearest first + * L = xonly(g / network / account / change / index) a leaf key in one address + * ``` + * + * See `docs/group-wallet-guardians.md` for why each step is what it is. In + * short: a fresh key per child is what lets the parent *agree* to guard it, a + * root nobody publishes is what keeps a guardian spend unlinkable to a Marmot + * room, and re-deriving every inherited key per child is what keeps a parent's + * wallet and its child's from sharing a leaf. + * + * ### The same rule as the wallet's + * + * Every step is a public tweak of the threshold key, so a leaked leaf private + * key recovers the group's threshold key. Nothing reconstructs one: a leaf is + * signed for by a FROST session over [signingCache]. + */ +object GuardianDerivation { + /** + * The fewest blocks a coin can sit confirmed before an ancestor can take it: + * about an hour, so the child's own spends always go first -- a guardian + * cannot race the child for a payment that has only just arrived. + * `docs/guardian-delay.md`. + */ + const val MIN_DELAY: Long = 6L + + /** + * The most: BIP68's block-based relative lock is the low 16 bits of + * `nSequence`, so 65,535 blocks, about 15 months. Staying within it also + * keeps bit 22 clear, so the lock always counts blocks, and keeps every + * guardian input far below `GroupSpend.MAX_SEQUENCE`, so a guardian spend + * can still be bumped. + */ + const val MAX_DELAY: Long = 0xFFFFL + + /** Every delay a leaf may carry. A guardian tag outside it does not read. */ + val DELAY_RANGE: LongRange = MIN_DELAY..MAX_DELAY + + /** + * The delay a parent is offered first for its own leaf, and the one every + * certificate carried before parents chose: two hours. Each guardian's own + * delay is written into its tag, and each ancestor's travels down the tree + * unchanged -- [Guardian.grantedTo] copies it -- so this is a default, not + * the delay. `docs/guardian-delay.md`. + */ + const val DEFAULT_DELAY: Long = 12L + + /** + * The key of the guardian root's HMAC. An input to every guardian key, so it + * is frozen the moment a certificate carries one: a rename moves every leaf. + */ + private const val ROOT_TAG = "bennu/group-wallet/guardian/v1" + + /** The tag of the hash a child's index is taken from. Frozen for the same reason. */ + private const val CHILD_TAG = "bennu/group-wallet/guardian/child/v1" + + /** + * One ancestor's guardian key as granted to one group: whose it is, and the + * extended public key that group's addresses derive that ancestor's leaves + * from. + * + * Held as the key and the chain code rather than as an + * [DeterministicWallet.ExtendedPublicKey], whose depth, parent fingerprint and + * path would make two grants of the same key compare unequal depending on how + * each was reached. Only the 65 bytes take part in a derivation. + */ + data class Guardian( + /** The ancestor's room id, which its leaf is named by. */ + val chatRoomId: String, + val publicKey: PublicKey, + val chainCode: ByteVector32, + val delay: Long = DEFAULT_DELAY, + ) { + /** As a depth-0 extended key, the form every derivation below starts from. */ + val extendedPublicKey: DeterministicWallet.ExtendedPublicKey + get() = DeterministicWallet.ExtendedPublicKey( + publickeybytes = publicKey.value, + chaincode = chainCode, + depth = 0, + path = KeyPath.empty, + parent = 0L, + ) + + /** `xpub` on mainnet and `tpub` on every test network, as the wallet's own xpub is. */ + fun encoded(chain: Chain): String = + extendedPublicKey.encode(if (chain.isMainnet()) DeterministicWallet.xpub else DeterministicWallet.tpub) + + /** The same ancestor, one public step further, for [childChatRoomId] -- and at the same delay. */ + fun grantedTo(childChatRoomId: String): Guardian { + val child = extendedPublicKey.derivePublicKey(childIndex(childChatRoomId)) + return copy(publicKey = child.publicKey, chainCode = child.chaincode) + } + } + + /** A group's guardian root, and the cache that signs as it. */ + class Root internal constructor( + val publicKey: PublicKey, + val chainCode: ByteVector32, + internal val cache: TweakCache, + ) { + val extendedPublicKey: DeterministicWallet.ExtendedPublicKey + get() = DeterministicWallet.ExtendedPublicKey(publicKey.value, chainCode, 0, KeyPath.empty, 0L) + } + + /** One guardian's leaf in one address, and -- on the guardian's side -- the cache that signs as it. */ + data class Signing( + val leafKey: XonlyPublicKey, + val cache: TweakCache, + ) + + /** + * The guardian root of the group holding [thresholdPublicKey]. + * + * @throws IllegalArgumentException if the key is not a point, or the HMAC + * lands on an invalid scalar -- around 2^-127, and BIP32 throws at the same place. + */ + fun root(thresholdPublicKey: HexKey): Root { + val threshold = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) + require(threshold.isValid()) { "the threshold key is not a valid point" } + + val i = Crypto.hmac512(ROOT_TAG.encodeToByteArray(), threshold.value.toByteArray()) + val tweak = i.copyOfRange(0, 32) + require(Crypto.isPrivKeyValid(tweak)) { "the guardian root landed on an invalid scalar" } + + val rootKey = threshold + PrivateKey(tweak).publicKey() + val cache = GroupWalletDerivation.plainTweak(TweakCache.create(threshold), ByteVector32(tweak), "the guardian root") + require(cache.tweakedPublicKey == rootKey.xOnly()) { "the guardian root's cache does not reach its key" } + + return Root(publicKey = rootKey, chainCode = ByteVector32(i.copyOfRange(32, 64)), cache = cache) + } + + /** + * The unhardened index a child's keys are derived at: the first four bytes + * of a tagged hash of its room id, top bit cleared. + */ + fun childIndex(childChatRoomId: String): Long { + val roomId = childChatRoomId.lowercase().hexToByteArray() + require(roomId.size == 32) { "a room id is 32 bytes, not ${roomId.size}" } + return Pack.int32BE(Crypto.taggedHash(roomId, CHILD_TAG).toByteArray(), 0).toLong() and GroupWalletDerivation.MAX_INDEX + } + + /** + * The network's index under a guardian key. Not BIP44's coin type: the + * networks this app knows, numbered once, so a guardian key granted for no + * network in particular gives each one unrelated leaves. + */ + fun networkIndex(chain: Chain): Long = when (chain) { + Chain.Mainnet -> 0L + Chain.Testnet3 -> 1L + Chain.Testnet4 -> 2L + Chain.Signet -> 3L + Chain.Regtest -> 4L + } + + /** + * What the group holding [thresholdPublicKey], whose room is [ownChatRoomId], + * writes into [childChatRoomId]'s certificate: its own root one step further, + * then each of [inherited] -- the keys its own certificate carries, nearest + * first -- one step further, in the same order. + * + * The same function a signer's device runs to check a proposed certificate: + * a certificate whose guardians are not exactly this list is not one the + * group agreed to. + * + * [delay] is the parent's own leaf's, which it chooses for this child. An + * inherited key keeps the delay its own ancestor chose: a group cannot + * shorten or lengthen another group's terms in its child's wallet. + */ + fun grant( + thresholdPublicKey: HexKey, + ownChatRoomId: String, + inherited: List, + childChatRoomId: String, + delay: Long = DEFAULT_DELAY, + ): List { + require(delay in DELAY_RANGE) { "a guardian's delay is $MIN_DELAY to $MAX_DELAY blocks, not $delay" } + val own = root(thresholdPublicKey).extendedPublicKey.derivePublicKey(childIndex(childChatRoomId)) + return listOf(Guardian(ownChatRoomId, own.publicKey, own.chaincode, delay)) + + inherited.map { it.grantedTo(childChatRoomId) } + } + + /** [guardian]'s key one level above the leaves of [account]'s `change` branch. */ + private fun branchKey(guardian: Guardian, chain: Chain, account: Long, change: Long): DeterministicWallet.ExtendedPublicKey = + guardian.extendedPublicKey.derivePublicKey(listOf(networkIndex(chain), account, change)) + + /** [guardian]'s leaf key in the address at `change/index` of [account] on [chain]. */ + fun leafKey(guardian: Guardian, chain: Chain, account: Long, change: Long, index: Long): XonlyPublicKey = + branchKey(guardian, chain, account, change).derivePublicKey(index).publicKey.xOnly() + + /** + * ` OP_CHECKSIGVERIFY OP_CHECKSEQUENCEVERIFY` -- miniscript's + * `and_v(v:pk(key),older(delay))`. A delay of 1-16 is the single opcode for + * it, as miniscript writes it; anything else is a minimal number push. + */ + fun leafScript(key: XonlyPublicKey, delay: Long): List { + require(delay in DELAY_RANGE) { "a guardian's delay is $MIN_DELAY to $MAX_DELAY blocks, not $delay" } + val lock = if (delay <= 16) ScriptEltMapping.code2elt.getValue(0x50 + delay.toInt()) + else OP_PUSHDATA(Script.encodeNumber(delay)) + return listOf(OP_PUSHDATA(key), OP_CHECKSIGVERIFY, lock, OP_CHECKSEQUENCEVERIFY) + } + + /** One leaf per guardian in the address at `change/index`, nearest first. */ + fun leaves(guardians: List, chain: Chain, account: Long, change: Long, index: Long): List = + guardians.map { ScriptTree.Leaf(leafScript(leafKey(it, chain, account, change, index), it.delay)) } + + /** + * The leaves as a caterpillar, nearest first: the first leaf at depth one, + * the rest one level further down each. Every guardian can act at the same + * moment, so the order decides only whose control block is shortest -- and + * the parent, who knows the child best, gets the cheapest spend. + */ + fun tree(leaves: List): ScriptTree { + require(leaves.isNotEmpty()) { "a tree needs a leaf" } + return leaves.dropLast(1).foldRight(leaves.last() as ScriptTree) { leaf, rest -> ScriptTree.Branch(leaf, rest) } + } + + /** The tree in the address at `change/index`, or null for an unguarded one. */ + fun treeAt(guardians: List, chain: Chain, account: Long, change: Long, index: Long): ScriptTree? = + guardians.takeIf { it.isNotEmpty() }?.let { tree(leaves(it, chain, account, change, index)) } + + /** + * The tree half of a `tr()` descriptor over a whole branch: `{a,{b,c}}`, the + * same caterpillar [tree] builds, each leaf ranged over the branch's indices. + */ + fun descriptorTree(guardians: List, chain: Chain, account: Long, change: Long): String { + require(guardians.isNotEmpty()) { "a tree needs a leaf" } + val leaves = guardians.map { guardian -> + val path = "${networkIndex(chain)}/$account/$change/*" + "and_v(v:pk(${guardian.encoded(chain)}/$path),older(${guardian.delay}))" + } + return leaves.dropLast(1).foldRight(leaves.last()) { leaf, rest -> "{$leaf,$rest}" } + } + + /** + * The room ids an ancestor walks from its own root down to [childChatRoomId], + * through the line of descent [guardians] -- a certificate's guardian list, + * nearest first -- names. Null when [ancestorChatRoomId] is not among them. + * + * For `guardians = [A1, A2, A3]` and `ancestor = A3`, that is `[A2, A1, C]`: + * the generations below A3, its own child first. + */ + fun lineage(guardians: List, childChatRoomId: String, ancestorChatRoomId: String): List? { + val position = guardians.indexOfFirst { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } + if (position < 0) return null + return guardians.take(position).map { it.chatRoomId }.reversed() + childChatRoomId + } + + /** + * The cache the group holding [thresholdPublicKey] signs a leaf with: its + * guardian root, then one plain step per generation down [lineage], then + * the network, the account and the address. Every step is a plain tweak, so + * the cache tracks exactly the point the descendant derives from its grant. + * + * No TapTweak follows: a script-path signature is by the leaf key itself. + */ + fun signingCache( + thresholdPublicKey: HexKey, + lineage: List, + chain: Chain, + account: Long, + change: Long, + index: Long, + ): Signing { + val root = root(thresholdPublicKey) + val path = lineage.map(::childIndex) + listOf(networkIndex(chain), account, change, index) + + var key = root.extendedPublicKey + var cache = root.cache + path.forEach { step -> + cache = GroupWalletDerivation.plainTweak(cache, GroupWalletDerivation.childTweak(key, step), "guardian step $step") + key = key.derivePublicKey(step) + } + + val leafKey = key.publicKey.xOnly() + require(cache.tweakedPublicKey == leafKey) { "the guardian cache does not reach its leaf key" } + return Signing(leafKey = leafKey, cache = cache) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt new file mode 100644 index 00000000..812b10b3 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt @@ -0,0 +1,746 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.nostr.subgroup.allows +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.ChatMessage +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.utils.sum +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * What an ancestor group knows of the guarded wallets beneath it, and how it + * comes to know. + * + * A descendant opens a guarded wallet in its own room. Its ancestors are not in + * that room, so a member who sits in both carries the signed statement across + * as a [GuardedWalletNoticeEvent]; every device in the ancestor's room checks it + * for itself, and from then on watches the wallet and can propose spending from + * it through its own leaf. See `docs/group-wallet-guardians.md`, "How an + * ancestor finds the coins". + * + * A notice forwarded into a middle group can be forwarded again from there, so + * a root needs a member in common with each generation, not with the grandchild. + */ +object GuardianManager { + private const val TAG = "GuardianManager" + + private val logger = Logger.withTag(TAG) + + /** + * Whose guarded wallet it is: a subgroup's, under its quorum's key, or one + * member's, under a key only they hold -- `docs/member-guarded-wallets.md`. + * Either way [id] is what the line of descent ends in, so every guardian + * signs for its leaf the same way. + */ + sealed interface GuardedSubject { + /** A room id, or a member wallet's `W`. */ + val id: String + + data class Subgroup(override val id: String, val name: String?) : GuardedSubject + + data class Member( + override val id: String, + val ownerPublicKey: HexKey, + val label: String?, + /** The member's profile name on this device, where one is known; filled where a database is to hand. */ + val ownerName: String? = null, + /** + * The group that directly guards it, by its founding name where this + * device can check a birth certificate for it, else its room name here; + * null when neither is known. Filled where a database is to hand. + * `docs/member-wallet-guarding-group.md`, D2. + */ + val guardianName: String? = null, + /** The holding group's own child it sits under, named the same way; null when the holder guards it directly. */ + val branchName: String? = null, + ) : GuardedSubject + } + + /** A descendant's guarded wallet, as one of its ancestors holds it. */ + data class GuardedWallet( + /** The ancestor holding it: the room it was told to. */ + val ancestorChatRoomId: String, + /** [subject]'s id: the descendant's room, or a member wallet's `W`. */ + val descendantChatRoomId: String, + /** + * What the ancestor believes it on, whole: a subgroup's signed statement, + * or the member wallet certificate the guarding group signed. + */ + val statement: Event, + /** The account the statement opens, rederived from the descendant's key. */ + val account: GroupWalletDerivation.Account, + /** A subgroup's birth certificate, carried in the statement -- or, for a member, the certificate itself. */ + val certificate: Event, + /** The rooms the ancestor walks from its own child down to the descendant -- `GuardianDerivation.lineage`. */ + val lineage: List, + val subject: GuardedSubject = GuardedSubject.Subgroup(descendantChatRoomId, SubgroupBirthCertificateEvent.parseName(certificate.tags)), + /** + * For a member's wallet: the birth certificate of the group that directly + * guards it, checked, where this device holds one -- what a notice + * carries upward so the groups above can name that group. + * `docs/member-wallet-guarding-group.md`, D4. + */ + val guardianCertificate: Event? = null, + ) { + /** What the descendant's parent certified it as, for a subgroup. The founding name: a rename does not reach it. */ + val name: String? get() = (subject as? GuardedSubject.Subgroup)?.name + + val chain: Chain get() = account.chain + + val openedAt: Instant get() = Instant.fromEpochSeconds(statement.createdAt) + + /** Where the ancestor sits among the guardians: whose leaf, in every address, is its. */ + val position: Int get() = account.guardians.indexOfFirst { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } + + /** + * How long a coin here waits before this ancestor can take it: the delay + * on its own leaf, which the group that granted it chose and which two of + * an ancestor's descendants can have set differently. + * `docs/guardian-delay.md`. + */ + val delay: Long get() = account.guardians[position].delay + + /** + * The group that directly guards it: the nearest guardian, which for a + * member's wallet is the group that signed its certificate -- + * `MemberWalletRequestEvent.verified` refuses a request whose nearest + * guardian is not the group it asks. `docs/member-wallet-guarding-group.md`, D1. + */ + val directGuardianChatRoomId: String get() = account.guardians.first().chatRoomId + + /** True when the ancestor holding it is the group that directly guards it. */ + val isGuardedHere: Boolean get() = position == 0 + + /** + * The ancestor's own child the wallet sits under -- the branch of its tree + * -- or null when the ancestor guards it directly. The ancestor signed + * that child's birth certificate, so it can always name it. + */ + val branchChatRoomId: String? get() = lineage.takeIf { position > 0 }?.first() + + /** The ancestor as the spender of a spend from this wallet, signing as [thresholdPublicKey] -- null to only build one. */ + fun spender(thresholdPublicKey: HexKey? = null): GroupSpend.Spender.Guardian = + GroupSpend.Spender.Guardian(position = position, lineage = lineage, thresholdPublicKey = thresholdPublicKey, name = displayName, label = label) + + /** A member's label for it, where they gave one; null for a subgroup's. */ + val label: String? get() = (subject as? GuardedSubject.Member)?.label + + /** How a spend from it names it: a subgroup's founding name, or `@` and a member's. */ + val displayName: String? + get() = when (val subject = subject) { + is GuardedSubject.Subgroup -> subject.name + is GuardedSubject.Member -> "@" + (subject.ownerName ?: subject.ownerPublicKey.take(8)) + } + } + + /** + * A guarded wallet statement believed on its own merits -- everything + * [verify] checks except the walk down from an ancestor's own guardian root, + * which only a device holding that ancestor's key can make. What a forwarder + * checks before passing a statement on (`docs/guarded-wallet-forwarding.md`, + * D2): a notice it would copy into every group above should be one it + * believes itself. + */ + data class Believable( + val statement: Event, + /** The descendant's room id, or a member wallet's `W`: what the line of descent ends in. */ + val descendantId: String, + /** The account the statement opens, rederived from the descendant's key. */ + val account: GroupWalletDerivation.Account, + /** A subgroup's birth certificate, carried in the statement -- or, for a member, the certificate itself. */ + val certificate: Event, + val subject: GuardedSubject, + ) { + /** Every guardian, nearest first: the groups that can be told. */ + val guardians: List get() = account.guardians + + val chain: Chain get() = account.chain + } + + /** + * [statement] believed, or null: + * + * 1. it is a wallet statement, and the room it is authored by signed it; + * 2. it is guarded, and carries the certificate its guardians came from; + * 3. the certificate's key makes that room, and the statement's xpub, tree + * and descriptors all rederive from it -- `Reading.verifiedAgainst`, which + * also checks the certificate certifies the room and grants exactly those + * guardians. + * + * Or a member wallet certificate the guarding group signed over the member's + * own request -- `MemberWalletCertificateEvent.verify`. + */ + fun believable(statement: Event): Believable? = runCatching { + if (statement.kind == MemberWalletCertificateEvent.KIND) { + val verified = MemberWalletCertificateEvent.verify(statement, statement.pubKey) ?: return null + return Believable( + statement = statement, + descendantId = verified.walletId, + account = verified.account, + certificate = statement, + subject = GuardedSubject.Member(verified.walletId, verified.memberPublicKey, verified.label), + ) + } + if (statement.kind != GroupWalletStatementEvent.KIND) return null + val descendantChatRoomId = statement.pubKey + if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null + + val reading = GroupWalletStatementEvent.read(statement.tags, statement.content) ?: return null + if (reading.guardians.isEmpty()) return null + val certificate = reading.certificate ?: return null + // A guarded wallet the certificate's own policy does not allow -- one it + // contradicts, or decided unguarded -- is not one an honest descendant + // opens, so it is not one to list. docs/subgroup-wallet-policy.md. + if (!SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags).let { it != null && it.allows(guarded = true) }) return null + + val descendantKey = SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags) ?: return null + if (!SharedKeyDerivation.marmotGroupId(descendantKey).equals(descendantChatRoomId, ignoreCase = true)) return null + val account = reading.verifiedAgainst(descendantKey) ?: return null + + Believable( + statement = statement, + descendantId = descendantChatRoomId, + account = account, + certificate = certificate, + subject = GuardedSubject.Subgroup(descendantChatRoomId, SubgroupBirthCertificateEvent.parseName(certificate.tags)), + ) + }.getOrNull() + + /** + * [statement] as a guarded wallet [ancestorChatRoomId] guards, or null when + * it is not one -- believed on its own merits, never on the word of whoever + * forwarded it: [believable], and + * + * 4. the ancestor is among the guardians, and the key the statement names + * for it is the key [ancestorThresholdPublicKey]'s guardian root reaches + * down the line of descent the guardians name. A key it does not reach is + * a leaf this group cannot sign, whatever the statement calls it. The + * line ends in the descendant's room, or in a member wallet's id. + */ + fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching { + val believed = believable(statement) ?: return null + val account = believed.account + + val lineage = GuardianDerivation.lineage(account.guardians, believed.descendantId, ancestorChatRoomId) ?: return null + val named = account.guardians.first { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } + val walked = GuardianDerivation.root(ancestorThresholdPublicKey).extendedPublicKey + .derivePublicKey(lineage.map(GuardianDerivation::childIndex)) + if (walked.publicKey != named.publicKey || walked.chaincode != named.chainCode) return null + + GuardedWallet( + ancestorChatRoomId = ancestorChatRoomId, + descendantChatRoomId = believed.descendantId, + statement = statement, + account = account, + certificate = believed.certificate, + lineage = lineage, + subject = believed.subject, + ) + }.getOrNull() + + /** + * [wallet] with its member's profile name, and the names of the group that + * directly guards it and of the branch it sits under, where this device knows + * them. [known] are birth certificates that came to hand some other way -- + * those the statements told to the holding room carry. + */ + private suspend fun named(database: BennuDatabase, wallet: GuardedWallet, known: List = emptyList()): GuardedWallet { + val member = wallet.subject as? GuardedSubject.Member ?: return wallet + val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey() + val guardians = wallet.account.guardians + + suspend fun certificateOf(position: Int): Event? = + guardians.getOrNull(position + 1)?.let { parent -> foundingCertificateOf(database, guardians[position].chatRoomId, parent.chatRoomId, known) } + + // Founding name first, then the room's name here: the order D2 of + // docs/member-wallet-guarding-group.md gives, so the card agrees with a + // subgroup row in the same list naming the same room. + suspend fun nameOf(position: Int, certificate: Event?): String? = + certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) } + ?: database.chatRoomDao().findChatRoomById(guardians[position].chatRoomId)?.chatRoom?.subject?.takeIf { it.isNotBlank() } + + val guardianCertificate = certificateOf(0) + return wallet.copy( + subject = member.copy( + ownerName = name, + guardianName = nameOf(0, guardianCertificate), + branchName = wallet.position.takeIf { it > 0 }?.let { nameOf(it - 1, certificateOf(it - 1)) }, + ), + guardianCertificate = guardianCertificate, + ) + } + + /** + * What [roomId] was called at its founding, read off a birth certificate + * [parentRoomId] signed for it -- or null when this device holds none it can + * check. Each candidate is checked with `SubgroupBirthCertificateEvent.certifies`, + * whoever handed it over: [carried] first, then the certificates the parent + * signed (every device in the parent holds them), then the one in [roomId]'s + * own key state (every device in the room). `docs/member-wallet-guarding-group.md`, D3. + */ + suspend fun foundingNameOf( + database: BennuDatabase, + roomId: String, + parentRoomId: String, + carried: List = emptyList(), + ): String? = foundingCertificateOf(database, roomId, parentRoomId, carried)?.let { SubgroupBirthCertificateEvent.parseName(it.tags) } + + /** The birth certificate [foundingNameOf] reads the name off, checked, or null. */ + suspend fun foundingCertificateOf( + database: BennuDatabase, + roomId: String, + parentRoomId: String, + carried: List = emptyList(), + ): Event? { + fun List.certifying(): Event? = firstOrNull { SubgroupBirthCertificateEvent.certifies(it, roomId, parentRoomId) } + + carried.certifying()?.let { return it } + database.groupSignedEventDao() + .getByChatRoomIdAndKind(parentRoomId, SubgroupBirthCertificateEvent.KIND) + .map { it.toEvent() } + .certifying()?.let { return it } + return listOfNotNull( + database.groupKeyStateDao().getByChatRoomId(roomId)?.birthCertificateJson?.let { Event.fromJsonOrNull(it) } + ).certifying() + } + + /** + * The guardian rooms a statement is told to from [chatRoomId]: those after it + * in [guardians], nearest first -- upward only + * (`docs/guarded-wallet-forwarding.md`, D3). A room the list does not name is + * the wallet's own, a subgroup's, and is told to every guardian. + * + * Every guardian *except* the room, which is what the button used to take, + * reaches down as well as up: from a root holding a grandchild's statement it + * would tell the middle group, which told the root. + */ + fun upwardOf(guardians: List, chatRoomId: String): List { + val position = guardians.indexOfFirst { it.chatRoomId.equals(chatRoomId, ignoreCase = true) } + return guardians.drop(position + 1).map { it.chatRoomId } + } + + /** + * Of [candidates] -- the members of both a room and a group above it, as this + * device's participant lists have them -- the one who sends a notice the + * moment a wallet arrives: the lowest key. Everybody else waits for the + * catch-up, by when the elected device's notice has usually arrived + * (`docs/guarded-wallet-forwarding.md`, D4). Null when there are none. + */ + fun electedSender(candidates: Set): HexKey? = candidates.map { it.lowercase() }.minOrNull() + + /** + * Every guarded wallet [ancestorChatRoomId] has been told about and can sign + * for, one per descendant account on each network. + * + * Read off the notices the room's inbound path filed, checked again each + * time. Where two statements describe one account, the rules + * `GroupWallet.newestAmong` applies to the descendant's own copy apply here: + * the earliest decides the guardians and a later one naming others is + * ignored, so a forwarder cannot move the addresses an ancestor watches. + */ + suspend fun guardedWalletsOf(database: BennuDatabase, ancestorChatRoomId: String): List { + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, ancestorChatRoomId) ?: return emptyList() + val order = compareBy({ it.openedAt }, { it.statement.id }) + + // What it was told, and -- for its own members' wallets -- what it signed: + // the group holds a member wallet certificate it signed, and needs no + // notice to learn of it. + val notices = database.marmotInnerEventDao() + .getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) + val told = notices.mapNotNull { row -> Event.fromJsonOrNull(row.content) } + val signed = database.groupSignedEventDao() + .getByChatRoomIdAndKind(ancestorChatRoomId, MemberWalletCertificateEvent.KIND) + .map { it.toEvent() } + + // Birth certificates the room was handed: the one a subgroup's statement + // carries, and the guardian's a member wallet's notice carries. Pooled, + // since each is checked against the room and parent it is used for, and + // one that certifies neither is never used. + val known = told.filter { it.kind == GroupWalletStatementEvent.KIND } + .mapNotNull { GroupWalletStatementEvent.read(it.tags, it.content)?.certificate } + + notices.mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } + + return (told + signed) + .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) } + .map { named(database, it, known) } + .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) } + .mapNotNull { (_, statements) -> + val first = statements.minWithOrNull(order) ?: return@mapNotNull null + statements.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) + } + .sortedBy { it.name ?: it.descendantChatRoomId } + } + + /** The guarded wallet [ancestorChatRoomId] holds for [descendantChatRoomId] on [chain] at [account], or null. */ + suspend fun guardedWalletFor( + database: BennuDatabase, + ancestorChatRoomId: String, + descendantChatRoomId: String, + chain: Chain, + account: Long, + ): GuardedWallet? = guardedWalletsOf(database, ancestorChatRoomId).firstOrNull { + it.descendantChatRoomId.equals(descendantChatRoomId, ignoreCase = true) && it.chain == chain && it.account.account == account + } + + /** A guarded statement this device can carry upward, and the rooms it can carry it into. */ + data class Shareable( + val statement: Event, + /** What the statement's room was certified as, for the screen. Null for a member's wallet. */ + val name: String?, + val rooms: List, + /** For a member's wallet: the member, and their profile name where this device knows one. */ + val ownerPublicKey: HexKey? = null, + val ownerName: String? = null, + /** For a member's wallet: its guardian's birth certificate, carried on the notice -- `GuardedWalletNoticeEvent`. */ + val certificate: Event? = null, + ) + + /** + * The guarded statements this device can tell to groups above [chatRoomId]: + * the room's own guarded wallet, and every one the room was itself told + * about -- passed on a generation further. Each with the guardian rooms this + * device is a member of and has not told yet. + */ + suspend fun shareableFrom(database: BennuDatabase, chatRoomId: String, chain: Chain): List { + val own = GroupWalletManager.walletFor(database, chatRoomId, chain) + ?.takeIf { it.account.isGuarded } + ?.let { wallet -> + val statement = wallet.signedEvent.toEvent() + val certificate = GroupWalletStatementEvent.read(statement.tags, statement.content)?.certificate + statement to (certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) }) + } + // Everything it guards or was told of -- its own members' wallets among + // them, since it holds those certificates itself -- passed on a + // generation further. + val passedOn = guardedWalletsOf(database, chatRoomId) + .filter { it.chain == chain } + + val candidates = listOfNotNull(own?.let { (statement, name) -> Shareable(statement, name, emptyList()) }) + + passedOn.map { wallet -> + val member = wallet.subject as? GuardedSubject.Member + Shareable(wallet.statement, wallet.name, emptyList(), member?.ownerPublicKey, member?.ownerName, wallet.guardianCertificate) + } + + return candidates.mapNotNull { candidate -> + val rooms = targetsFor(database, candidate.statement, fromChatRoomId = chatRoomId, withCertificate = candidate.certificate != null) + rooms.takeIf { it.isNotEmpty() }?.let { candidate.copy(rooms = it) } + } + } + + /** + * The groups above [fromChatRoomId] that [statement] should be told to and + * this device can tell: [upwardOf] the room, Marmot rooms this device holds, + * belonging to the same profile as the room it is told from -- one database + * holds every profile, and a device must never post into a room as a + * profile that is not the one in it -- and not told yet. Nothing for a + * statement this device does not believe ([believable]). + */ + private suspend fun targetsFor(database: BennuDatabase, statement: Event, fromChatRoomId: String, withCertificate: Boolean = false): List { + val believed = believable(statement) ?: return emptyList() + val profile = database.chatRoomDao().findChatRoomById(fromChatRoomId)?.chatRoom?.userPublicKey + + return upwardOf(believed.guardians, fromChatRoomId) + .mapNotNull { database.chatRoomDao().findChatRoomById(it) } + .filter { it.chatRoom.mlsGroupState != null } + .filter { profile == null || it.chatRoom.userPublicKey.equals(profile, ignoreCase = true) } + .filterNot { room -> told(database, room.chatRoom.id, statement.id, withCertificate) } + } + + /** + * Whether [chatRoomId] holds the statement [statementId] in any form: a + * notice carrying it, or the signed event itself -- which is how a group + * holds a member wallet certificate it signed, and never as a notice. + * + * With [withCertificate] -- this device has the guardian's birth certificate + * to add -- a notice counts only if it carries one: a room told before + * notices carried it is told again, once, so the name reaches it. + * `docs/member-wallet-guarding-group.md`, D5. + */ + internal suspend fun told(database: BennuDatabase, chatRoomId: String, statementId: HexKey, withCertificate: Boolean = false): Boolean = + database.groupSignedEventDao().getById(statementId)?.chatRoomId.equals(chatRoomId, ignoreCase = true) || + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) + .any { Event.fromJsonOrNull(it.content)?.id == statementId && (!withCertificate || GuardedWalletNoticeEvent.certificateIn(it.tags) != null) } + + /** + * For a member wallet's certificate, the birth certificate of the group that + * signed it, checked, where this device holds one -- what a notice from + * [chatRoomId] carries upward so the groups above can name that group. + * Null for a subgroup's statement, which carries its own. + * `docs/member-wallet-guarding-group.md`, D4. + */ + private suspend fun guardianCertificateFor(database: BennuDatabase, statement: Event, chatRoomId: String): Event? { + if (statement.kind != MemberWalletCertificateEvent.KIND) return null + val guardians = believable(statement)?.guardians ?: return null + val parent = guardians.getOrNull(1) ?: return null + val carried = database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) + .mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } + return foundingCertificateOf(database, guardians.first().chatRoomId, parent.chatRoomId, carried) + } + + /** + * Tells every group above [chatRoomId] that this device can tell, and that + * has not been told, about [statement] -- as the profile that is in + * [chatRoomId]. `docs/guarded-wallet-forwarding.md`, Phase 2. + * + * With [whenElected], only the groups this device is the elected sender for + * ([electedSender] over the members of both rooms, as this device's + * participant lists have them, itself always among them): the moment a wallet + * arrives every device in both rooms has it, and only one of them should + * post at once. The catch-up passes false, and tells whatever is still left. + * + * Returns the rooms told. + */ + suspend fun forward(database: BennuDatabase, statement: Event, chatRoomId: String, whenElected: Boolean): List { + val sender = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey ?: return emptyList() + val members = database.participantDao().findParticipantsByChatRoomId(chatRoomId).map { it.participantPublicKey.lowercase() }.toSet() + + val certificate = guardianCertificateFor(database, statement, chatRoomId) + val targets = targetsFor(database, statement, fromChatRoomId = chatRoomId, withCertificate = certificate != null).filter { target -> + if (!whenElected) return@filter true + val both = database.participantDao().findParticipantsByChatRoomId(target.chatRoom.id) + .map { it.participantPublicKey.lowercase() } + .filter { it in members } + .toSet() + sender.lowercase() + electedSender(both).equals(sender, ignoreCase = true) + } + if (targets.isNotEmpty()) share(database, statement, targets, sender, certificate = certificate) + return targets + } + + /** Every network a guarded wallet can be on: the catch-up forwards them all. */ + private val CHAINS: List = listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest) + + /** + * The catch-up: everything [shareableFrom] would list from [chatRoomId], on + * every network, through [forward] without the election -- whatever the + * elected device never sent, whatever arrived while this one was offline, + * and everything filed before forwarding existed. + * `docs/guarded-wallet-forwarding.md`, Phase 4. Run as the group's chat and + * its wallet screen open. Returns how many groups were told. + */ + suspend fun forwardAll(database: BennuDatabase, chatRoomId: String): Int { + if (!GroupWalletRollout.FORWARDS_GUARDED_WALLETS) return 0 + val own = CHAINS.mapNotNull { chain -> + GroupWalletManager.walletFor(database, chatRoomId, chain)?.takeIf { it.account.isGuarded }?.signedEvent?.toEvent() + } + val held = guardedWalletsOf(database, chatRoomId).map { it.statement } + + return (own + held).distinctBy { it.id }.sumOf { statement -> + runCatching { forward(database, statement, chatRoomId, whenElected = false).size } + .onFailure { logger.e("Could not forward ${statement.id.take(8)} from $chatRoomId", it) } + .getOrDefault(0) + } + } + + /** + * [forward] on arrival, from the inbound path: elected, behind + * `GroupWalletRollout.FORWARDS_GUARDED_WALLETS`, and never failing the + * arrival it rides on -- forwarding is an extra, and the arrival is the thing. + */ + suspend fun forwardOnArrival(database: BennuDatabase, statement: Event, chatRoomId: String) { + if (!GroupWalletRollout.FORWARDS_GUARDED_WALLETS) return + runCatching { forward(database, statement, chatRoomId, whenElected = true) } + .onSuccess { told -> if (told.isNotEmpty()) logger.i("Forwarded ${statement.id.take(8)} from $chatRoomId to ${told.size} group(s) above") } + .onFailure { logger.e("Could not forward ${statement.id.take(8)} from $chatRoomId", it) } + } + + /** + * Tells every room in [rooms] about [statement], as [userPublicKey]: one + * notice each, queued for the outbound pipeline the way every inner event + * is. Returns how many were queued. + * + * Each notice names its room in an `h` tag. Without it, one statement told + * to a grandchild's parent and grandparent in the same second is one id -- + * and one row, the last room's -- so the parent was never told. + * + * [certificate], for a member's wallet, is its guardian's birth certificate, + * carried as a tag -- `GuardedWalletNoticeEvent`. + */ + suspend fun share( + database: BennuDatabase, + statement: Event, + rooms: List, + userPublicKey: HexKey, + createdAt: Long = Clock.System.now().epochSeconds, + certificate: Event? = null, + ): Int { + val content = statement.toJson() + + // The sender is never handed its own MLS message back, so the line the + // other members' devices write when it arrives is written here for the + // sender's own -- before the notice, which then finds a line already + // there. docs/guarded-wallet-forwarding.md, D6. + val line = believable(statement)?.let { describe(named(database, it.subject)) } + + rooms.forEach { room -> + val tags = listOfNotNull(arrayOf("h", room.chatRoom.id), certificate?.let(GuardedWalletNoticeEvent::certificateTag)).toTypedArray() + val id = EventHasher.hashId(userPublicKey, createdAt, GuardedWalletNoticeEvent.KIND, tags, content) + line?.takeIf { firstNoticeOf(database, room.chatRoom.id, statement.id, excludingNotice = id) }?.let { + database.chatMessageDao().upsert( + ChatMessage( + giftWrapPayloadId = null, + messageType = ChatMessage.TYPE_GUARDED_WALLET_SHARED, + marmotGroupEventId = null, + marmotInnerEventId = null, + senderPublicKey = userPublicKey, + isUserMessage = true, + chatRoomId = room.chatRoom.id, + createdAt = Instant.fromEpochSeconds(createdAt), + content = it, + ) + ) + } + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = userPublicKey, + kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = room.chatRoom.id, + ) + ) + logger.i("Told ${room.chatRoom.id} about ${statement.pubKey}'s guarded wallet") + } + + return rooms.size + } + + /** Coins of a guarded wallet one of its guardians took, in one transaction. */ + data class Taken( + val txid: TxId, + val guardian: GuardianDerivation.Guardian, + val amount: Satoshi, + ) + + /** + * Which guardians of [account] took which of [coins] in [spending] -- one + * entry per guardian -- read off the witnesses alone. + * + * A guardian's input carries three things: a signature, a leaf, and the + * control block proving the leaf is in the address. The leaf is matched + * against the guardian leaves of the address the coin was at, so a leaf is + * named only by a guardian whose key it is; anything else -- the wallet's own + * key-path spend, a witness of another shape -- names nobody. + */ + fun takenIn( + spending: Transaction, + account: GroupWalletDerivation.Account, + coins: Map>, + ): List { + if (!account.isGuarded) return emptyList() + + return spending.txIn.mapNotNull { input -> + val (txOut, derivation) = coins[input.outPoint] ?: return@mapNotNull null + val stack = input.witness.stack.takeIf { it.size == 3 } ?: return@mapNotNull null + val leaves = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index) + val position = leaves.indexOfFirst { it.script == stack[1] }.takeIf { it >= 0 } ?: return@mapNotNull null + account.guardians[position] to txOut.amount + } + .groupBy({ it.first }, { it.second }) + .map { (guardian, amounts) -> Taken(spending.txid, guardian, amounts.sum()) } + } + + /** + * Writes a transcript line in [chatRoomId] for each of [taken] it has no line + * for yet. Returns how many it wrote. + * + * The whole of the child's notice that an ancestor spent from its wallet -- + * there is no channel from the ancestor's room into this one -- so it is + * written by whichever device reads the chain first, and every device that + * reads it afterwards finds it already there. + */ + suspend fun recordTaken(database: BennuDatabase, chatRoomId: String, taken: List): Int { + val written = database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) + .map { it.chatMessage } + .filter { it.messageType == ChatMessage.TYPE_GUARDIAN_SPEND } + .map { it.content } + + val fresh = taken.filter { spend -> written.none { it.contains(spend.txid.toString()) } } + fresh.forEach { spend -> + val name = database.chatRoomDao().findChatRoomById(spend.guardian.chatRoomId)?.chatRoom?.subject + ?.takeIf { it.isNotBlank() } + ?: "A group above this one" + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = spend.guardian.chatRoomId, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = chatRoomId, + content = "$name took ${spend.amount.sat} sats from this wallet through its guardian leaf, " + + "in transaction ${spend.txid}.", + messageType = ChatMessage.TYPE_GUARDIAN_SPEND, + ) + ) + logger.i("${spend.guardian.chatRoomId} took ${spend.amount.sat} sats from $chatRoomId's guarded wallet in ${spend.txid}") + } + return fresh.size + } + + /** + * What a notice that arrived in [chatRoomId] says, for its transcript line -- + * or null when it is not one this room can believe, which gets no line: a + * line saying a wallet was shared would read as the group being told + * something it was not. + */ + suspend fun describeNotice(database: BennuDatabase, chatRoomId: String, notice: Event): String? { + val statement = GuardedWalletNoticeEvent.statementOf(notice) ?: return null + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null + val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null + // One line per wallet per group: a second notice of a statement this room + // already holds -- told before, by another forwarder, or signed here -- + // is filed and silent. docs/guarded-wallet-forwarding.md, D6. + if (!firstNoticeOf(database, chatRoomId, statement.id, excludingNotice = notice.id)) return null + + return describe(named(database, wallet).subject) + } + + private fun describe(subject: GuardedSubject): String = when (subject) { + is GuardedSubject.Member -> "Shared @${subject.ownerName ?: subject.ownerPublicKey.take(8)}'s guarded wallet with this group." + is GuardedSubject.Subgroup -> subject.name?.let { "Shared the guarded wallet of $it with this group." } + ?: "Shared a subgroup's guarded wallet with this group." + } + + /** [subject] with its member's profile name, where this device knows one. */ + private suspend fun named(database: BennuDatabase, subject: GuardedSubject): GuardedSubject { + val member = subject as? GuardedSubject.Member ?: return subject + val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey() + return member.copy(ownerName = name) + } + + /** + * Whether a notice of [statementId] -- [excludingNotice], the one being + * filed or sent -- is the first [chatRoomId] holds: no other notice in the + * room carries the statement, and the room did not sign it itself. + */ + private suspend fun firstNoticeOf(database: BennuDatabase, chatRoomId: String, statementId: HexKey, excludingNotice: HexKey): Boolean { + if (database.groupSignedEventDao().getById(statementId)?.chatRoomId.equals(chatRoomId, ignoreCase = true)) return false + return database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) + .none { it.id != excludingNotice && Event.fromJsonOrNull(it.content)?.id == statementId } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt new file mode 100644 index 00000000..6fa8ec41 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt @@ -0,0 +1,145 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.wallet.GroupSpend +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.utils.RandomInstance +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.Descriptor +import fr.acinq.bitcoin.DeterministicWallet +import fr.acinq.bitcoin.KeyPath +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey + +/** + * The keys of a wallet one member holds and a group guards: a guarded wallet + * whose key path is the member's own key rather than a group's threshold key. + * + * Everything public is the group wallet's derivation with the member's key in + * the threshold key's place, and the guardian derivation with the wallet's id in + * a child room's place: + * + * ``` + * k random, generated on the member's device and never sent + * P_W = k·G the wallet key + * W = taggedHash("bennu/member-wallet/id/v1", serP(P_W)) the wallet's id + * account = GroupWalletDerivation.account(P_W, chain, 0, grant) + * grant = GuardianDerivation.grant(K_G, G, guardians(G), W) + * ``` + * + * So a member's wallet under G is guarded exactly as a guarded subgroup of G + * would be. What is new is only the private side: the member holds `k`, so + * every tweak the account and the address add to the point is added to the + * scalar too, and a spend is one Schnorr signature. See + * `docs/member-guarded-wallets.md`. + * + * ### Why `W` is a hash and not the key + * + * A room id here is a public key, and `GroupKeyStateEvent.isSignedByRoom` asks + * whether that key signed something. A `W` nobody holds a key for cannot be + * mistaken for a room by anything that checks signatures. + * + * ### The rule this inherits + * + * Every step below `P_W` is an unhardened public tweak, and every guardian holds + * the account xpub. A guardian who learns the private key of one address can + * therefore recover `k`. That is why `k` is random and good for one wallet only: + * never the nostr key, never a key from the profile's seed. + */ +object MemberWalletDerivation { + /** The tag of a wallet id's hash. Frozen the moment a certificate carries one: a rename moves every leaf. */ + private const val ID_TAG = "bennu/member-wallet/id/v1" + + /** + * The account a member wallet always opens at. One wallet is one key, so a + * second account would be a second wallet under a key that already has one. + */ + const val ACCOUNT: Long = 0L + + /** A fresh wallet key, from the platform's secure random. */ + fun generate(): PrivateKey { + while (true) { + val candidate = PrivateKey(ByteVector32(RandomInstance.bytes(32))) + if (candidate.isValid()) return candidate + } + } + + /** `W`: the tagged hash of the wallet key's compressed form, hex. */ + fun walletId(walletKey: PublicKey): String = + Crypto.taggedHash(walletKey.value.toByteArray(), ID_TAG).toByteArray().toHexKey() + + fun walletId(walletKey: HexKey): String = walletId(PublicKey(walletKey.hexToByteArray())) + + /** + * The account [walletKey] opens on [chain] under [guardians]: + * `GroupWalletDerivation.account` over the member's key. + */ + fun account(walletKey: PublicKey, chain: Chain, guardians: List): GroupWalletDerivation.Account = + GroupWalletDerivation.account(walletKey.toString(), chain, ACCOUNT, guardians) + + /** + * The account key as a private extended key: [walletPrivateKey] plus the + * scalar `GroupWalletDerivation.account` adds to the point, with the same + * chain code. Plain addition, so there is no parity to get wrong until the + * taproot tweak at the very end. + */ + fun accountPrivateKey(walletPrivateKey: PrivateKey, chain: Chain): DeterministicWallet.ExtendedPrivateKey { + val (tweak, chainCode) = GroupWalletDerivation.accountStep(walletPrivateKey.publicKey(), chain, ACCOUNT) + return DeterministicWallet.ExtendedPrivateKey( + secretkeybytes = (walletPrivateKey + PrivateKey(tweak)).value, + chaincode = chainCode, + depth = 0, + path = KeyPath.empty, + parent = 0L, + ) + } + + /** The private key of the internal key at `change/index`: CKDpriv twice below [accountPrivateKey]. */ + fun privateKeyAt(walletPrivateKey: PrivateKey, chain: Chain, change: Long, index: Long): PrivateKey { + require(change == GroupWalletDerivation.RECEIVE || change == GroupWalletDerivation.CHANGE) { "change must be 0 or 1, not $change" } + require(index in 0L..GroupWalletDerivation.MAX_INDEX) { "index $index is not an unhardened index" } + return accountPrivateKey(walletPrivateKey, chain).derivePrivateKey(listOf(change, index)).privateKey + } + + /** + * The receive and change descriptors of [account] with the account's private + * key in place of its xpub -- what any wallet that imports taproot + * descriptors can sweep the coins with. The member's backup of last resort, + * shown only behind a confirmation: whoever holds these holds the coins. + */ + fun privateDescriptors(walletPrivateKey: PrivateKey, account: GroupWalletDerivation.Account): Pair { + val extended = accountPrivateKey(walletPrivateKey, account.chain) + require(extended.extendedPublicKey == account.extendedPublicKey) { "this key does not open this account" } + val xprv = extended.encode(if (account.chain.isMainnet()) DeterministicWallet.xprv else DeterministicWallet.tprv) + + fun swap(descriptor: String): String { + val body = descriptor.substringBefore('#').replaceFirst(account.xpub, xprv) + return "$body#${Descriptor.checksum(body)}" + } + return swap(account.receiveDescriptor) to swap(account.changeDescriptor) + } + + /** + * The signature [input] of a checked spend needs from the wallet's own key: + * the address's private key under the address's taproot tweak, over the + * input's key-path sighash. + * + * Refuses a guardian's input -- the member never signs through a leaf -- and + * an input whose address is not one this key reaches, so a signature made + * here always verifies against the key the coin is at. + */ + fun sign(walletPrivateKey: PrivateKey, chain: Chain, input: GroupSpend.SpentInput): ByteVector64 { + require(input.leaf == null) { "a member signs on the key path, never through a guardian's leaf" } + val derivation = input.derivation + val privateKey = privateKeyAt(walletPrivateKey, chain, derivation.change, derivation.index) + require(privateKey.xOnlyPublicKey() == derivation.internalKey) { "this key does not reach the address at ${derivation.change}/${derivation.index}" } + + val signature = Crypto.signSchnorr(input.sighash, privateKey, derivation.taprootTweak) + require(Crypto.verifySignatureSchnorr(input.sighash, signature, input.signingKey)) { "the signature does not verify against the coin's key" } + return signature + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt new file mode 100644 index 00000000..bbb4de52 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt @@ -0,0 +1,866 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.model.types.ChatRoomType +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import com.machankura.bennu.compose.wallet.GroupSpend +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.psbt.Psbt +import fr.acinq.secp256k1.Hex +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.machankura.bennu.compose.wallet.GroupWalletRollout +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * A member's guarded wallet, from the asking to the guarding: + * `docs/member-guarded-wallets.md`. + * + * The member's device makes a random key, works out every ancestor leaf, stores + * the key and only then asks the group. A signer puts the request to the group, + * the group's quorum signs a certificate saying it guards that key for that + * person, and the certificate is what every device opens the wallet on. + */ +object MemberWalletManager { + private const val TAG = "MemberWalletManager" + + private val logger = Logger.withTag(TAG) + + /** + * The key [chatRoomId] signs with and the certificate it was born with -- + * what a member's grant is worked out from -- or null when this device knows + * neither. + * + * This device's own verified key state first. Behind it, the newest answer to + * a key notice in the room that checks out: a member welcomed after the + * founding holds no key state, and asks (`askForGroupKey`). Never filed as + * key state -- see [GroupKeyNoticeEvent]. + */ + suspend fun groupKeyFor(database: BennuDatabase, chatRoomId: String): GroupKeyNoticeEvent.GroupKey? { + GroupKeyStateManager.keyStateFor(database, chatRoomId)?.takeIf { it.verifies() }?.let { state -> + return GroupKeyNoticeEvent.GroupKey( + chatRoomId = state.chatRoomId, + thresholdPublicKey = state.thresholdPublicKey, + certificate = state.birthCertificateJson?.let { Event.fromJsonOrNull(it) }, + ) + } + + return noticesIn(database, chatRoomId) + .sortedByDescending { it.createdAt } + .firstNotNullOfOrNull { GroupKeyNoticeEvent.read(it, chatRoomId) } + } + + /** + * Whether [chatRoomId] guards its members' wallets, and at what delay: the + * newest policy its own room signed, open or closed, among the ones this + * device holds -- `docs/member-wallet-delay.md`. Null when it holds none, + * which means the group has not opened (D8), or that this device has not + * yet been told. + * + * The one reader, used by the member's device when it builds a request and + * by every signer when it judges one. + */ + suspend fun policyFor(database: BennuDatabase, chatRoomId: String): MemberWalletPolicyEvent.Policy? = + MemberWalletPolicyEvent.newestAmong( + database.groupSignedEventDao() + .getByChatRoomIdAndKind(chatRoomId, MemberWalletPolicyEvent.KIND) + .map { it.toEvent() } + + // A late member's only way to it: carried in a key answer, and + // checked again here as the room's own signature. + noticesIn(database, chatRoomId).mapNotNull { GroupKeyNoticeEvent.read(it, chatRoomId)?.policy?.event }, + chatRoomId, + ) + + /** + * Asks [chatRoomId] for its key, as [userPublicKey]. Returns false, asking + * nothing, when this device already knows it or has asked and not been + * answered: a second question would get the same answer. + */ + suspend fun askForGroupKey(database: BennuDatabase, chatRoomId: String, userPublicKey: HexKey): Boolean { + if (groupKeyFor(database, chatRoomId) != null) return false + + val notices = noticesIn(database, chatRoomId) + val answered = notices.mapNotNull { GroupKeyNoticeEvent.answers(it) }.toSet() + if (notices.any { GroupKeyNoticeEvent.isAsking(it) && it.pubKey == userPublicKey && it.id !in answered }) return false + + queue(database, chatRoomId, userPublicKey, GroupKeyNoticeEvent.askingTags(chatRoomId), content = "") + logger.i("Asked $chatRoomId for its key") + return true + } + + /** + * Answers [request], an asking notice that arrived in [chatRoomId], as + * [userPublicKey] -- when this device holds the room's verified key state and + * nobody has answered it yet. Returns whether it answered. + * + * Any member holding the state may answer, and none is elected to: a + * duplicate answer costs bandwidth and nothing else, since every answer is + * checked on its own and they all say the same thing. The chronicle's + * request is answered the same way. + */ + suspend fun answerKeyRequest(database: BennuDatabase, chatRoomId: String, request: Event, userPublicKey: HexKey): Boolean { + if (!GroupKeyNoticeEvent.isAsking(request) || request.pubKey == userPublicKey) return false + val state = GroupKeyStateManager.keyStateFor(database, chatRoomId)?.takeIf { it.verifies() } ?: return false + val path = state.pathIndices() ?: return false + if (noticesIn(database, chatRoomId).any { GroupKeyNoticeEvent.answers(it) == request.id }) return false + + val groupKey = GroupKeyNoticeEvent.GroupKey( + chatRoomId = state.chatRoomId, + thresholdPublicKey = state.thresholdPublicKey, + certificate = state.birthCertificateJson?.let { Event.fromJsonOrNull(it) }, + // The other thing a late member cannot read for themselves. + // docs/member-wallet-delay.md, Phase 3. + policy = policyFor(database, chatRoomId), + ) + queue(database, chatRoomId, userPublicKey, GroupKeyNoticeEvent.answeringTags(request.id, groupKey, path), content = state.thresholdPublicKey) + logger.i("Answered ${request.pubKey.take(8)}'s request for $chatRoomId's key") + return true + } + + // ---- The member's side ----------------------------------------------- + + /** Why a member cannot ask a group to guard a wallet for them here, said as a reason the screen can name. */ + enum class Refusal { + /** A read-only profile: it cannot sign the request. */ + CANNOT_SIGN, + + /** The room is not a Marmot group, so there is no quorum to sign and no room to carry it. */ + NOT_A_GROUP, + + /** This device does not know what the group signs with -- [askForGroupKey] is the way on. */ + KEY_UNKNOWN, + + /** The group's certificate carries guardian keys this build cannot read. */ + GUARDIANS_UNREADABLE, + + /** Member wallets are not offered on this network yet: `GroupWalletRollout.offersMemberWalletsOn`. */ + NOT_ON_THIS_NETWORK, + + /** The profile has no Electrum client, so it could not see its own coins. Read by the screen, not here. */ + CANNOT_WATCH, + + /** + * The group has not said it guards members' wallets: no policy, as far as + * this device knows. `docs/member-wallet-delay.md`, D8. + */ + NOT_OFFERED, + + /** The group's newest policy closed it to new members' wallets. D9. */ + CLOSED, + } + + /** + * The groups [ownerPublicKey] is in that could guard a wallet for them: Marmot + * rooms, whether or not their key is known yet -- but not a direct chat. + * + * A direct chat is a Marmot room too, of exactly two people, and it never has + * a key: a key ceremony needs at least `ChatRoomType.MINIMUM_ROBUST_GROUP_SIZE` + * participants. Listed, it would ask for a key nobody can ever answer with. + * So a room of fewer than three members is left out unless this device knows + * its key -- a real group can shrink to two after its ceremony, and still sign + * if the two make its quorum. The same "the two of us" the direct-message + * lookup uses (`ChatRepository.findDirectMessageRoom`). + */ + suspend fun groupsOf(database: BennuDatabase, ownerPublicKey: HexKey): List = + database.chatRoomDao().getChatRoomListByUserPublicKey(ownerPublicKey).filter { couldGuard(database, it) } + + /** Whether [room] is a group that could guard a member's wallet: [groupsOf]'s one rule, for a room on its own page too. */ + suspend fun couldGuard(database: BennuDatabase, room: LocalChatRoom): Boolean { + if (room.chatRoom.mlsGroupState == null) return false + val members = room.localParticipants.map { it.participant.participantPublicKey.lowercase() }.toSet() + return members.size >= ChatRoomType.MINIMUM_ROBUST_GROUP_SIZE || groupKeyFor(database, room.chatRoom.id) != null + } + + /** Why [chatRoomId] cannot guard a wallet for this profile on [chain], or null when it can. */ + suspend fun refusal(database: BennuDatabase, chatRoomId: String, canSign: Boolean, chain: Chain): Refusal? { + if (!canSign) return Refusal.CANNOT_SIGN + if (!GroupWalletRollout.offersMemberWalletsOn(chain)) return Refusal.NOT_ON_THIS_NETWORK + val room = database.chatRoomDao().findChatRoomById(chatRoomId) + if (room?.chatRoom?.mlsGroupState == null) return Refusal.NOT_A_GROUP + val groupKey = groupKeyFor(database, chatRoomId) ?: return Refusal.KEY_UNKNOWN + if (groupKey.certificate != null && SubgroupBirthCertificateEvent.parseGuardians(groupKey.certificate.tags) == null) { + return Refusal.GUARDIANS_UNREADABLE + } + // Only a group that has opened guards members' wallets, at the delay it + // chose -- and a late member learns it with the key, so no key and no + // policy is KEY_UNKNOWN above, with its button to ask. + return when (policyFor(database, chatRoomId)) { + null -> Refusal.NOT_OFFERED + is MemberWalletPolicyEvent.Policy.Closed -> Refusal.CLOSED + is MemberWalletPolicyEvent.Policy.Open -> null + } + } + + /** + * How many groups a wallet guarded by [chatRoomId] would be guarded by: the + * group, and every group above it whose key it passes down. Null when this + * device does not know the group's key. + */ + suspend fun reachOf(database: BennuDatabase, chatRoomId: String): Int? = + groupKeyFor(database, chatRoomId)?.let { it.guardians.size + 1 } + + /** + * How long a coin in a wallet [chatRoomId] guards would wait for each of its + * guardians, nearest first: the group's own leaf at the delay its open policy + * sets, and every group above it at the delay it chose -- the same list the + * grant in [request] carries. Null when this device does not know the + * group's key, or the group is not open. `docs/member-wallet-delay.md`. + */ + suspend fun delaysOf(database: BennuDatabase, chatRoomId: String): List? { + val key = groupKeyFor(database, chatRoomId) ?: return null + val policy = policyFor(database, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open ?: return null + return listOf(policy.delay) + key.guardians.map { it.delay } + } + + /** + * Steps 1 and 2: makes a random key, works out every ancestor's leaf and + * both descriptors, stores the key, and only then asks [chatRoomId] to + * guard the wallet, as the member [memberPrivateKey] holds. + * + * The row is written before the request is queued, so a crash between the + * two leaves a key and no request rather than a request and no key. The + * request is checked the way every signer will check it before it goes, so + * a quorum is never shown one this device would refuse. A member who holds a + * share of the group's key puts it to the group in the same breath; anybody + * else waits for a signer to. + * + * @throws IllegalStateException with the [Refusal] when it cannot be asked + */ + suspend fun request( + database: BennuDatabase, + chatRoomId: String, + memberPrivateKey: PrivateKey, + chain: Chain, + label: String?, + createdAt: Instant = Clock.System.now(), + ): MemberWallet { + refusal(database, chatRoomId, canSign = true, chain)?.let { throw IllegalStateException("Cannot ask: $it") } + val groupKey = groupKeyFor(database, chatRoomId) ?: throw IllegalStateException("Cannot ask: ${Refusal.KEY_UNKNOWN}") + val memberPublicKey = memberPrivateKey.xOnlyPublicKey().value.toHex() + + // The group's own leaf at the delay its newest policy sets, which the + // request carries so every signer judges it by what the group signed. + // refusal() has already refused a group that is not open. + val policy = policyFor(database, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open + ?: throw IllegalStateException("Cannot ask: ${Refusal.NOT_OFFERED}") + + val walletPrivateKey = MemberWalletDerivation.generate() + val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + val grant = GuardianDerivation.grant(groupKey.thresholdPublicKey, chatRoomId.lowercase(), groupKey.guardians, walletId, policy.delay) + val account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, grant) + + val request = MemberWalletRequestEvent.build( + memberPrivateKey = memberPrivateKey, + groupChatRoomId = chatRoomId, + walletPrivateKey = walletPrivateKey, + account = account, + label = label, + createdAt = createdAt.epochSeconds, + policy = policy.event, + ) + checkNotNull(MemberWalletRequestEvent.verified(request)) { "The request this device built does not check out" } + + val wallet = MemberWallet( + walletId = walletId, + ownerPublicKey = memberPublicKey, + guardingChatRoomId = chatRoomId, + chain = GroupWalletStatementEvent.chainName(chain), + walletPrivateKey = walletPrivateKey.value.toHex(), + label = MemberWalletRequestEvent.read(request)?.label, + requestJson = request.toJson(), + // The request's own second: the row and the event it carries agree on when. + createdAt = Instant.fromEpochSeconds(request.createdAt), + ) + database.memberWalletDao().upsert(wallet) + send(database, chatRoomId, request) + logger.i("Asked $chatRoomId to guard wallet ${walletId.take(8)}") + + sponsorIfSigner(database, chatRoomId, memberPublicKey, request) + return wallet + } + + /** + * Asks again -- for a request no signer put to the group, or one the group + * did not sign. With the request [wallet] was asked with, unchanged, when + * the group would still accept it; otherwise with a new one under the + * group's newest policy and a new key, as the member [memberPrivateKey] + * holds, and the old key discarded: no address of it was ever offered. + * `docs/member-wallet-delay.md`, Phase 5. + * + * Returns the wallet now asked for -- [wallet] itself, or its replacement. + * + * @throws IllegalStateException when a new request is needed and this group + * cannot be asked now, with the [Refusal] + */ + suspend fun askAgain(database: BennuDatabase, wallet: MemberWallet, memberPrivateKey: PrivateKey): MemberWallet { + val request = Event.fromJsonOrNull(wallet.requestJson) ?: throw IllegalStateException("The stored request does not read") + if (judgePolicy(database, wallet.guardingChatRoomId, request) is PolicyJudgement.At) { + send(database, wallet.guardingChatRoomId, request) + sponsorIfSigner(database, wallet.guardingChatRoomId, wallet.ownerPublicKey, request) + return wallet + } + + val chain = MemberWalletRequestEvent.read(request)?.chain ?: throw IllegalStateException("The stored request does not read") + val replacement = request(database, wallet.guardingChatRoomId, memberPrivateKey, chain, wallet.label) + discard(database, wallet.walletId) + logger.i("Asked ${wallet.guardingChatRoomId} again for a new wallet in place of ${wallet.walletId.take(8)}") + return replacement + } + + /** + * Forgets [walletId]'s key. Refused once a group has certified the wallet: + * from then on its addresses may have been paid. Before, none was ever + * offered, so no coin can be behind the key. + */ + suspend fun discard(database: BennuDatabase, walletId: String) { + val wallet = database.memberWalletDao().getById(walletId) ?: return + check(certificatesOf(database, wallet.guardingChatRoomId).none { it.walletId == walletId }) { + "A group guards this wallet: its key is not discarded" + } + database.memberWalletDao().delete(walletId) + } + + /** The request into [chatRoomId], whole, as an inner event's content: see `MemberWalletRequestEvent`. */ + private suspend fun send(database: BennuDatabase, chatRoomId: String, request: Event) { + queue( + database = database, + chatRoomId = chatRoomId, + userPublicKey = request.pubKey, + tags = arrayOf(arrayOf("h", chatRoomId.lowercase())), + content = request.toJson(), + kind = MemberWalletRequestEvent.KIND, + ) + } + + private suspend fun sponsorIfSigner(database: BennuDatabase, chatRoomId: String, memberPublicKey: HexKey, request: Event) { + if (!FrostSigningManager.canSign(database, chatRoomId)) return + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return + runCatching { putToGroup(database, room, memberPublicKey, request) } + .onFailure { logger.w("Asked $chatRoomId, and could not put it to the group: ${it.message}") } + } + + /** Where a member's wallet has got to, as one fact the profile shows. */ + enum class WalletState { + /** A key and a request here; nobody has put it to the group yet. */ + ASKED, + + /** A session is running over its certificate. */ + SIGNING, + + /** The session failed or was declined, and the group has not certified it. */ + NOT_SIGNED, + + /** Certified, and the key is on this device. */ + OPEN, + + /** Certified, and the key is on another device of this profile's. */ + WATCH_ONLY, + } + + /** One of a member's guarded wallets, as their profile lists it. */ + data class MemberWalletRow( + val walletId: String, + val groupChatRoomId: String, + /** The guarding group's room on this device, or null when this device is not in it. */ + val groupRoom: LocalChatRoom?, + val label: String?, + val chain: Chain, + /** The account the wallet opens: rederived from the request, guardians and all. */ + val account: GroupWalletDerivation.Account, + val state: WalletState, + /** Whether the member is still a member of the guarding group, as far as this device can see. */ + val isMember: Boolean, + /** The stored key's row, for a wallet whose key is here. Never handed to a screen. */ + internal val stored: MemberWallet?, + /** + * Why the group would refuse this wallet's request as it stands, for one + * not yet guarded -- [judgePolicy] -- or null when it would not. Asking + * again then makes a new request. `docs/member-wallet-delay.md`. + */ + val refusedBecause: Why? = null, + ) { + val isCertified: Boolean get() = state == WalletState.OPEN || state == WalletState.WATCH_ONLY + } + + /** + * Every guarded wallet of [ownerPublicKey]'s this device knows about, newest + * first: the ones whose key is here, and the ones a group this device is in + * has certified for this profile -- which includes wallets made on another + * of its devices. + */ + suspend fun walletsOf(database: BennuDatabase, ownerPublicKey: HexKey): List { + val stored = database.memberWalletDao().getByOwner(ownerPublicKey) + val certified = database.groupSignedEventDao().getByKind(MemberWalletCertificateEvent.KIND) + .filter { MemberWalletCertificateEvent.memberOf(it.toEvent()).equals(ownerPublicKey, ignoreCase = true) } + .mapNotNull { MemberWalletCertificateEvent.verify(it.toEvent(), it.chatRoomId) } + .distinctBy { it.walletId } + .associateBy { it.walletId } + + val fromKeys = stored.mapNotNull { wallet -> + val request = Event.fromJsonOrNull(wallet.requestJson) ?: return@mapNotNull null + val verified = MemberWalletRequestEvent.verified(request) ?: return@mapNotNull null + val state = when { + certified.containsKey(wallet.walletId) -> WalletState.OPEN + openSessionFor(database, wallet.guardingChatRoomId, request) != null -> WalletState.SIGNING + wasNotSigned(database, wallet.guardingChatRoomId, request) -> WalletState.NOT_SIGNED + else -> WalletState.ASKED + } + row(database, wallet.walletId, wallet.guardingChatRoomId, wallet.label, verified.account, state, ownerPublicKey, wallet) + .let { row -> + if (row.isCertified) row + else row.copy(refusedBecause = (judgePolicy(database, wallet.guardingChatRoomId, request) as? PolicyJudgement.Refused)?.why) + } + } + val elsewhere = certified.values + .filter { cert -> stored.none { it.walletId == cert.walletId } } + .map { row(database, it.walletId, it.groupChatRoomId, it.label, it.account, WalletState.WATCH_ONLY, ownerPublicKey, null) } + + return (fromKeys + elsewhere).sortedByDescending { it.stored?.createdAt?.epochSeconds ?: 0L } + } + + private suspend fun row( + database: BennuDatabase, + walletId: String, + groupChatRoomId: String, + label: String?, + account: GroupWalletDerivation.Account, + state: WalletState, + ownerPublicKey: HexKey, + stored: MemberWallet?, + ): MemberWalletRow { + val room = database.chatRoomDao().findChatRoomById(groupChatRoomId) + val isMember = room == null || database.participantDao().findParticipantsByChatRoomId(groupChatRoomId) + .any { it.participantPublicKey.equals(ownerPublicKey, ignoreCase = true) } + return MemberWalletRow(walletId, groupChatRoomId, room, label, account.chain, account, state, isMember, stored) + } + + /** [ownerPublicKey]'s wallet [walletId], or null when this device knows of none. */ + suspend fun walletOf(database: BennuDatabase, ownerPublicKey: HexKey, walletId: String): MemberWalletRow? = + walletsOf(database, ownerPublicKey).firstOrNull { it.walletId == walletId } + + /** + * [walletId]'s descriptors with its private key in them, or null when the key + * is not on this device. See `MemberWalletDerivation.privateDescriptors`. + */ + suspend fun exportKey(database: BennuDatabase, ownerPublicKey: HexKey, walletId: String): Pair? { + val row = walletOf(database, ownerPublicKey, walletId) ?: return null + val key = row.stored?.walletPrivateKey?.let { PrivateKey.fromHex(it) } ?: return null + return MemberWalletDerivation.privateDescriptors(key, row.account) + } + + /** + * Signs [psbt] as [walletId]'s own key and files the spend, returning the + * finished transaction for the caller to broadcast. + * + * Checked the way a group member checks a group spend -- `GroupSpend.check` + * against the account the wallet rederives to, never against the PSBT's own + * claims -- because the builder is shared and so are its mistakes; and then + * `correctlySpends`, the last word on whether the network will take it. + * + * @throws IllegalStateException when the key is not here, the wallet is not + * certified, the spend fails a check or is over the cap + */ + suspend fun signSpend(database: BennuDatabase, ownerPublicKey: HexKey, walletId: String, psbt: Psbt, at: Instant = Clock.System.now()): Transaction { + val row = walletOf(database, ownerPublicKey, walletId) ?: throw IllegalStateException("No such wallet") + check(row.state == WalletState.OPEN) { "Only a certified wallet whose key is here can spend" } + val key = PrivateKey.fromHex(checkNotNull(row.stored).walletPrivateKey) + + val checked = when (val result = GroupSpend.check(psbt, row.account, GroupSpend.Spender.Owner)) { + is GroupSpend.Result.Ok -> result.checked + is GroupSpend.Result.Refused -> throw IllegalStateException("This spend ${result.reason}") + } + GroupWalletRollout.memberCapFor(row.chain)?.let { cap -> + check(checked.amountSent <= cap) { "This spend sends more than the ${cap.sat} sats one spend may send on mainnet" } + } + + val signed = checked.witnessed(checked.inputs.map { MemberWalletDerivation.sign(key, row.chain, it) }) + signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + + database.memberWalletDao().upsertSpend( + MemberWalletSpend( + txid = signed.txid.toString(), + walletId = walletId, + psbt = GroupSpend.encode(psbt), + signedTransaction = Hex.encode(Transaction.write(signed)), + createdAt = at, + ) + ) + logger.i("Signed ${signed.txid} from wallet ${walletId.take(8)}") + return signed + } + + /** + * Files what the chain said of [txid]: handed to Electrum at [broadcastAt], + * and -- with [confirmations] non-null -- seen, and confirmed once it is at + * least one deep. + */ + suspend fun recordChain(database: BennuDatabase, txid: String, confirmations: Int?, broadcastAt: Instant? = null, at: Instant = Clock.System.now()) { + val spend = database.memberWalletDao().getSpend(txid) ?: return + val updated = spend.copy( + broadcastAt = broadcastAt ?: spend.broadcastAt, + seenAt = spend.seenAt ?: at.takeIf { confirmations != null }, + confirmedAt = spend.confirmedAt ?: at.takeIf { (confirmations ?: 0) >= 1 }, + ) + if (updated != spend) database.memberWalletDao().upsertSpend(updated) + } + + // ---- The group's side ------------------------------------------------ + + /** + * Every certificate [chatRoomId] holds that verifies as its own: the member + * wallets this group guards, newest first. One per wallet -- the `d` tag makes + * two certificates for one wallet replacements, and they say the same thing. + */ + suspend fun certificatesOf(database: BennuDatabase, chatRoomId: String): List = + database.groupSignedEventDao() + .getByChatRoomIdAndKind(chatRoomId, MemberWalletCertificateEvent.KIND) + .mapNotNull { MemberWalletCertificateEvent.verify(it.toEvent(), chatRoomId) } + .sortedByDescending { it.certificate.createdAt } + .distinctBy { it.walletId } + + /** + * Every request a member has put into [chatRoomId] that checks out and asks + * this room, newest first, one per wallet. + */ + suspend fun requestsIn(database: BennuDatabase, chatRoomId: String): List = + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(MemberWalletRequestEvent.KIND)) + .mapNotNull { MemberWalletRequestEvent.carried(it.asEvent()) } + .mapNotNull { MemberWalletRequestEvent.verified(it) } + .filter { it.reading.groupChatRoomId.equals(chatRoomId, ignoreCase = true) } + .sortedByDescending { it.request.createdAt } + .distinctBy { it.reading.walletId } + + /** + * The event id a certificate for [request] signed in [chatRoomId] will have. + * The room's id is the author, and the request fixes everything else -- which + * is what lets two sponsors find each other's session. + */ + fun certificateIdFor(chatRoomId: String, request: Event): HexKey { + val template = MemberWalletCertificateEvent.template(request) + return EventHasher.hashId(chatRoomId.lowercase(), template.createdAt, template.kind, template.tags, template.content) + } + + /** The session open in [chatRoomId] over [request]'s certificate, if one is still running. */ + suspend fun openSessionFor(database: BennuDatabase, chatRoomId: String, request: Event): FrostSigningSession? { + val certificateId = certificateIdFor(chatRoomId, request) + return database.frostSigningSessionDao().getSessionsForChatRoom(chatRoomId) + .filter { it.stage != FrostSigningStage.FAILED && it.stage != FrostSigningStage.COMPLETE } + .firstOrNull { session -> database.frostSigningSessionDao().getItems(session.id).any { it.eventId == certificateId } } + } + + /** Whether the latest session over [request]'s certificate in [chatRoomId] failed -- declined, or abandoned. */ + suspend fun wasNotSigned(database: BennuDatabase, chatRoomId: String, request: Event): Boolean { + val certificateId = certificateIdFor(chatRoomId, request) + val sessions = database.frostSigningSessionDao().getSessionsForChatRoom(chatRoomId) + .filter { session -> database.frostSigningSessionDao().getItems(session.id).any { it.eventId == certificateId } } + return sessions.isNotEmpty() && sessions.all { it.stage == FrostSigningStage.FAILED } + } + + /** + * The requests in [chatRoomId] still waiting for somebody to put them to the + * group: no certificate for the wallet, and no session running over one. + */ + suspend fun awaitingSponsor(database: BennuDatabase, chatRoomId: String): List { + val certified = certificatesOf(database, chatRoomId).map { it.walletId }.toSet() + return requestsIn(database, chatRoomId) + .filter { it.reading.walletId !in certified } + .filter { openSessionFor(database, chatRoomId, it.request) == null } + } + + /** + * Why [chatRoomId], signing as [thresholdPublicKey], should not sign a + * proposed member wallet [certificate] -- or null when it may. + * + * The check every signer makes before agreeing to guard a member's wallet, + * refused before anything is shown, for the reason a mismatched id is: + * + * - it is not exactly the certificate the request it carries asks for, or + * the request does not check out, or it asked another group; + * - the person asking is not a member of this room; + * - its guardians are not the ones this group grants: `SubgroupManager.grantFor` + * with the wallet's id in a child room's place -- the same list a guarded + * subgroup of this group would get. A coordinator who slipped a key in, + * dropped an ancestor or reordered the leaves is refused here. + * + * The group's own wallet policy decides only which keys the grant carries. + * It never refuses a member's wallet: an unguarded group guards its members + * with its own key alone. `docs/member-guarded-wallets.md`, Phase 7. + * + * The group's *member-wallet* policy decides whether it guards one at all, + * and the delay on its own leaf: [judgePolicy], `docs/member-wallet-delay.md`. + */ + suspend fun refuseCertificate( + database: BennuDatabase, + chatRoomId: String, + thresholdPublicKey: HexKey, + certificate: Event, + ): String? { + val verified = MemberWalletCertificateEvent.verify(certificate, chatRoomId, signed = false) + ?: return "is not a certificate this group could have been asked for" + + val member = database.participantDao().findParticipantsByChatRoomId(chatRoomId) + .any { it.participantPublicKey.equals(verified.memberPublicKey, ignoreCase = true) } + if (!member) return "was asked by somebody who is not a member" + + val delay = when (val judged = judgePolicy(database, chatRoomId, verified.request)) { + is PolicyJudgement.Refused -> return judged.reason + is PolicyJudgement.At -> judged.delay + } + + val expected = runCatching { SubgroupManager.grantFor(database, chatRoomId, thresholdPublicKey, verified.walletId, delay) }.getOrNull() + ?: return "grants keys this device cannot check" + return if (verified.account.guardians == expected) null else "grants guardian keys this group does not" + } + + /** What a signer makes of the policy a request was built under: the delay to judge it at, or why not. */ + sealed interface PolicyJudgement { + data class At(val delay: Long) : PolicyJudgement + data class Refused(val reason: String, val why: Why) : PolicyJudgement + } + + /** Why a request's policy will not do, said as a reason the member's screen can name. */ + enum class Why { + /** Built before policies, or under none: the group never said it guards members' wallets. */ + NO_POLICY, + + /** It carries a policy, but not an open one the group signed. */ + NOT_THE_GROUPS, + + /** The group has a newer delay; the request was built under an older one. */ + DELAY_CHANGED, + + /** The group has since stopped guarding members' wallets. */ + CLOSED, + } + + /** + * The delay [chatRoomId]'s own leaf must have in the wallet [request] asks + * for, or why the request cannot be signed -- `docs/member-wallet-delay.md`, + * D6. `held` is this device's newest policy, `carried` the one the request + * was built under: + * + * - carried, an open policy the group signed, and nothing held newer: at + * its delay. Newer than what this device holds is fine -- the group + * signed it, and this device missed it; + * - carried, but a newer open one held: stale, *asked under a delay the + * group has since changed*; + * - carried, but a newer closed one held: stale, *the group has stopped*; + * - carried and not an open policy the group signed: refused; + * - none carried: refused. A request from before policies never asked for + * the delay the group chose, or of a group that chose to guard members. + * + * Read from the request, not the certificate, so the member's screen and a + * sponsor's device can ask it before there is a certificate to check. + */ + suspend fun judgePolicy(database: BennuDatabase, chatRoomId: String, request: Event): PolicyJudgement { + val reading = MemberWalletRequestEvent.read(request) + ?: return PolicyJudgement.Refused("is not a request this group could have been asked", Why.NOT_THE_GROUPS) + val carried = reading.policy + ?: return PolicyJudgement.Refused("does not say the group guards members' wallets", Why.NO_POLICY) + val open = MemberWalletPolicyEvent.verify(carried, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open + ?: return PolicyJudgement.Refused("carries a policy this group did not sign open", Why.NOT_THE_GROUPS) + + val held = policyFor(database, chatRoomId) + if (held != null && MemberWalletPolicyEvent.ORDER.compare(held, open) > 0) { + return when (held) { + is MemberWalletPolicyEvent.Policy.Open -> + PolicyJudgement.Refused("was asked under a delay the group has since changed", Why.DELAY_CHANGED) + is MemberWalletPolicyEvent.Policy.Closed -> + PolicyJudgement.Refused("was asked of a group that has since stopped guarding members' wallets", Why.CLOSED) + } + } + return PolicyJudgement.At(open.delay) + } + + /** + * Puts [request] to [groupRoom]'s quorum, as [userPublicKey]: a signing + * session over the certificate the request determines, which this device's + * proposing counts as approving. Returns the session already running over it + * instead, when another signer got there first. + * + * @throws IllegalStateException when the wallet is already certified, or this + * device would refuse the certificate itself -- a quorum should never be asked + * for what the proposer's own device knows is wrong. + */ + suspend fun putToGroup(database: BennuDatabase, groupRoom: LocalChatRoom, userPublicKey: HexKey, request: Event): FrostSigningSession { + val chatRoomId = groupRoom.chatRoom.id + val reading = MemberWalletRequestEvent.verified(request)?.reading + ?: throw IllegalStateException("This request does not check out") + check(certificatesOf(database, chatRoomId).none { it.walletId == reading.walletId }) { "This group already guards that wallet" } + openSessionFor(database, chatRoomId, request)?.let { return it } + + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) + ?: throw IllegalStateException("This group has no shared key to sign with") + val template = MemberWalletCertificateEvent.template(request) + val unsigned = Event(certificateIdFor(chatRoomId, request), chatRoomId.lowercase(), template.createdAt, template.kind, template.tags, template.content, "") + refuseCertificate(database, chatRoomId, thresholdPublicKey, unsigned)?.let { reason -> + throw IllegalStateException("This group would refuse it: it $reason") + } + + logger.i("Putting ${reading.memberPublicKey.take(8)}'s wallet ${reading.walletId.take(8)} to $chatRoomId") + return FrostSigningManager.proposeSigning( + database = database, + localChatRoom = groupRoom, + userPublicKey = userPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + createdAt = template.createdAt, + ) + } + + // ---- Shown from the group, and from the person ----------------------- + + /** A member's wallet as the guarding group's page lists it: certified, or asked for and not yet put to the group. */ + data class GroupMemberWallet( + val walletId: String, + val ownerPublicKey: HexKey, + /** The member's profile name on this device, or null. */ + val ownerName: String?, + val label: String?, + val request: Event, + val isCertified: Boolean, + ) + + /** + * The member wallets [chatRoomId] guards, and the requests still waiting for + * a signer to put them to it -- the group's page's *Members' guarded + * wallets*, which is never mixed into its subgroups: a row there is a + * person, not a room. + */ + suspend fun memberWalletsOf(database: BennuDatabase, chatRoomId: String): List { + suspend fun nameOf(publicKey: HexKey) = database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() + val certified = certificatesOf(database, chatRoomId).map { + GroupMemberWallet(it.walletId, it.memberPublicKey, nameOf(it.memberPublicKey), it.label, it.request, isCertified = true) + } + val waiting = awaitingSponsor(database, chatRoomId).map { + GroupMemberWallet(it.reading.walletId, it.reading.memberPublicKey, nameOf(it.reading.memberPublicKey), it.reading.label, it.request, isCertified = false) + } + return certified + waiting + } + + /** + * Every guarded wallet of [ownerPublicKey]'s that a group [viewerPublicKey] + * is in on this device guards, as that group holds it -- the person's page's *Wallets your + * groups guard*. One entry per guarding group: a wallet guarded by a group + * and its parent, both here, is two ways in, each spending through its own + * leaf. + */ + suspend fun guardedByGroupsHere(database: BennuDatabase, viewerPublicKey: HexKey, ownerPublicKey: HexKey): List = + database.chatRoomDao().getChatRoomListByUserPublicKey(viewerPublicKey) + .filter { it.chatRoom.mlsGroupState != null } + .flatMap { room -> + val wallets = runCatching { GuardianManager.guardedWalletsOf(database, room.chatRoom.id) }.getOrDefault(emptyList()) + .filter { (it.subject as? GuardianManager.GuardedSubject.Member)?.ownerPublicKey.equals(ownerPublicKey, ignoreCase = true) } + if (wallets.isEmpty()) return@flatMap emptyList() + val canSpend = FrostSigningManager.canSign(database, room.chatRoom.id) + wallets.map { GuardedHere(it, room.chatRoom.subject?.takeIf { name -> name.isNotBlank() }, canSpend) } + } + + /** A member's wallet as one of the guarding groups on this device holds it. */ + data class GuardedHere( + val wallet: GuardianManager.GuardedWallet, + /** + * The holding group's room name here -- the group with a leaf in it, which + * is not always the one that directly guards it: that is + * `GuardedSubject.Member.guardianName`. + */ + val holderName: String?, + /** Whether this device holds a share of that group's key, and so can propose a spend through its leaf. */ + val canSpend: Boolean, + ) + + /** + * One of a member's wallets on their page, with every group here that holds + * a leaf in it -- `docs/member-wallet-guarding-group.md`, D7. The page used to + * draw a row per holder, so a wallet held by a group and its parent appeared + * twice, each row calling its holder the guardian. + */ + data class GuardedHereWallet( + val walletId: String, + val label: String?, + /** The group that directly guards it, as any holder here can name it, or null. */ + val guardianName: String?, + /** Where no holder can name it: a group it is known to sit below, or null. */ + val below: String?, + /** The groups here holding a leaf in it, nearest first. */ + val holders: List, + ) + + /** [rows] -- one per holding group, as [guardedByGroupsHere] gives them -- as one entry per wallet. */ + fun byWallet(rows: List): List = + rows.groupBy { it.wallet.descendantChatRoomId.lowercase() }.map { (_, held) -> + val holders = held.sortedBy { it.wallet.position } + val members = holders.mapNotNull { it.wallet.subject as? GuardianManager.GuardedSubject.Member } + GuardedHereWallet( + walletId = holders.first().wallet.descendantChatRoomId, + label = members.firstNotNullOfOrNull { it.label }, + guardianName = members.firstNotNullOfOrNull { it.guardianName }, + // The nearest holder's own child it sits under, or the holder + // itself: either is a group it is truly below. + below = holders.firstNotNullOfOrNull { holder -> + (holder.wallet.subject as? GuardianManager.GuardedSubject.Member)?.branchName ?: holder.holderName?.takeUnless { holder.wallet.isGuardedHere } + }, + holders = holders, + ) + } + + private suspend fun noticesIn(database: BennuDatabase, chatRoomId: String): List = + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(GroupKeyNoticeEvent.KIND)) + .map { it.asEvent() } + + /** + * A stored inner event as the event it was, unsigned: an inner event's + * authority is the MLS frame it arrived in, not a signature, so `sig` is + * empty here as it is everywhere inner events are read back. + */ + internal fun MarmotInnerEvent.asEvent(): Event = + Event(id = id, pubKey = publicKey, createdAt = createdAt.epochSeconds, kind = kind, tags = tags, content = content, sig = "") + + /** + * Queues one inner event in [chatRoomId] for the outbound pipeline, the way + * every inner event is: a row, which `encryptAndSendMarmotInnerEvent` sends. + */ + internal suspend fun queue( + database: BennuDatabase, + chatRoomId: String, + userPublicKey: HexKey, + tags: Array>, + content: String, + kind: Int = GroupKeyNoticeEvent.KIND, + createdAt: Instant = Clock.System.now(), + ): HexKey { + val id = EventHasher.hashId(userPublicKey, createdAt.epochSeconds, kind, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = userPublicKey, + kind = kind, + createdAt = createdAt, + tags = tags, + content = content, + chatRoomId = chatRoomId, + ) + ) + return id + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt index c6bee971..21f14eb4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.database.model.subgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.isDecided +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -193,6 +198,21 @@ object SubgroupManager { * A session of one, never batched, for the reason `GroupKeyStateManager.propose` * gives: a batch is only as available as its worst item, and everything after * this depends on it. + * + * The wallet policy comes off [key], the child's ceremony, where the picker + * put it and every admin was shown it -- never from a caller, for the reason + * the key does not. `docs/subgroup-wallet-policy.md`: + * + * | ceremony's policy | parent's own | certificate | + * |-------------------|---------------------|-------------------------------| + * | guarded | any | the grant, `guarded` | + * | unguarded | not guarded | no keys, `unguarded` | + * | unguarded | guarded | refused: D4 | + * | none (older) | not guarded | the grant, no policy -- today | + * | none (older) | guarded | the grant, `guarded` | + * + * @throws IllegalStateException for an unguarded ceremony under a guarded + * parent, with the reason and the remedy */ suspend fun proposeBirthCertificate( database: BennuDatabase, @@ -229,6 +249,45 @@ object SubgroupManager { "$parentChatRoomId has already certified $subgroupChatRoomId" } + // What the child's wallet is to be. A guarded parent can only make guarded + // subgroups, and every one of its signers refuses anything else -- so an + // unguarded ceremony under one is stranded, and proposing it would only + // spend a quorum's attention. It is not quietly certified as guarded + // instead: its admins joined on the understanding it would not be, and + // every child signer refuses a certificate that says otherwise. An older + // build's ceremony carried no policy and showed its admins none, so under + // a guarded parent the certificate says the only thing its signers accept. + val parentGuarded = walletPolicyOf(database, parentChatRoomId).isDecided(SubgroupWalletPolicy.GUARDED) + val walletPolicy = when (key.subgroupWalletPolicy) { + SubgroupWalletPolicy.UNGUARDED -> { + check(!parentGuarded) { + "This group is guarded, so its subgroups are too. Start the subgroup again: " + + "its admins joined it as unguarded." + } + SubgroupWalletPolicy.UNGUARDED + } + SubgroupWalletPolicy.GUARDED -> SubgroupWalletPolicy.GUARDED + null -> SubgroupWalletPolicy.GUARDED.takeIf { parentGuarded } + } + + // The parent's guardian keys for the child: its own, and the ones its + // ancestors granted it -- or none, for an unguarded child, whose + // certificate then grants nothing to it or to anything beneath it. Every + // signer recomputes this list and refuses a certificate carrying any + // other -- see [refuseCertificate]. + val guardians = if (walletPolicy == SubgroupWalletPolicy.UNGUARDED) { + emptyList() + } else { + val parentKey = FrostSigningManager.completedKey(database, parentChatRoomId)?.thresholdPublicKey + ?: throw IllegalStateException("$parentChatRoomId has no key to grant a guardian key under") + // The parent's own leaf's delay as its coordinator chose it, or the + // default an older build's ceremony would have written. Every + // inherited key keeps the delay its own ancestor chose. + // docs/guardian-delay.md. + grantFor(database, parentChatRoomId, parentKey, subgroupChatRoomId, key.guardianDelay ?: GuardianDerivation.DEFAULT_DELAY) + ?: throw IllegalStateException("$parentChatRoomId's own certificate carries guardian keys this build cannot read") + } + logger.i("Asking $parentChatRoomId to certify $subgroupChatRoomId as its subgroup") return FrostSigningManager.proposeSigning( @@ -242,12 +301,129 @@ object SubgroupManager { thresholdPublicKey = thresholdPublicKey, adminPublicKeys = adminPublicKeys, name = subgroupName, - path = path + path = path, + guardians = guardians, + walletPolicy = walletPolicy ), content = subgroupChatRoomId ) } + /** + * The guardian keys [chatRoomId]'s own certificate grants it, nearest first: + * empty for a group with no parent, or whose certificate predates guardian + * keys -- either way it grants only its own key onward -- and null when the + * certificate carries keys this build cannot read. + * + * Off the verified key state, which only holds a certificate + * `GroupKeyStateManager.stateFrom` checked. + */ + suspend fun guardiansOf(database: BennuDatabase, chatRoomId: String): List? { + val certificate = database.groupKeyStateDao().getByChatRoomId(chatRoomId) + ?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?: return emptyList() + return SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + } + + /** + * What [chatRoomId]'s own certificate says of its wallet -- + * `docs/subgroup-wallet-policy.md` -- or null for a room with no certificate: + * a root group, or a member who holds no key state for it. + * + * Off the verified key state, like [guardiansOf]. A state whose certificate + * carries a policy that does not read is dropped before it is stored, so a + * certificate held here always reads; if one somehow does not, it is logged + * and read as none rather than guessed at. + * + * The one reader the picker, every parent signer and the wallet screen share, + * so the three cannot disagree about what a group is. + */ + suspend fun walletPolicyOf(database: BennuDatabase, chatRoomId: String): WalletPolicyReading? { + val certificate = database.groupKeyStateDao().getByChatRoomId(chatRoomId) + ?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?: return null + return SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) + ?: run { + logger.w("$chatRoomId's certificate carries a wallet policy that does not read") + null + } + } + + /** + * What [parentChatRoomId], signing as [thresholdPublicKey], grants + * [subgroupChatRoomId]: `GuardianDerivation.grant` over the keys its own + * certificate carries. Null when those cannot be read. + */ + suspend fun grantFor( + database: BennuDatabase, + parentChatRoomId: String, + thresholdPublicKey: HexKey, + subgroupChatRoomId: String, + delay: Long = GuardianDerivation.DEFAULT_DELAY + ): List? { + val inherited = guardiansOf(database, parentChatRoomId) ?: return null + return GuardianDerivation.grant(thresholdPublicKey, parentChatRoomId, inherited, subgroupChatRoomId, delay) + } + + /** + * Why [chatRoomId] should not sign a proposed certificate, or null when it + * may: its guardian keys are not the ones the group grants, or its wallet + * policy is not one the group may make. + * + * The check every parent signer makes before agreeing to guard a child, or + * to certify one unguarded. A coordinator who slipped a key of their own into + * the list, dropped an ancestor, or reordered the leaves would be asking the + * group to vouch for a wallet tree it did not make; one who certified an + * unguarded child of a guarded group would be taking a branch out of the + * reach of every group above it. Either way the proposal is refused rather + * than shown. + * + * The group's own policy is read off this device's verified key state, never + * off the proposal. Under a guarded group anything but a guarded certificate + * is refused -- an undecided one included, since an undecided child is + * offered the plain wallet D4 exists to take away. A certificate with no keys + * and no policy from an older proposer grants nothing, and is still signable + * under any other group. See `docs/subgroup-wallet-policy.md`. + */ + suspend fun refuseCertificate( + database: BennuDatabase, + chatRoomId: String, + thresholdPublicKey: HexKey, + certificate: Event + ): String? { + val proposed = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + ?: return "carries a guardian key that does not read" + val policy = SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) + ?: return "carries a wallet policy that does not read, or that its keys contradict" + + if (walletPolicyOf(database, chatRoomId).isDecided(SubgroupWalletPolicy.GUARDED) && + !policy.isDecided(SubgroupWalletPolicy.GUARDED) + ) { + return "would make an unguarded subgroup of a guarded group" + } + + // Unguarded, or an older proposer's certificate with no keys: grants + // nothing. Phase 1's read has already refused an unguarded one with keys. + if (proposed.isEmpty()) return null + + val subgroupChatRoomId = SubgroupBirthCertificateEvent.parseSubgroupChatRoomId(certificate.tags) + ?: return "names no subgroup" + // The parent's own leaf's delay is the proposal's -- the coordinator chose + // it, in range, or the tag would not have read -- and everything else is + // recomputed: the keys, their order, and every inherited key's delay, + // which has to be the one this group's own certificate carries. A + // proposer cannot shorten or lengthen an ancestor's wait in the child's + // wallet. docs/guardian-delay.md. + val expected = runCatching { + grantFor(database, chatRoomId, thresholdPublicKey, subgroupChatRoomId, proposed.first().delay) + }.getOrNull() + ?: return "grants keys this device cannot check" + + return if (proposed == expected) null else "grants guardian keys this group does not" + } + /** * The newest certificate by [parentChatRoomId] that actually certifies * [subgroupChatRoomId], or null if this device holds none. @@ -315,6 +491,12 @@ object SubgroupManager { "cannot name a parent yet" ) + // Every other child signer refuses a certificate under another policy, so + // proposing it would only stall a quorum -- see [refuseKeyState]. + refusePolicy(key, certificate.toEvent())?.let { reason -> + throw IllegalStateException("$parentChatRoomId's certificate for $subgroupChatRoomId $reason") + } + return GroupKeyStateManager.propose( database = database, localChatRoom = ceremonyRoom, @@ -328,6 +510,41 @@ object SubgroupManager { ) } + /** + * Why a child signer should not sign [keyState] under [key], its own + * ceremony, or null when it may: the birth certificate it carries decides a + * wallet policy other than the one the ceremony announced. + * + * Every admin was shown that policy at the join gate, so joining was agreeing + * to it. A certificate proposed later under another -- by a parent admin + * resuming the flow, or one whose device read the parent differently -- would + * be the child signing a decision none of its members agreed to. A ceremony + * that announced none, from an older build, has nothing to hold the + * certificate to. `docs/subgroup-wallet-policy.md`, Phase 5. + */ + fun refuseKeyState(key: DkgSession, keyState: Event): String? { + val certificate = GroupKeyStateEvent.parseBirthCertificate(keyState.tags) ?: return null + return refusePolicy(key, certificate) + } + + private fun refusePolicy(key: DkgSession, certificate: Event): String? { + val agreed = key.subgroupWalletPolicy ?: return null + val certified = SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) + if (!certified.isDecided(agreed)) { + return "carries a certificate whose wallet policy is not the one this group was made under ($agreed)" + } + + // And the delay on the parent's own leaf, which the admins were shown + // at the same gate. docs/guardian-delay.md. + val agreedDelay = key.guardianDelay ?: return null + val certifiedDelay = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)?.firstOrNull()?.delay + return if (certifiedDelay == agreedDelay) { + null + } else { + "carries a certificate whose guardian delay is not the one this group was made under ($agreedDelay blocks)" + } + } + /** * A subgroup as the parent's own record has it, plus whatever this device * happens to hold about it. @@ -351,6 +568,21 @@ object SubgroupManager { val keyState: GroupKeyState?, ) { /** Whether this device can open the subgroup, rather than only know of it. */ + /** + * What the parent decided about the subgroup's wallet when it certified + * it -- `docs/subgroup-wallet-policy.md`. Founding history like [name]: + * decided once, and never changed by anything after. + */ + val walletPolicy: WalletPolicyReading? + get() = SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) + + /** + * The delay the parent gave its own leaf in the subgroup's wallet, or + * null for a certificate that grants no keys -- `docs/guardian-delay.md`. + */ + val guardianDelay: Long? + get() = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)?.firstOrNull()?.delay + val isJoined: Boolean get() = room != null } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt deleted file mode 100644 index 83081bf8..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/TranslationScaffold.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.machankura.bennu.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent - -/** - * The rows that join a translation to the chapters it is a translation of. - * - * A translation chapter carries no words. It is `(translation, chapter, - * position)` and nothing else, and it exists so that a translated chunk has - * somewhere to hang: a translation without one for a chapter is a translation - * that chapter cannot be worked on in. - * - * Both ends of that join arrive on their own schedule -- a chapter is signed - * into an artifact that already has translations, a translation is started on - * an artifact that already has chapters -- so the same scaffolding is built - * from either side and, when the two miss each other, afterwards. One function - * for all three, because three copies of a cross product is three chances to - * disagree about what a translation covers. - */ -object TranslationScaffold { - - /** - * A source chapter, reduced to what a translation chapter needs of it: - * which chapter, and where it sits. - * - * Taken as this rather than as a [MantraChapter] because the chapter is not - * always a row yet. When a chapter is signed into an artifact, the - * scaffolding goes out in the same breath as the chapter itself, against an - * id that exists only as the unsigned event a session is about to sign. - */ - data class SourceChapter( - val id: HexKey, - val index: Int, - ) { - companion object { - fun of(chapter: MantraChapter) = SourceChapter(id = chapter.id, index = chapter.index) - } - } - - /** - * A translation chapter for every pair of [translationArtifactVersionIds] - * and [chapters], in that nesting: a translation's chapters stay together - * and in reading order. - * - * The order is the order a session will sign them in and the order they - * will be applied in, so it is fixed here rather than left to a caller. - * - * [createdAt] is stamped on all of them rather than read per event, so that - * a scaffolding proposed as one act reads as one -- the timestamp of the - * chapter or the translation that occasioned it, not of whichever moment - * each template happened to be built in. - */ - fun chaptersOf( - translationArtifactVersionIds: List, - chapters: List, - createdAt: Long, - ): List> = - translationArtifactVersionIds.flatMap { translationArtifactVersionId -> - chapters.map { chapter -> - TranslationChapterEvent.build( - translationArtifactVersionId = translationArtifactVersionId, - chapterId = chapter.id, - // The source chapter's own position, never this list's: a - // catch-up proposes a subset, so counting the list would - // renumber the chapters it happens to be filling in. - index = chapter.index, - createdAt = createdAt, - ) - } - } - - /** - * The source chapters a translation has nothing for yet. - * - * Matched on the source chapter each translation chapter names rather than - * on how many there are of each. A translation that is missing its second - * chapter and has picked up its third is not a translation that is missing - * its last one, and a count would say it was. - */ - fun chaptersMissingFrom( - translationChapters: List, - sourceChapters: List, - ): List { - val covered = translationChapters.mapTo(mutableSetOf()) { it.chapterId } - - return sourceChapters.filterNot { it.id in covered } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt deleted file mode 100644 index a6a8fd2b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.network.relays - -import kotlinx.coroutines.flow.Flow -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.network.dto.RelayDTO - -/** - * The slice of the relay layer a one-off publish needs. - * - * The same cut [LiveSubscriptionTransport] makes and for the same reason: - * [RelaysSocketManager] starts collecting relay lists in its `init` and cannot be - * stood up in a test, so a screen that hands it an event would otherwise have no - * way to check what it does with the answers. - * - * Everything the app publishes as *itself* goes through the - * `BroadcastNostrEventRequest` queue instead, which is durable and retried. This - * exists for the one thing that must not: an event the group signed. The queue - * hangs off a `NostrEvent` row, and a row for the group's event would put its post - * into the home feed and offer it to every relay the sync loop reconciles with -- - * see `BroadcastGroupSignedEventViewModel` for the whole of that argument. - */ -interface EventPublishTransport { - - /** - * Sends [nostrEvent] to each of [relays], opening a socket to any it does not - * already hold, and answers once per relay: the relay's OK, its rejection, or - * the error that stopped it being asked. - * - * @see RelayPool.publishEvent - */ - @Throws(com.machankura.bennu.compose.exceptions.NostrPublishException::class, kotlin.coroutines.cancellation.CancellationException::class) - suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt index 1c85c200..1b45855e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt @@ -32,7 +32,7 @@ class RelaysSocketManager( private val relayRepository: com.machankura.bennu.compose.repository.RelayRepository, /** Injectable so that a test can drive the identity observer on a dispatcher it controls. */ private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO), -) : LiveSubscriptionTransport, EventPublishTransport { +) : LiveSubscriptionTransport { val logger = Logger.withTag("RelaysSocketManager") private val relayPoolsMutex = Mutex() @@ -116,7 +116,7 @@ class RelaysSocketManager( } @Throws(com.machankura.bennu.compose.exceptions.NostrPublishException::class, kotlin.coroutines.cancellation.CancellationException::class) - override suspend fun publishEvent(nostrEvent: com.machankura.bennu.compose.database.model.NostrEvent, relays: Set): Flow { + suspend fun publishEvent(nostrEvent: com.machankura.bennu.compose.database.model.NostrEvent, relays: Set): Flow { logger.d("publishEvent: $nostrEvent") return relayPool.publishEvent( nostrEvent = nostrEvent, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt deleted file mode 100644 index 8d65a414..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt +++ /dev/null @@ -1,177 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.network.serialization.CommonJson -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.intOrNull - -/** - * An unsigned event a member pasted for the group to sign, read and checked - * before a quorum is asked for it. - * - * The typed editors -- the profile form, the post composer, the relay - * editor -- each build one kind of event and know what it needs. This is the - * untyped way in: the event as JSON, the way another tool prints it, pasted - * whole. What comes out is the same thing the editors - * produce, a kind, tags and content for `FrostSigningRepository.proposeSigning`, - * and it is filed the same way when the quorum signs: `FrostSigningManager.complete` - * records it as a `GroupSignedEvent` and the group's screen reads its profile, - * posts and relay lists straight off those by kind. - * - * ### What is ignored - * - * `id`, `pubkey`, `sig` and `created_at`. The group is the author -- the - * session resolves the room's key and hashes the id over it -- and the time is - * when the session opens, which is what every typed editor does too. A pasted - * `created_at` in particular has to go: the kinds here are replaceable or - * addressable, so a stale one would make the new event *older* than the last and - * the proposal would look as though it did nothing. The screen says so. - * - * ### What is refused, and why before rather than after - * - * Only kinds the group's screen has a place for, and only events that place - * would accept. A signature is the most expensive thing this app does, and the - * readers refuse rather than repair: a kind 0 whose content is not a profile - * or a blank post would each be signed, filed and shown nowhere, with nothing - * to tell the member their quorum was spent on nothing. So every check a reader makes is made here first, on the paste. - */ -object GroupEventProposal { - /** - * The kinds a pasted event may be: exactly the ones the group's screen reads. - * - * Not the kinds `ChatMessage.applyInnerEvent` has an arm for. A subgroup - * certificate or a key state event has invariants a paste cannot be trusted - * to meet and a place in the room's life that a form is not, and the - * nip30303 kinds have editors of their own. The line is "has a section on the - * group's screen", because that is where a member goes to see it landed. - */ - val ACCEPTED_KINDS: Set = - setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + GroupRelaySet.KINDS - - sealed interface Reading - - /** An event the group could sign and the screen could show. */ - class Ready( - val kind: Kind, - val tags: Array>, - val content: String, - ) : Reading { - /** - * The event as the signing screen will describe it, for a preview before - * the button is pressed. The id, author and signature are placeholders: - * `ProposedEvent.summarize` reads none of them. - */ - fun preview(): Event = Event( - id = "", - pubKey = "", - createdAt = 0, - kind = kind, - tags = tags, - content = content, - sig = "", - ) - } - - /** Why the paste cannot be proposed as it is. */ - sealed interface Refused : Reading { - data object NotJson : Refused - - /** JSON, but an array, a string, a number -- anything but an object. */ - data object NotAnObject : Refused - - data object NoKind : Refused - - data class KindNotAccepted(val kind: Kind) : Refused - - /** `tags` present but not a list of lists of strings. */ - data object TagsMalformed : Refused - - /** `content` present but not a string. */ - data object ContentNotText : Refused - - /** A kind 0 whose content will not parse as a profile. */ - data object ProfileUnreadable : Refused - - /** A kind 1 with nothing to say, which the posts reader would drop. */ - data object PostBlank : Refused - } - - private const val KEY_KIND = "kind" - private const val KEY_TAGS = "tags" - private const val KEY_CONTENT = "content" - - /** The paste as something the group could sign, or the reason it is not. */ - fun read(json: String): Reading { - val element = runCatching { CommonJson.parseToJsonElement(json) }.getOrNull() - ?: return Refused.NotJson - - val obj = element as? JsonObject ?: return Refused.NotAnObject - - // A number or a numeric string: relays write the former and a hand - // types either, and there is nothing to be gained by refusing "1". - val kind = (obj[KEY_KIND] as? JsonPrimitive)?.intOrNull ?: return Refused.NoKind - if (kind !in ACCEPTED_KINDS) return Refused.KindNotAccepted(kind) - - val tags = when (val raw = obj[KEY_TAGS]) { - null -> emptyArray() - else -> readTags(raw) ?: return Refused.TagsMalformed - } - - val content = when (val raw = obj[KEY_CONTENT]) { - null -> "" - else -> (raw as? JsonPrimitive)?.takeIf { it.isString }?.content - ?: return Refused.ContentNotText - } - - return when (kind) { - // An empty kind 0 is a profile the group has wiped, which it is - // entitled to do; content that is not JSON is not a profile at all. - // The same line `GroupNostrProfile.of` draws. - MetadataEvent.KIND -> if (metadataOf(tags, content) == null) { - Refused.ProfileUnreadable - } else { - Ready(kind, tags, content) - } - - // The line `AddGroupPostViewModel.proposePost` draws, for the reason - // it gives: a blank post cannot be told from a broken one and, kind:1 - // not being replaceable, cannot be un-said. - TextNoteEvent.KIND -> if (content.isBlank()) { - Refused.PostBlank - } else { - Ready(kind, tags, content) - } - - // A relay list with no relay in it is a list the group has withdrawn, - // which the relays card shows as "no relays" rather than as nothing. - else -> Ready(kind, tags, content) - } - } - - private fun readTags(raw: JsonElement): Array>? { - val outer = raw as? JsonArray ?: return null - - return outer.map { tag -> - val inner = tag as? JsonArray ?: return null - inner.map { value -> - (value as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull ?: return null - }.toTypedArray() - }.toTypedArray() - } - - private fun metadataOf(tags: Array>, content: String) = MetadataEvent( - id = "", - pubKey = "", - createdAt = 0, - tags = tags, - content = content, - sig = "", - ).contactMetaData() -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt deleted file mode 100644 index 011964df..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt +++ /dev/null @@ -1,196 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.time.Instant - -/** - * The kind:0 a group signed about itself, as the group signed it. - * - * A Marmot room's id *is* the nostr pubkey it signs as -- see - * `docs/shared-key-derivation.md`, where those are one value -- so the group has - * an identity on nostr whether or not it has ever said anything about it. This is - * what it says: a name, a picture, a line about what the group is for, authored by - * the group rather than by whichever member typed it. - * - * ### Why this reads off [GroupSignedEvent] and not off `Profile` - * - * A `Profile` row hangs off a `NostrEvent` by foreign key, and a group-signed - * event is not a `NostrEvent`: no member sent it, it never travelled on the wire - * as itself, and the outbound pipeline would re-author it as its sender and strip - * the group's signature off. See `GroupSignedEvent`, which exists for exactly the - * events in that position. So the group's profile lives where the group's other - * signed statements live, and this is the reading of it. - * - * The consequence worth stating: **nothing here reaches a relay by being signed.** - * A member's kind:0 is published and is how the rest of nostr learns their name; a - * group's is signed and kept, and every device that followed the signing session - * -- or was handed the event afterwards -- holds it. It reaches a relay when a - * member sends it there from `BroadcastGroupSignedEventScreen`, which serialises - * the signed row directly rather than making a `NostrEvent` row for an event no - * member authored -- a decision this still does not make. - * - * ### What a reading has to earn - * - * [GroupSignedEvent.verifies] and nothing less: the author has to be the room, the - * id has to be the hash of the fields beside it, and the signature has to verify. - * That is what makes this the *group's* profile rather than a kind:0 that happened - * to be filed against the room -- and it is checkable from the row alone, with no - * ceremony or key state to consult first. - * - * A room never derived from its group's key signs as the bare threshold key rather - * than as its own id, so it has no profile *for its own pubkey* and gets none - * here. That is the derivation's limit rather than this reader's, and it is the - * same limit `GroupSignedEvent.verifies` documents. - */ -data class GroupNostrProfile( - /** The group's statement, whole, with the signature that makes it one. */ - val signedEvent: GroupSignedEvent, - /** Its content parsed: the fields nostr clients read a profile out of. */ - val metadata: UserMetadata, -) { - /** The group's nostr identity, which for a derived room is also its id. */ - val publicKey: HexKey get() = signedEvent.publicKey - - /** When the group signed it, which is what decides the newest of two. */ - val signedAt: Instant get() = signedEvent.createdAt - - /** - * What to call the group, or null when it has published no name. - * - * `display_name` before `name`, which is what `UserMetadata.anyName` does and - * what every other nostr client does. Null rather than the pubkey: a caller - * showing this beside the pubkey would otherwise show it twice. - */ - fun name(): String? = metadata.anyName()?.takeIf { it.isNotBlank() } - - fun about(): String? = metadata.about?.takeIf { it.isNotBlank() } - - fun picture(): String? = metadata.picture?.takeIf { it.isNotBlank() } - - fun banner(): String? = metadata.banner?.takeIf { it.isNotBlank() } - - fun website(): String? = metadata.website?.takeIf { it.isNotBlank() } - - fun nip05(): String? = metadata.nip05?.takeIf { it.isNotBlank() } - - fun lud16(): String? = metadata.lud16?.takeIf { it.isNotBlank() } - - /** The event as the group signed it, for [MetadataEvent.updateFromPast]. */ - fun asMetadataEvent(): MetadataEvent = signedEvent.toEvent().let { event -> - MetadataEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - } - - companion object { - /** - * The reading of one signed event, or null when it is not one of these. - * - * Three ways to be null and they are all the same refusal: the wrong kind, - * a signature that does not check out as [chatRoomId]'s, or content that - * will not parse as a profile. A caller gets a profile the group really - * signed or gets nothing. - */ - fun of(signedEvent: GroupSignedEvent, chatRoomId: String): GroupNostrProfile? { - if (signedEvent.kind != MetadataEvent.KIND) return null - if (!signedEvent.verifies()) return null - - // An empty kind:0 parses to an empty profile rather than to null -- - // wiping a profile is a thing groups are entitled to do, and quartz - // reads it as the blank one it is. Null here is a parse failure. - val metadata = MetadataEvent( - id = signedEvent.id, - pubKey = signedEvent.publicKey, - createdAt = signedEvent.createdAt.epochSeconds, - tags = signedEvent.tags, - content = signedEvent.content, - sig = signedEvent.signature, - ).contactMetaData() ?: return null - - return GroupNostrProfile(signedEvent = signedEvent, metadata = metadata) - } - - /** - * The newest profile [chatRoomId] signed among [signedEvents], or null if - * it signed none. - * - * Newest by the timestamp the group signed at, with the id breaking a tie, - * because kind:0 is replaceable: a group that edits its profile signs a - * second one and the second is the answer. Two devices reading the same - * events in whatever order the queries hand them over have to agree on - * which, and a tie on the second is not rare enough to leave to luck. - * - * Takes the events rather than fetching them so the same question can be - * asked of a query's result or of a flow's emission. - */ - fun newestAmong( - signedEvents: List, - chatRoomId: String, - ): GroupNostrProfile? = - signedEvents - .asSequence() - .mapNotNull { of(it, chatRoomId) } - .maxWithOrNull( - compareBy({ it.signedAt }, { it.signedEvent.id }) - ) - - /** - * The event to ask the group to sign for a profile with these fields. - * - * Built from [latest] where the group has one, so a field this app does not - * offer -- a birthday, a CLINK offer, whatever a future NIP adds -- survives - * an edit instead of being dropped by it. That is `updateFromPast`'s whole - * job, and reaching for `createNew` on a group that already has a profile - * would quietly wipe every such field. - * - * Blank means delete, which is `MetadataEvent`'s own rule for these - * arguments: an empty string removes the key and null leaves it alone. The - * screen sends what its fields hold, so clearing one clears it in the - * profile -- which is the only way to *un*-say something a group has said. - * - * [name] is written to both `name` and `display_name`, which are the two - * fields readers pick a name out of and which disagree at their peril. A - * group whose `display_name` was set by some other tool and whose `name` was - * edited here would keep answering to the old one in every client that - * prefers `display_name` -- an edit that visibly does not take. One field on - * the form, both keys in the event. - */ - fun template( - latest: GroupNostrProfile?, - name: String, - about: String, - picture: String, - website: String, - nip05: String, - lud16: String, - ): EventTemplate = latest?.let { - MetadataEvent.updateFromPast( - latest = it.asMetadataEvent(), - name = name, - displayName = name, - about = about, - picture = picture, - website = website, - nip05 = nip05, - lnAddress = lud16, - ) - } ?: MetadataEvent.createNew( - name = name, - displayName = name, - about = about, - picture = picture, - website = website, - nip05 = nip05, - lnAddress = lud16, - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt deleted file mode 100644 index a21ad3c8..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt +++ /dev/null @@ -1,121 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import kotlin.time.Instant - -/** - * A kind:1 the group signed: something it said publicly, as itself. - * - * The room's id is the pubkey it signs as, so a note authored by that key is the - * *group* posting rather than a member posting in the group. Those are different - * things and the room already has the second one -- the transcript. This is the - * first: a statement the group put a quorum's signature to, which any reader can - * check came from the group and not from whoever typed it. - * - * ### Why this is not a `Post` row - * - * `Post` hangs off both `NostrEvent` and `Profile` by foreign key, and a group has - * neither: a group-signed event is not a `NostrEvent` -- see `GroupNostrProfile`, - * which gives the reasoning at length -- and the group has no `Profile` row for the - * same reason. So a group's posts live where the group's other signed statements - * live, and this is the reading of them. - * - * ### Nothing here has reached a relay - * - * The same caveat `GroupNostrProfile` and `GroupRelayList` carry, and it bites - * hardest here: a post is the one kind of statement whose entire purpose is to be - * read by people outside the group. `FrostSigningManager.complete` applies signed - * events locally and puts nothing on the wire, so for now a group's posts are - * visible to its members and to nobody else. The relay lists beside them say where - * they should go; sending them is a job that does not exist yet. - */ -data class GroupPost( - /** The group's statement, whole, with the signature that makes it one. */ - val signedEvent: GroupSignedEvent, -) { - /** The group's nostr identity, which for a derived room is also its id. */ - val publicKey: HexKey get() = signedEvent.publicKey - - /** When the group signed it, which is the order posts are read in. */ - val postedAt: Instant get() = signedEvent.createdAt - - /** What the group said. */ - val content: String get() = signedEvent.content - - /** - * Whether this is the group speaking rather than answering. - * - * A kind:1 with no `e` tag starts a thread; one with them is a reply. Nothing - * here writes a reply yet -- the composer builds a bare note -- so this exists - * to keep an imported or chronicled reply from being drawn as an announcement. - */ - fun isNewThread(): Boolean = asTextNoteEvent().isNewThread() - - /** The event as the group signed it. */ - fun asTextNoteEvent(): TextNoteEvent = signedEvent.toEvent().let { event -> - TextNoteEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - } - - companion object { - /** - * The reading of one signed event, or null when it is not one of these. - * - * The same gate the profile and the relay lists use: the wrong kind, or a - * signature that does not check out as [chatRoomId]'s, and a caller gets - * nothing. A kind:1 a member sent into the room is that member's note, not - * the group's, and fails on the author. - */ - fun of(signedEvent: GroupSignedEvent, chatRoomId: String): GroupPost? { - if (signedEvent.kind != TextNoteEvent.KIND) return null - if (!signedEvent.verifies()) return null - - return GroupPost(signedEvent) - } - - /** - * Every post [chatRoomId] signed among [signedEvents], newest first. - * - * Newest first because that is how a feed is read, and the id breaks a tie - * so two devices holding the same posts show them in the same order. Unlike - * a profile or a relay list these accumulate rather than replace: kind:1 is - * not replaceable, so a second post stands beside the first. - * - * Blank posts are dropped. A signed note with nothing in it renders as an - * empty card that cannot be told from a broken one, and the composer will - * not produce one -- so anything that reaches here empty came from - * somewhere this app does not control. - */ - fun newestFirstAmong( - signedEvents: List, - chatRoomId: String, - ): List = - signedEvents - .mapNotNull { of(it, chatRoomId) } - .filter { it.content.isNotBlank() } - .sortedWith(compareByDescending { it.postedAt }.thenByDescending { - it.signedEvent.id - }) - - /** - * The event to ask the group to sign for a post saying [note]. - * - * A bare kind:1: no reply tags, no mentions, no subject. What the group is - * doing here is speaking, and every tag `TextNoteEvent.build` can add - * describes a relationship to something else -- a thread to reply into, a - * pubkey to notify -- which a group's first way of posting does not have - * and should not guess at. - */ - fun template(note: String): EventTemplate = - TextNoteEvent.build(note = note.trim()) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt deleted file mode 100644 index ec817e28..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt +++ /dev/null @@ -1,279 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.isLocalHost -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent -import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent -import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent -import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent -import com.vitorpamplona.quartz.nip65RelayList.tags.AdvertisedRelayInfo -import com.vitorpamplona.quartz.nip65RelayList.tags.AdvertisedRelayType -import kotlin.time.Instant -import com.vitorpamplona.quartz.nip51Lists.relayLists.tags.RelayTag as Nip51RelayTag -import com.vitorpamplona.quartz.nip17Dm.settings.tags.RelayTag as Nip17RelayTag - -/** - * Where a group lives on nostr, as the group itself has said. - * - * A Marmot room's id is the pubkey it signs as, so the group is an author like any - * other and the same four relay lists apply to it: where it publishes and is read - * from, where its messages arrive, where it can be searched for, and what it will - * not talk to. Each is a replaceable event of its own kind, so each is agreed -- - * and can be missing -- separately. - * - * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies], for the - * reasons `GroupNostrProfile` gives at length: a group-signed event is not a - * `NostrEvent`, and only an event the room itself authored is the group speaking. - * - * ### Nothing here reaches a relay by being signed - * - * The lists say where the group's work *should* go; sending it there is a separate - * act, taken by a member one event at a time from `BroadcastGroupSignedEventScreen`, - * and the General list is what that screen fills its relay picker from. See - * `GroupNostrProfile`, which carries the same caveat for the same reason. - * - * ### Public tags only, and not by preference - * - * NIP-51 puts a relay list's entries in the encrypted half by default -- a blocked - * list especially, since who you refuse to talk to is nobody's business. A group - * cannot use it. The encryption is NIP-44 to the author's own key, and there is no - * ECDH for a FROST threshold key here: the group can sign and cannot decrypt. So - * every list is written in public tags, which is a real difference from what a - * person's client would write and is worth knowing before blocking anything. - */ -data class GroupRelayList( - val set: GroupRelaySet, - /** - * The group's statement, or null for a set it has never agreed. - * - * Null and an empty [relays] are different states: never said, versus said and - * said nothing. A group that signs an empty list has withdrawn the one it had. - */ - val signedEvent: GroupSignedEvent?, - val relays: List, -) { - /** When the group signed it, or null for a set it has never agreed. */ - val signedAt: Instant? get() = signedEvent?.createdAt - - /** Whether the group has ever put its key to this set. */ - val isAgreed: Boolean get() = signedEvent != null - - companion object { - /** - * The reading of one signed event as [set], or null when it is not one. - * - * The same three refusals as `GroupNostrProfile.of`: the wrong kind, a - * signature that is not [chatRoomId]'s, or tags that carry no relay. - */ - fun of( - signedEvent: GroupSignedEvent, - chatRoomId: String, - set: GroupRelaySet, - ): GroupRelayList? { - if (signedEvent.kind != set.kind) return null - if (!signedEvent.verifies()) return null - - return GroupRelayList( - set = set, - signedEvent = signedEvent, - relays = set.parse(signedEvent.tags), - ) - } - - /** - * The newest list [chatRoomId] signed for [set] among [signedEvents]. - * - * Never null: a set the group has never agreed reads back as an unsigned, - * empty list rather than as an absence, so a caller always has a row per - * set to show and [isAgreed] is what separates the two. - * - * Newest by the group's own timestamp with the id breaking a tie, for the - * reason `GroupNostrProfile.newestAmong` gives: these are replaceable, and - * two devices reading the same events in different orders have to agree. - */ - fun newestAmong( - signedEvents: List, - chatRoomId: String, - set: GroupRelaySet, - ): GroupRelayList = - signedEvents - .asSequence() - .mapNotNull { of(it, chatRoomId, set) } - .maxWithOrNull(compareBy({ it.signedAt }, { it.signedEvent?.id })) - ?: GroupRelayList(set = set, signedEvent = null, relays = emptyList()) - - /** Every set, in the order the editor shows them. */ - fun allAmong( - signedEvents: List, - chatRoomId: String, - ): List = - GroupRelaySet.entries.map { newestAmong(signedEvents, chatRoomId, it) } - } -} - -/** - * One relay in one of a group's lists. - * - * [read] and [write] mean something only in [GroupRelaySet.General], which is the - * one list NIP-65 gives markers to; everywhere else a relay is simply in the list - * and both are true. They are kept on the shared type rather than split into two - * so that the editor has one row shape and one add path. - * - * **Neither is not a state.** NIP-65 writes a bare `r` tag for both, `read` for - * read-only and `write` for write-only, and has nothing at all for a relay that is - * neither -- a relay you will not read from and will not write to is one you have - * removed. The editor enforces that rather than this dropping it silently. - */ -data class GroupRelay( - val url: NormalizedRelayUrl, - val read: Boolean = true, - val write: Boolean = true, -) { - /** The host, for a list that is read rather than copied. */ - fun displayUrl(): String = url.displayUrl() -} - -/** - * The relay lists a group keeps, and what each one is for. - * - * The four a person's client keeps, because a group is an author like any other and - * these are the four questions the network asks about one. - * - * **Key packages (MIP-00, kind 10051) are deliberately not here**, though this app - * writes one for every person. A key package is a device's offer to be added to an - * MLS group, and a group has no device and joins nothing -- so a group advertising - * where its key packages live would be pointing at a place that will always be - * empty, which is worse than saying nothing. See `MarmotKeyPackage`, which is keyed - * by member. - * - * **Relay feeds (kind 10012) are not here either**, for the harder reason: the list - * lives in the encrypted half and a threshold key cannot decrypt. See - * [GroupRelayList]'s note on public tags. - */ -enum class GroupRelaySet( - val kind: Kind, - /** Whether NIP-65's read and write markers apply, which is General alone. */ - val hasReadWriteMarkers: Boolean = false, -) { - /** - * NIP-65: where the group publishes and where a reader should look for it. - * - * The one that matters most and the only one with markers. Everything the group - * signs is addressed to whoever wants to read it, and this is the answer to - * where. - */ - General(AdvertisedRelayListEvent.KIND, hasReadWriteMarkers = true), - - /** NIP-17: where a message addressed to the group's key should be sent. */ - Messages(ChatMessageRelayListEvent.KIND), - - /** NIP-50: the relays the group would have a search of its work run against. */ - Search(SearchRelayListEvent.KIND), - - /** NIP-51: relays the group will not talk to, whatever else says otherwise. */ - Blocked(BlockedRelayListEvent.KIND), - ; - - /** - * What a group with nothing agreed starts the editor at. - * - * The app's own relay, which is where everything else this build publishes and - * reads already goes -- see `Relays.ephemeral`. A group seeded with nothing - * would be a group whose first proposal is an empty list, which says less than - * having never said anything at all. - * - * Blocked is the exception and starts empty on purpose: a default there is a - * refusal to talk to somebody that nobody in the group chose. - */ - fun defaults(): List = when (this) { - Blocked -> emptyList() - else -> listOf(GroupRelay(Relays.ephemeral)) - } - - /** The relays out of a signed event's tags, in the order the group wrote them. */ - fun parse(tags: Array>): List = when (this) { - General -> tags.mapNotNull(AdvertisedRelayInfo::parse).map { - GroupRelay( - url = it.relayUrl, - read = it.type.isRead(), - write = it.type.isWrite(), - ) - } - // Both nip51 lists and NIP-17's use a "relay" tag, and the two RelayTag - // classes that parse it are different classes in different packages. Named - // apart at the import so a reader can see which NIP each line is following. - Messages -> tags.mapNotNull(Nip17RelayTag::parse).map { GroupRelay(it) } - Search, Blocked -> tags.mapNotNull(Nip51RelayTag::parse).map { GroupRelay(it) } - }.distinctBy { it.url } - - /** - * The event to ask the group to sign for this set. - * - * Built from scratch rather than from the group's last one, which is the - * opposite of what `GroupNostrProfile.template` does and for a reason: a - * profile is a bag of independent fields where an unknown one is worth keeping, - * and a relay list is one list where the whole point of signing a new one is to - * replace it. Carrying a tag forward here would make a removal impossible. - * - * A relay that is neither read nor write is dropped rather than written, since - * NIP-65 cannot express one -- the editor does not allow the state, and this is - * the second line of that defence rather than the first. - */ - fun template(relays: List): EventTemplate<*> { - val tags = when (this) { - General -> relays.mapNotNull { relay -> - val type = when { - relay.read && relay.write -> AdvertisedRelayType.BOTH - relay.read -> AdvertisedRelayType.READ - relay.write -> AdvertisedRelayType.WRITE - else -> return@mapNotNull null - } - AdvertisedRelayInfo.assemble(relay.url, type) - } - Messages -> relays.map { Nip17RelayTag.assemble(it.url) } - Search, Blocked -> relays.map { Nip51RelayTag.assemble(it.url) } - } - - // Empty content throughout. For General and Messages that is all the kind - // has; for the two nip51 lists it is where the encrypted half would go, and - // a group has no encrypted half. See [GroupRelayList]. - return EventTemplate( - createdAt = kotlin.time.Clock.System.now().epochSeconds, - kind = kind, - tags = tags.toTypedArray(), - content = "", - ) - } - - companion object { - /** - * The kinds a group's relay lists are written as. - * - * A set rather than a walk of [entries], for `ChatMessage.applyInnerEvent`, - * whose dispatch is one `when` over an event's kind -- and a `when` branch - * has to be a constant expression rather than a predicate over an enum. - */ - val KINDS: Set = entries.map { it.kind }.toSet() - - /** - * [url] as a relay a group could actually be told to use, or null. - * - * Structural only, and deliberately narrow: `wss://` because a group's - * signed list is read by strangers over the open network and `ws://` would - * ask them to fetch it in the clear, and no loopback because a relay only - * this device can reach is not something to put a quorum's signature on. - * Wisp's `RelayConfig.isValidUrl` refuses the same three things. - */ - fun relayUrlOrNull(url: String): NormalizedRelayUrl? { - val trimmed = url.trim() - if (!trimmed.startsWith("wss://", ignoreCase = true)) return null - - return RelayUrlNormalizer.normalizeOrNull(trimmed)?.takeUnless { it.isLocalHost() } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt index c6e7c1ce..171fcc73 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt @@ -14,14 +14,6 @@ import com.machankura.bennu.compose.network.serialization.CommonJson import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleIdTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChroniclePageTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleRecipientTag -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent /** * 30327 @@ -45,16 +37,7 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent * deliberately does not do: it never carries the chat, and it cannot make its * recipient able to *sign* anything. * - * ### Why not a [com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent] each - * - * The envelope fits and the meaning does not. A submission is an *act* -- this - * member is putting this event in front of this group -- and a chronicle asserts - * nothing; it re-delivers what the group already agreed. On one kind a - * four-hundred-event backfill is indistinguishable from four hundred new - * submissions and every device has to guess which it is looking at. It would - * also be one inner event and one kind:445 per payload, where a page is one, and - * the submission arm of `ChatMessage.applyInnerEvent` files a chat line per - * payload, which a chronicle must not. + * It carries nothing in this app at the moment -- see [KINDS]. */ @Immutable class ChronicleEvent( @@ -88,18 +71,12 @@ class ChronicleEvent( companion object { /** * Sits past `GroupKeyStateEvent` at 30326, in the Marmot inner-event - * space it shares with the nip30303 document kinds and the FROST signing - * family. + * space it shares with the FROST signing family. * - * 30313 was free next to the document kinds and is not used, on - * `FrostSigningEvents`' own advice: the DKG's 30310-30316 already overlap - * that range and are told apart only by living in NIP-17 gift wraps - * instead, which is "an accident of routing rather than a decision, and - * the next family added should not rely on it." This is that next family. - * - * It is also the right neighbourhood on the merits. A chronicle is not a - * document kind; it is a statement about the record, which is what a key - * state is too. + * 30313 is not used, on `FrostSigningEvents`' own advice: the DKG's + * 30310-30316 sit there, and once collided with document kinds that + * shared their numbers. This family took numbers nobody else uses + * instead. */ const val KIND: Kind = 30327 @@ -109,7 +86,7 @@ class ChronicleEvent( * The most JSON one page may carry. * * A byte cap rather than a count alone, because the payloads vary by two - * orders of magnitude -- a chunk is a paragraph, an artifact is a URL. + * orders of magnitude -- a paragraph of text against a single URL. * Sized so the finished kind:445 clears the tightest relay limits with * room for the MLS framing and the NIP-44 expansion that sit outside it; * measure it against a real one rather than trusting the arithmetic. @@ -130,8 +107,8 @@ class ChronicleEvent( * The most payloads one page may carry. * * The byte cap bounds the transport; this bounds the receiver's *work*, - * and they are not the same limit -- 64 KB of one-line dialects is a lot - * more signature verifies than 64 KB of chapters. + * and they are not the same limit -- 64 KB of one-line events is a lot + * more signature verifies than 64 KB of long ones. * * **Sized under what the byte cap allows, or it would never fire.** An * event carries a 64-character id, a 64-character pubkey and a @@ -154,82 +131,29 @@ class ChronicleEvent( const val MAX_PAGE_EVENTS = 96 /** - * The kinds a chronicle may carry, in the order they have to be applied. + * The kinds a chronicle may carry in this app: **none, at the moment.** * - * One list doing both jobs, because a separate allowlist is one more - * thing that can disagree with the order it is applied in. + * It was built to hand a late member the group's signed documents -- + * dialects, artifacts, chapters and their translations -- and those kinds + * were removed with the screens that made them (docs/ceremony-creation.md, + * Phase 7). Everything else the group signs is left out on purpose: * - * **The order is Room's, not nostr's.** Every one of these has a foreign - * key on the one before it, so a chronicle applied out of order is a - * constraint violation rather than a wrong answer. Kind order is not - * dependency order and never was -- a translation chapter (30308) hangs - * off a translation artifact version (30306) which hangs off an artifact - * version (30301) -- so this is a list rather than a `sortedBy { kind }`. + * - a `GroupKeyStateEvent` or a subgroup's birth certificate is a validly + * signed statement about the group that anyone holding a copy could + * replay -- see [ChronicleKinds]; + * - wallet statements have their own way to a member who joins late. * - * **It is an allowlist first.** Verification admits an event to the apply - * path on the strength of the group's signature, which makes every kind - * the group has ever signed replayable by any member at any time. A - * `GroupKeyStateEvent` is group-signed and passes verification perfectly, - * so a chronicle carrying an old one is a validly signed statement about - * what the room signs with, replayed by whoever kept a copy. Nothing but - * this list stops it. - * - * ### What is missing from it, and why - * - * **Only kinds the group actually signs can be here**, because a chronicle - * that cannot be verified is one that has to be believed. Six of the - * thirteen nip30303 kinds reach a signing session; the rest travel as - * rumors -- empty signature, member author, vouched for by the MLS frame - * they arrived in and by nothing that survives leaving it. - * - * Left out for that reason: - * - * - `TranslationEvent` (30311). Nothing builds one; the inbound arm - * exists and no producer does. - * - The contributor lists (30305, 30307, 30310). `applyInnerEvent` has - * no arm that writes a row for any of them, so chronicling them would - * cost bytes and restore nothing. - * - * Two kinds were on that list and are not any more, because the app - * stopped leaving them unsigned. `ArtifactVersionEvent` (30301) used to be - * derived from the signed artifact on arrival, and is now the second item - * of the batch that carries it. `TranslationChunkEvent` (30309) -- the - * translated text itself -- used to be submitted as its author's rumor, - * and is now proposed to the group like everything else. Both are - * therefore checkable, and a chronicle that left them out would hand a new - * member the whole structure and none of the prose. + * So the machinery stays and carries nothing: with an empty list a device + * asks for no chronicle, sends none, and applies nothing from one that an + * older build sends -- see `ChronicleManager`. Adding a kind back is a + * decision that belongs here, with the reason it is safe to replay. */ - private val APPLY_ORDER: List = listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ArtifactVersionEvent.KIND, - ChapterEvent.KIND, - ChunkEvent.KIND, - TranslationArtifactVersionEvent.KIND, - TranslationChapterEvent.KIND, - TranslationChunkEvent.KIND, - ) + val KINDS: ChronicleKinds = ChronicleKinds.NONE - /** Every kind a chronicle may carry. */ - val CHRONICLABLE_KINDS: Set = APPLY_ORDER.toSet() + /** Every kind a chronicle may carry in this app. */ + val CHRONICLABLE_KINDS: Set = KINDS.all - /** - * Where [kind] sits in dependency order, or null if a chronicle may not - * carry it at all. - */ - fun applyRank(kind: Kind): Int? = APPLY_ORDER.indexOf(kind).takeIf { it >= 0 } - - fun isChroniclable(kind: Kind): Boolean = kind in CHRONICLABLE_KINDS - - /** - * [payloads] in dependency order, so a page applies front to back. - * - * Stable within a rank: two chapters of one version have no order between - * them and keeping the caller's is one less thing that varies between two - * members assembling the same chronicle. - */ - fun inApplyOrder(payloads: List): List = - payloads.sortedBy { applyRank(it.kind) ?: Int.MAX_VALUE } + fun isChroniclable(kind: Kind): Boolean = KINDS.isChroniclable(kind) /** * The bytes [json] occupies once it is the `content` of a Marmot app event -- @@ -315,6 +239,7 @@ class ChronicleEvent( count: Int, recipient: HexKey, createdAt: Long = TimeUtils.now(), + kinds: ChronicleKinds = KINDS, initializer: TagArrayBuilder.() -> Unit = {}, ): EventTemplate { require(payloads.isNotEmpty()) { "A chronicle page carries at least one event" } @@ -322,7 +247,7 @@ class ChronicleEvent( "A chronicle page carries at most $MAX_PAGE_EVENTS events, not ${payloads.size}" } payloads.forEach { - require(isChroniclable(it.kind)) { "A chronicle may not carry kind ${it.kind}" } + require(kinds.isChroniclable(it.kind)) { "A chronicle may not carry kind ${it.kind}" } } val content = encodePage(payloads) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleKinds.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleKinds.kt new file mode 100644 index 00000000..2de65eb4 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleKinds.kt @@ -0,0 +1,51 @@ +package com.machankura.bennu.compose.nostr.chronicle + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * The kinds a chronicle may carry, in the order they have to be applied. + * + * One list doing both jobs, because a separate allowlist is one more thing that + * can disagree with the order it is applied in. The order is the database's, not + * nostr's: where one kind's rows hang off another's, the one they hang off comes + * first, so a page applies front to back. + * + * **It is an allowlist first.** Verification admits an event to the apply path on + * the strength of the group's signature, which makes every kind the group has + * ever signed replayable by any member at any time. A `GroupKeyStateEvent` is + * group-signed and passes verification perfectly, so a chronicle carrying an old + * one is a validly signed statement about what the room signs with, replayed by + * whoever kept a copy. Nothing but this list stops it. + * + * A value rather than a constant so the machinery can be exercised without + * making anything chroniclable in the app: the app's own list is + * [ChronicleEvent.KINDS], and the tests hand in theirs. + */ +class ChronicleKinds(private val applyOrder: List) { + + /** Every kind a chronicle may carry. */ + val all: Set = applyOrder.toSet() + + /** A chronicle that may carry nothing asks for nothing and sends nothing. */ + fun isEmpty(): Boolean = applyOrder.isEmpty() + + /** Where [kind] sits in apply order, or null if a chronicle may not carry it at all. */ + fun applyRank(kind: Kind): Int? = applyOrder.indexOf(kind).takeIf { it >= 0 } + + fun isChroniclable(kind: Kind): Boolean = kind in all + + /** + * [payloads] in apply order, so a page applies front to back. + * + * Stable within a rank: two events of one kind have no order between them, + * and keeping the caller's is one less thing that varies between two members + * assembling the same chronicle. + */ + fun inApplyOrder(payloads: List): List = + payloads.sortedBy { applyRank(it.kind) ?: Int.MAX_VALUE } + + companion object { + val NONE = ChronicleKinds(emptyList()) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/dkg/DkgRitualEvents.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/dkg/DkgRitualEvents.kt index 7df3a943..2cff072b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/dkg/DkgRitualEvents.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/dkg/DkgRitualEvents.kt @@ -1,19 +1,27 @@ package com.machankura.bennu.compose.nostr.dkg +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianDelayTag import com.machankura.bennu.compose.nostr.dkg.tags.DkgSessionIdTag import com.machankura.bennu.compose.nostr.dkg.tags.DkgThresholdTag import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip14Subject.SubjectTag +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupParentTag +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag /** * The nostr kinds a ChillDKG ritual is carried on. * - * These are **rumor** kinds: they only ever exist inside a NIP-17 gift wrap - * addressed to the group, so no relay sees them unencrypted and the replaceable - * semantics normally implied by the 3xxxx range never apply. They sit next to - * the app's other private kinds (30300-30309) deliberately — the transport, - * sealing and broadcast pipeline is the same one chat messages ride. + * These are **rumor** kinds: they only ever travel encrypted -- inside a NIP-17 + * gift wrap for a group's own ceremony, and as a Marmot inner event in the + * parent's room for a subgroup's -- so no relay sees them in the clear and the + * replaceable semantics normally implied by the 3xxxx range never apply. The + * transport, sealing and broadcast pipeline is the one chat messages ride. + * + * 30310-30312 used to be nip30303 document kinds too, and a round 1 read as a + * document submission once reached a parent's chat as raw hex. `ChatMessage` + * recognises these before any content kind for that reason, and the document + * kinds are gone. See docs/ceremony-creation.md. * * Who talks to whom, in order: * @@ -76,12 +84,16 @@ object DkgRitualEvents { sessionId: String, threshold: Int? = null, parentChatRoomId: String? = null, - subject: String? = null + subject: String? = null, + walletPolicy: SubgroupWalletPolicy? = null, + guardianDelay: Long? = null ): Array> = buildList { add(DkgSessionIdTag.assemble(sessionId)) threshold?.let { add(DkgThresholdTag.assemble(it)) } parentChatRoomId?.let { add(SubgroupParentTag.assemble(it)) } subject?.ifBlank { null }?.let { add(SubjectTag.assemble(it)) } + walletPolicy?.let { add(WalletPolicyTag.assemble(it)) } + guardianDelay?.let { add(GuardianDelayTag.assemble(it)) } }.toTypedArray() fun parseSessionId(tags: Array>): String? = @@ -124,4 +136,26 @@ object DkgRitualEvents { */ fun parseSubject(tags: Array>): String? = tags.firstNotNullOfOrNull(SubjectTag::parse) + + /** + * The wallet policy the coordinator chose for the subgroup this ceremony + * makes -- `docs/subgroup-wallet-policy.md`. + * + * Authenticates nothing, as [parseParentChatRoomId] does not: it is what the + * admins are shown before they join, and what the certificate is later + * proposed under. Absent for an ordinary ceremony and for one from an older + * build; unreadable is told apart from absent, because a proposal whose + * policy cannot be read is not one to join on the assumption it has none. + */ + fun parseWalletPolicy(tags: Array>): WalletPolicyTag.Result = + WalletPolicyTag.parseOne(tags) + + /** + * The delay the coordinator chose for the parent's own leaf, beside a + * guarded policy -- `docs/guardian-delay.md`. Authenticates nothing, as the + * policy does not: it is what the admins are shown, and what the certificate + * is proposed under. + */ + fun parseGuardianDelay(tags: Array>): GuardianDelayTag.Result = + GuardianDelayTag.parseOne(tags) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt index c879f8ef..f30411fa 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt @@ -51,23 +51,17 @@ import com.machankura.bennu.compose.nostr.frost.tags.FrostSilentMembersTag * * ### Why 3032x * - * These share the inner-event space with the nip30303 document kinds, which run - * 30300 up to [com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent] at 30312 -- - * the same space, because both are Marmot inner events and both are dispatched - * on kind by the same inbound path. Starting at 30320 leaves that family room to - * grow into. + * These started past the nip30303 document kinds, which ran 30300 up to 30312 + * in the same Marmot inner-event space and were dispatched on kind by the same + * inbound path. Those kinds are gone (docs/ceremony-creation.md), and 30300-30309 + * are free. * - * The DKG's 30310-30316 look like a clash and are not, but the reason is - * narrower than it used to be. The nip30303 kinds exist only inside Marmot inner - * events and the DKG's only inside NIP-17 gift wraps, so the numbers overlap - * where nothing reads across -- the DKG's proposal and host-key kinds sit on - * 30310 and 30311 alongside two nip30303 kinds, and its round-1 kind is 30312, - * alongside SubmissionEvent. - * - * These kinds are now the ones that *do* travel on both transports, which is - * exactly why they must not overlap with either family. They do not. But that - * separation was an accident of routing rather than a decision, and the next - * family added should not rely on it. + * The DKG's 30310-30316 *did* clash with that family once a subgroup's ceremony + * moved into its parent's Marmot room: its round 1 reached the parent's chat as + * an unreadable document submission. `ChatMessage` recognises this family's + * kinds and the DKG's before any content kind, so a protocol kind is never read + * as content whatever shares its number. A new family should still take numbers + * nobody else uses. */ object FrostSigningEvents { /** @@ -188,6 +182,21 @@ object FrostSigningEvents { return chain to account } + private const val GUARDED_TAG = "guarded" + + /** + * On a [TRANSACTION_PROPOSAL] from an ancestor's room: the descendant whose + * guarded wallet it spends from, through the room's guardian leaf. Absent + * for a spend from the room's own wallet. Which wallet it is is all this + * says; every signer then reads that wallet from the statement its own room + * was told, never from the proposal. + */ + fun guardedTags(descendantChatRoomId: String): Array> = arrayOf(arrayOf(GUARDED_TAG, descendantChatRoomId)) + + /** The descendant a guardian's [TRANSACTION_PROPOSAL] names, or null for the room's own wallet. */ + fun parseGuarded(tags: Array>): String? = + tags.firstOrNull { it.size >= 2 && it[0] == GUARDED_TAG }?.get(1)?.takeIf { it.isNotBlank() } + fun parseSessionId(tags: Array>): String? = tags.firstNotNullOfOrNull(FrostSessionIdTag::parse)?.sessionId diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt index 6bc23d79..15377cd5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt @@ -8,7 +8,7 @@ import fr.acinq.lightning.payment.Bolt11Invoice import kotlin.time.Clock /** - * Something the group lets its Lightning wallet do: kind 30346, FROST-signed, never broadcast + * Something the group lets its Lightning wallet do: kind 30363, FROST-signed, never broadcast * (`docs/group-lightning-wallet.md`, Phase 12). * * The operator's node acts on an authorisation, and every co-signer reads it as a budget: an HTLC the diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEvents.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEvents.kt index 06dcad1b..7ae71d2a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEvents.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEvents.kt @@ -14,54 +14,58 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind * apply. * * ``` - * proposer --[ 30333 ceremony proposal ]-> everyone "let's make a t-of-n Iceberg key" - * participant --[ 30334 DKG round 1 ]-> everyone commitments to seed contributions - * participant --[ 30335 DKG round 2 ]-> everyone contributions, each encrypted to its holder - * participant --[ 30336 DKG round 3 ]-> everyone public share + transcript signature - * anyone --[ 30337 ceremony failure ]-> everyone abort + blame - * group --[ 30338 wallet statement ] FROST-signed, never broadcast - * group --[ 30339 operator statement] FROST-signed, never broadcast - * opener --[ 30340 node seed ]-> each participant, encrypted to them - * operator --[ 30341 signing request ]-> everyone - * participant --[ 30342 echo ]-> everyone (label, message hash) - * participant --[ 30343 nonce batch ]-> everyone round-one contributions - * participant --[ 30344 signature share ]-> everyone round two - * operator --[ 30345 snapshot ]-> everyone balance, channels, payments - * group --[ 30346 authorisation ] FROST-signed: pay, close, force-close, splice-out - * member --[ 30347 invoice request ]-> everyone - * operator --[ 30348 invoice ]-> everyone - * old operator--[ 30349 stopped ]-> everyone its last commitment numbers + * proposer --[ 30350 ceremony proposal ]-> everyone "let's make a t-of-n Iceberg key" + * participant --[ 30351 DKG round 1 ]-> everyone commitments to seed contributions + * participant --[ 30352 DKG round 2 ]-> everyone contributions, each encrypted to its holder + * participant --[ 30353 DKG round 3 ]-> everyone public share + transcript signature + * anyone --[ 30354 ceremony failure ]-> everyone abort + blame + * group --[ 30355 wallet statement ] FROST-signed, never broadcast + * group --[ 30356 operator statement] FROST-signed, never broadcast + * opener --[ 30357 node seed ]-> each participant, encrypted to them + * operator --[ 30358 signing request ]-> everyone + * participant --[ 30359 echo ]-> everyone (label, message hash) + * participant --[ 30360 nonce batch ]-> everyone round-one contributions + * participant --[ 30361 signature share ]-> everyone round two + * operator --[ 30362 snapshot ]-> everyone balance, channels, payments + * group --[ 30363 authorisation ] FROST-signed: pay, close, force-close, splice-out + * member --[ 30364 invoice request ]-> everyone + * operator --[ 30365 invoice ]-> everyone + * old operator--[ 30366 stopped ]-> everyone its last commitment numbers * ``` * - * ### Why 30333 + * ### Why 30350 * - * 30330-30332 were the highest kinds in use when this family was reserved, and - * the note on `FrostSigningEvents` asks the next family not to rely on routing - * to keep it apart from the others. So this one is a fresh run with nothing - * else in it, and `GroupLightningEventsTest` asserts that none of it overlaps any - * kind the app already dispatches on. + * This family was first reserved at 30333-30349, the run after the highest + * kinds then in use. The guarded-wallet family took 30333-30337 on the main + * branch while this one was being built, and the two met at the merge, where + * nothing would have failed: each reads the other's events by kind. Rumor kinds + * are never published and nothing had shipped, so this family moved to a fresh + * run past the guarded wallets' with room before it. The note on + * `FrostSigningEvents` asks the next family not to rely on routing to keep it + * apart from the others; `GroupLightningEventsTest` asserts both that none of it + * overlaps a kind the app uses and that it starts past all of them. */ object GroupLightningEvents { - val CEREMONY_PROPOSAL: Kind = 30333 - val DKG_ROUND_1: Kind = 30334 - val DKG_ROUND_2: Kind = 30335 - val DKG_ROUND_3: Kind = 30336 - val CEREMONY_FAILURE: Kind = 30337 + val CEREMONY_PROPOSAL: Kind = 30350 + val DKG_ROUND_1: Kind = 30351 + val DKG_ROUND_2: Kind = 30352 + val DKG_ROUND_3: Kind = 30353 + val CEREMONY_FAILURE: Kind = 30354 - val WALLET_STATEMENT: Kind = 30338 - val OPERATOR_STATEMENT: Kind = 30339 - val NODE_SEED: Kind = 30340 + val WALLET_STATEMENT: Kind = 30355 + val OPERATOR_STATEMENT: Kind = 30356 + val NODE_SEED: Kind = 30357 - val SIGNING_REQUEST: Kind = 30341 - val ECHO: Kind = 30342 - val NONCE_BATCH: Kind = 30343 - val SIGNATURE_SHARE: Kind = 30344 + val SIGNING_REQUEST: Kind = 30358 + val ECHO: Kind = 30359 + val NONCE_BATCH: Kind = 30360 + val SIGNATURE_SHARE: Kind = 30361 - val SNAPSHOT: Kind = 30345 - val AUTHORISATION: Kind = 30346 - val INVOICE_REQUEST: Kind = 30347 - val INVOICE: Kind = 30348 - val STOPPED: Kind = 30349 + val SNAPSHOT: Kind = 30362 + val AUTHORISATION: Kind = 30363 + val INVOICE_REQUEST: Kind = 30364 + val INVOICE: Kind = 30365 + val STOPPED: Kind = 30366 /** The Iceberg ceremony's kinds, for routing to its ritual manager. */ val CEREMONY: Set = setOf(CEREMONY_PROPOSAL, DKG_ROUND_1, DKG_ROUND_2, DKG_ROUND_3, CEREMONY_FAILURE) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt index aac3190d..3e149964 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt @@ -7,7 +7,7 @@ import fr.acinq.bitcoin.Chain import kotlin.time.Clock /** - * Who runs the group's Lightning node: kind 30339, FROST-signed, never broadcast + * Who runs the group's Lightning node: kind 30356, FROST-signed, never broadcast * (`docs/group-lightning-wallet.md`, Phase 7). * * The term is what every co-signer fences on. It only goes up, and a request from anyone but the diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt index df552419..dc62369a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt @@ -8,7 +8,7 @@ import fr.acinq.bitcoin.Chain import kotlin.time.Clock /** - * The group's statement that it keeps a Lightning wallet: kind 30338, FROST-signed by the room through + * The group's statement that it keeps a Lightning wallet: kind 30355, FROST-signed by the room through * the ordinary proposal flow, never broadcast (`docs/group-lightning-wallet.md`, Phase 6). * * It binds together everything a co-signer checks before it answers for a channel: which onchain wallet diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactEvent.kt deleted file mode 100644 index 77d21318..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactEvent.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionMetadataTag -import com.machankura.bennu.compose.nostr.nip30303.tags.DialectIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.LicenseTag -import com.machankura.bennu.compose.nostr.nip30303.tags.UrlTag -import com.machankura.bennu.compose.nostr.nip30303.tags.VisibilityTag - - -@Immutable -class ArtifactEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - fun url() = tags.firstNotNullOfOrNull(UrlTag::parse)?.url - fun visibility() = tags.firstNotNullOfOrNull(VisibilityTag::parse)?.visibility - fun license() = tags.firstNotNullOfOrNull(LicenseTag::parse)?.license - - fun dialectIdReference() = tags.firstNotNullOfOrNull(DialectIdTag::parse)?.ref - fun dialectId() = dialectIdReference()?.eventId - - /** - * The label of the version this artifact starts life with. - * - * Carried on the artifact rather than in an event of its own because the - * group signs the artifact and nothing else. A first version proposed - * separately would need either a second quorum for one form or an id each - * device invents for itself, and invented ids differ on every device holding - * the same artifact. Null on artifacts written before this was declared. - */ - fun versionLabel() = tags.firstNotNullOfOrNull(ArtifactVersionMetadataTag::parse)?.versionLabel - - companion object { - const val KIND = 30300 - const val ALT_DESCRIPTION = "Artifact" - - fun build( - name: String, - url: String, - visibility: String, - license: String, - dialectId: String, - versionLabel: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, name, createdAt) { - alt(ALT_DESCRIPTION) - addUnique(UrlTag.assemble(url)) - addUnique(VisibilityTag.assemble(visibility)) - addUnique(LicenseTag.assemble(license)) - addUnique( - DialectIdTag.assemble(dialectId) - ) - addUnique(ArtifactVersionMetadataTag.assemble(versionLabel)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactVersionEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactVersionEvent.kt deleted file mode 100644 index 541a1616..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactVersionEvent.kt +++ /dev/null @@ -1,86 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionMetadataTag - - -@Immutable -class ArtifactVersionEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - fun versionLabel() = tags.firstNotNullOfOrNull(ArtifactVersionMetadataTag::parse)?.versionLabel - - fun artifactIdReference() = tags.firstNotNullOfOrNull(ArtifactIdTag::parse)?.ref - fun artifactId() = artifactIdReference()?.eventId - - companion object { - const val KIND = 30301 - const val ALT_DESCRIPTION = "ArtifactVersion" - - /** - * The first version [artifact] declares, ready to be signed with it. - * - * An artifact and the version it starts life with go to the group as one - * batch, so this is built from the artifact *after* it has been authored - * under the group's key -- [artifact] is the unsigned event the session - * will sign, which is where the id this carries comes from. Building it - * anywhere else would mean naming an artifact id before one exists. - * - * It takes the artifact's own timestamp, so the batch reads as one act - * rather than two events that happen to share a session. - * - * This used to be derived on arrival instead, from the label the - * artifact carries -- the same shape a chapter's chunks were in, and - * abandoned for the same reason. Deriving cost nothing while the - * alternative was a second quorum, and nothing is what it bought: a row - * naming the group as its author with no signature to show for it, which - * a chapter then hangs off. A batch is one quorum, so the version can - * carry the group's signature over its own label. - * - * Empty when the artifact declares no version -- every artifact written - * before it did -- which leaves a batch of one and an artifact with no - * version, exactly as before. - */ - fun initialVersionOf(artifact: Event): List> { - val versionLabel = ArtifactEvent( - id = artifact.id, - pubKey = artifact.pubKey, - createdAt = artifact.createdAt, - tags = artifact.tags, - content = artifact.content, - sig = artifact.sig - ).versionLabel() ?: return emptyList() - - return listOf( - build(content = versionLabel, createdAt = artifact.createdAt) { - addUnique(ArtifactIdTag.assemble(artifact.id)) - } - ) - } - - fun build( - content: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, content, createdAt) { - alt(ALT_DESCRIPTION) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChapterEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChapterEvent.kt deleted file mode 100644 index 933e1c38..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChapterEvent.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.NameTag -import com.machankura.bennu.compose.nostr.nip30303.tags.OriginalTextTag -import com.machankura.bennu.compose.nostr.nip30303.tags.WordStatisticsTag - - -@Immutable -class ChapterEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - val wordStatisticsTag = tags.firstNotNullOfOrNull(WordStatisticsTag::parse) - - fun artifactVersionIdReference() = tags.firstNotNullOfOrNull(ArtifactVersionIdTag::parse)?.ref - fun artifactVersionId() = artifactVersionIdReference()?.eventId - - fun name() = tags.firstNotNullOfOrNull(NameTag::parse)?.name - - /** - * The markdown the chapter is, whole. - * - * The chapter carries its text even though the chunks cut from it are - * signed alongside it and carry the same words between them. It is the - * chapter as the group signed it: chunk boundaries are a decision about how - * to divide the work, and a chapter that kept only the pieces could never be - * divided again differently without losing what was agreed to. - */ - fun originalText() = tags.firstNotNullOfOrNull(OriginalTextTag::parse)?.originalText - - fun index() = tags.firstNotNullOfOrNull(IndexTag::parse)?.index - fun wordCount() = wordStatisticsTag?.wordCount - fun characterCount() = wordStatisticsTag?.characterCount - - companion object { - const val KIND = 30302 - const val ALT_DESCRIPTION = "Chapter" - - fun build( - artifactVersionId: String, - name: String, - originalText: String, - index: Int, - wordCount: Int, - characterCount: Int, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, "", createdAt) { - alt(ALT_DESCRIPTION) - addUnique(ArtifactVersionIdTag.assemble(artifactVersionId)) - addUnique(NameTag.assemble(name)) - addUnique(OriginalTextTag.assemble(originalText)) - addUnique(IndexTag.assemble(index)) - addUnique(WordStatisticsTag.assemble(wordCount, characterCount)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChunkEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChunkEvent.kt deleted file mode 100644 index 8a9004be..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChunkEvent.kt +++ /dev/null @@ -1,94 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ChapterIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.WordStatisticsTag -import com.machankura.bennu.compose.text.Markdown - - -@Immutable -class ChunkEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - val wordStatisticsTag = tags.firstNotNullOfOrNull(WordStatisticsTag::parse) - - fun index() = tags.firstNotNullOfOrNull(IndexTag::parse)?.index - fun wordCount() = wordStatisticsTag?.wordCount - fun characterCount() = wordStatisticsTag?.characterCount - - fun chapterIdReference() = tags.firstNotNullOfOrNull(ChapterIdTag::parse)?.ref - fun chapterId() = chapterIdReference()?.eventId - - companion object { - const val KIND = 30303 - const val ALT_DESCRIPTION = "Chunk" - - /** - * The chunks [chapter]'s text splits into, ready to be signed with it. - * - * A chapter and its chunks go to the group as one batch, so these are - * built from the chapter *after* it has been authored under the group's - * key -- [chapter] is the unsigned event the session will sign, which is - * where the id each chunk carries comes from. Splitting anywhere else - * would mean naming a chapter id before one exists. - * - * They take the chapter's own timestamp, so the batch reads as one act - * rather than as events that happen to share a session. - * - * Empty when the chapter has no text to split, which is a chapter with - * nothing in it to translate. - */ - fun splitOf(chapter: Event): List> { - val originalText = ChapterEvent( - id = chapter.id, - pubKey = chapter.pubKey, - createdAt = chapter.createdAt, - tags = chapter.tags, - content = chapter.content, - sig = chapter.sig - ).originalText() ?: return emptyList() - - return Markdown.splitParagraphs(originalText).mapIndexed { index, paragraph -> - build( - chapterId = chapter.id, - text = paragraph, - index = index, - wordCount = Markdown.wordCount(paragraph), - characterCount = Markdown.characterCount(paragraph), - createdAt = chapter.createdAt, - ) - } - } - - fun build( - chapterId: String, - text: String, - index: Int, - wordCount: Int, - characterCount: Int, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, text, createdAt) { - alt(ALT_DESCRIPTION) - addUnique(ChapterIdTag.assemble(chapterId)) - addUnique(IndexTag.assemble(index)) - addUnique(WordStatisticsTag.assemble(wordCount, characterCount)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/DialectEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/DialectEvent.kt deleted file mode 100644 index e8fcae4c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/DialectEvent.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.CountryTag -import com.machankura.bennu.compose.nostr.nip30303.tags.LanguageTag -import com.machankura.bennu.compose.nostr.nip30303.tags.NameTag - - -@Immutable -class DialectEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - fun name() = tags.firstNotNullOfOrNull(NameTag::parse)?.name - fun country() = tags.firstNotNullOfOrNull(CountryTag::parse)?.country - fun language() = tags.firstNotNullOfOrNull(LanguageTag::parse)?.language - - companion object { - const val KIND = 30304 - const val ALT_DESCRIPTION = "Dialect" - - fun build( - name: String, - country: String, - language: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, language, createdAt) { - alt(ALT_DESCRIPTION) - addUnique(NameTag.assemble(name)) - addUnique(CountryTag.assemble(country)) - addUnique(LanguageTag.assemble(language)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/SubmissionEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/SubmissionEvent.kt deleted file mode 100644 index 4d458ac4..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/SubmissionEvent.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.PayloadIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.PayloadKindTag - -/** - * 30312 - * - * An envelope that carries one nip30303 event into a group. - * - * Every other nip30303 kind describes a thing -- an artifact, a dialect, a - * chapter, a translated chunk. A submission describes an act: *this member is - * putting this event in front of this group*. The two are separate on purpose, - * because they answer different questions and often have different answers. - * - * The payload travels whole, in [content], keeping its own id, author and - * signature. Nothing is rewritten to make it look like the submitter's work. - * That buys two things: - * - * - A group can take in work written by somebody who is not in it. A - * translation lifted from a public chronicle, a chapter transcribed by an - * outside contributor, an artifact somebody published years ago -- an admin - * submits it and the group applies it, with the original author still named - * on the row. - * - Authorship stops being a claim the transport makes. Before this, being - * the sender of a group message *was* being the author of the event inside - * it, so the only events a group could hold were ones its own members had - * written under their own keys. - * - * A submission is not an endorsement and grants nothing: a payload's author is - * whoever signed it, and who may submit is the group's business. - */ -@Immutable -class SubmissionEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - /** - * The submitted event, parsed out of [content]. - * - * Null when the content is not an event at all -- treat that as a - * submission that cannot be applied, not as an empty one. - */ - fun payload(): Event? = Event.fromJsonOrNull(content) - - fun payloadKind() = tags.firstNotNullOfOrNull(PayloadKindTag::parse)?.kind - - fun payloadIdReference() = tags.firstNotNullOfOrNull(PayloadIdTag::parse)?.ref - fun payloadId() = payloadIdReference()?.eventId - - /** Who wrote the payload, which is not who sent this submission. */ - fun payloadAuthor() = payloadIdReference()?.author - - companion object { - const val KIND = 30312 - const val ALT_DESCRIPTION = "Submission" - - fun build( - payload: Event, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, payload.toJson(), createdAt) { - alt(ALT_DESCRIPTION) - addUnique(PayloadKindTag.assemble(payload.kind)) - addUnique(PayloadIdTag.assemble(eventId = payload.id, pubkey = payload.pubKey)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationArtifactVersionContributorListEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationArtifactVersionContributorListEvent.kt deleted file mode 100644 index 4c6c049b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationArtifactVersionContributorListEvent.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils - - -@Immutable -class TranslationArtifactVersionContributorListEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - companion object { - const val KIND = 30305 - const val ALT_DESCRIPTION = "TranslationArtifactVersionContributorListEvent" - - fun build( - content: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, content, createdAt) { - alt(ALT_DESCRIPTION) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationArtifactVersionEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationArtifactVersionEvent.kt deleted file mode 100644 index ac851170..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationArtifactVersionEvent.kt +++ /dev/null @@ -1,59 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.DialectIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.LicenseTag -import com.machankura.bennu.compose.nostr.nip30303.tags.NameTag -import com.machankura.bennu.compose.nostr.nip30303.tags.VisibilityTag - - -@Immutable -class TranslationArtifactVersionEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - fun name() = tags.firstNotNullOfOrNull(NameTag::parse)?.name - fun visibility() = tags.firstNotNullOfOrNull(VisibilityTag::parse)?.visibility - fun license() = tags.firstNotNullOfOrNull(LicenseTag::parse)?.license - - fun artifactVersionIdReference() = tags.firstNotNullOfOrNull(ArtifactVersionIdTag::parse)?.ref - fun artifactVersionId() = artifactVersionIdReference()?.eventId - - fun dialectIdReference() = tags.firstNotNullOfOrNull(DialectIdTag::parse)?.ref - fun dialectId() = dialectIdReference()?.eventId - - companion object { - const val KIND = 30306 - const val ALT_DESCRIPTION = "TranslationArtifactVersion" - - fun build( - artifactVersionId: String, - dialectId: String, - name: String, - visibility: String, - license: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, "", createdAt) { - alt(ALT_DESCRIPTION) - addUnique(ArtifactVersionIdTag.assemble(artifactVersionId)) - addUnique(DialectIdTag.assemble(dialectId)) - addUnique(NameTag.assemble(name)) - addUnique(VisibilityTag.assemble(visibility)) - addUnique(LicenseTag.assemble(license)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChapterContributorListEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChapterContributorListEvent.kt deleted file mode 100644 index 62ce9b9a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChapterContributorListEvent.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils - - -@Immutable -class TranslationChapterContributorListEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - companion object { - const val KIND = 30307 - const val ALT_DESCRIPTION = "TranslationChapterContributorListEvent" - - fun build( - content: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, content, createdAt) { - alt(ALT_DESCRIPTION) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChapterEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChapterEvent.kt deleted file mode 100644 index d37c9bfc..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChapterEvent.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ChapterIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag - - -@Immutable -class TranslationChapterEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - fun translationArtifactVersionIdReference() = tags.firstNotNullOfOrNull(TranslationArtifactVersionIdTag::parse)?.ref - fun translationArtifactVersionId() = translationArtifactVersionIdReference()?.eventId - - fun chapterIdReference() = tags.firstNotNullOfOrNull(ChapterIdTag::parse)?.ref - fun chapterId() = chapterIdReference()?.eventId - - fun index() = tags.firstNotNullOfOrNull(IndexTag::parse)?.index - - companion object { - const val KIND = 30308 - const val ALT_DESCRIPTION = "TranslationChapter" - - fun build( - translationArtifactVersionId: String, - chapterId: String, - index: Int, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, "", createdAt) { - alt(ALT_DESCRIPTION) - addUnique(TranslationArtifactVersionIdTag.assemble(translationArtifactVersionId)) - addUnique(ChapterIdTag.assemble(chapterId)) - addUnique(IndexTag.assemble(index)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChunkEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChunkEvent.kt deleted file mode 100644 index 725d5421..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChunkEvent.kt +++ /dev/null @@ -1,55 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ChunkIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChapterIdTag - - -@Immutable -class TranslationChunkEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - fun translationChapterIdReference() = tags.firstNotNullOfOrNull(TranslationChapterIdTag::parse)?.ref - fun translationChapterId() = translationChapterIdReference()?.eventId - - fun index() = tags.firstNotNullOfOrNull(IndexTag::parse)?.index - - fun chunkIdReference() = tags.firstNotNullOfOrNull(ChunkIdTag::parse)?.ref - fun chunkId() = chunkIdReference()?.eventId - - companion object { - const val KIND = 30309 - const val ALT_DESCRIPTION = "TranslationChunk" - - fun build( - translationChapterId: String, - chunkId: String, - index: Int, - text: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, text, createdAt) { - alt(ALT_DESCRIPTION) - addUnique(TranslationChapterIdTag.assemble(translationChapterId)) - addUnique(ChunkIdTag.assemble(chunkId)) - addUnique(IndexTag.assemble(index)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChunkProposalEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChunkProposalEvent.kt deleted file mode 100644 index 2032dbe6..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationChunkProposalEvent.kt +++ /dev/null @@ -1,55 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.ChunkIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChapterIdTag - - -@Immutable -class TranslationChunkProposalEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - fun translationChapterIdReference() = tags.firstNotNullOfOrNull(TranslationChapterIdTag::parse)?.ref - fun translationChapterId() = translationChapterIdReference()?.eventId - - fun index() = tags.firstNotNullOfOrNull(IndexTag::parse)?.index - - fun chunkIdReference() = tags.firstNotNullOfOrNull(ChunkIdTag::parse)?.ref - fun chunkId() = chunkIdReference()?.eventId - - companion object { - const val KIND = 30309 - const val ALT_DESCRIPTION = "TranslationChunk" - - fun build( - translationChapterId: String, - chunkId: String, - index: Int, - text: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, text, createdAt) { - alt(ALT_DESCRIPTION) - addUnique(TranslationChapterIdTag.assemble(translationChapterId)) - addUnique(ChunkIdTag.assemble(chunkId)) - addUnique(IndexTag.assemble(index)) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationContributorListEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationContributorListEvent.kt deleted file mode 100644 index ac186cef..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationContributorListEvent.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils - - -@Immutable -class TranslationContributorListEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - companion object { - const val KIND = 30310 - const val ALT_DESCRIPTION = "TranslationContributorListEvent" - - fun build( - content: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, content, createdAt) { - alt(ALT_DESCRIPTION) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationEvent.kt deleted file mode 100644 index 978f0eea..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/TranslationEvent.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import androidx.compose.runtime.Immutable -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.TagArrayBuilder -import com.vitorpamplona.quartz.nip01Core.signers.eventTemplate -import com.vitorpamplona.quartz.nip22Comments.RootScope -import com.vitorpamplona.quartz.nip31Alts.alt -import com.vitorpamplona.quartz.nip50Search.SearchableEvent -import com.vitorpamplona.quartz.utils.TimeUtils -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationChunkIdTag - - -@Immutable -class TranslationEvent( - id: HexKey, - pubKey: HexKey, - createdAt: Long, - tags: Array>, - content: String, - sig: HexKey, -) : Event(id, pubKey, createdAt, KIND, tags, content, sig) { - - fun translationChunkIdReference() = tags.firstNotNullOfOrNull(TranslationChunkIdTag::parse)?.ref - fun translationChunkId() = translationChunkIdReference()?.eventId - - fun translationArtifactVersionIdReference() = tags.firstNotNullOfOrNull(TranslationArtifactVersionIdTag::parse)?.ref - fun translationArtifactVersionId() = translationArtifactVersionIdReference()?.eventId - - companion object { - const val KIND = 30311 - const val ALT_DESCRIPTION = "Translation" - - fun build( - content: String, - createdAt: Long = TimeUtils.now(), - initializer: TagArrayBuilder.() -> Unit = {}, - ) = eventTemplate(KIND, content, createdAt) { - alt(ALT_DESCRIPTION) - initializer() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactIdTag.kt deleted file mode 100644 index 05679d22..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -data class ArtifactIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "artifactId" - - fun parse(tag: Array): ArtifactIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return ArtifactIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactVersionIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactVersionIdTag.kt deleted file mode 100644 index ceed58a3..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactVersionIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class ArtifactVersionIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "artifactVersionId" - - fun parse(tag: Array): ArtifactVersionIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return ArtifactVersionIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactVersionMetadataTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactVersionMetadataTag.kt deleted file mode 100644 index ebb206d9..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ArtifactVersionMetadataTag.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class ArtifactVersionMetadataTag( - val versionLabel: String, -) { - fun toTagArray() = assemble( - versionLabel = versionLabel, - ) - - companion object { - const val TAG_NAME = "artifactVersion" - - fun parse(tag: Array): ArtifactVersionMetadataTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return ArtifactVersionMetadataTag( - versionLabel = tag[1], - ) - } - - fun assemble( - versionLabel: String, - ): Array = arrayOf( - TAG_NAME, - versionLabel - ) - - fun assemble(artifactVersionMetadataTag: ArtifactVersionMetadataTag) = assemble( - versionLabel = artifactVersionMetadataTag.versionLabel, - ) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ChapterIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ChapterIdTag.kt deleted file mode 100644 index 898388c2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ChapterIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class ChapterIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "chapterIdTag" - - fun parse(tag: Array): ChapterIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return ChapterIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ChunkIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ChunkIdTag.kt deleted file mode 100644 index 0ef01f08..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ChunkIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class ChunkIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "chunkIdTag" - - fun parse(tag: Array): ChunkIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return ChunkIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ContributorTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ContributorTag.kt deleted file mode 100644 index 71ebe987..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/ContributorTag.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -/** - * Based on NIP-F4 - */ -class ContributorTag( - val pubKey: HexKey, - val role: String? = null, -) { - fun toTagArray() = assemble(pubKey, role) - - companion object { - const val TAG_NAME = "p" - - const val ROLE_TRANSLATOR = "translator" - const val ROLE_PROOF_READER = "proofreader" - const val ROLE_EDITOR = "editor" - - private val KNOWN_ROLES = setOf(ROLE_TRANSLATOR, ROLE_PROOF_READER, ROLE_EDITOR) - - fun isTagged(tag: Array) = tag.has(1) && tag[0] == TAG_NAME && tag[1].length == 64 - - fun parse(tag: Array): ContributorTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - // NIP-F4 overloads slot 2 as role — but only host/cohost/editor are spec-defined. - // Anything else (notably a stale relay-hint URL copied from a kind:3 p-tag) gets - // dropped so it doesn't render as 'Role: wss://relay…' under the author chip. - val role = tag.getOrNull(2)?.takeIf { it in KNOWN_ROLES } - return ContributorTag(tag[1], role) - } - - fun assemble( - pubKey: HexKey, - role: String? = null, - ): Array = - if (role.isNullOrEmpty()) { - arrayOf(TAG_NAME, pubKey) - } else { - arrayOf(TAG_NAME, pubKey, role) - } - - fun assemble(author: ContributorTag) = assemble(author.pubKey, author.role) - - fun assemble(authors: List) = authors.map { assemble(it) } - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/CountryTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/CountryTag.kt deleted file mode 100644 index 07b578fd..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/CountryTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class CountryTag( - val country: String, -) { - fun toTagArray() = assemble(country = country) - - companion object { - const val TAG_NAME = "country" - - fun parse(tag: Array): CountryTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return CountryTag(country = tag[1]) - } - - fun assemble(country: String): Array = arrayOf(TAG_NAME, country) - - fun assemble(countryTag: CountryTag) = assemble(country = countryTag.country) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/DialectIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/DialectIdTag.kt deleted file mode 100644 index 7b544d8e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/DialectIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class DialectIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "dialectIdTag" - - fun parse(tag: Array): DialectIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return DialectIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/IndexTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/IndexTag.kt deleted file mode 100644 index 10833c25..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/IndexTag.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class IndexTag( - val index: Int, -) { - fun toTagArray() = assemble( - index = index, - ) - - companion object { - const val TAG_NAME = "index" - - fun parse(tag: Array): IndexTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - val index = tag[1].toIntOrNull() ?: return null - return IndexTag( - index = index, - ) - } - - fun assemble( - index: Int, - ): Array = arrayOf( - TAG_NAME, - index.toString() - ) - - fun assemble(indexTag: IndexTag) = assemble( - index = indexTag.index, - ) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/LanguageTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/LanguageTag.kt deleted file mode 100644 index 3060d6c6..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/LanguageTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class LanguageTag( - val language: String, -) { - fun toTagArray() = assemble(language = language) - - companion object { - const val TAG_NAME = "language" - - fun parse(tag: Array): LanguageTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return LanguageTag(language = tag[1]) - } - - fun assemble(language: String): Array = arrayOf(TAG_NAME, language) - - fun assemble(languageTag: LanguageTag) = assemble(language = languageTag.language) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/LicenseTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/LicenseTag.kt deleted file mode 100644 index 3bf5a07b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/LicenseTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class LicenseTag( - val license: String, -) { - fun toTagArray() = assemble(license = license) - - companion object { - const val TAG_NAME = "license" - - fun parse(tag: Array): LicenseTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return LicenseTag(license = tag[1]) - } - - fun assemble(license: String): Array = arrayOf(TAG_NAME, license) - - fun assemble(licenseTag: LicenseTag) = assemble(license = licenseTag.license) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/NameTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/NameTag.kt deleted file mode 100644 index d467590c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/NameTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class NameTag( - val name: String, -) { - fun toTagArray() = assemble(name = name) - - companion object { - const val TAG_NAME = "name" - - fun parse(tag: Array): NameTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return NameTag(name = tag[1]) - } - - fun assemble(name: String): Array = arrayOf(TAG_NAME, name) - - fun assemble(nameTag: NameTag) = assemble(name = nameTag.name) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/OriginalTextTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/OriginalTextTag.kt deleted file mode 100644 index 29c06d83..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/OriginalTextTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class OriginalTextTag( - val originalText: String, -) { - fun toTagArray() = assemble(originalText = originalText) - - companion object { - const val TAG_NAME = "original_text" - - fun parse(tag: Array): OriginalTextTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return OriginalTextTag(originalText = tag[1]) - } - - fun assemble(originalText: String): Array = arrayOf(TAG_NAME, originalText) - - fun assemble(originalTextTag: OriginalTextTag) = assemble(originalText = originalTextTag.originalText) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/PayloadIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/PayloadIdTag.kt deleted file mode 100644 index b8f9a4a0..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/PayloadIdTag.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -/** - * The event a submission carries, named on the submission itself. - * - * The payload is already in the submission's content, so this tag is not how a - * reader gets at it -- it is how they filter for it. The author slot matters - * more than usual here: on a submission it names whoever wrote the payload, - * who is not necessarily the member who submitted it. - */ -data class PayloadIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "payloadId" - - fun parse(tag: Array): PayloadIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return PayloadIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/PayloadKindTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/PayloadKindTag.kt deleted file mode 100644 index 4ab55914..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/PayloadKindTag.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -/** - * The kind of the event a submission carries. - * - * Lets a client decide whether it can apply a submission without parsing the - * payload JSON out of the content first. - */ -class PayloadKindTag( - val kind: Int, -) { - fun toTagArray() = assemble( - kind = kind, - ) - - companion object { - const val TAG_NAME = "payloadKind" - - fun parse(tag: Array): PayloadKindTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - val kind = tag[1].toIntOrNull() ?: return null - return PayloadKindTag( - kind = kind, - ) - } - - fun assemble( - kind: Int, - ): Array = arrayOf( - TAG_NAME, - kind.toString() - ) - - fun assemble(payloadKindTag: PayloadKindTag) = assemble( - kind = payloadKindTag.kind, - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationArtifactVersionIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationArtifactVersionIdTag.kt deleted file mode 100644 index 2cb6e164..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationArtifactVersionIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class TranslationArtifactVersionIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "translationArtifactVersionId" - - fun parse(tag: Array): DialectIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return DialectIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationChapterIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationChapterIdTag.kt deleted file mode 100644 index 0bd306ac..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationChapterIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class TranslationChapterIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "translationChapterIdTag" - - fun parse(tag: Array): TranslationChapterIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return TranslationChapterIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationChunkIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationChunkIdTag.kt deleted file mode 100644 index 7d448c61..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationChunkIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class TranslationChunkIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "translationChunkIdTag" - - fun parse(tag: Array): TranslationChunkIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return TranslationChunkIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationIdTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationIdTag.kt deleted file mode 100644 index ba7361d6..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/TranslationIdTag.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.tags.events.EventReference -import com.vitorpamplona.quartz.utils.arrayOfNotNull -import com.vitorpamplona.quartz.utils.ensure - -class TranslationIdTag( - val ref: EventReference, -) { - constructor(eventId: String, relayHint: NormalizedRelayUrl?, pubkey: String?) : this( - EventReference(eventId, pubkey, relayHint) - ) - - companion object { - const val TAG_NAME = "translationIdTag" - - fun parse(tag: Array): TranslationIdTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(tag[1].length == 64) { return null } - - val relayHint = tag.getOrNull(2)?.let { RelayUrlNormalizer.normalizeOrNull(it) } - - return TranslationIdTag(tag[1], relayHint, tag.getOrNull(3)) - } - - fun assemble( - eventId: HexKey, - relay: NormalizedRelayUrl? = null, - pubkey: String? = null, - ) = arrayOfNotNull(TAG_NAME, eventId, relay?.url, pubkey) - - fun assemble(ref: EventReference) = assemble(ref.eventId, ref.relayHint, ref.author) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/UrlTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/UrlTag.kt deleted file mode 100644 index c0f1b10a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/UrlTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class UrlTag( - val url: String, -) { - fun toTagArray() = assemble(url = url) - - companion object { - const val TAG_NAME = "url" - - fun parse(tag: Array): UrlTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return UrlTag(url = tag[1]) - } - - fun assemble(url: String): Array = arrayOf(TAG_NAME, url) - - fun assemble(urlTag: UrlTag) = assemble(url = urlTag.url) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/VisibilityTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/VisibilityTag.kt deleted file mode 100644 index 267551c2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/VisibilityTag.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class VisibilityTag( - val visibility: String, -) { - fun toTagArray() = assemble(visibility = visibility) - - companion object { - const val TAG_NAME = "visibility" - - fun parse(tag: Array): VisibilityTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - return VisibilityTag(visibility = tag[1]) - } - - fun assemble(visibility: String): Array = arrayOf(TAG_NAME, visibility) - - fun assemble(visibilityTag: VisibilityTag) = assemble(visibility = visibilityTag.visibility) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/WordStatisticsTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/WordStatisticsTag.kt deleted file mode 100644 index 9728424e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/nip30303/tags/WordStatisticsTag.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -class WordStatisticsTag( - val wordCount: Int, - val characterCount: Int, -) { - fun toTagArray() = assemble( - wordCount = wordCount, - characterCount = characterCount, - ) - - companion object { - const val TAG_NAME = "word_stats" - - fun parse(tag: Array): WordStatisticsTag? { - ensure(tag.has(2)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - - val wordCount = tag[1].toIntOrNull() ?: return null - val characterCount = tag[2].toIntOrNull() ?: return null - - return WordStatisticsTag( - wordCount = wordCount, - characterCount = characterCount, - ) - } - - fun assemble( - wordCount: Int, - characterCount: Int, - ): Array = arrayOf( - TAG_NAME, - wordCount.toString(), - characterCount.toString(), - ) - - fun assemble(wordStatisticsTag: WordStatisticsTag) = assemble( - wordCount = wordStatisticsTag.wordCount, - characterCount = wordStatisticsTag.characterCount, - ) - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt index 3a37c245..a8249c02 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt @@ -5,11 +5,14 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag import com.vitorpamplona.quartz.nip01Core.tags.people.PTag +import com.machankura.bennu.compose.managers.GuardianDerivation import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.frost.tags.FrostDerivationPathTag +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupKeyTag import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupParentTag +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag /** * A group saying, with a quorum, that another group is its child. @@ -50,6 +53,28 @@ import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupParentTag * can check `marmotGroupId(key, path) == content` for itself, which is the * difference between approving a hash and approving a group. * + * ### Guardian keys + * + * A certificate may also carry [GuardianTag]s: the parent's own guardian key for + * this child, and behind it every key the parent's ancestors granted the parent, + * each one public step further -- `GuardianDerivation.grant`. Carrying them is + * the parent agreeing to guard the child's wallet, if the child ever opens a + * guarded one; it delegates nothing on its own. They are not among the checks in + * [certifies], which is about lineage. Whether they are the keys the parent + * grants is checked by every parent signer before the certificate is signed -- + * `SubgroupManager.refuseCertificate` -- and nowhere after, because nobody else holds + * the key that check needs and nobody else needs it: the parent's quorum can + * already spend through its own leaf whatever the others would let it. + * + * ### The wallet policy + * + * A certificate may carry a [WalletPolicyTag]: the parent deciding whether the + * child's wallet is guarded or unguarded, rather than leaving it to the child -- + * `docs/subgroup-wallet-policy.md`. A guarded certificate carries the guardian + * keys and an unguarded one carries none, and [parseWalletPolicy] refuses one + * whose policy and keys disagree. Like the keys, the policy is not among the + * checks in [certifies]: it is read where it is used. + * * ### What [certifies] deliberately does not check * * The name and the `p` tags are the **founding** roster. A certificate is signed @@ -95,14 +120,53 @@ object SubgroupBirthCertificateEvent { thresholdPublicKey: HexKey, adminPublicKeys: List, name: String, - path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH + path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, + guardians: List = emptyList(), + walletPolicy: SubgroupWalletPolicy? = null ): Array> = arrayOf( DTag.assemble(subgroupChatRoomId), SubgroupParentTag.assemble(parentChatRoomId), SubgroupKeyTag.assemble(thresholdPublicKey), FrostDerivationPathTag.assemble(path), arrayOf(NAME_TAG_NAME, name) - ) + adminPublicKeys.distinct().map { PTag.assemble(it, null) } + ) + adminPublicKeys.distinct().map { PTag.assemble(it, null) } + + guardians.map(GuardianTag::assemble) + + listOfNotNull(walletPolicy?.let(WalletPolicyTag::assemble)) + + /** + * What the certificate says about the child's wallet: [WalletPolicyReading.Undecided] + * when it carries no policy, as every certificate from before policies does, + * and null when the reading cannot be used -- + * + * - a `wallet` tag that does not read, or two of them; + * - guardian keys that do not read; + * - a policy that contradicts the keys beside it: `guarded` with none, or + * `unguarded` with some. + * + * A certificate that says one thing in its policy and another in its keys is + * not a thing to guess the meaning of, and a policy present and unreadable + * must never read as absent -- that would hand the child the choice the + * parent took away. + */ + fun parseWalletPolicy(tags: Array>): WalletPolicyReading? { + val guardians = parseGuardians(tags) ?: return null + return when (val tag = WalletPolicyTag.parseOne(tags)) { + WalletPolicyTag.Result.Absent -> WalletPolicyReading.Undecided + WalletPolicyTag.Result.Unreadable -> null + is WalletPolicyTag.Result.Present -> when (tag.policy) { + SubgroupWalletPolicy.GUARDED -> WalletPolicyReading.Decided(tag.policy).takeIf { guardians.isNotEmpty() } + SubgroupWalletPolicy.UNGUARDED -> WalletPolicyReading.Decided(tag.policy).takeIf { guardians.isEmpty() } + } + } + } + + /** + * The guardian keys the parent grants the child, nearest first -- empty for a + * certificate that carries none, and null when one is unreadable, so that a + * list with an entry quietly dropped is never mistaken for the list. + */ + fun parseGuardians(tags: Array>): List? = + GuardianTag.parseAll(tags) /** The child this certificate is about, or null if it names none. */ fun parseSubgroupChatRoomId(tags: Array>): String? = diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupWalletPolicy.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupWalletPolicy.kt new file mode 100644 index 00000000..d275faef --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupWalletPolicy.kt @@ -0,0 +1,60 @@ +package com.machankura.bennu.compose.nostr.subgroup + +/** + * What a parent decided, at a subgroup's birth, about the subgroup's wallet -- + * `docs/subgroup-wallet-policy.md`. + * + * Chosen by the coordinator on the subgroup picker, carried on the ceremony + * proposal so every admin sees it before joining, and signed by the parent's + * quorum into the birth certificate. Every honest device then offers, signs, + * derives and watches only the wallet it allows. + * + * Not a rule the chain enforces: the child's key is the child's, and a quorum of + * modified clients can sign whatever it likes with it. It is the parent's signed + * decision, which every client running this app keeps. + */ +enum class SubgroupWalletPolicy(val tagValue: String) { + /** + * The child can only open a guarded wallet, and its certificate carries the + * guardian keys that wallet's leaves are built from. A guarded group's own + * subgroups are guarded too. + */ + GUARDED("guarded"), + + /** + * The child can only open a plain wallet. Its certificate carries no guardian + * keys, so nothing above it can reach its wallet or anything beneath it. + */ + UNGUARDED("unguarded"); + + companion object { + fun fromTagValue(value: String): SubgroupWalletPolicy? = entries.firstOrNull { it.tagValue == value } + } +} + +/** What a birth certificate says about the child's wallet. */ +sealed interface WalletPolicyReading { + /** The parent decided, and signed it. */ + data class Decided(val policy: SubgroupWalletPolicy) : WalletPolicyReading + + /** + * No policy tag: a certificate from before policies, which leaves the choice + * to the child -- a guarded wallet if its certificate carries keys, a plain + * one beside it either way. + */ + data object Undecided : WalletPolicyReading +} + +/** Whether this reading is the parent having decided [policy]. */ +fun WalletPolicyReading?.isDecided(policy: SubgroupWalletPolicy): Boolean = + (this as? WalletPolicyReading.Decided)?.policy == policy + +/** + * Whether a wallet that is [guarded] -- or plain, when false -- is one this + * reading allows: a decided policy allows its own kind only, and an undecided + * or absent one allows either, as before policies. + */ +fun WalletPolicyReading?.allows(guarded: Boolean): Boolean = when (this) { + is WalletPolicyReading.Decided -> guarded == (policy == SubgroupWalletPolicy.GUARDED) + WalletPolicyReading.Undecided, null -> true +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianDelayTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianDelayTag.kt new file mode 100644 index 00000000..77e7a6c5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianDelayTag.kt @@ -0,0 +1,44 @@ +package com.machankura.bennu.compose.nostr.subgroup.tags + +import com.machankura.bennu.compose.managers.GuardianDerivation + +/** + * The delay a coordinator chose for the parent's own leaf in a guarded + * subgroup's wallet, on the subgroup's ceremony proposal: + * + * ``` + * ["guardian_delay", ""] + * ``` + * + * Shown to every admin at the join gate, and what the certificate is later + * proposed under. Beside `["wallet", "guarded"]` and nowhere else. See + * `docs/guardian-delay.md`. + * + * Shape and range only. Whether it is the delay the certificate carries is the + * child signers' question, asked of the certificate. + */ +object GuardianDelayTag { + const val TAG_NAME = "guardian_delay" + + fun assemble(delay: Long): Array = arrayOf(TAG_NAME, delay.toString()) + + /** + * The delay [tags] carry: [Result.Absent] for none, the delay for exactly one + * that reads and is in `GuardianDerivation.DELAY_RANGE`, and + * [Result.Unreadable] otherwise -- a delay present and unusable is never + * mistaken for one absent. + */ + fun parseOne(tags: Array>): Result { + val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } + if (named.isEmpty()) return Result.Absent + if (named.size > 1) return Result.Unreadable + val delay = named.single().getOrNull(1)?.toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } + return delay?.let { Result.Present(it) } ?: Result.Unreadable + } + + sealed interface Result { + data object Absent : Result + data object Unreadable : Result + data class Present(val delay: Long) : Result + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt new file mode 100644 index 00000000..a94f9f11 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt @@ -0,0 +1,71 @@ +package com.machankura.bennu.compose.nostr.subgroup.tags + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.vitorpamplona.quartz.nip01Core.core.has +import com.vitorpamplona.quartz.utils.ensure +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PublicKey + +/** + * One ancestor's guardian key, as granted to the group a statement is about: + * + * ``` + * ["guardian", , <33-byte key hex>, <32-byte chain code hex>, ] + * ``` + * + * On a birth certificate it is the parent agreeing to guard the child -- its + * own key and every key its own ancestors gave it, one step further each, in + * that order -- and on a guarded wallet statement it is the child agreeing to be + * guarded by exactly those keys. See `GuardianDerivation` and + * `docs/group-wallet-guardians.md`. + * + * Shape only, as `SubgroupKeyTag` is. Whether a key is the one the ancestor + * actually grants is settled by rederiving it, never by looking at it. + */ +object GuardianTag { + const val TAG_NAME = "guardian" + + private val ROOM_ID = Regex("^[0-9a-f]{64}$") + private val KEY = Regex("^0[23][0-9a-f]{64}$") + private val CHAIN_CODE = Regex("^[0-9a-f]{64}$") + + fun assemble(guardian: GuardianDerivation.Guardian): Array = arrayOf( + TAG_NAME, + guardian.chatRoomId.lowercase(), + guardian.publicKey.toString(), + guardian.chainCode.toHex(), + guardian.delay.toString(), + ) + + /** The guardian [tag] names, or null when it is not a guardian tag or any of its fields is the wrong shape. */ + fun parse(tag: Array): GuardianDerivation.Guardian? { + ensure(tag.has(4)) { return null } + ensure(tag[0] == TAG_NAME) { return null } + ensure(ROOM_ID.matches(tag[1])) { return null } + ensure(KEY.matches(tag[2])) { return null } + ensure(CHAIN_CODE.matches(tag[3])) { return null } + // Within the range a leaf may carry, so a delay a modified client wrote + // below the floor is a tag that does not read, rather than a leaf that + // lets a guardian race the child. Every tag before this said 12. + val delay = tag[4].toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } ?: return null + + val publicKey = runCatching { PublicKey.fromHex(tag[2]) }.getOrNull()?.takeIf { it.isValid() } ?: return null + return GuardianDerivation.Guardian( + chatRoomId = tag[1], + publicKey = publicKey, + chainCode = ByteVector32(tag[3]), + delay = delay, + ) + } + + /** + * Every guardian in [tags], in order -- or null when any tag *named* + * `guardian` fails to read. A list with one entry quietly dropped is a + * different list, and the order is the tree. + */ + fun parseAll(tags: Array>): List? { + val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } + val parsed = named.mapNotNull(::parse) + return parsed.takeIf { it.size == named.size } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/WalletPolicyTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/WalletPolicyTag.kt new file mode 100644 index 00000000..41048607 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/WalletPolicyTag.kt @@ -0,0 +1,49 @@ +package com.machankura.bennu.compose.nostr.subgroup.tags + +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy + +/** + * A subgroup's wallet policy, as its parent decided it: + * + * ``` + * ["wallet", "guarded" | "unguarded"] + * ``` + * + * On a key ceremony's proposal it is what the coordinator chose, shown to every + * admin before they join; on a birth certificate it is the parent's quorum + * signing that choice. See `SubgroupWalletPolicy` and + * `docs/subgroup-wallet-policy.md`. + * + * Shape only, as `GuardianTag` is. Whether a policy agrees with the guardian + * keys beside it is the certificate's question, not the tag's. + */ +object WalletPolicyTag { + const val TAG_NAME = "wallet" + + fun assemble(policy: SubgroupWalletPolicy): Array = arrayOf(TAG_NAME, policy.tagValue) + + /** The policy [tag] names, or null when it is not a wallet tag or names no policy this build knows. */ + fun parse(tag: Array): SubgroupWalletPolicy? { + if (tag.size < 2 || tag[0] != TAG_NAME) return null + return SubgroupWalletPolicy.fromTagValue(tag[1]) + } + + /** + * The policy [tags] carry: null for none, the policy for exactly one readable + * tag -- and [Unreadable] when a tag *named* `wallet` fails to read or there + * are two, so that a policy present and unreadable is never mistaken for one + * absent. + */ + fun parseOne(tags: Array>): Result { + val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } + if (named.isEmpty()) return Result.Absent + if (named.size > 1) return Result.Unreadable + return parse(named.single())?.let { Result.Present(it) } ?: Result.Unreadable + } + + sealed interface Result { + data object Absent : Result + data object Unreadable : Result + data class Present(val policy: SubgroupWalletPolicy) : Result + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt new file mode 100644 index 00000000..14cf44b9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt @@ -0,0 +1,150 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupBirthCertificateTag +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * A member asking the group for its key, and a member answering -- the two + * things a guarded wallet's grant is worked out from. + * + * A member's guarded wallet carries the group's leaf and its ancestors' leaves, + * and the member's own device works them out before it asks the group to guard + * anything: `GuardianDerivation.grant` over the group's threshold key and the + * guardian keys in the group's own birth certificate. Both are read off the + * group's verified key state, which only ceremony participants hold. A member + * welcomed later has neither. See `docs/member-guarded-wallets.md`, D4. + * + * ``` + * member without a key state --[ 30336, no content ]-> the room "what does this group sign with?" + * member holding one --[ 30336, the key + its cert ]-> the room + * the asking device checks the answer on its own + * ``` + * + * ### Nothing the answerer says is taken on its word + * + * The answer carries the threshold key, the path, and the certificate if the + * group has one, and every one of them checks itself: the key at the path + * rederives the room's id, and the certificate certifies that room and names + * that key. A forged answer cannot name another key, and one that leaves out or + * swaps the certificate gives a grant every signer refuses, because each signer + * works the grant out again from its own key state. + * + * The signed key state itself is not carried: its row keeps what it said and not + * the event, and nothing in it is needed beyond what checks itself. + * + * ### The group's policy on members' wallets, too + * + * An answer also carries, whole, the newest `MemberWalletPolicyEvent` the + * answering device holds -- the other thing a late member needs before asking + * for a wallet, and one MLS will not let them read from before their welcome. + * It checks itself as well: the group's own room signed it. See + * `docs/member-wallet-delay.md`, Phase 3. + * + * ### Never filed as key state + * + * An answer is read in one place, for one purpose, every time it is used. Filing + * it into `GroupKeyState` would give every late member a key state and quietly + * change what `GroupWalletManager.thresholdKeyFor` answers for them across the + * app. + * + * ### Why 30336 + * + * After the member wallet's certificate (30334) and request (30335). + */ +object GroupKeyNoticeEvent { + val KIND: Kind = 30336 + + private const val ROOM_TAG = "h" + private const val REQUEST_TAG = "e" + private const val PATH_TAG = "frost_path" + private const val POLICY_TAG = "member_wallet_policy" + + /** What a group signs with, as a member's device has checked it. */ + data class GroupKey( + val chatRoomId: String, + val thresholdPublicKey: HexKey, + /** The group's own birth certificate, or null for a group nobody's subgroup. */ + val certificate: Event?, + /** + * The group's newest policy on its members' wallets as the answer carried + * it, verified, or null when the answering device held none. Never read + * off a key state: `MemberWalletManager.policyFor` reads the group's own. + */ + val policy: MemberWalletPolicyEvent.Policy? = null, + ) { + /** The guardian keys the group's certificate grants it, nearest first: what it passes down. */ + val guardians: List + get() = certificate?.let { SubgroupBirthCertificateEvent.parseGuardians(it.tags) }.orEmpty() + } + + /** The asking shape's tags. */ + fun askingTags(chatRoomId: String): Array> = arrayOf(arrayOf(ROOM_TAG, chatRoomId)) + + /** The answering shape's tags, answering [requestId]. The content is [GroupKey.thresholdPublicKey]. */ + fun answeringTags(requestId: HexKey, groupKey: GroupKey, path: List): Array> = + listOfNotNull( + arrayOf(ROOM_TAG, groupKey.chatRoomId), + arrayOf(REQUEST_TAG, requestId), + arrayOf(PATH_TAG, SharedKeyDerivation.formatPath(path)), + groupKey.certificate?.let { SubgroupBirthCertificateTag.assemble(it) }, + groupKey.policy?.let { arrayOf(POLICY_TAG, it.event.toJson()) }, + ).toTypedArray() + + /** Whether [event] asks rather than answers. */ + fun isAsking(event: Event): Boolean = event.kind == KIND && event.content.isBlank() + + /** The asking notice [event] answers, or null when it answers none. */ + fun answers(event: Event): HexKey? = + event.takeIf { it.kind == KIND && it.content.isNotBlank() }?.tags + ?.firstOrNull { it.size >= 2 && it[0] == REQUEST_TAG }?.get(1) + + /** + * The key [event] says [chatRoomId] signs with, or null when it is not an + * answer or does not check out: + * + * 1. it is an answer, and names [chatRoomId]; + * 2. the key at the path it names rederives [chatRoomId]; + * 3. a certificate it carries certifies [chatRoomId], names that key, and + * reads -- its guardian keys and its wallet policy both. One present and + * unreadable is refused rather than read as none, for the reason + * `GroupKeyStateManager.stateFrom` refuses it; + * 4. a member-wallet policy it carries is [chatRoomId]'s own, signed by + * the room. The same rule: present and unreadable is not "no policy". + */ + fun read(event: Event, chatRoomId: String): GroupKey? = runCatching { + if (event.kind != KIND || event.content.isBlank()) return null + fun value(name: String): String? = event.tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + if (!value(ROOM_TAG).equals(chatRoomId, ignoreCase = true)) return null + + val thresholdPublicKey = event.content.trim().lowercase() + val path = value(PATH_TAG)?.let { SharedKeyDerivation.parsePathString(it) } ?: return null + if (!SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path).equals(chatRoomId, ignoreCase = true)) return null + + val certificateTags = event.tags.filter { it.isNotEmpty() && it[0] == SubgroupBirthCertificateTag.TAG_NAME } + if (certificateTags.size > 1) return null + val certificate = certificateTags.singleOrNull()?.let { tag -> + SubgroupBirthCertificateTag.parse(tag)?.certificate ?: return null + } + if (certificate != null) { + val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return null + if (!SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId)) return null + if (!SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true)) return null + SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) ?: return null + SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) ?: return null + } + + val policyTags = event.tags.filter { it.isNotEmpty() && it[0] == POLICY_TAG } + if (policyTags.size > 1) return null + val policy = policyTags.singleOrNull()?.let { tag -> + val carried = tag.getOrNull(1)?.let { Event.fromJsonOrNull(it) } ?: return null + MemberWalletPolicyEvent.verify(carried, chatRoomId) ?: return null + } + + GroupKey(chatRoomId = chatRoomId.lowercase(), thresholdPublicKey = thresholdPublicKey, certificate = certificate, policy = policy) + }.getOrNull() +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt index 1587e43a..119f2e22 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt @@ -1,5 +1,7 @@ package com.machankura.bennu.compose.nostr.wallet +import com.machankura.bennu.compose.nostr.subgroup.allows +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -15,9 +17,8 @@ import kotlin.time.Instant * threshold key -- [account] is what [GroupWalletStatementEvent.Reading.verifiedAgainst] * returned, never what the statement said. * - * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies], the way - * `GroupRelayList` is: only an event the room itself authored is the group - * speaking. + * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies]: only an + * event the room itself authored is the group speaking. */ data class GroupWallet( val signedEvent: GroupSignedEvent, @@ -51,20 +52,43 @@ data class GroupWallet( * The newest wallet the group opened on [chain] at [account], or null for * one it never has. * - * Newest by the group's own timestamp with the id breaking a tie, for the - * reason `GroupRelayList.newestAmong` gives: two devices reading the same - * events in different orders have to agree. + * Newest by the group's own timestamp with the id breaking a tie, because + * two devices reading the same events in different orders have to agree. + * + * Two rules first, for a guarded account, each of which keeps a later + * statement from moving every address of one already holding coins: + * + * 1. a guarded statement outranks a plain one -- an account opened guarded + * stays guarded, whatever a client that predates guardians signs later; + * 2. among guarded ones the earliest decides the guardians, and a later one + * naming others is ignored. Changing who guards a wallet is another + * account. + * + * And before either, a statement [policy] does not allow is no wallet at + * all -- `docs/subgroup-wallet-policy.md`. Under a parent that decided + * *guarded* a plain statement is ignored even with no guarded one beside + * it, which is stronger than rule 1: an older client's plain wallet then + * opens nothing on this device, no addresses derived and no coins + * watched, rather than a wallet the rest of the group refuses to spend. */ fun newestAmong( signedEvents: List, thresholdPublicKey: HexKey, chain: Chain, account: Long = 0L, - ): GroupWallet? = - signedEvents - .asSequence() + policy: WalletPolicyReading? = null, + ): GroupWallet? { + val order = compareBy({ it.openedAt }, { it.signedEvent.id }) + val opened = signedEvents .mapNotNull { of(it, thresholdPublicKey) } .filter { it.chain == chain && it.account.account == account } - .maxWithOrNull(compareBy({ it.openedAt }, { it.signedEvent.id })) + .filter { policy.allows(it.account.isGuarded) } + + val guarded = opened.filter { it.account.isGuarded } + val first = guarded.minWithOrNull(order) + ?: return opened.maxWithOrNull(order) + + return guarded.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) + } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt index c45589dc..1ec3bd0d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt @@ -1,6 +1,12 @@ package com.machankura.bennu.compose.nostr.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupBirthCertificateTag +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -33,11 +39,21 @@ import kotlin.time.Clock * statement naming any xpub but the rederived one is not the group's wallet, * whoever signed it. * + * ### A guarded statement + * + * A subgroup whose birth certificate grants it guardian keys may open its wallet + * *guarded*: every address carries a leaf per ancestor, and the statement is the + * child's quorum agreeing to that. It carries the guardians as [GuardianTag]s + * and the certificate itself, whole, so that a member who holds no key state -- + * one welcomed in after the founding -- can still check every address, and so + * that an ancestor it is forwarded to can check where its own key came from. + * See `docs/group-wallet-guardians.md`. + * * ### Never on a relay * * The xpub is every address and the whole balance, to whoever has it. Like the * signing kinds this only ever lives inside an encryption a relay cannot open, - * and the broadcast screen refuses it by kind -- see [NEVER_BROADCAST]. + * and nothing in the app sends a group-signed event to a relay. * * ### Why 30331 * @@ -50,9 +66,6 @@ import kotlin.time.Clock object GroupWalletStatementEvent { val KIND: Kind = 30331 - /** The kinds a member may never send to a relay, whatever the group signed. */ - val NEVER_BROADCAST: Set = setOf(KIND) + com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents.GROUP_SIGNED - private const val D_TAG = "d" private const val CHAIN_TAG = "chain" private const val ACCOUNT_TAG = "account" @@ -70,13 +83,24 @@ object GroupWalletStatementEvent { val xpub: String, val receiveDescriptor: String, val changeDescriptor: String, + /** The guardians it names, nearest first; empty for a plain statement. */ + val guardians: List = emptyList(), + /** The birth certificate a guarded statement carries, unverified. */ + val certificate: Event? = null, ) { /** * The account this statement describes, if [thresholdPublicKey] rederives * every value it carries; null otherwise. + * + * For a guarded one, also: the certificate certifies the room the key + * makes, it names that key, and its guardian keys are exactly the ones + * the statement names -- the guardians come from the parent's signature + * and the child's agreement together, or the statement opens nothing. */ fun verifiedAgainst(thresholdPublicKey: HexKey): GroupWalletDerivation.Account? { - val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account) } + if (guardians.isNotEmpty() && !guardiansCheckOut(thresholdPublicKey)) return null + + val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians) } .getOrNull() ?: return null @@ -86,6 +110,16 @@ object GroupWalletStatementEvent { it.changeDescriptor == changeDescriptor } } + + private fun guardiansCheckOut(thresholdPublicKey: HexKey): Boolean = runCatching { + val certificate = certificate ?: return false + val chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return false + + SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId) && + SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true) && + SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) == guardians + }.getOrDefault(false) } /** @@ -94,8 +128,24 @@ object GroupWalletStatementEvent { */ fun identifier(chain: Chain, account: Long): String = "${chainName(chain)}:$account" - fun template(account: GroupWalletDerivation.Account, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( + /** + * The statement opening [account]. A guarded account needs the [certificate] + * its guardians were granted in, which the statement carries whole. + */ + fun template( + account: GroupWalletDerivation.Account, + certificate: Event? = null, + createdAt: Long = Clock.System.now().epochSeconds, + ): EventTemplate<*> { + require(!account.isGuarded || certificate != null) { "a guarded wallet's statement carries the certificate that granted its guardians" } + + val guarded = if (account.isGuarded) { + account.guardians.map(GuardianTag::assemble) + listOf(SubgroupBirthCertificateTag.assemble(certificate!!)) + } else { + emptyList() + } + + return EventTemplate( createdAt = createdAt, kind = KIND, tags = arrayOf( @@ -104,9 +154,10 @@ object GroupWalletStatementEvent { arrayOf(ACCOUNT_TAG, account.account.toString()), arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), - ), + ) + guarded, content = account.xpub, ) + } /** The statement's fields, or null when any is missing or unreadable. Nothing is verified here. */ fun read(tags: Array>, content: String): Reading? { @@ -123,7 +174,11 @@ object GroupWalletStatementEvent { // account both stand; reading it back here keeps "newest per account" one rule. if (value(D_TAG) != identifier(chain, account)) return null - return Reading(chain, account, content, receive, change) + // Guardians that do not all read are not a shorter list of guardians. + val guardians = GuardianTag.parseAll(tags) ?: return null + val certificate = tags.firstNotNullOfOrNull(SubgroupBirthCertificateTag::parse)?.certificate + + return Reading(chain, account, content, receive, change, guardians, certificate) } /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt new file mode 100644 index 00000000..90bf334b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt @@ -0,0 +1,76 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * A member telling an ancestor group about a descendant's guarded wallet. + * + * The descendant's quorum signed a guarded `GroupWalletStatementEvent` in its + * own room, and the ancestors whose keys are in it are not in that room. A + * member who sits in both carries the statement across, whole, as the content of + * one of these in the ancestor's MLS room: + * + * ``` + * descendant's room every member holds the signed 30331 "we keep a guarded wallet" + * member in both --[ 30333 carrying it ]-> the ancestor's room + * every ancestor device checks it on its own, and watches the wallet + * ``` + * + * The forwarder vouches for nothing. A device believes the statement inside for + * the same reasons a descendant member does -- the descendant's room signed it, + * a certificate it carries certifies that room, the xpub rederives from the key + * the certificate names -- plus one of its own: its own guardian key in the + * statement is the key its group's walk reaches. See `GuardianManager.verify`. + * + * No table: the row the inbound path files for every inner event is the record, + * and each read checks it again. + * + * ### The guardian's birth certificate + * + * A notice carrying a member's wallet certificate (30334) also carries, where + * the forwarder holds it, the birth certificate of the group that signed it -- + * the 30329 its own parent signed: + * + * ``` + * kind: 30333 + * content: + * tags: + * ["h", ] + * ["certificate", ] + * ``` + * + * It is what lets a device in a group above, never in the guarding group's + * room, show the wallet under that group's founding name. It is a tag so an + * older build, which reads the content and nothing else, still believes the + * wallet; and it is checked rather than trusted, as everything here is -- a + * certificate that does not certify that group is ignored, and the wallet is + * believed all the same. `docs/member-wallet-guarding-group.md`, D4. + * + * ### Never on a relay + * + * The statement inside is an xpub, which is every address and the whole + * balance. Like the statement, this only ever lives inside an encryption a relay + * cannot open: it is an MLS application message and nothing else. + * + * ### Why 30333 + * + * The first free number past the transaction proposal (30332), beside the + * statement it carries. + */ +object GuardedWalletNoticeEvent { + val KIND: Kind = 30333 + + const val CERTIFICATE_TAG = "certificate" + + /** The statement a notice carries, or null when its content is not an event. Nothing is verified here. */ + fun statementOf(notice: Event): Event? = + notice.takeIf { it.kind == KIND }?.let { Event.fromJsonOrNull(it.content) } + + /** The guardian's birth certificate a notice's [tags] carry, or null. Nothing is verified here. */ + fun certificateIn(tags: Array>): Event? = + tags.firstOrNull { it.size >= 2 && it[0] == CERTIFICATE_TAG }?.let { Event.fromJsonOrNull(it[1]) } + + /** The tag carrying [certificate]. */ + fun certificateTag(certificate: Event): Array = arrayOf(CERTIFICATE_TAG, certificate.toJson()) +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt new file mode 100644 index 00000000..20c64a0a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt @@ -0,0 +1,158 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate + +/** + * A group saying it guards a wallet for one of its members: the group's + * signature over the member's request, and what every device opens the wallet + * on. + * + * ``` + * member --[ 30335 request, signed by them ]-> the group's room + * any signer --[ 30320 proposal over a 30334 ]-> the group's room + * ...a signing session... + * everyone holds the signed 30334 "this group guards W for this person" + * ``` + * + * ``` + * kind: 30334 + * pubkey: G set by the signing session + * created_at: the request's created_at so every sponsor proposes one event id + * content: W + * tags: + * ["d", W] + * ["p", ] + * ["wallet_key", ] + * ["chain", …] + * ["guardian", …] as in the request + * ["descriptor", …, "receive"] + * ["descriptor", …, "change"] + * ["label", …] if the request had one + * ["request", ] + * ``` + * + * ### Not a birth certificate + * + * A `SubgroupBirthCertificateEvent` says *this room is my child*, and every + * reader of 30329 assumes a room -- its `certifies` rederives one from the key, + * `SubgroupManager.subgroupsOf` lists one, the transcript announces one being + * born. A member's wallet is not a room, so it has its own kind and none of the + * lineage meaning. `docs/member-guarded-wallets.md`, "Should it be a birth + * certificate?". + * + * ### Built from the request and nothing else + * + * [template] is the only way a certificate is made, and [verify] checks one is + * exactly [template] of the request it carries. So the sponsor who puts a + * request to the group chooses nothing, two sponsors propose one event id, and + * no tag can say one thing in the request and another in the certificate. + * + * The request is embedded rather than looked up, as a guarded statement embeds + * its birth certificate: an ancestor who was never in the group's room can + * check that the member asked, from the group's signature alone. + * + * ### Never on a relay + * + * It carries an xpub. + * + * ### Why 30334 + * + * The first free number past the guarded-wallet notice (30333), which carries + * it upward to the groups above. + */ +object MemberWalletCertificateEvent { + val KIND: Kind = 30334 + + private const val D_TAG = "d" + private const val MEMBER_TAG = "p" + private const val REQUEST_TAG = "request" + + /** A certificate believed: who it guards a wallet for, and the wallet it opens. */ + data class Verified( + val certificate: Event, + val request: Event, + val groupChatRoomId: String, + val memberPublicKey: HexKey, + val walletId: String, + val label: String?, + /** The account the request rederived to, guardians and all. */ + val account: GroupWalletDerivation.Account, + ) + + /** + * The certificate [request] asks for: the request's own tags, minus the + * possession signature it already carries whole, under the wallet id. + */ + fun template(request: Event): EventTemplate<*> { + val reading = requireNotNull(MemberWalletRequestEvent.read(request)) { "not a request" } + val carried = request.tags.filterNot { it.isNotEmpty() && it[0] in setOf("h", "wallet", "possession") } + + return EventTemplate( + createdAt = request.createdAt, + kind = KIND, + tags = ( + listOf( + arrayOf(D_TAG, reading.walletId), + arrayOf(MEMBER_TAG, reading.memberPublicKey), + ) + carried + listOf(arrayOf(REQUEST_TAG, request.toJson())) + ).toTypedArray(), + content = reading.walletId, + ) + } + + /** The request [certificate] carries, or null. Nothing is verified here. */ + fun requestOf(certificate: Event): Event? = + certificate.tags.filter { it.size >= 2 && it[0] == REQUEST_TAG }.singleOrNull()?.let { Event.fromJsonOrNull(it[1]) } + + /** The member [certificate] names, or null. Nothing is verified here. */ + fun memberOf(certificate: Event): HexKey? = + certificate.tags.firstOrNull { it.size >= 2 && it[0] == MEMBER_TAG }?.get(1) + + /** + * [certificate] believed as [groupChatRoomId]'s, with no database: + * + * 1. it is a 30334, and the room signed it; + * 2. the request it carries is believed (`MemberWalletRequestEvent.verified`) + * and asked this room; + * 3. it is exactly [template] of that request -- every tag, the content and + * the time; + * 4. so its `p` is the member who asked. + * + * Whether the guardians are the ones the group grants is what the group's + * signers checked before signing. A reader trusts the group's quorum for + * that, and it is no new trust: that quorum can already take every coin. + * + * [signed] false is for a certificate still being proposed, which has no + * signature yet: everything else is checked, and its author has to be the + * room the session will sign as. + */ + fun verify(certificate: Event, groupChatRoomId: String, signed: Boolean = true): Verified? = runCatching { + if (certificate.kind != KIND) return null + if (signed && !GroupKeyStateEvent.isSignedByRoom(certificate, groupChatRoomId)) return null + if (!signed && !certificate.pubKey.equals(groupChatRoomId, ignoreCase = true)) return null + + val request = requestOf(certificate) ?: return null + val verified = MemberWalletRequestEvent.verified(request) ?: return null + if (!verified.reading.groupChatRoomId.equals(groupChatRoomId, ignoreCase = true)) return null + + val expected = template(request) + if (certificate.createdAt != expected.createdAt) return null + if (certificate.content != expected.content) return null + if (certificate.tags.map { it.toList() } != expected.tags.map { it.toList() }) return null + + Verified( + certificate = certificate, + request = request, + groupChatRoomId = groupChatRoomId.lowercase(), + memberPublicKey = verified.reading.memberPublicKey, + walletId = verified.reading.walletId, + label = verified.reading.label, + account = verified.account, + ) + }.getOrNull() +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEvent.kt new file mode 100644 index 00000000..f9cf0f74 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEvent.kt @@ -0,0 +1,136 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import kotlin.time.Clock + +/** + * A group saying, with a quorum, whether it guards its members' wallets and at + * what delay -- `docs/member-wallet-delay.md`. + * + * ``` + * open: ["d", "member-wallets"], ["guardian_delay", ""] + * closed: ["d", "member-wallets"], ["closed"] + * ``` + * + * Signed by the group's own quorum in its own room, about its own leaf: the + * delay on the group's leaf in every wallet a member asks it to guard from now + * on. Every group above keeps the delay it chose for the group, as it does in a + * subgroup's wallet. + * + * ### The group's opt-in + * + * No policy means the group does not guard members' wallets. A closed one means + * it has stopped: no new member wallets until a newer open one. Closing never + * releases a wallet already guarded -- the group's leaf is in every one of its + * addresses -- and a later policy never changes one, since each wallet's delay + * is fixed in its certificate. + * + * ### Not the birth certificate + * + * The certificate is the parent's statement about the group, signed once at its + * birth, and a root group has none. This is the group's decision about its own + * leaf, which the group can change. See the note's *Where the delay should live*. + * + * ### Why 30337 + * + * After the key notice (30336), the last of the member-wallet kinds. + */ +object MemberWalletPolicyEvent { + val KIND: Kind = 30337 + + /** The `d` tag: one policy about members' wallets per group, the newest winning. */ + const val IDENTIFIER = "member-wallets" + + private const val D_TAG = "d" + private const val DELAY_TAG = "guardian_delay" + private const val CLOSED_TAG = "closed" + + /** The group guards members' wallets, its own leaf at [delay] blocks. */ + fun open(delay: Long, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> { + require(delay in GuardianDerivation.DELAY_RANGE) { + "a guardian's delay is ${GuardianDerivation.MIN_DELAY} to ${GuardianDerivation.MAX_DELAY} blocks, not $delay" + } + return EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf(arrayOf(D_TAG, IDENTIFIER), arrayOf(DELAY_TAG, delay.toString())), + content = "", + ) + } + + /** The group takes no new members' wallets. */ + fun closed(createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf(arrayOf(D_TAG, IDENTIFIER), arrayOf(CLOSED_TAG)), + content = "", + ) + + /** What a policy says, as its group signed it. */ + sealed interface Policy { + val event: Event + val createdAt: Long get() = event.createdAt + + /** The group guards members' wallets, its own leaf at [delay] blocks. */ + data class Open(val delay: Long, override val event: Event) : Policy + + /** The group has stopped taking new members' wallets. */ + data class Closed(override val event: Event) : Policy + } + + /** + * [event] as [chatRoomId]'s policy, or null when it is not one: + * + * 1. the kind, and the `d` tag; + * 2. exactly one of a `guardian_delay` that reads and is in + * `GuardianDerivation.DELAY_RANGE`, or a bare `closed` -- a policy that + * says both, or neither, says nothing a device can act on; + * 3. signed by [chatRoomId] itself, which any device can check holding the + * room's id alone. + */ + fun verify(event: Event, chatRoomId: String): Policy? = runCatching { + val policy = read(event) ?: return null + if (!GroupKeyStateEvent.isSignedByRoom(event, chatRoomId)) return null + policy + }.getOrNull() + + /** + * What [event] says, by its shape alone -- checks 1 and 2 of [verify], and + * not the signature. For a proposal the group has not signed yet, which a + * signer reads before agreeing to it; anything that acts on a policy goes + * through [verify]. + */ + fun read(event: Event): Policy? = runCatching { + if (event.kind != KIND) return null + if (event.tags.count { it.size >= 2 && it[0] == D_TAG && it[1] == IDENTIFIER } != 1) return null + if (event.tags.any { it.isNotEmpty() && it[0] == D_TAG && (it.size < 2 || it[1] != IDENTIFIER) }) return null + + val delays = event.tags.filter { it.isNotEmpty() && it[0] == DELAY_TAG } + val closed = event.tags.filter { it.isNotEmpty() && it[0] == CLOSED_TAG } + val policy = when { + delays.size == 1 && closed.isEmpty() -> { + val delay = delays.single().getOrNull(1)?.toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } + ?: return null + Policy.Open(delay, event) + } + delays.isEmpty() && closed.size == 1 -> Policy.Closed(event) + else -> return null + } + policy + }.getOrNull() + + /** + * The newest of [events] that is [chatRoomId]'s policy, open or closed -- + * by the group's own timestamp, the id breaking a tie, so two devices that + * read the same events in another order agree. + */ + fun newestAmong(events: List, chatRoomId: String): Policy? = + events.mapNotNull { verify(it, chatRoomId) }.maxWithOrNull(ORDER) + + /** The order policies are compared in: [newestAmong]'s, and the signers' staleness check. */ + val ORDER: Comparator = compareBy({ it.createdAt }, { it.event.id }) +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt new file mode 100644 index 00000000..71bdea21 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt @@ -0,0 +1,262 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.MemberWalletDerivation +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import kotlin.time.Clock + +/** + * A member asking their group to guard a wallet only they can spend from. + * + * The member's device has already made the wallet's key, worked out every + * ancestor's leaf and both descriptors, and stored the key. This is the first + * thing that leaves the device, and it carries all of it, so the group signs off + * on a wallet the member has already built rather than one it builds for them. + * See `docs/member-guarded-wallets.md`, Phase 3. + * + * ``` + * kind: 30335 + * pubkey: + * content: + * tags: + * ["h", G] the group asked + * ["wallet", W] + * ["wallet_key", ] + * ["chain", "mainnet" | "signet" | …] + * ["guardian", , , , "12"] one per guardian, nearest first + * ["descriptor", tr(…,{…}), "receive"] + * ["descriptor", tr(…,{…}), "change"] + * ["label", "Savings"] optional + * ["possession", ] + * ``` + * + * ### Signed twice + * + * By the member's nostr key, so it is bound to who asked, and -- in the + * `possession` tag -- by the wallet key itself, over [possessionMessage], so the + * member is shown to hold the key they are asking about. Without the second, Bob + * could ask for a certificate on Alice's wallet key under his own name. + * + * `k` signs exactly that one message, under its own tagged hash. It is never an + * output key: the account step always tweaks it first. + * + * ### Carried whole + * + * An inner event is an unsigned rumor -- its authority is the MLS frame -- and the + * row it travels in keeps no signature. This one's signature has to survive the + * room, because the group's certificate embeds it for ancestors who were never + * in the room. So the room carries an inner event of this kind whose content is + * the signed request, whole, as a 30333 notice carries a statement: [carried]. + * + * ### Never on a relay + * + * It carries an xpub, which is every address and the whole balance. + * + * ### Why 30335 + * + * After the certificate it asks for, at 30334. + */ +object MemberWalletRequestEvent { + val KIND: Kind = 30335 + + private const val ROOM_TAG = "h" + private const val WALLET_TAG = "wallet" + private const val WALLET_KEY_TAG = "wallet_key" + private const val CHAIN_TAG = "chain" + private const val DESCRIPTOR_TAG = "descriptor" + private const val RECEIVE_MARKER = "receive" + private const val CHANGE_MARKER = "change" + private const val LABEL_TAG = "label" + private const val POSSESSION_TAG = "possession" + private const val POLICY_TAG = "member_wallet_policy" + + /** The tag of the possession signature's message. Frozen once a request carries one. */ + private const val POSSESSION_HASH_TAG = "bennu/member-wallet/possession/v1" + + /** The longest label a request carries: a name for a wallet, not a note. */ + const val MAX_LABEL_LENGTH = 64 + + /** What a request says, read but not yet believed. [verified] is what believes it. */ + data class Reading( + val memberPublicKey: HexKey, + val groupChatRoomId: String, + val walletId: String, + val walletKey: PublicKey, + val chain: Chain, + val xpub: String, + val receiveDescriptor: String, + val changeDescriptor: String, + val guardians: List, + val label: String?, + val possession: ByteVector64, + /** + * The group's member-wallet policy the request was built under, whole and + * unverified -- or null for a request from before policies, which every + * signer now refuses and every reader of an old certificate still + * accepts. See `docs/member-wallet-delay.md`. + */ + val policy: Event? = null, + ) + + /** A request that checks out on everything a reader can check without the group's key. */ + data class Verified( + val request: Event, + val reading: Reading, + /** The account the request opens, rederived from the wallet key -- never what it said. */ + val account: GroupWalletDerivation.Account, + /** The open policy it was built under, verified as the group's own; null for a request from before policies. */ + val policy: MemberWalletPolicyEvent.Policy.Open? = null, + ) + + /** + * What `k` signs: the member, the group, the wallet key and the network -- + * everything that has to bind one key to one person in one group on one chain. + */ + fun possessionMessage(memberPublicKey: HexKey, groupChatRoomId: String, walletKey: PublicKey, chain: Chain): ByteVector32 = + Crypto.taggedHash( + memberPublicKey.lowercase().hexToByteArray() + + groupChatRoomId.lowercase().hexToByteArray() + + walletKey.value.toByteArray() + + chain.chainHash.value.toByteArray(), + POSSESSION_HASH_TAG, + ) + + /** + * The request for [account] -- opened under the wallet key [walletPrivateKey] + * holds -- of [groupChatRoomId], signed as the member [memberPrivateKey] holds. + */ + fun build( + memberPrivateKey: PrivateKey, + groupChatRoomId: String, + walletPrivateKey: PrivateKey, + account: GroupWalletDerivation.Account, + label: String?, + createdAt: Long = Clock.System.now().epochSeconds, + /** The group's open policy the grant was worked out under, carried whole. */ + policy: Event? = null, + ): Event { + val memberPublicKey = memberPrivateKey.xOnlyPublicKey().value.toHex() + val walletKey = walletPrivateKey.publicKey() + require(account.extendedPublicKey == MemberWalletDerivation.account(walletKey, account.chain, account.guardians).extendedPublicKey) { + "the account is not the wallet key's" + } + val possession = Crypto.signSchnorr(possessionMessage(memberPublicKey, groupChatRoomId, walletKey, account.chain), walletPrivateKey, null) + + val tags = listOfNotNull( + arrayOf(ROOM_TAG, groupChatRoomId.lowercase()), + arrayOf(WALLET_TAG, MemberWalletDerivation.walletId(walletKey)), + arrayOf(WALLET_KEY_TAG, walletKey.toString()), + arrayOf(CHAIN_TAG, GroupWalletStatementEvent.chainName(account.chain)), + *account.guardians.map(GuardianTag::assemble).toTypedArray(), + arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), + arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), + label?.trim()?.takeIf { it.isNotEmpty() }?.let { arrayOf(LABEL_TAG, it.take(MAX_LABEL_LENGTH)) }, + policy?.let { arrayOf(POLICY_TAG, it.toJson()) }, + arrayOf(POSSESSION_TAG, possession.toHex()), + ).toTypedArray() + + val id = EventHasher.hashId(memberPublicKey, createdAt, KIND, tags, account.xpub) + val sig = Crypto.signSchnorr(ByteVector32(id), memberPrivateKey, null) + return Event(id = id, pubKey = memberPublicKey, createdAt = createdAt, kind = KIND, tags = tags, content = account.xpub, sig = sig.toHex()) + } + + /** The request's fields, or null when any is missing, doubled or the wrong shape. Nothing is verified here. */ + fun read(event: Event): Reading? = runCatching { + if (event.kind != KIND) return null + fun single(name: String): String? = + event.tags.filter { it.isNotEmpty() && it[0] == name }.takeIf { it.size == 1 }?.single()?.takeIf { it.size >= 2 }?.get(1) + fun descriptor(marker: String): String? = + event.tags.filter { it.size >= 3 && it[0] == DESCRIPTOR_TAG && it[2] == marker }.singleOrNull()?.get(1) + + val labels = event.tags.filter { it.isNotEmpty() && it[0] == LABEL_TAG } + if (labels.size > 1) return null + val label = labels.singleOrNull()?.getOrNull(1)?.takeIf { it.isNotBlank() && it.length <= MAX_LABEL_LENGTH } + if (labels.isNotEmpty() && label == null) return null + + // Present and unreadable is not "built under no policy". + val policies = event.tags.filter { it.isNotEmpty() && it[0] == POLICY_TAG } + if (policies.size > 1) return null + val policy = policies.singleOrNull()?.let { tag -> tag.getOrNull(1)?.let { Event.fromJsonOrNull(it) } ?: return null } + + Reading( + memberPublicKey = event.pubKey.lowercase(), + groupChatRoomId = single(ROOM_TAG)?.lowercase() ?: return null, + walletId = single(WALLET_TAG)?.lowercase() ?: return null, + walletKey = single(WALLET_KEY_TAG)?.let { PublicKey.fromHex(it) }?.takeIf { it.isValid() } ?: return null, + chain = single(CHAIN_TAG)?.let(GroupWalletStatementEvent::chainNamed) ?: return null, + xpub = event.content.takeIf { it.isNotBlank() } ?: return null, + receiveDescriptor = descriptor(RECEIVE_MARKER) ?: return null, + changeDescriptor = descriptor(CHANGE_MARKER) ?: return null, + guardians = GuardianTag.parseAll(event.tags)?.takeIf { it.isNotEmpty() } ?: return null, + label = label, + possession = single(POSSESSION_TAG)?.let { ByteVector64(it) } ?: return null, + policy = policy, + ) + }.getOrNull() + + /** + * [event] believed, on everything a reader can check without the group's key: + * + * 1. it is a request, signed by the member it names; + * 2. its wallet id is the wallet key's; + * 3. the wallet key signed the possession message; + * 4. its nearest guardian is the group it asks, so a request cannot leave + * out the one group it is asking; + * 5. the wallet key, under those guardians, rederives the xpub and both + * descriptors byte for byte; + * 6. a policy it carries is an open one the group it asks signed, and its + * nearest guardian's delay is that policy's -- `docs/member-wallet-delay.md`. + * A request carrying none still reads: certificates signed before + * policies embed one, and their wallets are guarded all the same. That + * a *new* request must carry one is the signers' rule, not a reader's. + * + * Whether the guardians are the ones the group grants is not here: only a + * device holding the group's key can say, and the group's signers do. + */ + fun verified(event: Event): Verified? = runCatching { + val reading = read(event) ?: return null + if (!GroupKeyStateEvent.isSignedByRoom(event, reading.memberPublicKey)) return null + if (MemberWalletDerivation.walletId(reading.walletKey) != reading.walletId) return null + + val message = possessionMessage(reading.memberPublicKey, reading.groupChatRoomId, reading.walletKey, reading.chain) + if (!Crypto.verifySignatureSchnorr(message, reading.possession, reading.walletKey.xOnly())) return null + + if (!reading.guardians.first().chatRoomId.equals(reading.groupChatRoomId, ignoreCase = true)) return null + + val account = MemberWalletDerivation.account(reading.walletKey, reading.chain, reading.guardians) + if (account.xpub != reading.xpub || account.receiveDescriptor != reading.receiveDescriptor || account.changeDescriptor != reading.changeDescriptor) return null + + val policy = reading.policy?.let { carried -> + val open = MemberWalletPolicyEvent.verify(carried, reading.groupChatRoomId) as? MemberWalletPolicyEvent.Policy.Open ?: return null + if (reading.guardians.first().delay != open.delay) return null + open + } + + Verified(request = event, reading = reading, account = account, policy = policy) + }.getOrNull() + + /** + * The signed request an inner event of this kind carries -- or null when its + * content is not one, or was sent by somebody other than the member who + * signed it. A request is passed on by nobody: whoever puts it in the room + * is the one asking. + */ + fun carried(inner: Event): Event? { + if (inner.kind != KIND) return null + val request = Event.fromJsonOrNull(inner.content)?.takeIf { it.kind == KIND } ?: return null + return request.takeIf { it.pubKey.equals(inner.pubKey, ignoreCase = true) } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index f39387eb..0f7843e7 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -1,7 +1,11 @@ package com.machankura.bennu.compose.repository +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload @@ -13,9 +17,6 @@ import com.machankura.bennu.compose.nostr.MarmotProfile import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SubgroupManager -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.intermdiate.LocalChatMessage import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom @@ -87,25 +88,17 @@ interface ChatRepository { suspend fun parentOf(chatRoomId: String): HexKey? /** - * The kind:0 this group signed about itself, or null while it has signed - * none. - * - * The group's identity on nostr is the room's own id, so it has one to - * describe whether or not it ever has. Read off the group's signed events and - * verified there -- see `GroupNostrProfile` -- so a room shows the profile its - * own key signed or shows that it has none. + * What this room's own birth certificate says of its wallet, or null for a + * room with none. See `SubgroupManager.walletPolicyOf`. */ - suspend fun groupNostrProfile(chatRoomId: String): GroupNostrProfile? + suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? /** - * Where this group has said it lives on nostr: one entry per relay set, always - * all of them. - * - * A set the group has never agreed comes back unsigned and empty rather than - * missing, because "never said" is a state the screen has to show and a gap in - * a list is not one. See `GroupRelayList.isAgreed`. + * The guardian keys this room's own certificate grants it, nearest first -- + * empty for a room with none, null when they do not read. See + * `SubgroupManager.guardiansOf`. */ - suspend fun groupRelayLists(chatRoomId: String): List + suspend fun guardiansOf(chatRoomId: String): List? /** * The wallet this group has opened on [chain], or null when it has not -- @@ -126,25 +119,30 @@ interface ChatRepository { suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? /** - * The kind:1s this group signed, newest first. - * - * The group speaking as itself, which is a different thing from a member - * speaking in the room -- the transcript is the second. Unlike the profile and - * the relay lists these accumulate rather than replace, so this is a list and - * an empty one means the group has said nothing publicly. + * The guarded account this group could open on [chain] instead, and the + * certificate granting its guardians -- or null for a group whose birth + * certificate grants it none. */ - suspend fun groupPosts(chatRoomId: String): List + suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? + + /** The guarded wallets of groups below this one that it has been told about and can sign for. */ + suspend fun guardedWallets(chatRoomId: String): List + + /** The guarded statements this device can carry from this group to the groups above it, with where to. */ + suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List + + /** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */ + suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int /** - * One event the group signed, as the group signed it, or null when this - * device does not hold it or it was signed in some other room. - * - * Scoped to the room rather than looked up by id alone, because the id - * arrives as a navigation argument and the screen it opens names a room in - * its title: an event from one room shown under another room's name would - * be a lie the signature check cannot catch, since both rooms' events verify. + * Tells the groups above this one about every guarded wallet it holds that + * they have not heard of -- the catch-up of `docs/guarded-wallet-forwarding.md`. + * Returns how many groups were told. Nothing, by default. */ - suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? + suspend fun forwardGuardedWallets(chatRoomId: String): Int = 0 + + /** Writes a transcript line for each guardian spend from this group's wallet it has none for yet. */ + suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int /** * Whether this device holds a share of the group's key, and so could take @@ -372,10 +370,9 @@ interface ChatRepository { override suspend fun parentOf(chatRoomId: String): HexKey? = null - override suspend fun groupNostrProfile(chatRoomId: String): GroupNostrProfile? = null + override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = null - override suspend fun groupRelayLists(chatRoomId: String): List = - GroupRelayList.allAmong(emptyList(), chatRoomId) + override suspend fun guardiansOf(chatRoomId: String): List? = emptyList() override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = null @@ -384,12 +381,27 @@ interface ChatRepository { chain: Chain ): GroupWalletDerivation.Account? = null - override suspend fun groupPosts(chatRoomId: String): List = emptyList() - - override suspend fun groupSignedEvent( + override suspend fun groupWalletGuardedOpening( chatRoomId: String, - id: HexKey - ): GroupSignedEvent? = null + chain: Chain + ): GroupWalletManager.GuardedOpening? = null + + override suspend fun guardedWallets(chatRoomId: String): List = emptyList() + + override suspend fun shareableGuardedWallets( + chatRoomId: String, + chain: Chain + ): List = emptyList() + + override suspend fun shareGuardedWallet( + shareable: GuardianManager.Shareable, + userPublicKey: HexKey + ): Int = 0 + + override suspend fun recordGuardianSpends( + chatRoomId: String, + taken: List + ): Int = 0 override suspend fun canSign(chatRoomId: String): Boolean = false diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/DkgRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/DkgRepository.kt index 3857ff5b..4f84d7cd 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/DkgRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/DkgRepository.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.repository +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.database.model.DkgParticipantMessage import com.machankura.bennu.compose.database.model.DkgSession import com.machankura.bennu.compose.database.model.FrostSigningSession @@ -85,7 +86,9 @@ interface DkgRepository { threshold: Int, parentChatRoomId: HexKey? = null, participantPublicKeys: Set? = null, - subject: String? = null + subject: String? = null, + walletPolicy: SubgroupWalletPolicy? = null, + guardianDelay: Long? = null ): DkgSession? /** What the ritual is waiting on this device's owner for, if anything. */ @@ -110,6 +113,12 @@ interface DkgRepository { * room has no standing to propose one -- both of which mean there is nothing * true to propose. */ + /** + * Ends a ceremony this device is in, for everyone in it -- see + * `ChillDkgRitualManager.abandon`. Returns whether it was ended. + */ + suspend fun abandon(localChatRoom: LocalChatRoom, sessionId: String): Boolean + suspend fun proposeGroupKeyState( localChatRoom: LocalChatRoom, userPublicKey: HexKey, @@ -220,7 +229,9 @@ interface DkgRepository { threshold: Int, parentChatRoomId: HexKey?, participantPublicKeys: Set?, - subject: String? + subject: String?, + walletPolicy: SubgroupWalletPolicy?, + guardianDelay: Long? ): DkgSession? = null override suspend fun pendingApproval(session: DkgSession): DkgApprovalStep? = null @@ -232,6 +243,8 @@ interface DkgRepository { nostrPrivateKey: ByteArray ) = Unit + override suspend fun abandon(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false + override suspend fun proposeGroupKeyState( localChatRoom: LocalChatRoom, userPublicKey: HexKey, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt index 548c2283..3ae9926c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt @@ -242,6 +242,19 @@ interface FrostSigningRepository { chain: Chain, ): FrostSigningSession? + /** + * Opens a session over one transaction from [descendantChatRoomId]'s guarded + * wallet, signed through this room's guardian leaf, or null when it could not + * be proposed. See `FrostSigningManager.proposeGuardianSpend`. + */ + suspend fun proposeGuardianSpend( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + ): FrostSigningSession? + /** The spend a transaction session signs, checked again; null for anything else. */ suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? @@ -254,6 +267,9 @@ interface FrostSigningRepository { /** The change indices under [account] the room's open spends already pay back to. */ suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set + /** The receive indices of [account], a descendant's guarded wallet, the room's open spends already fund. */ + suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set + /** Every spend the room has proposed, newest first, as it moves from proposed to confirmed. */ fun observeGroupTransactions(chatRoomId: String): Flow> @@ -331,10 +347,19 @@ interface FrostSigningRepository { chain: Chain, ): FrostSigningSession? = null + override suspend fun proposeGuardianSpend( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + ): FrostSigningSession? = null + override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = null override suspend fun reservedOutPoints(chatRoomId: String): Set = emptySet() override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet() + override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet() override fun observeGroupTransactions(chatRoomId: String): Flow> = flowOf(emptyList()) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MantraRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MantraRepository.kt deleted file mode 100644 index 6c7912ea..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MantraRepository.kt +++ /dev/null @@ -1,113 +0,0 @@ -package com.machankura.bennu.compose.repository - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -interface MantraRepository { - suspend fun getArtifacts(chatRoomId: String): List - - suspend fun getArtifact(id: String): MantraArtifact? - - suspend fun getArtifactVersions(artifactId: String): List - - suspend fun getArtifactVersion(id: String): MantraArtifactVersion? - - suspend fun getChaptersForArtifact(artifactId: String): List - - /** - * The chapters of one version of an artifact, in reading order. A chapter - * hangs off a version rather than off the artifact, so this is what a new - * chapter's index counts. - */ - suspend fun getChaptersForArtifactVersion(artifactVersionId: String): List - - suspend fun getChapter(id: String): MantraChapter? - - suspend fun getChunksForChapter(chapterId: String): List - - suspend fun getChunk(id: String): MantraChunk? - - suspend fun getTranslationsForArtifact(artifactId: String): List - - suspend fun getTranslation(id: String): MantraTranslationArtifactVersion? - - /** - * The translations of one artifact version: what a chapter signed into that - * version has to be scaffolded into, and what a translation is caught up - * against. - */ - suspend fun getTranslationsForArtifactVersion(artifactVersionId: String): List - - suspend fun getTranslationChapter(id: String): MantraTranslationChapter? - - suspend fun getTranslationChapters(translationArtifactVersionId: String): List - - suspend fun getTranslationChunks(translationChapterId: String): List - - suspend fun getDialects(chatRoomId: String): List - - suspend fun getDialect(id: String): MantraDialect? - - suspend fun addArtifactVersion( - localChatRoom: LocalChatRoom, - artifactId: HexKey, - versionLabel: String, - userPublicKey: HexKey, - ): MantraArtifactVersion? - - companion object { - const val DEFAULT_VISIBILITY = "private" - const val DEFAULT_LICENSE = "cc" - - val NO_OP_MANTRA_REPOSITORY = object: MantraRepository{ - override suspend fun getArtifacts(chatRoomId: String): List = emptyList() - - override suspend fun getArtifact(id: String): MantraArtifact? = null - - override suspend fun getArtifactVersions(artifactId: String): List = emptyList() - - override suspend fun getArtifactVersion(id: String): MantraArtifactVersion? = null - - override suspend fun getChaptersForArtifact(artifactId: String): List = emptyList() - - override suspend fun getChaptersForArtifactVersion(artifactVersionId: String): List = emptyList() - - override suspend fun getChapter(id: String): MantraChapter? = null - - override suspend fun getChunksForChapter(chapterId: String): List = emptyList() - - override suspend fun getChunk(id: String): MantraChunk? = null - - override suspend fun getTranslationsForArtifact(artifactId: String): List = emptyList() - - override suspend fun getTranslation(id: String): MantraTranslationArtifactVersion? = null - - override suspend fun getTranslationsForArtifactVersion(artifactVersionId: String): List = emptyList() - - override suspend fun getTranslationChapter(id: String): MantraTranslationChapter? = null - - override suspend fun getTranslationChapters(translationArtifactVersionId: String): List = emptyList() - - override suspend fun getTranslationChunks(translationChapterId: String): List = emptyList() - - override suspend fun getDialects(chatRoomId: String): List = emptyList() - - override suspend fun getDialect(id: String): MantraDialect? = null - - override suspend fun addArtifactVersion( - localChatRoom: LocalChatRoom, - artifactId: HexKey, - versionLabel: String, - userPublicKey: HexKey, - ): MantraArtifactVersion? = null - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt new file mode 100644 index 00000000..174e375d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt @@ -0,0 +1,115 @@ +package com.machankura.bennu.compose.repository + +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.managers.GuardianManager +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.psbt.Psbt +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlin.time.Instant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain + +/** + * A member's guarded wallets, for the screens: asking a group to guard one, and + * -- from the group's side -- the requests and certificates in a room. + * `docs/member-guarded-wallets.md`. The key-holding identity is the + * repository's, never the screen's: nothing above this layer touches a key. + */ +interface MemberWalletRepository { + /** The groups [ownerPublicKey] is in that could guard a wallet: Marmot rooms, whether or not their key is known yet. */ + suspend fun groupsOf(ownerPublicKey: HexKey): List + + /** Why [chatRoomId] cannot guard a wallet for the active profile on [chain], or null when it can. */ + suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? + + /** How many groups a wallet guarded by [chatRoomId] would be guarded by, or null while its key is unknown. */ + suspend fun reachOf(chatRoomId: String): Int? + + /** Each guardian's delay for a wallet [chatRoomId] would guard, nearest first, or null while its key is unknown. */ + suspend fun delaysOf(chatRoomId: String): List? + + /** Asks [chatRoomId] what it signs with, for a member who holds no key state. Whether it asked. */ + suspend fun askForGroupKey(chatRoomId: String): Boolean + + /** Makes the key, works out the leaves, stores the key, and asks [chatRoomId] to guard it. */ + suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet + + /** Every guarded wallet of [ownerPublicKey]'s this device knows about, newest first. */ + suspend fun walletsOf(ownerPublicKey: HexKey): List + + /** One of them, or null. */ + suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? + + /** Asks the group again, with the request the wallet was first asked with. */ + /** Asks again for [walletId]; returns the wallet now asked for, a new one when the old request would be refused. */ + suspend fun askAgain(walletId: String): String + + /** Forgets a wallet's key -- refused once a group guards it. */ + suspend fun discard(walletId: String) + + /** The wallet's receive and change descriptors with its private key in them, or null when the key is not here. */ + suspend fun exportKey(walletId: String): Pair? + + /** What [chatRoomId] is called on this device, or null when it has no room for it. */ + suspend fun roomName(chatRoomId: String): String? + + /** Signs [psbt] as [walletId]'s own key, files the spend, and returns the transaction to broadcast. */ + suspend fun signSpend(walletId: String, psbt: Psbt): Transaction + + /** Files what the chain said of a member's spend. */ + suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant? = null) + + /** The spends the member signed from [walletId], newest first. */ + fun observeSpends(walletId: String): Flow> + + /** The member wallets [chatRoomId] guards, and the requests waiting for a signer to put them to it. */ + suspend fun memberWalletsOf(chatRoomId: String): List + + /** [chatRoomId]'s newest member-wallet policy this device holds, or null. See `MemberWalletManager.policyFor`. */ + suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? + + /** Whether [chatRoomId] is a group that could guard a member's wallet -- not a direct chat. See `MemberWalletManager.couldGuard`. */ + suspend fun couldGuard(chatRoomId: String): Boolean + + /** Puts a member's request to [chatRoomId]'s quorum as the active profile, which counts as its approval. */ + suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession + + /** Every wallet of [ownerPublicKey]'s a group the active profile is in guards. */ + suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List + + companion object { + val NO_OP = object : MemberWalletRepository { + override suspend fun groupsOf(ownerPublicKey: HexKey): List = emptyList() + override suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? = MemberWalletManager.Refusal.CANNOT_SIGN + override suspend fun reachOf(chatRoomId: String): Int? = null + + override suspend fun delaysOf(chatRoomId: String): List? = null + override suspend fun askForGroupKey(chatRoomId: String): Boolean = false + override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet = + throw UnsupportedOperationException("no repository") + override suspend fun walletsOf(ownerPublicKey: HexKey): List = emptyList() + override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = null + override suspend fun askAgain(walletId: String): String = walletId + override suspend fun discard(walletId: String) = Unit + override suspend fun exportKey(walletId: String): Pair? = null + override suspend fun roomName(chatRoomId: String): String? = null + override suspend fun signSpend(walletId: String, psbt: Psbt): Transaction = throw UnsupportedOperationException("no repository") + override suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant?) = Unit + override fun observeSpends(walletId: String): Flow> = flowOf(emptyList()) + override suspend fun memberWalletsOf(chatRoomId: String): List = emptyList() + + override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = null + + override suspend fun couldGuard(chatRoomId: String): Boolean = false + override suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession = throw UnsupportedOperationException("no repository") + override suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List = emptyList() + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/BlockDuration.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/BlockDuration.kt new file mode 100644 index 00000000..cddf0127 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/BlockDuration.kt @@ -0,0 +1,71 @@ +package com.machankura.bennu.compose.text + +import kotlin.math.abs +import kotlin.math.roundToInt + +/** + * A number of blocks said in time, roughly -- `docs/guardian-delay.md`, D5. + * + * Always beside the block count, never instead of it: blocks are what a + * guardian's leaf counts, and ten minutes is the target, not a promise, so a + * delay of 144 blocks can take twenty hours or thirty. Hence *about*. + * + * The rule: + * + * 1. within 5% of exactly one hour, day, month or year, that unit, singular -- + * 6 blocks is *about 1 hour*, 4,320 *about 1 month*; + * 2. otherwise the largest of years, months, days, hours and minutes in which + * the delay comes to at least 2, rounded -- 216 blocks is *about 36 hours*, + * 65,535 *about 15 months*. + * + * Years therefore appear only near exactly one year: the longest delay a leaf + * can carry is 1.25 years, and *about 15 months* says more than *about 1 year*. + */ +object BlockDuration { + /** Bitcoin's target, and the testnets' and signet's. Regtest has none. */ + const val MINUTES_PER_BLOCK: Long = 10L + + /** The units, each with its length in minutes: a month is a twelfth of a Julian year. */ + enum class Unit(val minutes: Double) { + MINUTES(1.0), + HOURS(60.0), + DAYS(1_440.0), + MONTHS(43_830.0), + YEARS(525_960.0), + } + + data class Approximate(val count: Int, val unit: Unit) + + /** How close to exactly one of a unit a delay has to be to be said as one. */ + private const val ONE_TOLERANCE = 0.05 + + fun approximate(blocks: Long): Approximate { + require(blocks > 0) { "a duration is at least one block, not $blocks" } + val minutes = (blocks * MINUTES_PER_BLOCK).toDouble() + val largestFirst = Unit.entries.reversed() + + largestFirst.filter { it != Unit.MINUTES }.forEach { unit -> + if (abs(minutes / unit.minutes - 1.0) <= ONE_TOLERANCE) return Approximate(1, unit) + } + largestFirst.forEach { unit -> + val count = minutes / unit.minutes + if (count >= 2.0) return Approximate(count.roundToInt(), unit) + } + return Approximate(minutes.roundToInt(), Unit.MINUTES) + } +} + +/** A count of blocks, its thousands grouped: `65,535`. */ +fun Long.groupedBlocks(): String = toString().reversed().chunked(3).joinToString(",").reversed() + +/** + * *144 blocks, about 1 day*, in fixed English: for the words that are not + * composables -- a proposal's summary -- as the rest of `ProposedEvent` is. + * Screens use `delayText`, which reads the catalogue. + */ +fun BlockDuration.describe(blocks: Long): String { + val approximate = approximate(blocks) + val unit = approximate.unit.name.lowercase().let { if (approximate.count == 1) it.removeSuffix("s") else it } + val count = if (blocks == 1L) "1 block" else "${blocks.groupedBlocks()} blocks" + return "$count, about ${approximate.count} $unit" +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Markdown.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Markdown.kt deleted file mode 100644 index b9f07412..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Markdown.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.machankura.bennu.compose.text - -/** - * Lightweight helpers for the markdown original text of chapters/chunks. - * - * Counts are computed on the raw markdown text (no rendering/stripping): - * words are whitespace-separated tokens and characters are the string length. - */ -object Markdown { - private val WHITESPACE = Regex("\\s+") - - /** A paragraph break is one or more blank lines. */ - private val PARAGRAPH_BREAK = Regex("(?:\\r?\\n){2,}") - - fun wordCount(text: String): Int { - val trimmed = text.trim() - return if (trimmed.isEmpty()) 0 else trimmed.split(WHITESPACE).count { it.isNotBlank() } - } - - fun characterCount(text: String): Int = text.length - - /** - * Split markdown into paragraphs (blocks separated by blank lines), - * trimmed and with empties removed. Each paragraph becomes a chunk. - */ - fun splitParagraphs(text: String): List = - text.split(PARAGRAPH_BREAK) - .map { it.trim() } - .filter { it.isNotEmpty() } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 71fe4018..3b15b1ef 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -1,24 +1,19 @@ package com.machankura.bennu.compose.text +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatementEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.text.grouped -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import fr.acinq.bitcoin.Satoshi import fr.acinq.lightning.payment.Bolt11Invoice @@ -26,8 +21,8 @@ import fr.acinq.lightning.payment.Bolt11Invoice * An event a group is being asked to sign, said in words. * * Shown as the thing rather than as an event: a member deciding whether to sign - * is deciding about a dialect or an artifact, and "kind 30304" answers a - * question nobody asked. The raw kind stays for anything not recognised, since + * is deciding about a wallet or a subgroup, and "kind 30331" answers a question + * nobody asked. The raw kind stays for anything not recognised, since * refusing to describe an event is better than describing it wrongly. * * Not a composable, and deliberately: the same words appear on the signing @@ -41,100 +36,12 @@ object ProposedEvent { */ data class Summary(val label: String, val detail: String) - fun summarize(event: Event): Summary = when (event.kind) { - DialectEvent.KIND -> Summary( - label = "New dialect", - detail = DialectEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { dialect -> - listOfNotNull(dialect.name(), dialect.country(), dialect.language()) - .joinToString(" · ") - } - ) - - ArtifactEvent.KIND -> Summary( - label = "New artifact", - detail = ArtifactEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { artifact -> - // The url is the substance of an artifact -- signing one is putting - // the group's name to what it points at -- so it goes next to the - // name rather than being left for the detail screen afterwards. - listOfNotNull(event.content, artifact.versionLabel(), artifact.url()) - .joinToString(" · ") - } - ) - - // Signed alongside the artifact it belongs to rather than on its own, - // so this is almost always read as the second line of a batch of two. - // Named after the artifact rather than the label, because the label is - // the whole of the content and would otherwise be said twice. - ArtifactVersionEvent.KIND -> Summary( - label = "Version of the artifact", - detail = event.content.ifBlank { "Unlabelled" } - ) - - ChapterEvent.KIND -> Summary( - label = "New chapter", - detail = ChapterEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { chapter -> - // The text is the substance of a chapter -- signing one is putting - // the group's name to what everybody will translate from -- but it - // is a whole chapter, so its size stands in for it here. The chunk - // count says how many of the batch's other items came out of this - // text, which is the rest of what is being signed. - val chunkCount = chapter.originalText()?.let { Markdown.splitParagraphs(it).size } - - listOfNotNull( - chapter.name(), - chapter.wordCount()?.let { "$it words" }, - chunkCount?.let { "$it ${if (it == 1) "chunk" else "chunks"}" } - ).joinToString(" · ") - } - ) - - TranslationArtifactVersionEvent.KIND -> Summary( - label = "New translation", - detail = TranslationArtifactVersionEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { translation -> - // Named after the dialect it is into, which is the whole of what is - // being decided: everything else in the batch follows from it. - listOfNotNull(translation.name(), translation.visibility(), translation.license()) - .joinToString(" · ") - } - ) - - TranslationChapterEvent.KIND -> Summary( - label = "Chapter of the translation", - detail = TranslationChapterEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { chapter -> - // A translation chapter is a place for translated chunks to hang - // off, so there is nothing in it to read -- only where in the work - // it sits. Counted from one, the way the chapter list reads. - chapter.index()?.let { "Chapter ${it + 1}" } ?: "Position unknown" - } - ) - - TranslationChunkEvent.KIND -> Summary( - label = "Translated passage", - detail = TranslationChunkEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { chunk -> - // The translation itself is the whole of what is being decided -- - // a member signing this is agreeing that these words say what the - // original said -- so it is the detail rather than a count of it. - // Where in the chapter it sits comes first, since that is what - // says which passage to read it against. - listOfNotNull( - chunk.index()?.let { "Passage ${it + 1}" }, - event.content - ).joinToString(" · ") - } - ) - + /** + * [nameOf] names a member by public key, for the one summary that is about a + * person: a caller with profiles to hand passes them, and one without gets + * the summary without a name rather than a wrong one. + */ + fun summarize(event: Event, nameOf: (HexKey) -> String? = { null }): Summary = when (event.kind) { // The one thing a group signs that is about the group rather than about // its work, and the only one a member sees before the room has done // anything. Shown as the path and the ceremony rather than as the key: @@ -161,43 +68,37 @@ object ProposedEvent { SubgroupBirthCertificateEvent.parseAdminPublicKeys(event.tags) .size .takeIf { it > 0 } - ?.let { "run by $it members" } + ?.let { "run by $it members" }, + // The promise this certificate makes on the group's behalf, said + // as one: a guardian key is this group, and every group above it, + // able to spend from the subgroup's wallet if it opens a guarded one. + SubgroupBirthCertificateEvent.parseGuardians(event.tags) + ?.size + ?.takeIf { it > 0 } + ?.let { count -> + when (count) { + 1 -> "this group can spend from its wallet" + 2 -> "this group and the one above it can spend from its wallet" + else -> "this group and the ${count - 1} above it can spend from its wallet" + } + }, + // How long this group's own leaf waits, which its coordinator + // chose; every inherited one keeps its own. docs/guardian-delay.md. + SubgroupBirthCertificateEvent.parseGuardians(event.tags) + ?.firstOrNull() + ?.let { "this group after ${BlockDuration.describe(it.delay)}" }, + // The decision this certificate makes for the child, said in both + // directions: an absent line is not a decision anybody can be said + // to have read. An older certificate decides nothing and says so + // by saying nothing, as it always has. + when (SubgroupBirthCertificateEvent.parseWalletPolicy(event.tags)) { + WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) -> "its wallet must be guarded" + WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) -> "its wallet will not be guarded" + else -> null + } ).joinToString(" · ") ) - // The group's own profile. Named by what the group would be called and - // what it would say about itself, which is the whole of what is being - // decided; the JSON in the content is the one thing a signer should not - // have to read to find that out. - MetadataEvent.KIND -> Summary( - label = "Nostr profile", - detail = MetadataEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).contactMetaData()?.let { metadata -> - listOfNotNull( - metadata.anyName()?.takeIf { it.isNotBlank() }, - metadata.about?.takeIf { it.isNotBlank() } - ).joinToString(" · ").ifEmpty { "An empty profile" } - } ?: "Unreadable profile" - ) - - // A post in the group's name. The words are what is being decided, so - // they are the detail rather than a count of them -- the same call the - // translated-passage arm makes. - TextNoteEvent.KIND -> Summary(label = "Post", detail = event.content) - - // One of the group's relay lists, shown as hosts: every entry in one - // starts wss://, so the scheme is the part that never tells two apart. - // An empty one is a list the group is withdrawing, and says so. - in GroupRelaySet.KINDS -> { - val set = GroupRelaySet.entries.first { it.kind == event.kind } - - Summary( - label = "${set.name} relay list", - detail = set.parse(event.tags).joinToString { it.displayUrl() }.ifEmpty { "No relays" } - ) - } - // The group opening a wallet. What a member is agreeing to is that the // group keeps coins here, so the summary names the network -- the one // thing that changes what the coins are worth -- and the account, and @@ -252,6 +153,50 @@ object ProposedEvent { ) } ?: Summary(label = "Authorise the Lightning wallet", detail = "An authorisation this device cannot read") + // The group agreeing to guard one member's wallet. What a signer weighs + // is whose wallet, and what the group can do with it: take any coin that + // has sat for its leaf's delay, alongside every group above it after + // theirs, while only the member can spend before then. The keys are their device's to check. + // The group deciding whether it guards its members' wallets, and at what + // delay. A signer weighs the delay, and that it reaches only wallets + // asked for from now on; closing leaves every guarded wallet guarded. + // docs/member-wallet-delay.md. + MemberWalletPolicyEvent.KIND -> Summary( + label = "Members' guarded wallets", + detail = when (val policy = MemberWalletPolicyEvent.read(event)) { + is MemberWalletPolicyEvent.Policy.Open -> + "this group after ${BlockDuration.describe(policy.delay)} · for wallets asked for from now on" + is MemberWalletPolicyEvent.Policy.Closed -> + "no new ones · wallets already guarded stay guarded" + null -> "A policy this device cannot read" + } + ) + + MemberWalletCertificateEvent.KIND -> Summary( + label = "Guard a member's wallet", + detail = MemberWalletCertificateEvent.requestOf(event) + ?.let { MemberWalletRequestEvent.read(it) } + ?.let { reading -> + // Each guardian's own delay, nearest first: the group's own + // leaf, and every group above it at the delay it chose. + // docs/guardian-delay.md. + val delays = reading.guardians.map { BlockDuration.describe(it.delay) } + val reach = when (delays.size) { + 1 -> "this group can take its coins after ${delays[0]}" + 2 -> "this group can take its coins after ${delays[0]}, and the one above it after ${delays[1]}" + else -> "this group can take its coins after ${delays[0]}, and the ${delays.size - 1} above it after ${delays.drop(1).joinToString(", ")}" + } + listOfNotNull( + nameOf(reading.memberPublicKey)?.let { "For @$it" }, + reading.label, + "on ${GroupWalletStatementEvent.chainName(reading.chain)}", + reach, + "only the member can spend from it before then", + ).joinToString(" · ") + } + ?: "A member wallet this device cannot read" + ) + else -> Summary(label = "Event of kind ${event.kind}", detail = event.content) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt index feeb6953..58e14c01 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt @@ -5,6 +5,7 @@ import com.machankura.bennu.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Bitcoin import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Satoshi /** * A spend the group is being asked to sign, said in words -- [ProposedEvent]'s @@ -14,13 +15,40 @@ import fr.acinq.bitcoin.Chain object ProposedSpend { fun summarize(spend: GroupSpend.Checked, chain: Chain): ProposedEvent.Summary = ProposedEvent.Summary( - label = "Spend from the group's wallet", + // A guardian's spend takes a descendant's coins, so whose they are + // is the first thing a signer reads. + // A funding comes next: where the money goes, as every signer's + // device derived it -- never the proposer's word for it. + label = when (val guardian = spend.spender as? GroupSpend.Spender.Guardian) { + null -> spend.fundings.singleOrNull()?.takeIf { spend.payments.size == 1 } + ?.let { "Fund ${walletOf(it)}" } + ?: "Spend from the group's wallet" + else -> "Spend from ${guardedWallet(guardian.name, guardian.label)}" + }, detail = when (val payment = spend.payments.singleOrNull()) { - null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" - else -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}" + null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" + when (val funding = spend.fundings.singleOrNull()) { + null -> if (spend.fundings.isEmpty()) "" else + ", ${Satoshi(spend.fundings.sumOf { spend.tx.txOut[it.outputIndex].amount.sat }).grouped()} of them to ${spend.fundings.size} guarded wallets" + else -> ", ${spend.tx.txOut[funding.outputIndex].amount.grouped()} of them to ${walletOf(funding)}" + } + else -> when (val funding = spend.fundings.singleOrNull()) { + null -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}" + else -> "Send ${payment.txOut.amount.grouped()} sats to ${walletOf(funding)}, address ${funding.derived.index}" + } } ) + private fun walletOf(funding: GroupSpend.Funding): String = guardedWallet(funding.wallet.displayName, funding.wallet.label) + + /** + * A guarded wallet in a sentence: *#Translation's guarded wallet*, *@alice's + * guarded wallet* -- and, for a member's wallet with a label, *@alice's + * guarded wallet “Savings”*, since one person can have several and a signer + * should know which is being spent from. `docs/member-wallet-guarding-group.md`, Phase 5. + */ + fun guardedWallet(name: String?, label: String?): String = + "${name ?: "a subgroup"}'s guarded wallet" + (label?.let { " “$it”" } ?: "") + /** The address [script] pays, or the script itself where it has no address. */ fun addressOf(script: ByteVector, chain: Chain): String = Bitcoin.addressFromPublicKeyScript(chain.chainHash, script.toByteArray()).right ?: script.toHex() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt index 4017c0ef..6c153fa9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.ui.view.model.MemberWalletsViewModel +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.NewMemberWalletRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -99,6 +104,11 @@ fun ActiveProfileScreen( // an identity to sign out of (previews, tests), in which case the button keeps its // pending route for every kind. signOut: SignOutDependencies? = null, + // The member's guarded wallets (docs/member-guarded-wallets.md). The no-op + // repository lists none, for previews and tests; null wallets is a profile + // that cannot watch the chain, whose rows show no balance. + memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, + wallets: GroupOnchainWallets? = null, ) { // Whether this identity can sign, which decides which rows below exist. @@ -130,6 +140,16 @@ fun ActiveProfileScreen( if (signOutState is SignOutViewModel.State.Failed) notify(couldNotSignOut) } + val memberWalletsViewModel: MemberWalletsViewModel = viewModel( + factory = MemberWalletsViewModel.factory( + ownerPublicKey = activeUserPublicKey, + memberWalletRepository = memberWalletRepository, + wallets = wallets, + ), + ) + // Each time the profile is shown: a certificate can arrive while it is not. + LaunchedEffect(true) { memberWalletsViewModel.refresh() } + val activeProfileViewModel: ActiveProfileViewModel = viewModel( factory = ActiveProfileViewModel.factory( nostrEventId = nostrEventId, @@ -272,6 +292,17 @@ fun ActiveProfileScreen( } } + memberWalletItems( + rows = memberWalletsViewModel.rows, + onOpen = { walletId -> + onNavigateToRoute.invoke(MemberWalletRoute(activeUserPublicKey = activeUserPublicKey, walletId = walletId)) + }, + // A read-only identity cannot sign a request, so it is not offered one. + onNew = if (canSign) { + { onNavigateToRoute.invoke(NewMemberWalletRoute(activeUserPublicKey = activeUserPublicKey)) } + } else null, + ) + // Key packages are signed, and there is nothing to recover for // an identity the device holds no secret for: neither row for a // read-only identity. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt deleted file mode 100644 index 0e84f739..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddArtifactScreen.kt +++ /dev/null @@ -1,406 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.DriveFileRenameOutline -import androidx.compose.material.icons.filled.Label -import androidx.compose.material.icons.filled.Link -import androidx.compose.material.icons.filled.LocalOffer -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.ChatRoomMessagingUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.view.model.AddArtifactViewModel -import com.machankura.bennu.compose.ui.view.state.AddArtifactUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_artifact_to_the_group_library -import bennu.composeapp.generated.resources.direct_message_detail -import bennu.composeapp.generated.resources.direct_message_functionality_will_be_here -import bennu.composeapp.generated.resources.eg_first_edition -import bennu.composeapp.generated.resources.eg_https_harper_com_2_kill_bird -import bennu.composeapp.generated.resources.eg_to_kill_a_mocking_bird -import bennu.composeapp.generated.resources.initial_version_label -import bennu.composeapp.generated.resources.name_of_artifact -import bennu.composeapp.generated.resources.no_dialects_have_been_defined_in_this_group -import bennu.composeapp.generated.resources.propose_artifact -import bennu.composeapp.generated.resources.source_dialect -import bennu.composeapp.generated.resources.url -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Composable -fun AddArtifactScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddArtifactUIState: AddArtifactUIState = AddArtifactUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - mantraRepository: MantraRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addArtifactViewModel: AddArtifactViewModel = viewModel( - factory = AddArtifactViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddArtifactUIState = initialAddArtifactUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - activeUserPublicKey = activeUserPublicKey, - mantraRepository = mantraRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - ScreenStateTransition(addArtifactViewModel.addArtifactUIState) { uiState -> - when (val addArtifactUIState = uiState) { - is AddArtifactUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer( - modifier = Modifier.height(MaterialTheme.spacing.space600) - ) - Text( - text = addArtifactUIState.message, - ) - } - } - is AddArtifactUIState.Loaded -> { - val nameFieldState = rememberTextFieldState() - val urlFieldState = rememberTextFieldState() - val versionLabelFieldState = rememberTextFieldState("1.0") - - // The id of the group dialect this artifact is written in. Null until - // one is picked; dialects are defined from the group detail screen. - var selectedDialectId: String? by remember { mutableStateOf(null) } - - // The two things the form cannot ask for again. A dialect has to - // already exist and nothing here can create one; a shared key has to - // have been ceremonied and this is not where that happens. Either - // missing is a dead end rather than something to propose and be told - // about afterwards, and the button says so. - val canAddArtifact = selectedDialectId != null && addArtifactUIState.canSign - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - addArtifactUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_artifact), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose artifact") }, - enabled = canAddArtifact, - onClick = { - addArtifactViewModel.addArtifact( - localChatRoom = addArtifactUIState.localChatRoom, - nameField = nameFieldState, - urlField = urlFieldState, - versionLabelField = versionLabelFieldState, - dialectId = selectedDialectId, - onSuccess = { sessionId -> - // Onto the session rather than to the - // artifact. Nothing has been created yet - // -- the artifact appears when enough - // members sign -- so a detail screen for - // a row that does not exist would read as - // a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed artifact") - ) - } - ) - - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - // TODO: Check that we have direct message relays for this user... - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text(stringResource(Res.string.add_artifact_to_the_group_library)) - - if (!addArtifactUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign an " + - "artifact into its library. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = nameFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.DriveFileRenameOutline, - contentDescription = "Name of the artifact" - ) - }, - label = { - Text( - text = stringResource(Res.string.name_of_artifact) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_to_kill_a_mocking_bird) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = urlFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Link, - contentDescription = "Link to the artifact" - ) - }, - label = { - Text( - text = stringResource(Res.string.url) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_https_harper_com_2_kill_bird) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = versionLabelFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.LocalOffer, - contentDescription = "Verison label" - ) - }, - label = { - Text( - text = stringResource(Res.string.initial_version_label) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_first_edition) - ) - }, - ) - - Text(stringResource(Res.string.source_dialect)) - - if (addArtifactUIState.dialects.isEmpty()) { - Text( - text = stringResource(Res.string.no_dialects_have_been_defined_in_this_group), - style = MaterialTheme.typography.bodySmall - ) - } else { - FlowRow( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - addArtifactUIState.dialects.forEach { dialect -> - FilterChip( - selected = selectedDialectId == dialect.id, - onClick = { selectedDialectId = dialect.id }, - label = { Text(dialect.name) } - ) - } - } - } - - // TODO: Add Visibility - } - } - } - } - AddArtifactUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding( - MaterialTheme.spacing.space250 - ), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - - Spacer( - modifier = Modifier.weight(1f) - ) - Text( - text = stringResource(Res.string.direct_message_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - Text( - text = stringResource(Res.string.direct_message_functionality_will_be_here), - style = MaterialTheme.typography.bodySmall, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator( - fillScreen = false - ) - - Spacer( - modifier = Modifier.weight(2f) - ) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddArtifactUIState == AddArtifactUIState.Loading) { - addArtifactViewModel.initiateChatRoomDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun AddArtifactScreenPreview() { - BennuTheme { - Surface( - modifier = Modifier.fillMaxSize() - ) { - AddArtifactScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialAddArtifactUIState = AddArtifactUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ) - ), - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt deleted file mode 100644 index f5fdd087..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddChapterScreen.kt +++ /dev/null @@ -1,326 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.DriveFileRenameOutline -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.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.text.Markdown -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.AddChapterViewModel -import com.machankura.bennu.compose.ui.view.state.AddChapterUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_chapter -import bennu.composeapp.generated.resources.chapter_name -import bennu.composeapp.generated.resources.eg_chapter_1_the_beginning -import bennu.composeapp.generated.resources.original_text_markdown -import bennu.composeapp.generated.resources.paste_the_chapter_s_markdown_blank_lines -import bennu.composeapp.generated.resources.propose_chapter -import bennu.composeapp.generated.resources.this_artifact_has_no_version_for_a_chapter -import bennu.composeapp.generated.resources.add_chapter_to -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun AddChapterScreen( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddChapterUIState: AddChapterUIState = AddChapterUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addChapterViewModel: AddChapterViewModel = viewModel( - factory = AddChapterViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddChapterUIState = initialAddChapterUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(addChapterViewModel.addChapterUIState) { uiState -> - when (val addChapterUIState = uiState) { - is AddChapterUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = addChapterUIState.message) - } - } - - is AddChapterUIState.Loaded -> { - val nameFieldState = rememberTextFieldState() - val originalTextFieldState = rememberTextFieldState() - - // Live counts / paragraph (chunk) preview from the markdown text. - val originalText = originalTextFieldState.text.toString() - val wordCount = Markdown.wordCount(originalText) - val characterCount = Markdown.characterCount(originalText) - val paragraphCount = Markdown.splitParagraphs(originalText).size - - // A chapter hangs off a version, and the group has to be able to - // sign; without both there is nothing this screen can propose. - val artifactVersion = addChapterUIState.artifactVersion - - // The chapter and a chunk per paragraph are signed in one session, - // and a session signs a bounded number of events. Past that the - // chapter has to be split in two, which is worth saying while there - // is still a cursor in the text rather than after a failed propose. - val tooManyChunks = paragraphCount > AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER - - val canProposeChapter = artifactVersion != null && - addChapterUIState.canSign && - paragraphCount > 0 && - !tooManyChunks - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.add_chapter_to, addChapterUIState.artifact.name)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_chapter), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose chapter") }, - enabled = canProposeChapter, - onClick = { - if (artifactVersion == null) return@ExtendedFab - - addChapterViewModel.addChapter( - localChatRoom = addChapterUIState.localChatRoom, - artifactVersion = artifactVersion, - nameField = nameFieldState, - originalTextField = originalTextFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the artifact. Nothing has been created - // yet -- the chapter appears when enough - // members sign -- so landing on the list - // it is not in would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed chapter") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (!addChapterUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "chapter into existence. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } else if (artifactVersion == null) { - Text( - text = stringResource(Res.string.this_artifact_has_no_version_for_a_chapter), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } else if (tooManyChunks) { - Text( - text = "$paragraphCount chunks is more than the group can sign in " + - "one go. Split the chapter so that no part of it is over " + - "${AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER} paragraphs.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = nameFieldState, - leadingIcon = { - Icon( - Icons.Default.DriveFileRenameOutline, - contentDescription = "Name of the chapter" - ) - }, - label = { Text(stringResource(Res.string.chapter_name)) }, - placeholder = { Text(stringResource(Res.string.eg_chapter_1_the_beginning)) }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth().weight(1f), - state = originalTextFieldState, - label = { Text(stringResource(Res.string.original_text_markdown)) }, - placeholder = { Text(stringResource(Res.string.paste_the_chapter_s_markdown_blank_lines)) }, - ) - - Text( - // The chunk count is what the group is asked to sign - // alongside the chapter, so it is a count of the work - // being proposed rather than a curiosity about the text. - text = "$wordCount words · $characterCount characters · " + - "$paragraphCount ${if (paragraphCount == 1) "chunk" else "chunks"} " + - "of ${AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER}", - style = MaterialTheme.typography.labelMedium, - color = if (tooManyChunks) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.typography.labelMedium.color - } - ) - } - } - } - - AddChapterUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.add_chapter), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddChapterUIState == AddChapterUIState.Loading) { - addChapterViewModel.initiateAddChapter() - } - } -} - -@ConformancePreviews -@Composable -private fun AddChapterScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AddChapterScreen( - activeUserPublicKey = "", - artifactId = "artifactId", - chatRoomId = "chatRoomId", - relayHint = null, - initialAddChapterUIState = AddChapterUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "chatRoomId", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ), - artifact = MantraArtifact( - id = "artifactId", - publicKey = "author", - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = "dialectId", - license = "cc", - chatRoomId = "chatRoomId", - signature = "" - ), - artifactVersion = MantraArtifactVersion( - id = "artifactVersionId", - artifactId = "artifactId", - publicKey = "author", - versionLabel = "1.0", - chatRoomId = "chatRoomId", - signature = "" - ), - canSign = true, - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt deleted file mode 100644 index 137b9e39..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddDialectScreen.kt +++ /dev/null @@ -1,342 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.Public -import androidx.compose.material.icons.filled.Title -import androidx.compose.material.icons.filled.Translate -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.AddDialectViewModel -import com.machankura.bennu.compose.ui.view.state.AddDialectUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_a_dialect_the_group_can_translate_into -import bennu.composeapp.generated.resources.add_dialect -import bennu.composeapp.generated.resources.country -import bennu.composeapp.generated.resources.dialect_name -import bennu.composeapp.generated.resources.eg_lesotho -import bennu.composeapp.generated.resources.eg_sesotho -import bennu.composeapp.generated.resources.eg_st -import bennu.composeapp.generated.resources.language -import bennu.composeapp.generated.resources.propose_dialect -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun AddDialectScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddDialectUIState: AddDialectUIState = AddDialectUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addDialectViewModel: AddDialectViewModel = viewModel( - factory = AddDialectViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddDialectUIState = initialAddDialectUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - activeUserPublicKey = activeUserPublicKey, - frostSigningRepository = frostSigningRepository - ) - ) - - ScreenStateTransition(addDialectViewModel.addDialectUIState) { uiState -> - when (val addDialectUIState = uiState) { - is AddDialectUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer( - modifier = Modifier.height(MaterialTheme.spacing.space600) - ) - Text( - text = addDialectUIState.message, - ) - } - } - is AddDialectUIState.Loaded -> { - val nameFieldState = rememberTextFieldState() - val countryFieldState = rememberTextFieldState() - val languageFieldState = rememberTextFieldState() - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - addDialectUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_dialect), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose dialect") }, - enabled = addDialectUIState.canSign, - onClick = { - addDialectViewModel.addDialect( - localChatRoom = addDialectUIState.localChatRoom, - nameField = nameFieldState, - countryField = countryFieldState, - languageField = languageFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the group. Nothing has been created - // yet -- the dialect appears when enough - // members sign -- so landing on the list - // it is not in would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed dialect") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text(stringResource(Res.string.add_a_dialect_the_group_can_translate_into)) - - if (!addDialectUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "dialect into existence. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = nameFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Title, - contentDescription = "Name of the dialect" - ) - }, - label = { - Text( - text = stringResource(Res.string.dialect_name) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_sesotho) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = countryFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Public, - contentDescription = "Country of the dialect" - ) - }, - label = { - Text( - text = stringResource(Res.string.country) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_lesotho) - ) - }, - ) - - OutlinedTextField( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor), - state = languageFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon( - Icons.Default.Translate, - contentDescription = "Language of the dialect" - ) - }, - label = { - Text( - text = stringResource(Res.string.language) - ) - }, - placeholder = { - Text( - text = stringResource(Res.string.eg_st) - ) - }, - ) - } - } - } - } - AddDialectUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding( - MaterialTheme.spacing.space250 - ), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - - Spacer( - modifier = Modifier.weight(1f) - ) - Text( - text = stringResource(Res.string.add_dialect), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator( - fillScreen = false - ) - - Spacer( - modifier = Modifier.weight(2f) - ) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddDialectUIState == AddDialectUIState.Loading) { - addDialectViewModel.initiateAddDialect() - } - } -} - -@ConformancePreviews -@Composable -private fun AddDialectScreenPreview() { - BennuTheme { - Surface( - modifier = Modifier.fillMaxSize() - ) { - AddDialectScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialAddDialectUIState = AddDialectUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ) - ), - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt deleted file mode 100644 index 4db17762..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt +++ /dev/null @@ -1,310 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.AddGroupPostViewModel -import com.machankura.bennu.compose.ui.view.state.AddGroupPostUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_post_needs_something_to_say -import bennu.composeapp.generated.resources.add_post -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_post -import bennu.composeapp.generated.resources.propose_post -import bennu.composeapp.generated.resources.the_group_signs_a_post_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_a_post -import bennu.composeapp.generated.resources.what_should_the_group_say -import org.jetbrains.compose.resources.stringResource - -/** - * The draft of something the group would say, in its own name. - * - * Not a message in the room: this is signed by the group's key and read by anybody, - * which is why the byline over the draft is the group's rather than the writer's. - * Whoever types it is proposing words for the group to put its signature to, and - * the words become a post -- attributed to the group and to nobody in particular -- - * only once a quorum has signed. - * - * The byline is the whole of the design here. Every other composer in this app puts - * the author's name over the draft because the author is the person typing; getting - * that wrong on this screen would have a member writing what looks like their own - * note and finding the group had said it. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun AddGroupPostScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddGroupPostUIState: AddGroupPostUIState = AddGroupPostUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addGroupPostViewModel: AddGroupPostViewModel = viewModel( - factory = AddGroupPostViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddGroupPostUIState = initialAddGroupPostUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in the click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_post) - val nothingToSay = stringResource(Res.string.a_post_needs_something_to_say) - - ScreenStateTransition(addGroupPostViewModel.addGroupPostUIState) { uiState -> - when (val addGroupPostUIState = uiState) { - is AddGroupPostUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState(message = addGroupPostUIState.message, onRetry = null) - } - - is AddGroupPostUIState.Loaded -> { - val noteFieldState = rememberTextFieldState() - val canSign = addGroupPostUIState.canSign - - // imePadding: this screen is a text field the size of the screen, - // and without it the software keyboard covers what is being typed. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(text = stringResource(Res.string.add_post)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_post), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose post") }, - enabled = canSign, - onClick = { - addGroupPostViewModel.proposePost( - localChatRoom = addGroupPostUIState.localChatRoom, - noteField = noteFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. Nothing has been - // posted yet -- the post appears - // when a quorum signs -- so landing - // on the list it is not in would - // read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // Both stay on the draft. One is an - // empty note and one is a failure to - // propose, and neither is a reason to - // throw away what was written. - onEmpty = { notify(nothingToSay) }, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - // Whose name this goes out in, said before a word is typed. - // It is the group's, and it is the one thing about this - // screen a member could reasonably get wrong. - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - ProfileAvatar( - size = MaterialTheme.spacing.space500, - publicKey = chatRoomId, - picture = addGroupPostUIState.groupNostrProfile?.picture(), - name = addGroupPostUIState.groupNostrProfile?.name() - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - Text( - text = addGroupPostUIState.groupNostrProfile?.name() - ?: addGroupPostUIState.localChatRoom.chatRoom.subject - ?: chatRoomId.take(16), - style = MaterialTheme.typography.titleSmall, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.the_group_signs_a_post_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_a_post - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth().weight(1f) - .background(BottomAppBarDefaults.containerColor), - state = noteFieldState, - // The draft grows into the screen rather than scrolling - // inside three lines: a post is the one thing here - // somebody writes at length, and a composer that hides - // what was written two sentences ago is a composer - // nobody proofreads in. - lineLimits = TextFieldLineLimits.MultiLine(), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - placeholder = { - Text(stringResource(Res.string.what_should_the_group_say)) - } - ) - } - } - } - - AddGroupPostUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - Text( - text = stringResource(Res.string.add_post), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddGroupPostUIState == AddGroupPostUIState.Loading) { - addGroupPostViewModel.initiateAddGroupPost() - } - } -} - -@ConformancePreviews -@Composable -private fun AddGroupPostScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AddGroupPostScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialAddGroupPostUIState = AddGroupPostUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A group that can sign, so the composer renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt deleted file mode 100644 index b55fac5b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddTranslationArtifactVersionScreen.kt +++ /dev/null @@ -1,341 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Translate -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.AddTranslationArtifactVersionViewModel -import com.machankura.bennu.compose.ui.view.state.AddTranslationArtifactVersionUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_translation -import bennu.composeapp.generated.resources.propose_translation -import bennu.composeapp.generated.resources.this_artifact_has_no_version_for_a -import bennu.composeapp.generated.resources.translate_into_which_dialect -import bennu.composeapp.generated.resources.translate -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Composable -fun AddTranslationArtifactVersionScreen( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState = AddTranslationArtifactVersionUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addTranslationArtifactVersionViewModel: AddTranslationArtifactVersionViewModel = viewModel( - factory = AddTranslationArtifactVersionViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddTranslationArtifactVersionUIState = initialAddTranslationArtifactVersionUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(addTranslationArtifactVersionViewModel.addTranslationArtifactVersionUIState) { uiState -> - when (val addTranslationUIState = uiState) { - is AddTranslationArtifactVersionUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = addTranslationUIState.message) - } - } - - is AddTranslationArtifactVersionUIState.Loaded -> { - // A translation is into a dialect the group already signed into - // existence. Nothing is chosen to begin with: picking the first one - // for somebody would be choosing the language of the work. - var selectedDialectId: String? by remember { mutableStateOf(null) } - val selectedDialect = addTranslationUIState.dialects - .firstOrNull { dialect -> dialect.id == selectedDialectId } - - // A translation hangs off a version, and the group has to be able to - // sign; without both there is nothing this screen can propose. - val artifactVersion = addTranslationUIState.artifactVersion - val chapterCount = addTranslationUIState.chapters.size - - // The translation and a chapter apiece are signed together, and a - // session signs a bounded number of events -- so a long artifact is - // proposed in more than one, and the admins answer once per - // session. That is a number worth seeing before the tap. - val sessionCount = 1 + ( - (chapterCount - AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION) - .coerceAtLeast(0) + FrostSigningManager.MAX_BATCH_SIZE - 1 - ) / FrostSigningManager.MAX_BATCH_SIZE - - val canProposeTranslation = artifactVersion != null && - selectedDialect != null && - addTranslationUIState.canSign - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.translate, addTranslationUIState.artifact.name)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_translation), - icon = { Icon(Icons.Default.Translate, contentDescription = "Propose translation") }, - enabled = canProposeTranslation, - onClick = { - if (artifactVersion == null || selectedDialect == null) return@ExtendedFab - - addTranslationArtifactVersionViewModel.addTranslation( - localChatRoom = addTranslationUIState.localChatRoom, - artifact = addTranslationUIState.artifact, - artifactVersion = artifactVersion, - dialect = selectedDialect, - chapters = addTranslationUIState.chapters, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the artifact. Nothing has been created - // yet -- the translation appears when - // enough members sign -- so landing on - // the list it is not in would read as a - // failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed translation") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (!addTranslationUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "translation into existence. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } else if (artifactVersion == null) { - Text( - text = stringResource(Res.string.this_artifact_has_no_version_for_a), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - Text(stringResource(Res.string.translate_into_which_dialect)) - - if (addTranslationUIState.dialects.isEmpty()) { - // The only way out of this screen, and it is not on it: - // a dialect is the group's too, and asking for one is - // its own quorum from the room's own detail screen. - Text( - text = "This group has no dialects yet. Add one from the group's " + - "details before translating anything into it.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - FlowRow( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - addTranslationUIState.dialects.forEach { dialect -> - FilterChip( - selected = selectedDialectId == dialect.id, - onClick = { selectedDialectId = dialect.id }, - label = { Text(dialect.name) } - ) - } - } - - Text( - // What the group is being asked to sign, counted before - // the tap rather than described after it: the chapters - // are the rest of the batch. The empty case is worth - // its own sentence, so that a translation of an artifact - // nobody has written into yet does not read as broken. - text = if (chapterCount == 0) { - "The artifact has no chapters yet, so the group would sign the " + - "translation on its own. Chapters signed afterwards are put " + - "into it as they are added." - } else { - "The group signs the translation and " + - "$chapterCount ${if (chapterCount == 1) "chapter" else "chapters"}" + - (if (sessionCount == 1) "" else ", in $sessionCount sessions to sign") + - ". Chunks are translated one at a time afterwards." - }, - style = MaterialTheme.typography.labelMedium, - ) - } - } - } - - AddTranslationArtifactVersionUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.add_translation), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddTranslationArtifactVersionUIState == AddTranslationArtifactVersionUIState.Loading) { - addTranslationArtifactVersionViewModel.initiateAddTranslation() - } - } -} - -@ConformancePreviews -@Composable -private fun AddTranslationArtifactVersionScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AddTranslationArtifactVersionScreen( - activeUserPublicKey = "", - artifactId = "artifactId", - chatRoomId = "chatRoomId", - relayHint = null, - initialAddTranslationArtifactVersionUIState = AddTranslationArtifactVersionUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ), - artifact = MantraArtifact( - id = "artifactId", - publicKey = "author", - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = "dialectId", - license = "cc", - chatRoomId = "chatRoomId", - signature = "" - ), - dialects = listOf( - MantraDialect( - id = "dialectId", - publicKey = "author", - name = "Sesotho", - country = "Lesotho", - language = "st", - chatRoomId = "chatRoomId", - signature = "" - ) - ), - artifactVersion = MantraArtifactVersion( - id = "artifactVersionId", - artifactId = "artifactId", - publicKey = "author", - versionLabel = "1.0", - chatRoomId = "chatRoomId", - signature = "" - ), - canSign = true, - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt deleted file mode 100644 index ce39a59a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ArtifactDetailScreen.kt +++ /dev/null @@ -1,354 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.layout.width -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Article -import androidx.compose.material.icons.filled.PostAdd -import androidx.compose.material.icons.filled.Translate -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.widgets.DetailRow -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddChapterRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddTranslationRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ChapterDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationArtifactVersionDetailRoute -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.ArtifactDetailViewModel -import com.machankura.bennu.compose.ui.view.state.ArtifactDetailUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.add_chapter -import bennu.composeapp.generated.resources.add_translation -import bennu.composeapp.generated.resources.artifact_detail -import bennu.composeapp.generated.resources.chapters -import bennu.composeapp.generated.resources.details -import bennu.composeapp.generated.resources.no_chapters_yet -import bennu.composeapp.generated.resources.no_translations_yet -import bennu.composeapp.generated.resources.no_versions -import bennu.composeapp.generated.resources.translations -import bennu.composeapp.generated.resources.version -import bennu.composeapp.generated.resources.versions -import bennu.composeapp.generated.resources.chapter -import bennu.composeapp.generated.resources.words_characters -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ArtifactDetailScreen( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialArtifactDetailUIState: ArtifactDetailUIState = ArtifactDetailUIState.Loading, - mantraRepository: MantraRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val artifactDetailViewModel: ArtifactDetailViewModel = viewModel( - factory = ArtifactDetailViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialArtifactDetailUIState = initialArtifactDetailUIState, - mantraRepository = mantraRepository, - ) - ) - - ScreenStateTransition(artifactDetailViewModel.artifactDetailUIState) { uiState -> - when (val artifactDetailUIState = uiState) { - is ArtifactDetailUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = artifactDetailUIState.message) - } - } - - is ArtifactDetailUIState.Loaded -> { - val artifact = artifactDetailUIState.artifact - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(artifact.name) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - // Chapters - item { - Text( - text = stringResource(Res.string.chapters), - style = MaterialTheme.typography.labelMedium - ) - } - if (artifactDetailUIState.chapters.isEmpty()) { - item { Text(stringResource(Res.string.no_chapters_yet)) } - } else { - items( - items = artifactDetailUIState.chapters, - key = { chapter -> chapter.id } - ) { chapter -> - Card( - onClick = { - onNavigateToRoute.invoke( - ChapterDetailRoute( - activeUserPublicKey = activeUserPublicKey, - chapterId = chapter.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - ListItem( - leadingContent = { - Icon( - Icons.Default.Article, - contentDescription = "Chapter" - ) - }, - overlineContent = { Text(stringResource(Res.string.chapter, chapter.index)) }, - headlineContent = { Text(chapter.name) }, - supportingContent = { - Text(stringResource(Res.string.words_characters, chapter.wordCount, chapter.characterCount)) - } - ) - } - } - } - - item { - TextButton( - enabled = artifactDetailUIState.versions.isNotEmpty(), - onClick = { - onNavigateToRoute.invoke( - AddChapterRoute( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifact.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon( - Icons.Default.PostAdd, - contentDescription = "Add chapter" - ) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - Text(stringResource(Res.string.add_chapter)) - } - } - - item { HorizontalDivider() } - - // Translations - item { - Text( - text = stringResource(Res.string.translations), - style = MaterialTheme.typography.labelMedium - ) - } - if (artifactDetailUIState.translations.isEmpty()) { - item { Text(stringResource(Res.string.no_translations_yet)) } - } else { - items( - items = artifactDetailUIState.translations, - key = { translation -> translation.id } - ) { translation -> - Card( - onClick = { - onNavigateToRoute.invoke( - TranslationArtifactVersionDetailRoute( - activeUserPublicKey = activeUserPublicKey, - translationArtifactVersionId = translation.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - ListItem( - leadingContent = { - Icon( - Icons.Default.Translate, - contentDescription = "Translation" - ) - }, - headlineContent = { Text(translation.name) }, - supportingContent = { Text(translation.visibility) } - ) - } - } - } - - item { - TextButton( - enabled = artifactDetailUIState.versions.isNotEmpty(), - onClick = { - onNavigateToRoute.invoke( - AddTranslationRoute( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifact.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon( - Icons.Default.Translate, - contentDescription = "Add translation" - ) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - Text(stringResource(Res.string.add_translation)) - } - } - - item { HorizontalDivider() } - - // Details - item { - Text( - text = stringResource(Res.string.details), - style = MaterialTheme.typography.labelMedium - ) - } - item { - Card { - DetailRow(label = "Name", value = artifact.name) - DetailRow(label = "Url", value = artifact.url) - DetailRow(label = "Visibility", value = artifact.visibility) - DetailRow(label = "License", value = artifact.license) - DetailRow(label = "Dialect", value = artifact.dialectId) - DetailRow(label = "Author", value = artifact.publicKey) - DetailRow(label = "Created", value = artifact.createdAt.toString()) - } - } - - // Versions - item { - Text( - text = stringResource(Res.string.versions), - style = MaterialTheme.typography.labelMedium - ) - } - if (artifactDetailUIState.versions.isEmpty()) { - item { Text(stringResource(Res.string.no_versions)) } - } else { - items( - items = artifactDetailUIState.versions, - key = { version -> version.id } - ) { version -> - Card { - ListItem( - headlineContent = { Text(version.versionLabel) }, - overlineContent = { Text(stringResource(Res.string.version)) } - ) - } - } - } - } - } - } - - ArtifactDetailUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.artifact_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialArtifactDetailUIState == ArtifactDetailUIState.Loading) { - artifactDetailViewModel.initiateArtifactDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun ArtifactDetailScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - ArtifactDetailScreen( - activeUserPublicKey = "", - artifactId = "artifactId", - chatRoomId = "chatRoomId", - relayHint = null, - initialArtifactDetailUIState = ArtifactDetailUIState.Loaded( - artifact = MantraArtifact( - id = "artifactId", - publicKey = "author", - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = "dialectId", - license = "cc", - chatRoomId = "chatRoomId", - signature = "" - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt deleted file mode 100644 index 07d356e5..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt +++ /dev/null @@ -1,582 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -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.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.CellTower -import androidx.compose.material.icons.filled.ContentCopy -import androidx.compose.material.icons.filled.Delete -import androidx.compose.material.icons.filled.Dns -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.FilledTonalButton -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LocalContentColor -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.semantics.disabled -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextAlign -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.accepted_by_n_of_m_relays -import bennu.composeapp.generated.resources.add_a_relay_to_broadcast_to -import bennu.composeapp.generated.resources.add_relay -import bennu.composeapp.generated.resources.broadcast -import bennu.composeapp.generated.resources.copied_the_raw_json -import bennu.composeapp.generated.resources.copy_raw_json -import bennu.composeapp.generated.resources.eg_wss_relay_example_com -import bennu.composeapp.generated.resources.no_relays_to_broadcast_to -import bennu.composeapp.generated.resources.relay_url -import bennu.composeapp.generated.resources.relays -import bennu.composeapp.generated.resources.sends_the_event_exactly_as_the_group_signed_it -import bennu.composeapp.generated.resources.signed_by_the_group_on -import bennu.composeapp.generated.resources.that_is_not_a_relay_address -import bennu.composeapp.generated.resources.that_relay_is_already_in_this_list -import bennu.composeapp.generated.resources.the_signed_event -import bennu.composeapp.generated.resources.where_the_group_has_said_it_lives_is_filled_in -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.text.ProposedEvent -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.label -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome -import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.emptyFlow -import kotlin.time.Instant - -/** - * One event the group signed, and the relays to send it to. - * - * The group's screen shows what the group has signed; this is where one of those - * leaves the device. The list starts at where the group has said it lives and the - * member can change it, the button sends to every relay in it at once, and each - * row then says what its relay answered -- accepted, rejected in the relay's own - * words, or nothing. The raw JSON is at the bottom for anyone who would rather - * hand it to some other tool. - * - * **The button sends rather than proposes.** Every other screen off the identity - * block opens a signing session, because what it makes is a statement by the - * group. This one moves a statement the group has already made, which any member - * holding it may do: the signature is the group's, and no share of the key is - * needed to repeat it. See `BroadcastGroupSignedEventViewModel` for why the send - * goes to the pool directly rather than through the app's broadcast queue. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun BroadcastGroupSignedEventScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - signedEventId: HexKey, - initialBroadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState = - BroadcastGroupSignedEventUIState.Loading, - chatRepository: ChatRepository, - publishTransport: EventPublishTransport, - onNavigateBack: () -> Unit, -) { - val broadcastGroupSignedEventViewModel: BroadcastGroupSignedEventViewModel = viewModel( - factory = BroadcastGroupSignedEventViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = signedEventId, - initialBroadcastGroupSignedEventUIState = initialBroadcastGroupSignedEventUIState, - chatRepository = chatRepository, - publishTransport = publishTransport, - ) - ) - - val clipboardManager = LocalClipboardManager.current - - // Read out here rather than in a click handler: both are composable and an - // onClick lambda is not. - val notify = rememberNotifier(rememberCoroutineScope()) - val noRelays = stringResource(Res.string.add_a_relay_to_broadcast_to) - val copied = stringResource(Res.string.copied_the_raw_json) - - ScreenStateTransition(broadcastGroupSignedEventViewModel.broadcastGroupSignedEventUIState) { uiState -> - when (val broadcastGroupSignedEventUIState = uiState) { - is BroadcastGroupSignedEventUIState.Error -> { - // Nothing to retry: the room and the event came from navigation - // arguments, and reading them again with the same ones fails the - // same way. - ErrorState(message = broadcastGroupSignedEventUIState.message, onRetry = null) - } - - is BroadcastGroupSignedEventUIState.Loaded -> { - val signedEvent = broadcastGroupSignedEventUIState.signedEvent - val urlFieldState = rememberTextFieldState() - val isPending = broadcastGroupSignedEventViewModel.isActionPending.value - val relays = broadcastGroupSignedEventViewModel.relays - - // The list comes from the state rather than from whatever loaded - // it, so a screen handed a loaded state -- a preview, a layout - // test -- fills in the same as the app does. Once only, so a list - // the member emptied stays empty. - LaunchedEffect(broadcastGroupSignedEventUIState) { - broadcastGroupSignedEventViewModel.seedRelays( - relayLists = broadcastGroupSignedEventUIState.relayLists, - kind = signedEvent.kind, - ) - } - - // A refusal is about what is in the field, so it goes the moment - // the field changes rather than sitting under a URL that has since - // been corrected. - LaunchedEffect(urlFieldState) { - snapshotFlow { urlFieldState.text.toString() } - .collect { broadcastGroupSignedEventViewModel.clearAddFailure() } - } - - // As the group signed it, byte for byte: what is copied is exactly - // what goes on the wire, because the point of copying it is to - // hand somebody something they can verify. - val json = signedEvent.toEvent().toJson() - val summary = ProposedEvent.summarize(signedEvent.toEvent()) - - val canSend = !isPending - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - broadcastGroupSignedEventUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.broadcast), - icon = { Icon(Icons.Default.CellTower, contentDescription = "Broadcast to these relays") }, - enabled = canSend, - onClick = { - broadcastGroupSignedEventViewModel.broadcast( - signedEvent = signedEvent, - // Stays on the screen: an empty list is - // a question rather than a mistake. - onNoRelays = { notify(noRelays) } - ) - } - ) - } - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - .padding(horizontal = MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - // What is being sent, in the words the signing screen used - // for it: a member deciding where a post goes is deciding - // about a post, and "kind 1" answers a question nobody asked. - item { - Column( - modifier = Modifier.fillMaxWidth() - .padding(top = MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = summary.label, - style = MaterialTheme.typography.titleMedium - ) - - Text( - text = summary.detail, - style = MaterialTheme.typography.bodyMedium, - maxLines = 4 - ) - - Text( - text = stringResource( - Res.string.signed_by_the_group_on, - signedEvent.createdAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - item { - Text( - text = stringResource( - Res.string.sends_the_event_exactly_as_the_group_signed_it - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - - item { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) - - Text( - text = stringResource(Res.string.relays), - style = MaterialTheme.typography.titleSmall - ) - - Text( - text = stringResource( - Res.string.where_the_group_has_said_it_lives_is_filled_in - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - - item { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - OutlinedTextField( - modifier = Modifier.weight(1f) - .background(BottomAppBarDefaults.containerColor), - state = urlFieldState, - lineLimits = TextFieldLineLimits.SingleLine, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(Icons.Default.Dns, contentDescription = Decorative) - }, - label = { Text(stringResource(Res.string.relay_url)) }, - placeholder = { - Text(stringResource(Res.string.eg_wss_relay_example_com)) - }, - isError = broadcastGroupSignedEventViewModel.addFailure != null - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - IconButton( - onClick = { - if ( - broadcastGroupSignedEventViewModel.addRelay( - urlFieldState.text.toString() - ) - ) { - urlFieldState.clearText() - } - } - ) { - Icon( - Icons.Default.Add, - contentDescription = stringResource(Res.string.add_relay) - ) - } - } - - // Named rather than silent. An add button that does - // nothing for a URL it refuses is indistinguishable from - // a missed tap. - broadcastGroupSignedEventViewModel.addFailure?.let { failure -> - Text( - text = when (failure) { - BroadcastGroupSignedEventViewModel.AddFailure.NotARelay -> - stringResource(Res.string.that_is_not_a_relay_address) - BroadcastGroupSignedEventViewModel.AddFailure.AlreadyListed -> - stringResource( - Res.string.that_relay_is_already_in_this_list - ) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center, - modifier = Modifier.fillMaxWidth() - ) - } - } - - // The last press, summed up, above the rows that break it - // down. Persistent rather than a snackbar, because it is - // the answer the member came for and a snackbar would be - // gone before the last relay had been read. - broadcastGroupSignedEventViewModel.lastBroadcast?.let { last -> - item { - Text( - text = stringResource( - Res.string.accepted_by_n_of_m_relays, - last.accepted, - last.asked - ), - style = MaterialTheme.typography.bodyMedium, - color = if (last.accepted == last.asked) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.error - } - ) - } - } - - if (relays.isEmpty()) { - item { - EmptyState( - message = stringResource(Res.string.no_relays_to_broadcast_to), - icon = Icons.Default.Dns - ) - } - } else { - items(items = relays, key = { it.url }) { relay -> - BroadcastRelayRow( - relay = relay, - outcome = broadcastGroupSignedEventViewModel.outcomes[relay], - // A row cannot leave while its relay is being - // asked: the answer would arrive for a relay - // that is no longer there to show it. - canRemove = !isPending, - onRemove = { - broadcastGroupSignedEventViewModel.removeRelay(relay) - } - ) - } - } - - item { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.sectionGap)) - - Text( - text = stringResource(Res.string.the_signed_event), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.relatedGap)) - - Surface( - modifier = Modifier.fillMaxWidth(), - color = MaterialTheme.colorScheme.surfaceVariant, - shape = MaterialTheme.shapes.small - ) { - Text( - text = json, - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding) - ) - } - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) - - FilledTonalButton( - onClick = { - clipboardManager.setText(AnnotatedString(json)) - notify(copied) - }, - modifier = Modifier.fillMaxWidth() - ) { - Icon(Icons.Default.ContentCopy, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space100)) - Text(text = stringResource(Res.string.copy_raw_json)) - } - - Spacer(modifier = Modifier.height(MaterialTheme.spacing.sectionGap)) - } - } - } - } - - BroadcastGroupSignedEventUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - Text( - text = stringResource(Res.string.broadcast), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialBroadcastGroupSignedEventUIState == BroadcastGroupSignedEventUIState.Loading) { - broadcastGroupSignedEventViewModel.initiateBroadcastGroupSignedEvent() - } - } -} - -/** - * One relay to send to, and what it said the last time it was asked. - * - * The answer is on a second line under the host rather than in an icon, because - * the answers that matter are the relay's own words -- "blocked: not on the - * allow list" is something a member can act on, and a red icon is not. - */ -@Composable -private fun BroadcastRelayRow( - relay: NormalizedRelayUrl, - outcome: RelayOutcome?, - canRemove: Boolean, - onRemove: () -> Unit -) { - Row( - modifier = Modifier.fillMaxWidth().padding(vertical = MaterialTheme.spacing.relatedGap), - verticalAlignment = Alignment.CenterVertically - ) { - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - // The host rather than the whole URL: every relay here starts - // `wss://` -- nothing else is allowed in -- so the scheme is four - // characters of nothing in front of the part that differs. - text = relay.displayUrl(), - style = MaterialTheme.typography.bodyMedium - ) - - outcome?.let { - Text( - text = it.label(), - style = MaterialTheme.typography.bodySmall, - color = when (it) { - RelayOutcome.Accepted -> MaterialTheme.colorScheme.primary - is RelayOutcome.Rejected, is RelayOutcome.Failed -> - MaterialTheme.colorScheme.error - RelayOutcome.Sending, RelayOutcome.NoAnswer -> - MaterialTheme.colorScheme.onSurfaceVariant - } - ) - } - } - - IconButton(onClick = onRemove, enabled = canRemove) { - Icon( - Icons.Default.Delete, - contentDescription = "Remove relay", - // The button's own disabled colour while a send is out, rather - // than a red that promises a tap will do something. - tint = if (canRemove) MaterialTheme.colorScheme.error else LocalContentColor.current - ) - } - } -} - -@ConformancePreviews -@Composable -private fun BroadcastGroupSignedEventScreenPreview() { - val chatRoomId = "d4c3b2a1".repeat(8) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - BroadcastGroupSignedEventScreen( - activeUserPublicKey = "", - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = "b".repeat(64), - initialBroadcastGroupSignedEventUIState = BroadcastGroupSignedEventUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - signedEvent = GroupSignedEvent( - id = "b".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = TextNoteEvent.KIND, - tags = emptyArray(), - content = "The first chapter is out.", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - // Nothing agreed, so the list fills in from the app's own - // publish set -- the state a group meets this screen in - // before it has edited its relays. - relayLists = GroupRelayList.allAmong(emptyList(), chatRoomId), - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = object : EventPublishTransport { - override suspend fun publishEvent( - nostrEvent: com.machankura.bennu.compose.database.model.NostrEvent, - relays: Set - ): Flow = emptyFlow() - }, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt deleted file mode 100644 index cdb12652..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChapterDetailScreen.kt +++ /dev/null @@ -1,220 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Segment -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.ChapterDetailViewModel -import com.machankura.bennu.compose.ui.view.state.ChapterDetailUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.chapter_detail -import bennu.composeapp.generated.resources.no_chunks -import bennu.composeapp.generated.resources.original_text -import bennu.composeapp.generated.resources.chapter_words_characters -import bennu.composeapp.generated.resources.chunk -import bennu.composeapp.generated.resources.chunks -import bennu.composeapp.generated.resources.words_characters -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ChapterDetailScreen( - activeUserPublicKey: HexKey, - chapterId: String, - chatRoomId: String, - relayHint: String?, - initialChapterDetailUIState: ChapterDetailUIState = ChapterDetailUIState.Loading, - mantraRepository: MantraRepository, - onNavigateBack: () -> Unit, -) { - val chapterDetailViewModel: ChapterDetailViewModel = viewModel( - factory = ChapterDetailViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chapterId = chapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialChapterDetailUIState = initialChapterDetailUIState, - mantraRepository = mantraRepository, - ) - ) - - ScreenStateTransition(chapterDetailViewModel.chapterDetailUIState) { uiState -> - when (val chapterDetailUIState = uiState) { - is ChapterDetailUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = chapterDetailUIState.message) - } - } - - is ChapterDetailUIState.Loaded -> { - val chapter = chapterDetailUIState.chapter - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(chapter.name) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - Text( - text = stringResource(Res.string.chapter_words_characters, chapter.index, chapter.wordCount, chapter.characterCount), - style = MaterialTheme.typography.labelMedium - ) - } - - // Original text (markdown, shown as-is). - item { - Text( - text = stringResource(Res.string.original_text), - style = MaterialTheme.typography.labelMedium - ) - } - item { - Card { - Text( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - text = chapter.originalText, - style = MaterialTheme.typography.bodyMedium - ) - } - } - - item { HorizontalDivider() } - - // Chunks - item { - Text( - text = stringResource(Res.string.chunks, chapterDetailUIState.chunks.size), - style = MaterialTheme.typography.labelMedium - ) - } - if (chapterDetailUIState.chunks.isEmpty()) { - item { Text(stringResource(Res.string.no_chunks)) } - } else { - items( - items = chapterDetailUIState.chunks, - key = { chunk -> chunk.id } - ) { chunk -> - Card { - ListItem( - leadingContent = { - Icon( - Icons.Default.Segment, - contentDescription = "Chunk" - ) - }, - overlineContent = { Text(stringResource(Res.string.chunk, chunk.index)) }, - headlineContent = { Text(chunk.text) }, - supportingContent = { - Text(stringResource(Res.string.words_characters, chunk.wordCount, chunk.characterCount)) - } - ) - } - } - } - } - } - } - - ChapterDetailUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.chapter_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialChapterDetailUIState == ChapterDetailUIState.Loading) { - chapterDetailViewModel.initiateChapterDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun ChapterDetailScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - ChapterDetailScreen( - activeUserPublicKey = "", - chapterId = "chapterId", - chatRoomId = "chatRoomId", - relayHint = null, - initialChapterDetailUIState = ChapterDetailUIState.Loaded( - chapter = MantraChapter( - id = "chapterId", - artifactVersionId = "versionId", - publicKey = "author", - name = "Chapter 1 — The Beginning", - originalText = "When he was nearly thirteen...\n\nWhen enough years had gone by...", - index = 0, - wordCount = 12, - characterCount = 64, - signature = "", - chatRoomId = "chatRoomId" - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt index 8ae76194..845c0b71 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt @@ -7,13 +7,41 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightni import bennu.composeapp.generated.resources.group_wallet_on_s import fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.wallet.GroupLightningRollout +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Box +import bennu.composeapp.generated.resources.change +import bennu.composeapp.generated.resources.guard_members_wallets +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute +import bennu.composeapp.generated.resources.guarded_wallet_after +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.composable.navigation.routes.NewMemberWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute +import bennu.composeapp.generated.resources.members_guarded_wallets +import bennu.composeapp.generated.resources.ask_this_group_to_guard_a_wallet_for_you +import bennu.composeapp.generated.resources.asked_by_s_not_yet_signed +import bennu.composeapp.generated.resources.put_to_the_group +import bennu.composeapp.generated.resources.couldn_t_put_it_to_the_group +import bennu.composeapp.generated.resources.at_s +import bennu.composeapp.generated.resources.s_dot_s +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material3.ListItem +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.foundation.clickable +import androidx.compose.ui.text.style.TextOverflow +import bennu.composeapp.generated.resources.unguarded_wallet +import bennu.composeapp.generated.resources.guarded_wallet +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.wallet.GroupWalletRollout import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import bennu.composeapp.generated.resources.open_on_s import bennu.composeapp.generated.resources.not_opened_yet import bennu.composeapp.generated.resources.group_wallet -import androidx.compose.material.icons.filled.AccountBalanceWallet +import bennu.composeapp.generated.resources.s_onchain_wallet import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -34,10 +62,6 @@ import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DeleteForever import androidx.compose.material.icons.filled.PersonRemove -import androidx.compose.material.icons.filled.Badge -import androidx.compose.material.icons.filled.Campaign -import androidx.compose.material.icons.filled.DataObject -import androidx.compose.material.icons.filled.Dns import androidx.compose.material.icons.filled.Draw import androidx.compose.material.icons.filled.PersonAdd import androidx.compose.material.icons.filled.Unsubscribe @@ -51,7 +75,6 @@ import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface @@ -72,7 +95,6 @@ import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.machankura.bennu.compose.database.model.ChatRoom @@ -83,15 +105,10 @@ import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.ProfilePreviewRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRitualRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroupEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.SearchMemberToAddToChatRoomRoute import com.machankura.bennu.compose.extensions.inComparableGroups @@ -105,20 +122,8 @@ import com.machankura.bennu.compose.ui.theme.BennuTheme import com.machankura.bennu.compose.ui.view.model.ChatRoomDetailViewModel import com.machankura.bennu.compose.ui.view.state.ChatRoomDetailUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata import com.machankura.bennu.compose.ui.theme.spacing import bennu.composeapp.generated.resources.run_by_members -import bennu.composeapp.generated.resources.nostr_profile -import bennu.composeapp.generated.resources.relays -import bennu.composeapp.generated.resources.posts -import bennu.composeapp.generated.resources.not_described_yet -import bennu.composeapp.generated.resources.n_of_m_relay_lists_agreed -import bennu.composeapp.generated.resources.no_posts_yet -import bennu.composeapp.generated.resources.one_post -import bennu.composeapp.generated.resources.n_posts -import bennu.composeapp.generated.resources.propose_event -import bennu.composeapp.generated.resources.no_name_on_this_profile import bennu.composeapp.generated.resources.parent_group import bennu.composeapp.generated.resources.a_subgroup import bennu.composeapp.generated.resources.created_you_are_not_a_member @@ -130,8 +135,6 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectSubgro import com.machankura.bennu.compose.ui.composable.navigation.routes.NostrEventDetailRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import com.machankura.bennu.compose.managers.SubgroupManager -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupRelaySet import bennu.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource import bennu.composeapp.generated.resources.delete_group @@ -179,7 +182,7 @@ fun ChatRoomDetailScreen( initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading, nostrRepository: NostrRepository, chatRepository: ChatRepository, - mantraRepository: MantraRepository, + memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, onNavigateToRoute: (Route) -> Unit, onPopBackToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, @@ -191,10 +194,11 @@ fun ChatRoomDetailScreen( initialChatRoomDetailUIState = initialChatRoomDetailUIState, nostrRepository = nostrRepository, chatRepository = chatRepository, - mantraRepository = mantraRepository, - activeUserPublicKey = activeUserPublicKey + activeUserPublicKey = activeUserPublicKey, + memberWalletRepository = memberWalletRepository, ) ) + val couldNotPutToGroup = stringResource(Res.string.couldn_t_put_it_to_the_group) // Read outside the click handlers: stringResource and rememberNotifier are both // composable, and a lambda passed to onClick is not. @@ -326,14 +330,21 @@ fun ChatRoomDetailScreen( Text(text = stringResource(Res.string.parent_group)) }, supportingContent = { - Text( - text = parentChatRoomId - .take(16) - .inComparableGroups(), - fontFamily = FontFamily.Monospace, - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis - ) + Column { + Text( + text = parentChatRoomId + .take(16) + .inComparableGroups(), + fontFamily = FontFamily.Monospace, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis + ) + // What the parent decided about + // this room's wallet at its birth. + // Nothing for one that decided + // nothing, as before policies. + walletPolicyLabel(chatRoomDetailUIState.walletPolicy, chatRoomDetailUIState.guardianDelay)?.let { Text(it) } + } } ) } @@ -354,125 +365,25 @@ fun ChatRoomDetailScreen( HorizontalDivider() } - // Under the room's identity and above its work, because - // that is what it is: what the rest of nostr reads for - // the key the signing key row names. The room's subject - // and description above are this device's names for it; - // this is the group's own, signed by the group. - // - // One row per kind of statement, each opening the screen - // that shows it, rather than the statements themselves. - // Five sections of cards, every card with a button under - // it, made this screen as long as everything the group - // had ever said, with its members and its subgroups - // somewhere underneath. What a member opening it wants - // first is the shape of that -- a name and a few counts - // -- not every word of it. The row carries the shape; - // the screen behind it carries the rest, with the same - // broadcasts and the same gated ways in the sections had. + // The group's coins, signed by the room's key and read + // by nobody outside the room: the statement opening it + // never leaves the group. Shown to every member, open + // or not -- the screen behind it is where a member who + // can sign asks the group to open one. // // Marmot rooms only, and absent rather than empty in a // NIP-17 one. A NIP-17 room's id is not a key it can - // sign as, so it has no nostr identity at all -- and a - // row saying it has not described one yet would promise - // something that is never coming. - if (chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState != null) { + // sign as, so it has no wallet to open. + if ( + GroupWalletRollout.ENABLED && + chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState != null + ) { item { - SignedWorkRow( - icon = Icons.Default.Badge, - headline = stringResource(Res.string.nostr_profile), - // The name the group gave itself and its - // address where it claims one: the two - // things a reader checks a profile for. - // Named rather than falling back to the - // pubkey, for the reason the card gives. - supporting = chatRoomDetailUIState.groupNostrProfile - ?.let { profile -> - listOfNotNull( - profile.name() - ?: stringResource(Res.string.no_name_on_this_profile), - profile.nip05() - ).joinToString(" · ") - } - ?: stringResource(Res.string.not_described_yet), - onOpen = { - onNavigateToRoute.invoke( - GroupNostrProfileRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // Directly under the profile, because between them - // they are the whole of the group's account of - // itself on nostr: who it says it is, and where it - // says it can be found. - item { - SignedWorkRow( - icon = Icons.Default.Dns, - headline = stringResource(Res.string.relays), - // How many of the four lists the group has - // agreed, counted against the sets rather - // than the entries: the entries come back - // empty in a room that has none of this to - // say, and "0 of 0" would say nothing. - supporting = stringResource( - Res.string.n_of_m_relay_lists_agreed, - chatRoomDetailUIState.groupRelayLists.count { it.isAgreed }, - GroupRelaySet.entries.size - ), - onOpen = { - onNavigateToRoute.invoke( - GroupRelaysRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // Under the relay lists, because these are what the - // lists are *for*: the profile says who the group - // is, the relays say where to find it, and these are - // what a reader would find there. - item { - SignedWorkRow( - icon = Icons.Default.Campaign, - headline = stringResource(Res.string.posts), - supporting = when (val count = chatRoomDetailUIState.groupPosts.size) { - 0 -> stringResource(Res.string.no_posts_yet) - 1 -> stringResource(Res.string.one_post) - else -> stringResource(Res.string.n_posts, count) - }, - onOpen = { - onNavigateToRoute.invoke( - GroupPostsRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // The group's coins. After the identity block's - // last signed row and before the paste, because it - // is signed by the same key and read by nobody - // outside the room: the statement opening it never - // leaves the group. Shown to every member, open or - // not -- the screen behind it is where a member who - // can sign asks the group to open one. - if (GroupWalletRollout.ENABLED) item { SignedWorkRow( icon = Icons.Default.AccountBalanceWallet, - headline = stringResource(Res.string.group_wallet), + headline = chatRoomDetailUIState.localChatRoom.chatRoom.subject + ?.let { stringResource(Res.string.s_onchain_wallet, it) } + ?: stringResource(Res.string.group_wallet), supporting = chatRoomDetailUIState.groupWallet?.let { wallet -> stringResource( Res.string.open_on_s, @@ -532,44 +443,6 @@ fun ChatRoomDetailScreen( ) } - // The untyped way into everything above it. Each - // row opens a screen with a form that builds one - // kind of event; this takes any of those kinds as - // JSON, pasted from wherever it was made, and it - // lands on whichever screen is its kind's once the - // quorum signs -- the same reading, off the same - // signed events. Last in the block because it is - // about the block rather than about any one row of - // it, and behind the same gate for the same reason. - if (chatRoomDetailUIState.canEditNostrProfile) { - item { - TextButton( - onClick = { - onNavigateToRoute.invoke( - ProposeGroupEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon( - Icons.Default.DataObject, - contentDescription = Decorative - ) - - Spacer( - modifier = Modifier.width( - MaterialTheme.spacing.space125 - ) - ) - - Text(stringResource(Res.string.propose_event)) - } - } - } - item { HorizontalDivider() } @@ -647,6 +520,76 @@ fun ChatRoomDetailScreen( } } + // A member's wallet is a person, not a room, so it is its + // own section and its row opens the person -- there is no + // chat to open. docs/member-guarded-wallets.md, Phase 11. + if (chatRoomDetailUIState.memberWallets.isNotEmpty() || chatRoomDetailUIState.canAskForMemberWallet || chatRoomDetailUIState.showsMemberWalletPolicy) { + item { HorizontalDivider() } + item { + Text( + text = stringResource(Res.string.members_guarded_wallets), + style = MaterialTheme.typography.labelMedium + ) + } + // Whether the group guards members' wallets at all, and at + // what delay -- first, because every row under it is a + // wallet it agreed to under one. docs/member-wallet-delay.md. + if (chatRoomDetailUIState.showsMemberWalletPolicy) { + item { + MemberWalletPolicyRow( + policy = chatRoomDetailUIState.memberWalletPolicy, + onChange = if (chatRoomDetailUIState.canSponsor) { + { + onNavigateToRoute.invoke( + MemberWalletPolicyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId) + ) + } + } else null, + ) + } + } + items( + items = chatRoomDetailUIState.memberWallets, + key = { "member-wallet-" + it.walletId } + ) { wallet -> + MemberWalletRow( + wallet = wallet, + isPending = chatRoomDetailViewModel.isActionPending.value, + onOpen = { + onNavigateToRoute.invoke( + ProfilePreviewRoute(activeUserPublicKey = activeUserPublicKey, profilePublicKey = wallet.ownerPublicKey) + ) + }, + onPutToGroup = if (!wallet.isCertified && chatRoomDetailUIState.canSponsor) { + { + chatRoomDetailViewModel.putToGroup( + request = wallet.request, + onSuccess = { sessionId -> + onNavigateToRoute.invoke( + FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId) + ) + }, + onFailure = { notify(couldNotPutToGroup) }, + ) + } + } else null, + ) + } + if (chatRoomDetailUIState.canAskForMemberWallet) { + item { + TextButton( + onClick = { + onNavigateToRoute.invoke(NewMemberWalletRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) + } + ) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) + Text(stringResource(Res.string.ask_this_group_to_guard_a_wallet_for_you)) + } + } + } + } + item { HorizontalDivider() } @@ -668,12 +611,17 @@ fun ChatRoomDetailScreen( // -- and those are reached from the transcript line that // names the ceremony they are about, never from here, // which has no way to say which. + // + // To the creation screen, which hands over to the group's + // ceremony if it already has one: the ceremony screen only + // shows a ceremony it is named, and this button has none + // to name. See docs/ceremony-creation.md. if (chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState == null) { item { TextButton( onClick = { onNavigateToRoute.invoke( - DkgRitualRoute( + CreateSharedKeyRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId ) @@ -1197,8 +1145,8 @@ internal fun GroupKeyStateSheetContent( } /** - * One row of the identity block: a kind of statement the group has signed, a - * line summarising it, and the way to the screen where it is read in full. + * One row for a kind of statement the group has signed: a line summarising it, + * and the way to the screen where it is read in full. * * The same shape as the signing key and parent group rows above it -- a card * with a leading icon and a trailing chevron -- because it is the same kind of @@ -1235,6 +1183,39 @@ private fun SignedWorkRow( } } +/** + * One member's guarded wallet, as the guarding group's page lists it: the + * person, by the live name of their profile, and the label they gave it. A + * request no signer has put to the group yet says so, and offers the one thing + * a signer can do about it. + */ +@Composable +private fun MemberWalletRow( + wallet: MemberWalletManager.GroupMemberWallet, + isPending: Boolean, + onOpen: () -> Unit, + onPutToGroup: (() -> Unit)?, +) { + val name = stringResource(Res.string.at_s, wallet.ownerName ?: wallet.ownerPublicKey.take(8)) + ListItem( + modifier = Modifier.clickable(onClick = onOpen).minimumInteractiveComponentSize(), + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + headlineContent = { + Text( + text = wallet.label?.let { stringResource(Res.string.s_dot_s, name, it) } ?: name, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + supportingContent = if (wallet.isCertified) null else { + { Text(stringResource(Res.string.asked_by_s_not_yet_signed, name)) } + }, + trailingContent = onPutToGroup?.let { put -> + { TextButton(onClick = put, enabled = !isPending) { Text(stringResource(Res.string.put_to_the_group)) } } + }, + ) +} + /** * One subgroup, as the parent's record and this device's rooms together have it. * @@ -1267,24 +1248,69 @@ private fun SubgroupCard( ) }, supportingContent = { - Text( - text = when { - subgroup.isJoined -> stringResource( - Res.string.run_by_members, - subgroup.adminPublicKeys.size.toString() - ) - // The room does not exist anywhere yet: the parent has - // certified it and nobody has created it. Between steps 2 - // and 4 of docs/subgroups.md this is every member's view. - subgroup.keyState == null -> stringResource(Res.string.certified_not_yet_created) - else -> stringResource(Res.string.created_you_are_not_a_member) - } - ) + Column { + Text( + text = when { + subgroup.isJoined -> stringResource( + Res.string.run_by_members, + subgroup.adminPublicKeys.size.toString() + ) + // The room does not exist anywhere yet: the parent has + // certified it and nobody has created it. Between steps 2 + // and 4 of docs/subgroups.md this is every member's view. + subgroup.keyState == null -> stringResource(Res.string.certified_not_yet_created) + else -> stringResource(Res.string.created_you_are_not_a_member) + } + ) + // What the parent decided about its wallet, from the certificate: + // founding history, like the name the row falls back to. + walletPolicyLabel(subgroup.walletPolicy, subgroup.guardianDelay)?.let { Text(it) } + } } ) } } +/** + * The group's own stand on its members' wallets, with *Change* -- or *Guard + * members' wallets* when it has none open -- for a device that can put a change + * to the group. `docs/member-wallet-delay.md`, Phase 6. + */ +@Composable +private fun MemberWalletPolicyRow(policy: MemberWalletPolicyEvent.Policy?, onChange: (() -> Unit)?) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Box(modifier = Modifier.weight(1f)) { MemberWalletPolicyState(policy) } + onChange?.let { change -> + TextButton(onClick = change) { + Text( + stringResource( + if (policy is MemberWalletPolicyEvent.Policy.Open) Res.string.change else Res.string.guard_members_wallets + ) + ) + } + } + } +} + +/** + * *Guarded wallet, after 144 blocks, about 1 day* or *Unguarded wallet* for a + * policy a parent decided, and null for one it left to the subgroup -- + * `docs/subgroup-wallet-policy.md`. The delay is the parent's own leaf's, + * `docs/guardian-delay.md`. + */ +@Composable +private fun walletPolicyLabel(policy: WalletPolicyReading?, guardianDelay: Long?): String? = when (policy) { + WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) -> guardianDelay + ?.let { stringResource(Res.string.guarded_wallet_after, delayText(it)) } + ?: stringResource(Res.string.guarded_wallet) + WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) -> stringResource(Res.string.unguarded_wallet) + else -> null +} + /** One labelled value of a key state, whole and comparable. */ @Composable private fun GroupKeyStateField( @@ -1415,9 +1441,9 @@ private fun ChatRoomMessagingScreenPreview() { subject = "Message title", description = "Description of a chat room so that members now why they are here.", initialGiftWrapPayloadId = "sdfaer", - // A Marmot room, so the nostr profile section renders - // at all -- it is hidden in a NIP-17 one, which has no - // key to have an identity on nostr. + // A Marmot room, so the signed-work block renders at + // all -- it is hidden in a NIP-17 one, which has no key + // to sign with. mlsGroupState = "state" ), localParticipants = listOf( @@ -1447,32 +1473,9 @@ private fun ChatRoomMessagingScreenPreview() { announcedBy = "d".repeat(64), announcedAt = Instant.fromEpochSeconds(1_700_000_000) ), - // A group that has described itself, so the section renders - // with something in it rather than only in its empty state. - // Built directly rather than read out of a signed event: the - // reading checks a signature, and there is no real one here. - groupNostrProfile = GroupNostrProfile( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = "publicKey", - publicKey = "publicKey", - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - metadata = UserMetadata().apply { - displayName = "Translation collective" - about = "A group translating hard books into Sesotho." - nip05 = "group@example.com" - } - ), - canEditNostrProfile = true ), nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, onNavigateToRoute = {}, onPopBackToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CreateSharedKeyScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CreateSharedKeyScreen.kt new file mode 100644 index 00000000..bd6fd170 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CreateSharedKeyScreen.kt @@ -0,0 +1,306 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Remove +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_shared_key_needs_at_least_members +import bennu.composeapp.generated.resources.couldn_t_load_this_group +import bennu.composeapp.generated.resources.couldn_t_read_your_keys +import bennu.composeapp.generated.resources.couldn_t_start_the_key_ceremony +import bennu.composeapp.generated.resources.everyone_has_to_be_online_at_the_same_time +import bennu.composeapp.generated.resources.how_many_members_will_it_take_to_sign +import bennu.composeapp.generated.resources.of +import bennu.composeapp.generated.resources.shared_key +import bennu.composeapp.generated.resources.shared_key_for +import bennu.composeapp.generated.resources.start_key_ceremony +import bennu.composeapp.generated.resources.the_group_can_hold_one_key_together_split_so +import bennu.composeapp.generated.resources.this_is_fixed_once_the_ceremony_runs +import bennu.composeapp.generated.resources.this_room_was_made_from_a_key_the_group_already_holds +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import org.jetbrains.compose.resources.stringResource +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.managers.ChillDkgRitualManager +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.theme.BennuTheme +import com.machankura.bennu.compose.ui.theme.ConformancePreviews +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.CreateSharedKeyViewModel +import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState + +/** + * Starts a NIP-17 group's own key ceremony: the quorum, and one button. + * + * The only screen that does. The ceremony screen it hands over to shows a + * ceremony and never offers to start one, because doing both from one button + * slot is how a member approving a subgroup's ceremony opened a second, whole-room + * one in the parent's room. See docs/ceremony-creation.md. + * + * [onCeremonyOpened] is called with the ceremony to show, whether this screen + * opened it or found one already there. The caller replaces this screen with it, + * so back from the ceremony goes wherever the member came from. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CreateSharedKeyScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialUIState: CreateSharedKeyUIState = CreateSharedKeyUIState.Loading, + activeIdentityStateFlow: StateFlow, + chatRepository: ChatRepository, + dkgRepository: DkgRepository, + onCeremonyOpened: (dkgSessionId: String) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: CreateSharedKeyViewModel = viewModel( + factory = CreateSharedKeyViewModel.factory( + chatRoomId = chatRoomId, + activeUserPublicKey = activeUserPublicKey, + initialUIState = initialUIState, + activeIdentityStateFlow = activeIdentityStateFlow, + chatRepository = chatRepository, + dkgRepository = dkgRepository, + ) + ) + + LaunchedEffect(true) { + if (initialUIState == CreateSharedKeyUIState.Loading) { + viewModel.initiate() + } + } + + val state = viewModel.uiState + + LaunchedEffect(state) { + if (state is CreateSharedKeyUIState.Existing) onCeremonyOpened(state.dkgSessionId) + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { + // The room's name only once it is loaded; before that, and on a + // refusal, the plain title rather than "Shared key for " and + // nothing. + val subject = (state as? CreateSharedKeyUIState.Loaded)?.localChatRoom?.chatRoom?.subject + Text( + text = subject + ?.let { stringResource(Res.string.shared_key_for, it) } + ?: stringResource(Res.string.shared_key), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { innerPadding -> + ScreenStateTransition(state) { uiState -> + when (uiState) { + // Existing is a hand-over in flight: nothing to draw but the wait. + CreateSharedKeyUIState.Loading, + is CreateSharedKeyUIState.Existing -> LoadingDataIndicator( + modifier = Modifier.padding(innerPadding).fillMaxSize() + ) + + is CreateSharedKeyUIState.Error -> ErrorState( + modifier = Modifier.padding(innerPadding).readableContent(), + message = when (uiState.reason) { + CreateSharedKeyUIState.Error.Reason.ROOM_NOT_FOUND -> + stringResource(Res.string.couldn_t_load_this_group) + CreateSharedKeyUIState.Error.Reason.NO_KEYS -> + stringResource(Res.string.couldn_t_read_your_keys) + CreateSharedKeyUIState.Error.Reason.NOT_STARTED -> + stringResource(Res.string.couldn_t_start_the_key_ceremony) + }, + onRetry = viewModel::initiate, + ) + + is CreateSharedKeyUIState.Refused -> EmptyState( + modifier = Modifier.padding(innerPadding).readableContent(), + icon = Icons.Default.Key, + message = when (uiState.reason) { + CreateSharedKeyUIState.Refused.Reason.MARMOT_ROOM -> + stringResource(Res.string.this_room_was_made_from_a_key_the_group_already_holds) + CreateSharedKeyUIState.Refused.Reason.TOO_FEW_MEMBERS -> + stringResource( + Res.string.a_shared_key_needs_at_least_members, + ChillDkgRitualManager.MINIMUM_PARTICIPANTS + ) + }, + ) + + is CreateSharedKeyUIState.Loaded -> { + val isActionPending = viewModel.isActionPending.value + + Column( + modifier = Modifier + .padding(innerPadding) + .readableContent() + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Text( + text = stringResource(Res.string.the_group_can_hold_one_key_together_split_so), + style = MaterialTheme.typography.bodyMedium + ) + + Text( + text = stringResource( + Res.string.everyone_has_to_be_online_at_the_same_time, + uiState.participantCount + ), + style = MaterialTheme.typography.bodyMedium + ) + + SharedKeyQuorumStepper( + threshold = viewModel.threshold.value, + participantCount = uiState.participantCount, + quorumRange = viewModel.quorumRange(), + onThresholdChange = viewModel::setThreshold + ) + + Button( + modifier = Modifier.fillMaxWidth(), + enabled = !isActionPending, + onClick = { viewModel.create(onCreated = onCeremonyOpened) } + ) { + if (isActionPending) { + CircularProgressIndicator(modifier = Modifier.size(20.dp)) + } else { + Icon(Icons.Default.Key, contentDescription = Decorative) + Text( + modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap), + text = stringResource(Res.string.start_key_ceremony) + ) + } + } + } + } + } + } + } +} + +/** Same shape as the group-creation quorum picker, so the choice reads the same. */ +@Composable +private fun SharedKeyQuorumStepper( + threshold: Int, + participantCount: Int, + quorumRange: IntRange, + onThresholdChange: (Int) -> Unit, +) { + Column( + modifier = Modifier.fillMaxWidth().padding(top = MaterialTheme.spacing.space50), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50) + ) { + Text( + text = stringResource(Res.string.how_many_members_will_it_take_to_sign), + style = MaterialTheme.typography.titleSmall + ) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200), + verticalAlignment = Alignment.CenterVertically + ) { + FilledIconButton( + onClick = { onThresholdChange(threshold - 1) }, + enabled = threshold > quorumRange.first + ) { + Icon(Icons.Default.Remove, contentDescription = "Fewer signers") + } + + Text( + text = stringResource(Res.string.of, threshold, participantCount), + style = MaterialTheme.typography.titleMedium + ) + + FilledIconButton( + onClick = { onThresholdChange(threshold + 1) }, + enabled = threshold < quorumRange.last + ) { + Icon(Icons.Default.Add, contentDescription = "More signers") + } + } + + Text( + text = stringResource(Res.string.this_is_fixed_once_the_ceremony_runs), + style = MaterialTheme.typography.labelMedium + ) + } +} + +@ConformancePreviews +@Composable +private fun CreateSharedKeyScreenPreview() { + BennuTheme { + Surface(modifier = Modifier.fillMaxSize()) { + CreateSharedKeyScreen( + activeUserPublicKey = "", + chatRoomId = "chatRoomId", + initialUIState = CreateSharedKeyUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = "chatRoomId", + userPublicKey = "", + subject = "Group discussions", + description = null, + mlsGroupState = null, + ) + ), + participantCount = 3, + ), + activeIdentityStateFlow = MutableStateFlow(null), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + onCeremonyOpened = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgApprovalScaffold.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgApprovalScaffold.kt index ebc36d6b..cc11d7a6 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgApprovalScaffold.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgApprovalScaffold.kt @@ -65,7 +65,7 @@ internal fun DkgApprovalScaffold( approveLabel: String, activeUserPublicKey: HexKey, chatRoomId: String, - dkgSessionId: String? = null, + dkgSessionId: String, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, dkgRepository: DkgRepository, @@ -118,23 +118,6 @@ internal fun DkgApprovalScaffold( } is DkgRitualUIState.Loaded -> { - // Loaded means the room is loaded, not the ritual: [initiate] sets - // this state and only then starts collecting the session, so the - // first emission always has a null session and a null pending step. - // Reading that as "nothing to approve" would flash the empty state - // on the way in, which looks exactly like the screen not working. - if (state.session == null) { - Column( - modifier = Modifier.fillMaxWidth().padding(padding).readableContent().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - CircularProgressIndicator() - } - - return@Scaffold - } - // The ritual may have moved on since this screen was opened -- a // redelivery can carry it forward, and the member may have approved // on another device. Approving anyway would be approving a step that @@ -201,10 +184,10 @@ internal fun DkgApprovalScaffold( } Button( - onClick = { - dkgRitualViewModel.approve(step) - onDone() - }, + // Closes once the approval has gone out, not on the + // press: closing clears the view model and would cancel + // the publish with it. The button spins meanwhile. + onClick = { dkgRitualViewModel.approve(step, onApproved = onDone) }, enabled = !isActionPending, modifier = Modifier.weight(1f) ) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgJoinApprovalScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgJoinApprovalScreen.kt index a3c9c9d0..7fb0325e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgJoinApprovalScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgJoinApprovalScreen.kt @@ -1,5 +1,13 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.database.model.subgroupWalletPolicy +import org.jetbrains.compose.resources.stringResource +import bennu.composeapp.generated.resources.the_subgroup_s_wallet_will_not_be_guarded +import bennu.composeapp.generated.resources.the_subgroup_s_wallet_will_be_guarded +import bennu.composeapp.generated.resources.Res import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth @@ -32,7 +40,7 @@ import com.machankura.bennu.compose.ui.theme.spacing fun DkgJoinApprovalScreen( activeUserPublicKey: HexKey, chatRoomId: String, - dkgSessionId: String? = null, + dkgSessionId: String, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, dkgRepository: DkgRepository, @@ -55,10 +63,31 @@ fun DkgJoinApprovalScreen( Text( text = "$group is creating a shared key that takes " + - "${session?.threshold ?: 0} of ${state.participantCount} members to sign with.", + "${session.threshold} of ${state.participantCount} members to sign with.", style = MaterialTheme.typography.bodyLarge ) + // What the subgroup's wallet will be, as the coordinator chose it and the + // parent's quorum will sign it -- the one place an admin is told before + // joining is agreeing to it. A ceremony with no policy says nothing. + // See docs/subgroup-wallet-policy.md. + session.subgroupWalletPolicy?.let { policy -> + Text( + text = when (policy) { + // The parent's own leaf's delay, as the coordinator chose it -- + // or the default an older build's ceremony is certified at. + // An inherited ancestor's is not here: a member deciding + // whether to join cannot check it. docs/guardian-delay.md. + SubgroupWalletPolicy.GUARDED -> stringResource( + Res.string.the_subgroup_s_wallet_will_be_guarded, + delayText(session.guardianDelay ?: GuardianDerivation.DEFAULT_DELAY) + ) + SubgroupWalletPolicy.UNGUARDED -> stringResource(Res.string.the_subgroup_s_wallet_will_not_be_guarded) + }, + style = MaterialTheme.typography.bodyLarge + ) + } + Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt index e77f5151..8e5c882a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt @@ -13,14 +13,12 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Groups import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.RadioButtonUnchecked -import androidx.compose.material.icons.filled.Remove import androidx.compose.material3.BottomAppBar import androidx.compose.material3.Button import androidx.compose.material3.Card @@ -36,7 +34,19 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import bennu.composeapp.generated.resources.abandon +import bennu.composeapp.generated.resources.abandon_ceremony +import bennu.composeapp.generated.resources.abandon_this_key_ceremony_question +import bennu.composeapp.generated.resources.cancel +import bennu.composeapp.generated.resources.it_ends_for_everyone_in_it_no_key_is_created import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -57,7 +67,6 @@ import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant import com.machankura.bennu.compose.database.model.types.DkgRitualStage import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.machankura.bennu.compose.extensions.memberName -import com.machankura.bennu.compose.managers.ChillDkgRitualManager import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.DkgRepository import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator @@ -65,6 +74,8 @@ import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileColor import com.machankura.bennu.compose.ui.theme.BennuTheme import com.machankura.bennu.compose.database.model.types.DkgApprovalStep import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgJoinApprovalRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectSubgroupAdminsRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRound1ApprovalRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRound2ApprovalRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route @@ -87,7 +98,6 @@ import bennu.composeapp.generated.resources.before_the_subgroup_exists_its_paren import bennu.composeapp.generated.resources.the_parent_group_is_certifying_this_subgroup import bennu.composeapp.generated.resources.the_parent_group_could_not_certify_this_subgroup import bennu.composeapp.generated.resources.the_parent_group_has_certified_this_subgroup -import bennu.composeapp.generated.resources.how_many_members_will_it_take_to_sign import bennu.composeapp.generated.resources.key import bennu.composeapp.generated.resources.members import bennu.composeapp.generated.resources.nothing_was_created_and_no_key_exists_it_is @@ -95,19 +105,15 @@ import bennu.composeapp.generated.resources.review_and_confirm import bennu.composeapp.generated.resources.review_and_contribute import bennu.composeapp.generated.resources.review_and_join import bennu.composeapp.generated.resources.shared_key -import bennu.composeapp.generated.resources.start_key_ceremony import bennu.composeapp.generated.resources.the_ceremony_was_abandoned -import bennu.composeapp.generated.resources.the_group_can_hold_one_key_together_split_so import bennu.composeapp.generated.resources.the_group_has_a_shared_key import bennu.composeapp.generated.resources.the_group_has_agreed_what_the_admin_room import bennu.composeapp.generated.resources.the_group_could_not_agree_what_the_admin import bennu.composeapp.generated.resources.the_group_is_agreeing_what_the_admin_room import bennu.composeapp.generated.resources.agree_the_groups_signing_key import bennu.composeapp.generated.resources.before_the_room_exists_the_group_signs -import bennu.composeapp.generated.resources.this_is_fixed_once_the_ceremony_runs import bennu.composeapp.generated.resources.try_again import bennu.composeapp.generated.resources.your_share_of_it_is_on_this_device_only_your -import bennu.composeapp.generated.resources.everyone_has_to_be_online_at_the_same_time import bennu.composeapp.generated.resources.of import bennu.composeapp.generated.resources.of_members_will_be_needed_to_sign_with_this import bennu.composeapp.generated.resources.shared_key_for @@ -120,21 +126,26 @@ import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab import com.machankura.bennu.compose.ui.theme.ConformancePreviews /** - * The shared-key ceremony: a ChillDKG ritual run across the group's NIP-17 - * chat, shown as a ladder of rounds so members can see it is moving and who it - * is waiting on. + * One shared-key ceremony: a ChillDKG ritual, shown as a ladder of rounds so + * members can see it is moving and who it is waiting on. * * A DKG needs *everyone* present, which is unusual for a chat feature and the * main thing this screen has to communicate — hence a count against every step * rather than an indeterminate spinner. + * + * It shows a ceremony and never starts one. It used to do both, from the same + * slot in the bottom bar the approvals use, and a member coming back from + * approving a subgroup's ceremony found "Start key ceremony" where "Review and + * join" had been. Starting lives in `CreateSharedKeyScreen` and the subgroup + * picker, which know what a ceremony is for -- see docs/ceremony-creation.md. */ @OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable fun DkgRitualScreen( activeUserPublicKey: HexKey, chatRoomId: String, - /** Which of the room's ceremonies to show; null takes the newest. */ - dkgSessionId: String? = null, + /** Which of the room's ceremonies to show -- see `DkgRitualRoute.dkgSessionId`. */ + dkgSessionId: String, initialDkgRitualUIState: DkgRitualUIState = DkgRitualUIState.Loading, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, @@ -168,7 +179,7 @@ fun DkgRitualScreen( is DkgRitualUIState.Loaded -> { val session = dkgRitualUIState.session val participantCount = dkgRitualUIState.participantCount - val canStartRitual = dkgRitualViewModel.canStartRitual() + var isConfirmingAbandon by remember { mutableStateOf(false) } val isActionPending = dkgRitualViewModel.isActionPending.value Scaffold( @@ -177,7 +188,16 @@ fun DkgRitualScreen( TopAppBar( title = { Text( - text = stringResource(Res.string.shared_key_for, dkgRitualUIState.localChatRoom.chatRoom.subject ?: "this group"), + // The ceremony's name, not the room's: a subgroup's + // runs in its parent's room, and "Shared key for + // #Checkers" over Tapscript's ceremony names the + // one group it is not for. + text = stringResource( + Res.string.shared_key_for, + session.subject + ?: dkgRitualUIState.localChatRoom.chatRoom.subject + ?: "this group" + ), maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -207,17 +227,17 @@ fun DkgRitualScreen( DkgApprovalStep.HOST_KEY -> DkgJoinApprovalRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, - dkgSessionId = dkgRitualUIState.session?.id + dkgSessionId = session.id ) DkgApprovalStep.ROUND_1 -> DkgRound1ApprovalRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, - dkgSessionId = dkgRitualUIState.session?.id + dkgSessionId = session.id ) DkgApprovalStep.ROUND_2 -> DkgRound2ApprovalRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, - dkgSessionId = dkgRitualUIState.session?.id + dkgSessionId = session.id ) } ) @@ -230,34 +250,26 @@ fun DkgRitualScreen( return@Scaffold } - // Any member can open a ritual — the coordinator has no say in - // the key — but only when there isn't one already running. - if (canStartRitual) { + // A failed ceremony is tried again from the screen that knows what + // it was for, never from here: this screen only shows a ceremony. + if (session.stage == DkgRitualStage.FAILED) { BottomAppBar( floatingActionButton = { ExtendedFab( - label = if (session == null) { - stringResource(Res.string.start_key_ceremony) - } else { - stringResource(Res.string.try_again) - }, - icon = { - if (isActionPending) { - CircularProgressIndicator(modifier = Modifier.size(20.dp)) - } else { - Icon(Icons.Default.Key, contentDescription = "Start") - } - }, - onClick = { dkgRitualViewModel.startRitual() } + label = stringResource(Res.string.try_again), + icon = { Icon(Icons.Default.Key, contentDescription = Decorative) }, + onClick = { + onNavigateToRoute( + retryRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + session = session, + ) + ) + } ) }, - actions = { - Text( - modifier = Modifier.padding(start = MaterialTheme.spacing.space200), - text = stringResource(Res.string.of, dkgRitualViewModel.threshold.value, participantCount), - style = MaterialTheme.typography.labelLarge - ) - } + actions = {} ) } } @@ -271,32 +283,6 @@ fun DkgRitualScreen( .padding(MaterialTheme.spacing.space125), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) ) { - if (session == null) { - Text( - text = stringResource(Res.string.the_group_can_hold_one_key_together_split_so), - style = MaterialTheme.typography.bodyMedium - ) - - Text( - text = stringResource(Res.string.everyone_has_to_be_online_at_the_same_time, participantCount), - style = MaterialTheme.typography.bodyMedium - ) - - if (canStartRitual) { - QuorumStepper( - threshold = dkgRitualViewModel.threshold.value, - participantCount = participantCount, - quorumRange = dkgRitualViewModel.quorumRange(), - onThresholdChange = dkgRitualViewModel::setThreshold - ) - } else { - Text( - text = "A shared key needs at least " + - "${ChillDkgRitualManager.MINIMUM_PARTICIPANTS} members to split it between.", - style = MaterialTheme.typography.labelLarge - ) - } - } else { RitualProgress( session = session, participantCount = participantCount, @@ -318,7 +304,44 @@ fun DkgRitualScreen( dkgRitualViewModel.createAdminGroup(onNavigateToRoute) } ) - } + + // Here rather than on the approval screens, where the + // consequence can be read against the whole ceremony: + // it ends for everyone, not just for this member. + if (dkgRitualUIState.canAbandon) { + TextButton( + onClick = { isConfirmingAbandon = true }, + enabled = !isActionPending, + colors = ButtonDefaults.textButtonColors( + contentColor = MaterialTheme.colorScheme.error + ) + ) { + Text(stringResource(Res.string.abandon_ceremony)) + } + } + } + + if (isConfirmingAbandon) { + AlertDialog( + onDismissRequest = { isConfirmingAbandon = false }, + title = { Text(stringResource(Res.string.abandon_this_key_ceremony_question)) }, + text = { Text(stringResource(Res.string.it_ends_for_everyone_in_it_no_key_is_created)) }, + confirmButton = { + TextButton( + onClick = { + isConfirmingAbandon = false + dkgRitualViewModel.abandon() + } + ) { + Text(stringResource(Res.string.abandon)) + } + }, + dismissButton = { + TextButton(onClick = { isConfirmingAbandon = false }) { + Text(stringResource(Res.string.cancel)) + } + }, + ) } } } @@ -348,6 +371,25 @@ fun DkgRitualScreen( } } +/** + * Where a failed ceremony is tried again: the screen that starts that kind. + * + * A group's own goes back to `CreateSharedKeyScreen`. A subgroup's goes back to + * the picker, filled in from the ceremony that failed, because trying again is a + * new ceremony over choices the member may want to change -- an admin who never + * showed up, say. + */ +internal fun retryRoute(activeUserPublicKey: HexKey, chatRoomId: String, session: DkgSession): Route = + session.parentChatRoomId + ?.let { parent -> + SelectSubgroupAdminsRoute( + activeUserPublicKey = activeUserPublicKey, + parentChatRoomId = parent, + retrying = session.id, + ) + } + ?: CreateSharedKeyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId) + /** The ladder, and the members it is climbing. */ @Composable private fun RitualProgress( @@ -815,55 +857,6 @@ private fun RitualStep( } } -/** Same shape as the group-creation quorum picker, so the choice reads the same. */ -@Composable -private fun QuorumStepper( - threshold: Int, - participantCount: Int, - quorumRange: IntRange, - onThresholdChange: (Int) -> Unit, -) { - Column( - modifier = Modifier.fillMaxWidth().padding(top = MaterialTheme.spacing.space50), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50) - ) { - Text( - text = stringResource(Res.string.how_many_members_will_it_take_to_sign), - style = MaterialTheme.typography.titleSmall - ) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200), - verticalAlignment = Alignment.CenterVertically - ) { - FilledIconButton( - onClick = { onThresholdChange(threshold - 1) }, - enabled = threshold > quorumRange.first - ) { - Icon(Icons.Default.Remove, contentDescription = "Fewer signers") - } - - Text( - text = stringResource(Res.string.of, threshold, participantCount), - style = MaterialTheme.typography.titleMedium - ) - - FilledIconButton( - onClick = { onThresholdChange(threshold + 1) }, - enabled = threshold < quorumRange.last - ) { - Icon(Icons.Default.Add, contentDescription = "More signers") - } - } - - Text( - text = stringResource(Res.string.this_is_fixed_once_the_ceremony_runs), - style = MaterialTheme.typography.labelMedium - ) - } -} - @ConformancePreviews @Composable private fun DkgRitualScreenPreview() { @@ -872,17 +865,29 @@ private fun DkgRitualScreenPreview() { DkgRitualScreen( activeUserPublicKey = "", chatRoomId = "chatRoomId", + dkgSessionId = "session", initialDkgRitualUIState = DkgRitualUIState.Loaded( localChatRoom = LocalChatRoom( chatRoom = ChatRoom( - id = "", + id = "chatRoomId", userPublicKey = "", subject = "Group discussions", description = "See something... say something.", initialGiftWrapPayloadId = null, mlsGroupState = null ), - ) + ), + session = DkgSession( + id = "session", + chatRoomId = "chatRoomId", + coordinatorPublicKey = "", + userPublicKey = "", + threshold = 2, + participantCount = 3, + hostPublicKey = "", + round1Random = "", + round2AuxRandom = "", + ), ), activeIdentityStateFlow = MutableStateFlow(null), chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound1ApprovalScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound1ApprovalScreen.kt index 6c8d9259..d2c43ed7 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound1ApprovalScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound1ApprovalScreen.kt @@ -36,7 +36,7 @@ import bennu.composeapp.generated.resources.you fun DkgRound1ApprovalScreen( activeUserPublicKey: HexKey, chatRoomId: String, - dkgSessionId: String? = null, + dkgSessionId: String, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, dkgRepository: DkgRepository, @@ -58,7 +58,7 @@ fun DkgRound1ApprovalScreen( Text( text = "Everyone has joined. ${state.participantCount} members are making a key that " + - "takes ${session?.threshold ?: 0} of them to sign with.", + "takes ${session.threshold} of them to sign with.", style = MaterialTheme.typography.bodyLarge ) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound2ApprovalScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound2ApprovalScreen.kt index 1e0def45..128f402a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound2ApprovalScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRound2ApprovalScreen.kt @@ -37,7 +37,7 @@ import bennu.composeapp.generated.resources.this_is_the_last_thing_the_ceremony_ fun DkgRound2ApprovalScreen( activeUserPublicKey: HexKey, chatRoomId: String, - dkgSessionId: String? = null, + dkgSessionId: String, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, dkgRepository: DkgRepository, @@ -59,7 +59,7 @@ fun DkgRound2ApprovalScreen( Text( text = "Everyone's contributions have been combined into a " + - "${session?.threshold ?: 0}-of-${state.participantCount} key.", + "${session.threshold}-of-${state.participantCount} key.", style = MaterialTheme.typography.bodyLarge ) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt deleted file mode 100644 index ff5fe6c9..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt +++ /dev/null @@ -1,398 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Notes -import androidx.compose.material.icons.filled.AlternateEmail -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material.icons.filled.Image -import androidx.compose.material.icons.filled.Link -import androidx.compose.material.icons.filled.Title -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.text.style.TextAlign -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.EditGroupNostrProfileViewModel -import com.machankura.bennu.compose.ui.view.state.EditGroupNostrProfileUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.about -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_profile -import bennu.composeapp.generated.resources.edit_nostr_profile -import bennu.composeapp.generated.resources.eg_a_group_translating_hard_books -import bennu.composeapp.generated.resources.eg_group_example_com -import bennu.composeapp.generated.resources.eg_group_getalby_com -import bennu.composeapp.generated.resources.eg_https_example_com -import bennu.composeapp.generated.resources.eg_https_example_com_group_png -import bennu.composeapp.generated.resources.eg_translation_collective -import bennu.composeapp.generated.resources.lightning_address -import bennu.composeapp.generated.resources.name -import bennu.composeapp.generated.resources.nostr_address -import bennu.composeapp.generated.resources.picture_url -import bennu.composeapp.generated.resources.propose_nostr_profile -import bennu.composeapp.generated.resources.the_group_signs_its_profile_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_a_profile -import bennu.composeapp.generated.resources.website -import bennu.composeapp.generated.resources.what_the_group_says_about_itself_on_nostr -import org.jetbrains.compose.resources.stringResource - -/** - * The form for what a group says about itself on nostr. - * - * A group's kind:0 is signed by the group, so pressing the button proposes rather - * than saves: the form goes out as one event for the room's quorum to put its key - * to, and the screen hands over to the signing session it opened. Nothing about the - * profile has changed by the time this screen closes. - * - * The fields start at what the group already says, so an edit is an edit. And they - * are sent as they stand -- **an emptied field clears what the group had said**, - * which is the only way to unsay something a group has signed. Fields this form - * does not offer are carried across untouched; see `GroupNostrProfile.template`. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun EditGroupNostrProfileScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState = - EditGroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val editGroupNostrProfileViewModel: EditGroupNostrProfileViewModel = viewModel( - factory = EditGroupNostrProfileViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupNostrProfileUIState = initialEditGroupNostrProfileUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in the click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so the message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_profile) - - ScreenStateTransition(editGroupNostrProfileViewModel.editGroupNostrProfileUIState) { uiState -> - when (val editGroupNostrProfileUIState = uiState) { - is EditGroupNostrProfileUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState( - message = editGroupNostrProfileUIState.message, - onRetry = null - ) - } - - is EditGroupNostrProfileUIState.Loaded -> { - val profile = editGroupNostrProfileUIState.groupNostrProfile - - // Seeded from the profile the group already signed, so the form is - // an edit of it. `rememberTextFieldState` saves what is typed, which - // is what survives a rotation with the edits intact. - val nameFieldState = rememberTextFieldState(profile?.name() ?: "") - val aboutFieldState = rememberTextFieldState(profile?.about() ?: "") - val pictureFieldState = rememberTextFieldState(profile?.picture() ?: "") - val websiteFieldState = rememberTextFieldState(profile?.website() ?: "") - val nip05FieldState = rememberTextFieldState(profile?.nip05() ?: "") - val lud16FieldState = rememberTextFieldState(profile?.lud16() ?: "") - - val canSign = editGroupNostrProfileUIState.canSign - - // imePadding: this screen is nothing but text fields, and without it - // the software keyboard covers whichever one is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - editGroupNostrProfileUIState.localChatRoom - .RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_nostr_profile), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose nostr profile") }, - enabled = canSign, - onClick = { - editGroupNostrProfileViewModel.proposeNostrProfile( - localChatRoom = - editGroupNostrProfileUIState.localChatRoom, - groupNostrProfile = profile, - nameField = nameFieldState, - aboutField = aboutFieldState, - pictureField = pictureFieldState, - websiteField = websiteFieldState, - nip05Field = nip05FieldState, - lud16Field = lud16FieldState, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. The profile has not - // changed yet -- it changes when a - // quorum signs -- so landing on a - // group still showing the old one - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // Stay on the form with what was typed - // still in it. The proposal is what - // failed, and every word of it is worth - // keeping for the retry. - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - .verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text(stringResource(Res.string.what_the_group_says_about_itself_on_nostr)) - - Text( - text = stringResource( - Res.string.the_group_signs_its_profile_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_a_profile - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - NostrProfileField( - state = nameFieldState, - icon = Icons.Default.Title, - iconDescription = "Name of the group", - label = stringResource(Res.string.name), - placeholder = stringResource(Res.string.eg_translation_collective) - ) - - NostrProfileField( - state = aboutFieldState, - icon = Icons.AutoMirrored.Filled.Notes, - iconDescription = "What the group is for", - label = stringResource(Res.string.about), - placeholder = stringResource( - Res.string.eg_a_group_translating_hard_books - ), - // The one field with prose in it, and the only one a - // single line would truncate while it was being typed. - lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 3) - ) - - NostrProfileField( - state = pictureFieldState, - icon = Icons.Default.Image, - iconDescription = "Picture of the group", - label = stringResource(Res.string.picture_url), - placeholder = stringResource(Res.string.eg_https_example_com_group_png) - ) - - NostrProfileField( - state = websiteFieldState, - icon = Icons.Default.Link, - iconDescription = "Website of the group", - label = stringResource(Res.string.website), - placeholder = stringResource(Res.string.eg_https_example_com) - ) - - NostrProfileField( - state = nip05FieldState, - icon = Icons.Default.AlternateEmail, - iconDescription = "Nostr address of the group", - label = stringResource(Res.string.nostr_address), - placeholder = stringResource(Res.string.eg_group_example_com) - ) - - NostrProfileField( - state = lud16FieldState, - icon = Icons.Default.Bolt, - iconDescription = "Lightning address of the group", - label = stringResource(Res.string.lightning_address), - placeholder = stringResource(Res.string.eg_group_getalby_com) - ) - } - } - } - - EditGroupNostrProfileUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - Text( - text = stringResource(Res.string.edit_nostr_profile), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialEditGroupNostrProfileUIState == EditGroupNostrProfileUIState.Loading) { - editGroupNostrProfileViewModel.initiateEditGroupNostrProfile() - } - } -} - -/** - * One field of the profile, in the shape the app's other forms use. - * - * Six of these on one screen is what makes it worth a function: the borderless - * outlined field over the bottom bar's tint is four lines of colours apiece, and - * six copies of that is where a divergence hides. - */ -@Composable -private fun NostrProfileField( - state: TextFieldState, - icon: ImageVector, - iconDescription: String, - label: String, - placeholder: String, - lineLimits: TextFieldLineLimits = TextFieldLineLimits.SingleLine -) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), - state = state, - lineLimits = lineLimits, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(icon, contentDescription = iconDescription) - }, - label = { - Text(text = label) - }, - placeholder = { - Text(text = placeholder) - } - ) -} - -@ConformancePreviews -@Composable -private fun EditGroupNostrProfileScreenPreview() { - BennuTheme { - Surface( - modifier = Modifier.fillMaxSize() - ) { - EditGroupNostrProfileScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialEditGroupNostrProfileUIState = EditGroupNostrProfileUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation collective", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A group that can sign, so the form renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt deleted file mode 100644 index a3c9eaec..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt +++ /dev/null @@ -1,551 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -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.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material.icons.filled.Delete -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material.icons.filled.Dns -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.PrimaryScrollableTabRow -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Tab -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.EditGroupRelaysViewModel -import com.machankura.bennu.compose.ui.view.state.EditGroupRelaysUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.add_relay -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_these_relays -import bennu.composeapp.generated.resources.edit_relays -import bennu.composeapp.generated.resources.eg_wss_relay_example_com -import bennu.composeapp.generated.resources.no_relays_in_this_list -import bennu.composeapp.generated.resources.nothing_has_changed_to_propose -import bennu.composeapp.generated.resources.propose_relays -import bennu.composeapp.generated.resources.relay_read -import bennu.composeapp.generated.resources.relay_set_blocked -import bennu.composeapp.generated.resources.relay_set_blocked_purpose -import bennu.composeapp.generated.resources.relay_set_general -import bennu.composeapp.generated.resources.relay_set_general_purpose -import bennu.composeapp.generated.resources.relay_set_messages -import bennu.composeapp.generated.resources.relay_set_messages_purpose -import bennu.composeapp.generated.resources.relay_set_search -import bennu.composeapp.generated.resources.relay_set_search_purpose -import bennu.composeapp.generated.resources.relay_url -import bennu.composeapp.generated.resources.relay_write -import bennu.composeapp.generated.resources.relays_are_public_a_group_cannot_encrypt -import bennu.composeapp.generated.resources.that_is_not_a_relay_address -import bennu.composeapp.generated.resources.that_relay_is_already_in_this_list -import bennu.composeapp.generated.resources.the_group_signs_each_list_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_relays -import bennu.composeapp.generated.resources.where_the_group_lives_on_nostr -import org.jetbrains.compose.resources.StringResource -import org.jetbrains.compose.resources.stringResource - -/** - * The four relay lists a group keeps, edited as one sitting. - * - * A tab per list, a field to add one, a row per relay with a way to drop it, and -- - * in the one list NIP-65 gives markers to -- a read and a write chip. The shape is - * borrowed from Wisp's relay screen, which is the interface this app was asked to - * match, with one deliberate departure. - * - * **The button proposes rather than publishes.** Wisp signs with the user's own key - * and a tab's publish button is done the moment it is pressed. A group signs with a - * quorum, so what leaves this screen is a proposal, and the screen hands over to - * the session it opened. Nothing has changed until enough members sign. - * - * And it proposes **every list that changed at once**, rather than the tab in front - * of you. Four sessions for one sitting would ask a quorum the same question four - * times over what is plainly one decision -- see `EditGroupRelaysViewModel`, which - * carries the reasoning and works out what actually differs. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun EditGroupRelaysScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupRelaysUIState: EditGroupRelaysUIState = EditGroupRelaysUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val editGroupRelaysViewModel: EditGroupRelaysViewModel = viewModel( - factory = EditGroupRelaysViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupRelaysUIState = initialEditGroupRelaysUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in a click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_these_relays) - val nothingChanged = stringResource(Res.string.nothing_has_changed_to_propose) - - ScreenStateTransition(editGroupRelaysViewModel.editGroupRelaysUIState) { uiState -> - when (val editGroupRelaysUIState = uiState) { - is EditGroupRelaysUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState(message = editGroupRelaysUIState.message, onRetry = null) - } - - is EditGroupRelaysUIState.Loaded -> { - val urlFieldState = rememberTextFieldState() - val selectedSet = editGroupRelaysViewModel.selectedSet - val canSign = editGroupRelaysUIState.canSign - - // The editor's working copy comes from the state rather than from - // whatever loaded it, so a screen handed a loaded state -- a - // preview, a layout test -- fills in the same as the app does. - // Seeding leaves edits alone, so re-running this changes nothing. - LaunchedEffect(editGroupRelaysUIState.signed) { - editGroupRelaysViewModel.seedWorkingCopy(editGroupRelaysUIState.signed) - } - - // A refusal is about what is in the field, so it goes the moment - // the field changes rather than sitting under a URL that has since - // been corrected. - LaunchedEffect(urlFieldState) { - snapshotFlow { urlFieldState.text.toString() } - .collect { editGroupRelaysViewModel.clearAddFailure() } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - editGroupRelaysUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_relays), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose relays") }, - enabled = canSign, - onClick = { - editGroupRelaysViewModel.proposeRelayLists( - localChatRoom = - editGroupRelaysUIState.localChatRoom, - signed = editGroupRelaysUIState.signed, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. The lists have not - // changed yet -- they change when a - // quorum signs -- so landing on a - // group still showing the old ones - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // Both stay on the form with the edits - // still in it. One is a question and - // one is a failure, and neither is a - // reason to throw away the typing. - onNothingToPropose = { notify(nothingChanged) }, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - PrimaryScrollableTabRow( - modifier = Modifier.padding(MaterialTheme.spacing.compactPadding), - edgePadding = 10.dp, - selectedTabIndex = selectedSet.ordinal, - ) { - GroupRelaySet.entries.forEach { set -> - Tab( - selected = set == selectedSet, - onClick = { editGroupRelaysViewModel.selectSet(set) }, - text = { Text(text = stringResource(set.label())) } - ) - } - } - - Column( - modifier = Modifier.fillMaxWidth() - .padding(horizontal = MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.itemGap - ), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text( - text = stringResource(Res.string.where_the_group_lives_on_nostr), - style = MaterialTheme.typography.titleSmall - ) - - // What this tab's list is actually for. Four relay lists - // is four questions nobody can be expected to hold apart - // from their names alone. - Text( - text = stringResource(selectedSet.purpose()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - Text( - text = stringResource( - Res.string.the_group_signs_each_list_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (selectedSet == GroupRelaySet.Blocked) { - // Said where it matters. A person's client keeps - // this list encrypted, and somebody blocking a relay - // here should know the group cannot. - Text( - text = stringResource( - Res.string.relays_are_public_a_group_cannot_encrypt - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - } - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_relays - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - OutlinedTextField( - modifier = Modifier.weight(1f) - .background(BottomAppBarDefaults.containerColor), - state = urlFieldState, - lineLimits = TextFieldLineLimits.SingleLine, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(Icons.Default.Dns, contentDescription = Decorative) - }, - label = { Text(stringResource(Res.string.relay_url)) }, - placeholder = { - Text(stringResource(Res.string.eg_wss_relay_example_com)) - }, - isError = editGroupRelaysViewModel.addFailure != null - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - IconButton( - onClick = { - if ( - editGroupRelaysViewModel.addRelay( - urlFieldState.text.toString() - ) - ) { - urlFieldState.clearText() - } - } - ) { - Icon( - Icons.Default.Add, - contentDescription = "Add relay" - ) - } - } - - // Named rather than silent. An add button that does - // nothing for a URL it refuses is indistinguishable from - // a missed tap. - editGroupRelaysViewModel.addFailure?.let { failure -> - Text( - text = when (failure) { - EditGroupRelaysViewModel.AddFailure.NotARelay -> - stringResource(Res.string.that_is_not_a_relay_address) - EditGroupRelaysViewModel.AddFailure.AlreadyListed -> - stringResource( - Res.string.that_relay_is_already_in_this_list - ) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - } - - val relays = editGroupRelaysViewModel.relaysOf(selectedSet) - - if (relays.isEmpty()) { - EmptyState( - message = stringResource(Res.string.no_relays_in_this_list), - icon = Icons.Default.Dns - ) - } else { - LazyColumn( - modifier = Modifier.fillMaxWidth() - .padding(horizontal = MaterialTheme.spacing.screenMargin) - ) { - items(items = relays, key = { it.url.url }) { relay -> - RelayRow( - relay = relay, - hasReadWriteMarkers = selectedSet.hasReadWriteMarkers, - onToggleRead = { - editGroupRelaysViewModel - .toggleRead(selectedSet, relay) - }, - onToggleWrite = { - editGroupRelaysViewModel - .toggleWrite(selectedSet, relay) - }, - onRemove = { - editGroupRelaysViewModel - .removeRelay(selectedSet, relay) - } - ) - } - } - } - } - } - } - - EditGroupRelaysUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - Text( - text = stringResource(Res.string.edit_relays), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialEditGroupRelaysUIState == EditGroupRelaysUIState.Loading) { - editGroupRelaysViewModel.initiateEditGroupRelays() - } - } -} - -/** - * The tab's name, and the sentence saying what its list decides. - * - * Kept here rather than on [GroupRelaySet] so the enum stays what it is -- four - * nostr kinds and how to read and write them -- with no catalogue behind it. A - * `when` rather than a field on each entry, so adding a set is a compile error here - * rather than a tab with no name. - */ -private fun GroupRelaySet.label(): StringResource = when (this) { - GroupRelaySet.General -> Res.string.relay_set_general - GroupRelaySet.Messages -> Res.string.relay_set_messages - GroupRelaySet.Search -> Res.string.relay_set_search - GroupRelaySet.Blocked -> Res.string.relay_set_blocked -} - -private fun GroupRelaySet.purpose(): StringResource = when (this) { - GroupRelaySet.General -> Res.string.relay_set_general_purpose - GroupRelaySet.Messages -> Res.string.relay_set_messages_purpose - GroupRelaySet.Search -> Res.string.relay_set_search_purpose - GroupRelaySet.Blocked -> Res.string.relay_set_blocked_purpose -} - -/** - * One relay of one list. - * - * The read and write chips only in [hasReadWriteMarkers], which is NIP-65 alone -- - * the other three kinds have a relay in the list or not, and a chip there would - * offer a distinction the event cannot carry. - */ -@Composable -private fun RelayRow( - relay: GroupRelay, - hasReadWriteMarkers: Boolean, - onToggleRead: () -> Unit, - onToggleWrite: () -> Unit, - onRemove: () -> Unit -) { - Row( - modifier = Modifier.fillMaxWidth().padding(vertical = MaterialTheme.spacing.relatedGap), - verticalAlignment = Alignment.CenterVertically - ) { - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - // The host rather than the whole URL: every relay here starts - // `wss://` -- nothing else is allowed in -- so the scheme is four - // characters of nothing in front of the part that differs. - text = relay.displayUrl(), - style = MaterialTheme.typography.bodyMedium - ) - - if (hasReadWriteMarkers) { - Row( - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - FilterChip( - selected = relay.read, - onClick = onToggleRead, - label = { Text(stringResource(Res.string.relay_read)) } - ) - FilterChip( - selected = relay.write, - onClick = onToggleWrite, - label = { Text(stringResource(Res.string.relay_write)) } - ) - } - } - } - - IconButton(onClick = onRemove) { - Icon( - Icons.Default.Delete, - contentDescription = "Remove relay", - tint = MaterialTheme.colorScheme.error - ) - } - } -} - -@ConformancePreviews -@Composable -private fun EditGroupRelaysScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - EditGroupRelaysScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialEditGroupRelaysUIState = EditGroupRelaysUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // Unsigned lists, which is a group opening this for the first - // time -- so the editor fills in from `GroupRelaySet.defaults` - // and the preview shows the relay a new group actually starts - // with rather than an empty tab. - signed = GroupRelayList.allAmong(emptyList(), "publicKey"), - // A group that can sign, so the form renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt deleted file mode 100644 index 86d51191..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt +++ /dev/null @@ -1,353 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Badge -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.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 com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.edit_nostr_profile -import bennu.composeapp.generated.resources.no_name_on_this_profile -import bennu.composeapp.generated.resources.nostr_profile -import bennu.composeapp.generated.resources.signed_by_the_group_on -import bennu.composeapp.generated.resources.this_group_has_not_said_anything_about_itself -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupNostrProfileViewModel -import com.machankura.bennu.compose.ui.view.state.GroupNostrProfileUIState -import kotlin.time.Instant - -/** - * What the group says about itself on nostr, as the group signed it. - * - * Pushed from its row on the group's screen, which names the profile and - * nothing more. This is where it is read: the card, the broadcast under it, - * and -- for a member holding a share of the key -- the way into the editor. - * A group that has said nothing is told so, and offered the editor from the - * same place, since describing itself is the one thing to do about that. - * - * The profile is worth reading either way; proposing one is a signature by the - * group, and `proposeSigningBatch` throws for a device holding no share of the - * key. The editor is hidden rather than disabled, the way every gated way in - * on the group's screen is. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupNostrProfileScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupNostrProfileUIState: GroupNostrProfileUIState = GroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupNostrProfileViewModel: GroupNostrProfileViewModel = viewModel( - factory = GroupNostrProfileViewModel.factory( - chatRoomId = chatRoomId, - initialGroupNostrProfileUIState = initialGroupNostrProfileUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupNostrProfileUIState == GroupNostrProfileUIState.Loading) { - groupNostrProfileViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.nostr_profile), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupNostrProfileViewModel.groupNostrProfileUIState) { uiState -> - when (val state = uiState) { - is GroupNostrProfileUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupNostrProfileUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupNostrProfileUIState.Loaded -> { - val edit: () -> Unit = { - onNavigateToRoute.invoke( - EditGroupNostrProfileRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - state.groupNostrProfile?.let { groupNostrProfile -> - // The card and its broadcast button as one item, - // so the button stays under the event it sends - // however the list is arranged. - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - GroupNostrProfileCard( - groupNostrProfile = groupNostrProfile, - publicKey = chatRoomId - ) - - BroadcastButton( - onClick = { - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = groupNostrProfile.signedEvent.id - ) - ) - } - ) - } - } ?: EmptyState( - message = stringResource( - Res.string.this_group_has_not_said_anything_about_itself - ), - // The way to fill the absence, where this device - // could: describing the group is a signature by it. - action = if (state.canSign) { - { EditNostrProfileButton(onClick = edit) } - } else { - null - } - ) - } - - if (state.canSign && state.groupNostrProfile != null) { - item { - EditNostrProfileButton(onClick = edit) - } - } - } - } - } - } - } -} - -/** - * What the group says about itself on nostr, as the group signed it. - * - * A preview rather than a profile screen: the name, the picture, the nostr address - * and the first lines of the group's own account of itself, which is what a member - * opening the group's details came here to check. The whole thing is one signed - * event and the proposal list is where it can be read out in full. - * - * **The picture and the name come from the metadata; the tint comes from the key.** - * [publicKey] is the room's id, which is the pubkey the group signs as, so a group - * with no picture yet still gets the colour it has everywhere else in the app. - * - * The signing date is here because a group's profile is standing state with no - * other clue to its age -- and because the alternative reading, that this arrived - * from a relay a moment ago, is exactly what has not happened. Nothing on this card - * was published by being signed -- see `GroupNostrProfile` -- and the broadcast - * button under it is how it gets to a relay. - */ -@Composable -private fun GroupNostrProfileCard( - groupNostrProfile: GroupNostrProfile, - publicKey: HexKey -) { - Card(modifier = Modifier.fillMaxWidth()) { - ListItem( - leadingContent = { - ProfileAvatar( - publicKey = publicKey, - picture = groupNostrProfile.picture(), - name = groupNostrProfile.name() - ) - }, - headlineContent = { - Text( - // Named rather than falling back to the pubkey: the signing key - // row on the group's screen already shows that, and showing it - // twice would say the group has a name when it has not. - text = groupNostrProfile.name() - ?: stringResource(Res.string.no_name_on_this_profile), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Column( - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - groupNostrProfile.nip05()?.let { - Text( - text = it, - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - - groupNostrProfile.about()?.let { - Text( - text = it, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.signed_by_the_group_on, - groupNostrProfile.signedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - ) - } -} - -/** The way into `EditGroupNostrProfileScreen`. The icon is decorative because the label is beside it. */ -@Composable -private fun EditNostrProfileButton(onClick: () -> Unit) { - TextButton(onClick = onClick) { - Icon(Icons.Default.Badge, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.edit_nostr_profile)) - } -} - -@ConformancePreviews -@Composable -private fun GroupNostrProfileScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupNostrProfileScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = "d".repeat(64), - relayHint = null, - initialGroupNostrProfileUIState = GroupNostrProfileUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "d".repeat(64), - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - // Built directly rather than read out of a signed event: the - // reading checks a signature, and there is no real one here. - groupNostrProfile = GroupNostrProfile( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = "d".repeat(64), - publicKey = "d".repeat(64), - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - metadata = UserMetadata().apply { - displayName = "Translation collective" - about = "A group translating hard books into Sesotho." - nip05 = "group@example.com" - } - ), - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt deleted file mode 100644 index c3857ca0..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt +++ /dev/null @@ -1,352 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Campaign -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_reply -import bennu.composeapp.generated.resources.add_post -import bennu.composeapp.generated.resources.posted_on -import bennu.composeapp.generated.resources.posts -import bennu.composeapp.generated.resources.this_group_has_not_posted_anything_yet -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.inComparableGroups -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupPostsViewModel -import com.machankura.bennu.compose.ui.view.state.GroupPostsUIState -import kotlin.time.Instant - -/** - * What the group has said publicly, as itself, newest first. - * - * Pushed from its row on the group's screen, which counts the posts and nothing - * more. This is where they are read: one card per post with a broadcast under - * it, and -- for a member holding a share of the key -- the way into the - * composer. A group that has said nothing is told so, and offered the composer - * from the same place. - * - * A post is the one thing the group signs that is meant to be *read* by people - * who were never in the room, so a member without a share reads it like - * anybody else and simply cannot propose the next one: proposing is a signature - * by the group, and `proposeSigningBatch` throws for a device holding no share. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupPostsScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupPostsUIState: GroupPostsUIState = GroupPostsUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupPostsViewModel: GroupPostsViewModel = viewModel( - factory = GroupPostsViewModel.factory( - chatRoomId = chatRoomId, - initialGroupPostsUIState = initialGroupPostsUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupPostsUIState == GroupPostsUIState.Loading) { - groupPostsViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.posts), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupPostsViewModel.groupPostsUIState) { uiState -> - when (val state = uiState) { - is GroupPostsUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupPostsUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupPostsUIState.Loaded -> { - val add: () -> Unit = { - onNavigateToRoute.invoke( - AddGroupPostRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (state.groupPosts.isEmpty()) { - item { - EmptyState( - message = stringResource( - Res.string.this_group_has_not_posted_anything_yet - ), - action = if (state.canSign) { - { AddPostButton(onClick = add) } - } else { - null - } - ) - } - } else { - items( - items = state.groupPosts, - key = { post -> post.signedEvent.id } - ) { post -> - // The card and its broadcast button as one item, - // so the button stays under the event it sends - // however the list is arranged. - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - GroupPostCard( - post = post, - publicKey = chatRoomId, - groupNostrProfile = state.groupNostrProfile - ) - - BroadcastButton( - onClick = { - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = post.signedEvent.id - ) - ) - } - ) - } - } - - if (state.canSign) { - item { - AddPostButton(onClick = add) - } - } - } - } - } - } - } - } -} - -/** - * One thing the group said, as the group signed it. - * - * The whole note rather than a preview. A post is short by construction -- kind:1 - * with no long-form arm behind it -- and truncating the one kind of content on this - * screen that exists to be *read* would mean opening something to see a paragraph. - * - * **The byline is the group's**, taken from its profile where it has one and from - * the room's own id where it has not. It is worth spelling out because a post is - * the one thing here a reader might otherwise attribute to whichever member - * proposed it -- and the point of signing it as the group is that they cannot. - * - * A reply is marked as one. Nothing in this app writes replies, so the mark is for - * an event that arrived some other way; drawing one as an announcement would put - * half a conversation on a group's page with no sign that it was half. - */ -@Composable -private fun GroupPostCard( - post: GroupPost, - publicKey: HexKey, - groupNostrProfile: GroupNostrProfile? -) { - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - ProfileAvatar( - size = MaterialTheme.spacing.space400, - publicKey = publicKey, - picture = groupNostrProfile?.picture(), - name = groupNostrProfile?.name() - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - Column(modifier = Modifier.weight(1f)) { - Text( - text = groupNostrProfile?.name() ?: publicKey.take(16).inComparableGroups(), - style = MaterialTheme.typography.titleSmall, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - - Text( - text = stringResource( - Res.string.posted_on, - post.postedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - - if (!post.isNewThread()) { - Text( - text = stringResource(Res.string.a_reply), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - Text( - text = post.content, - style = MaterialTheme.typography.bodyMedium - ) - } - } -} - -/** The way into `AddGroupPostScreen`. The icon is decorative because the label is beside it. */ -@Composable -private fun AddPostButton(onClick: () -> Unit) { - TextButton(onClick = onClick) { - Icon(Icons.Default.Campaign, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.add_post)) - } -} - -@ConformancePreviews -@Composable -private fun GroupPostsScreenPreview() { - val chatRoomId = "d".repeat(64) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupPostsScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialGroupPostsUIState = GroupPostsUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - groupPosts = listOf( - GroupPost( - signedEvent = GroupSignedEvent( - id = "b".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = TextNoteEvent.KIND, - tags = emptyArray(), - content = "The first chapter is out. Read it, and tell us where it reads wrong.", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ) - ) - ), - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt deleted file mode 100644 index 7fe9eb63..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt +++ /dev/null @@ -1,327 +0,0 @@ -package com.machankura.bennu.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.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Dns -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.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 com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.edit_relays -import bennu.composeapp.generated.resources.no_relays_in_this_list -import bennu.composeapp.generated.resources.not_set_yet -import bennu.composeapp.generated.resources.relay_set_blocked -import bennu.composeapp.generated.resources.relay_set_general -import bennu.composeapp.generated.resources.relay_set_messages -import bennu.composeapp.generated.resources.relay_set_search -import bennu.composeapp.generated.resources.relays -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupRelaysViewModel -import com.machankura.bennu.compose.ui.view.state.GroupRelaysUIState -import kotlin.time.Instant - -/** - * Where the group has said it lives on nostr, one line per relay list. - * - * Pushed from its row on the group's screen, which says how many of the four - * lists the group has agreed and nothing more. This is where they are read, - * with a broadcast under each one the group has signed and -- for a member - * holding a share of the key -- the way into the editor. - * - * There is no empty state to draw: every set gets a row whatever the group has - * said, and the row is where "never agreed" and "agreed empty" are told apart. - * See [GroupRelayListsCard]. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupRelaysScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupRelaysUIState: GroupRelaysUIState = GroupRelaysUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupRelaysViewModel: GroupRelaysViewModel = viewModel( - factory = GroupRelaysViewModel.factory( - chatRoomId = chatRoomId, - initialGroupRelaysUIState = initialGroupRelaysUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupRelaysUIState == GroupRelaysUIState.Loading) { - groupRelaysViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.relays), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupRelaysViewModel.groupRelaysUIState) { uiState -> - when (val state = uiState) { - is GroupRelaysUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupRelaysUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupRelaysUIState.Loaded -> { - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - GroupRelayListsCard( - relayLists = state.groupRelayLists, - onBroadcast = { signedEvent -> - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = signedEvent.id - ) - ) - } - ) - } - - // The lists are worth reading either way; proposing them - // is a signature by the group, and `proposeSigningBatch` - // throws for a device holding no share of the key. Hidden - // rather than disabled, the way every gated way in on the - // group's screen is. - if (state.canSign) { - item { - TextButton( - onClick = { - onNavigateToRoute.invoke( - EditGroupRelaysRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon(Icons.Default.Dns, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.edit_relays)) - } - } - } - } - } - } - } - } -} - -/** - * Where the group has said it lives on nostr, one line per relay list. - * - * One card holding four rows rather than four cards: they are read together -- the - * question is whether the group is reachable, not what any single list says -- and - * four cards of one line each is four dividers to scroll past for the same four - * facts. - * - * **A list the group has never agreed reads "not set yet", and an agreed empty one - * reads "no relays".** Those are different things: one is a group that has not got - * round to it, and the other is a group that decided. Collapsing them would hide a - * deliberate withdrawal behind an oversight. - */ -@Composable -private fun GroupRelayListsCard( - relayLists: List, - onBroadcast: (GroupSignedEvent) -> Unit -) { - Card(modifier = Modifier.fillMaxWidth()) { - relayLists.forEach { list -> - ListItem( - leadingContent = { - Icon(Icons.Default.Dns, contentDescription = Decorative) - }, - headlineContent = { - Text(text = stringResource(list.set.summaryLabel())) - }, - supportingContent = { - Text( - text = when { - !list.isAgreed -> stringResource(Res.string.not_set_yet) - list.relays.isEmpty() -> - stringResource(Res.string.no_relays_in_this_list) - // Hosts rather than URLs: every one of them starts - // `wss://`, so the scheme is the part that never - // distinguishes two entries. - else -> list.relays.joinToString { it.displayUrl() } - }, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - ) - - // Under the row it sends, and only where there is something signed - // to send: a list the group has never agreed is not an event. Inside - // the card because the four rows share one, so "under the event" has - // to mean under the row -- and at the end, where M3 puts a card's - // actions. An agreed empty list gets one too: a withdrawal is a - // statement, and relays still holding the old list need to hear it. - list.signedEvent?.let { signedEvent -> - Box( - modifier = Modifier.fillMaxWidth() - .padding(horizontal = MaterialTheme.spacing.compactPadding), - contentAlignment = Alignment.CenterEnd - ) { - BroadcastButton(onClick = { onBroadcast(signedEvent) }) - } - } - } - } -} - -/** The name of a relay list, for the row that summarises it. */ -private fun GroupRelaySet.summaryLabel() = when (this) { - GroupRelaySet.General -> Res.string.relay_set_general - GroupRelaySet.Messages -> Res.string.relay_set_messages - GroupRelaySet.Search -> Res.string.relay_set_search - GroupRelaySet.Blocked -> Res.string.relay_set_blocked -} - -@ConformancePreviews -@Composable -private fun GroupRelaysScreenPreview() { - val chatRoomId = "d".repeat(64) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupRelaysScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialGroupRelaysUIState = GroupRelaysUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - // One agreed list and three the group has not got round to, - // so the two things a row can say are both on the screen. - groupRelayLists = GroupRelaySet.entries.map { set -> - if (set == GroupRelaySet.General) { - GroupRelayList( - set = set, - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - relays = listOf( - GroupRelay(RelayUrlNormalizer.normalize("wss://relay.one.example")) - ) - ) - } else { - GroupRelayList(set = set, signedEvent = null, relays = emptyList()) - } - }, - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt index 7ea771b3..c8d69d99 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt @@ -1,6 +1,29 @@ package com.machankura.bennu.compose.ui.composable +import bennu.composeapp.generated.resources.only_coins_confirmed_for_can_be_spent +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.MutableState +import fr.acinq.bitcoin.Satoshi +import bennu.composeapp.generated.resources.finding_your_coins +import bennu.composeapp.generated.resources.s_sats_come_back_to_this_wallet_as_change +import bennu.composeapp.generated.resources.this_wallet_has_nothing_confirmed_to_spend +import bennu.composeapp.generated.resources.this_wallet_doesn_t_have_that_much_confirmed import bennu.composeapp.generated.resources.while_the_wallet_is_new_at_most_s_sats +import androidx.compose.material3.OutlinedCard +import androidx.compose.ui.text.font.FontFamily +import bennu.composeapp.generated.resources.address_s +import bennu.composeapp.generated.resources.finding_an_address_in_s_s_wallet +import bennu.composeapp.generated.resources.fund_s_s_guarded_wallet +import bennu.composeapp.generated.resources.fund_s_s_guarded_wallet_s +import bennu.composeapp.generated.resources.spend_from_s_s_guarded_wallet_s +import bennu.composeapp.generated.resources.sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats +import bennu.composeapp.generated.resources.this_group_can_spend_these_coins_again +import bennu.composeapp.generated.resources.to +import bennu.composeapp.generated.resources.s_s_guarded_wallet +import bennu.composeapp.generated.resources.wait_for_this_group_s_open_payments_to_s +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.ui.view.state.FundingTarget import androidx.compose.foundation.selection.toggleable import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.ui.semantics.Role @@ -88,6 +111,9 @@ import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain import org.jetbrains.compose.resources.stringResource +import bennu.composeapp.generated.resources.spend_from_s_s_guarded_wallet +import bennu.composeapp.generated.resources.a_subgroup +import com.machankura.bennu.compose.wallet.GroupSpend /** * A spend from the group's wallet, proposed. @@ -108,6 +134,8 @@ fun GroupSendScreen( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, wallets: GroupOnchainWallets?, + guardedChatRoomId: String? = null, + fundChatRoomId: String? = null, onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, onNavigateBack: () -> Unit, ) { @@ -120,6 +148,8 @@ fun GroupSendScreen( chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, wallets = wallets, + guardedChatRoomId = guardedChatRoomId, + fundChatRoomId = fundChatRoomId, ) ) @@ -135,8 +165,21 @@ fun GroupSendScreen( topBar = { TopAppBar( title = { + // Whose wallet is in the title: a guardian's spend takes a + // descendant's coins, and nothing else on the form says so -- + // and a funding pays one, which the title says the same way. + val ready = groupSendViewModel.groupSendUIState as? GroupSendUIState.Ready + val guardian = ready?.spender as? GroupSpend.Spender.Guardian + val funded = ready?.funding?.wallet Text( - text = stringResource(Res.string.send_from_the_group_s_wallet), + text = when { + // A member's label says which of their wallets. + guardian?.label != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet_s, guardian.name ?: stringResource(Res.string.a_subgroup), guardian.label) + guardian != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup)) + funded != null -> funded.label?.let { label -> stringResource(Res.string.fund_s_s_guarded_wallet_s, funded.displayName ?: stringResource(Res.string.a_subgroup), label) } + ?: stringResource(Res.string.fund_s_s_guarded_wallet, funded.displayName ?: stringResource(Res.string.a_subgroup)) + else -> stringResource(Res.string.send_from_the_group_s_wallet) + }, maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -168,73 +211,27 @@ fun GroupSendScreen( verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) ) { val preview = groupSendViewModel.preview() - // A problem with the amount is said on the amount field, beside what caused it. - val amountProblem = preview?.takeIf { groupSendViewModel.isAboutTheAmount(it) } - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = groupSendViewModel.addressField, - lineLimits = TextFieldLineLimits.SingleLine, - label = { Text(stringResource(Res.string.address)) }, + // A funding's destination is fixed, not typed: the title names + // the wallet, and an address field could make it pay another. + // A funded wallet's address not known yet is said on its card. + SpendForm( + addressField = groupSendViewModel.addressField, + amountField = groupSendViewModel.amountField, + feerateField = groupSendViewModel.feerateField, + sendEverything = groupSendViewModel.sendEverything, + spendable = groupSendViewModel.spendable(), + guardianDelay = groupSendViewModel.guardianDelay(), + cap = GroupWalletRollout.capFor(chain), + preview = preview, + amountProblem = preview?.takeIf { groupSendViewModel.isAboutTheAmount(it) }, + coinsKnown = state.walletState != null, + chain = chain, + destination = state.funding?.let { funding -> { FundingDestination(funding) } }, + fundedName = state.funding?.wallet?.let { it.displayName ?: stringResource(Res.string.a_subgroup) }, + waitingOnFunding = state.funding != null && state.funding.address == null, ) - // The row is the target, so the label toggles too: one 48dp control with one name. - Row( - modifier = Modifier.fillMaxWidth() - .toggleable( - value = groupSendViewModel.sendEverything.value, - role = Role.Switch, - onValueChange = { groupSendViewModel.sendEverything.value = it }, - ) - .minimumInteractiveComponentSize(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text(stringResource(Res.string.send_everything)) - Switch(checked = groupSendViewModel.sendEverything.value, onCheckedChange = null) - } - - // Hidden rather than cleared, so turning send-everything off again finds the amount typed. - if (!groupSendViewModel.sendEverything.value) { - val spendable = groupSendViewModel.spendable() - val cap = GroupWalletRollout.capFor(chain) - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = groupSendViewModel.amountField, - outputTransformation = GroupedSats, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next), - label = { Text(stringResource(Res.string.amount_in_sats)) }, - suffix = { Text(stringResource(Res.string.sats)) }, - isError = amountProblem != null, - supportingText = if (amountProblem == null && spendable == null && cap == null) null else { - { - if (amountProblem != null) { - Text(problemWith(amountProblem, chain)) - } else Column { - spendable?.let { Text(stringResource(Res.string.s_sats_confirmed_and_free_to_spend, it.grouped())) } - cap?.let { Text(stringResource(Res.string.while_the_wallet_is_new_at_most_s_sats, it.grouped())) } - } - } - }, - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = groupSendViewModel.feerateField, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), - label = { Text(stringResource(Res.string.feerate_in_sats_per_byte)) }, - ) - - // Still finding change is still finding coins: neither is anything to correct. - if (state.walletState == null || preview == GroupSpendBuilder.Result.FindingChange) { - LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_the_group_s_coins)) - } else if (amountProblem == null) { - preview?.let { SendPreview(it, chain) } - } - Text( text = stringResource(Res.string.nothing_leaves_until_a_quorum_signs), style = MaterialTheme.typography.bodySmall, @@ -270,18 +267,181 @@ fun GroupSendScreen( } } -/** What the form would build, or why it cannot. */ +/** + * The fields of a send and what they would build: the address, send + * everything, the amount, the feerate, and the preview -- one form for every + * wallet that spends, so the group's and a member's cannot drift. The button + * under it is the caller's, because what it does is not the same: a group asks + * its quorum, a member signs alone. + * + * [ownWallet] is a member spending their own guarded wallet, which changes the + * words -- "your coins", "this wallet" -- and nothing else. [destination], when + * there is one, takes the address field's place: a funding pays a wallet the + * form names rather than an address somebody types. + */ @Composable -private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) { +internal fun SpendForm( + addressField: TextFieldState, + amountField: TextFieldState, + feerateField: TextFieldState, + sendEverything: MutableState, + /** The confirmed coins free to spend, or null before Electrum has answered. */ + spendable: Satoshi?, + cap: Satoshi?, + /** + * A guardian's own leaf's delay, when the form spends a descendant's guarded + * wallet as its guardian -- what makes its balance lower than the wallet's. + * `docs/guardian-delay.md`. + */ + guardianDelay: Long? = null, + preview: GroupSpendBuilder.Result?, + /** A problem with the amount, said on the amount field, beside what caused it. */ + amountProblem: GroupSpendBuilder.Result?, + coinsKnown: Boolean, + chain: Chain, + ownWallet: Boolean = false, + destination: (@Composable () -> Unit)? = null, + /** The wallet a funding pays, as the preview names it. */ + fundedName: String? = null, + /** A funding whose address is not known yet: its card says so, and there is no preview to show. */ + waitingOnFunding: Boolean = false, +) { + // No column of its own: the fields go into the caller's, under its spacing, + // exactly as they did before the form was shared. + destination?.invoke() ?: OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = addressField, + lineLimits = TextFieldLineLimits.SingleLine, + label = { Text(stringResource(Res.string.address)) }, + ) + + // The row is the target, so the label toggles too: one 48dp control with one name. + Row( + modifier = Modifier.fillMaxWidth() + .toggleable( + value = sendEverything.value, + role = Role.Switch, + onValueChange = { sendEverything.value = it }, + ) + .minimumInteractiveComponentSize(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text(stringResource(Res.string.send_everything)) + Switch(checked = sendEverything.value, onCheckedChange = null) + } + + // Hidden rather than cleared, so turning send-everything off again finds the amount typed. + if (!sendEverything.value) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = amountField, + outputTransformation = GroupedSats, + lineLimits = TextFieldLineLimits.SingleLine, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next), + label = { Text(stringResource(Res.string.amount_in_sats)) }, + suffix = { Text(stringResource(Res.string.sats)) }, + isError = amountProblem != null, + supportingText = if (amountProblem == null && spendable == null && cap == null) null else { + { + if (amountProblem != null) { + Text(problemWith(amountProblem, chain, ownWallet)) + } else Column { + spendable?.let { Text(stringResource(Res.string.s_sats_confirmed_and_free_to_spend, it.grouped())) } + // Why a guardian's balance can be lower than the wallet's: + // only coins past its own leaf's lock. + guardianDelay?.let { Text(stringResource(Res.string.only_coins_confirmed_for_can_be_spent, delayText(it, chain))) } + cap?.let { Text(stringResource(Res.string.while_the_wallet_is_new_at_most_s_sats, it.grouped())) } + } + } + }, + ) + } + + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = feerateField, + lineLimits = TextFieldLineLimits.SingleLine, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + label = { Text(stringResource(Res.string.feerate_in_sats_per_byte)) }, + ) + + // Still finding change is still finding coins: neither is anything to correct. + if (!coinsKnown || preview == GroupSpendBuilder.Result.FindingChange) { + LoadingDataIndicator(fillScreen = false, text = stringResource(if (ownWallet) Res.string.finding_your_coins else Res.string.finding_the_group_s_coins)) + } else if (amountProblem == null && !waitingOnFunding) { + preview?.let { SendPreview(it, chain, ownWallet, fundedName) } + } +} + +/** + * Where a funding goes: the descendant's wallet, the address in it this send + * pays and its index, and what the group keeps over the coins once they land. + * While the address is not known yet, or every one is held, it says that instead. + */ +@Composable +private fun FundingDestination(funding: FundingTarget) { + val name = funding.wallet.displayName ?: stringResource(Res.string.a_subgroup) + OutlinedCard(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text(text = stringResource(Res.string.to), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(text = stringResource(Res.string.s_s_guarded_wallet, name), style = MaterialTheme.typography.titleMedium) + val address = funding.address + when { + address != null -> { + Text( + text = address.address, + style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + Text( + text = stringResource(Res.string.address_s, address.derivation.index.toString()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + funding.allHeld -> Text( + text = stringResource(Res.string.wait_for_this_group_s_open_payments_to_s, name), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + else -> LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_an_address_in_s_s_wallet, name)) + } + // What funding a guarded wallet means for this group: the coins come + // back within its reach, through its own leaf, after that leaf's + // lock -- which the group that granted it chose. docs/guardian-delay.md. + Text( + text = stringResource(Res.string.this_group_can_spend_these_coins_again, delayText(funding.wallet.delay, funding.wallet.chain)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** What the form would build, or why it cannot. [fundedName] names the wallet a funding pays. */ +@Composable +private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain, ownWallet: Boolean, fundedName: String? = null) { when (result) { is GroupSpendBuilder.Result.Built -> Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { Text( - text = stringResource(Res.string.sends_s_sats_with_a_fee_of_s_sats, result.amount.grouped(), result.fee.grouped()), + text = if (result.funded != null && fundedName != null) { + stringResource(Res.string.sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats, result.amount.grouped(), fundedName, result.fee.grouped()) + } else { + stringResource(Res.string.sends_s_sats_with_a_fee_of_s_sats, result.amount.grouped(), result.fee.grouped()) + }, style = MaterialTheme.typography.bodyLarge, ) result.change?.let { change -> Text( - text = stringResource(Res.string.s_sats_come_back_to_the_group_as_change, change.grouped()), + text = stringResource( + if (ownWallet) Res.string.s_sats_come_back_to_this_wallet_as_change else Res.string.s_sats_come_back_to_the_group_as_change, + change.grouped(), + ), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -296,7 +456,7 @@ private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) { } else -> Text( - text = problemWith(result, chain), + text = problemWith(result, chain, ownWallet), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, ) @@ -305,11 +465,15 @@ private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) { /** Why [result] cannot be proposed, in words. */ @Composable -private fun problemWith(result: GroupSpendBuilder.Result, chain: Chain): String = when (result) { +private fun problemWith(result: GroupSpendBuilder.Result, chain: Chain, ownWallet: Boolean): String = when (result) { GroupSpendBuilder.Result.NotAnAddress -> stringResource(Res.string.that_isn_t_an_address_on_s, GroupWalletStatementEvent.chainName(chain)) - GroupSpendBuilder.Result.NothingToSpend -> stringResource(Res.string.the_group_has_nothing_confirmed_to_spend) - GroupSpendBuilder.Result.NotEnough -> stringResource(Res.string.the_group_doesn_t_have_that_much_confirmed) + GroupSpendBuilder.Result.NothingToSpend -> stringResource( + if (ownWallet) Res.string.this_wallet_has_nothing_confirmed_to_spend else Res.string.the_group_has_nothing_confirmed_to_spend + ) + GroupSpendBuilder.Result.NotEnough -> stringResource( + if (ownWallet) Res.string.this_wallet_doesn_t_have_that_much_confirmed else Res.string.the_group_doesn_t_have_that_much_confirmed + ) GroupSpendBuilder.Result.TooManyOpen -> stringResource(Res.string.too_many_spends_are_open_with_change) is GroupSpendBuilder.Result.OverCap -> stringResource(Res.string.while_the_wallet_is_new_at_most_s_sats, result.cap.grouped()) is GroupSpendBuilder.Result.InvalidAmount -> when (result.input) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index c77bfd1a..5f500049 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -1,6 +1,43 @@ package com.machankura.bennu.compose.ui.composable import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import bennu.composeapp.generated.resources.a_group_below_s +import bennu.composeapp.generated.resources.a_group_below_this_one +import bennu.composeapp.generated.resources.fund_s_s_guarded_wallet_s +import bennu.composeapp.generated.resources.fund_s_s_wallet_guarded_by_s +import bennu.composeapp.generated.resources.guarded_by_n_groups +import bennu.composeapp.generated.resources.guarded_by_s +import bennu.composeapp.generated.resources.guarded_by_s_below_s +import bennu.composeapp.generated.resources.members_wallets +import bennu.composeapp.generated.resources.n_wallets +import bennu.composeapp.generated.resources.s_comma_s +import bennu.composeapp.generated.resources.spend_from_s_s_guarded_wallet_s +import bennu.composeapp.generated.resources.spend_from_s_s_wallet_guarded_by_s +import bennu.composeapp.generated.resources.this_group +import androidx.compose.foundation.clickable +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.ui.unit.dp +import com.machankura.bennu.compose.ui.composable.navigation.routes.ProfilePreviewRoute +import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar +import com.machankura.bennu.compose.ui.view.state.PersonGuardedWallets +import com.machankura.bennu.compose.ui.view.state.byPerson +import org.jetbrains.compose.resources.pluralStringResource +import bennu.composeapp.generated.resources.this_group_s_delay_in_this_wallet +import bennu.composeapp.generated.resources.a_group_above_this_one +import bennu.composeapp.generated.resources.guardian_after +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import bennu.composeapp.generated.resources.the_group_above_decided_this_wallet_is_not_guarded +import bennu.composeapp.generated.resources.the_group_above_decided_this_wallet_is_guarded +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.material3.OutlinedCard +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import bennu.composeapp.generated.resources.fund +import bennu.composeapp.generated.resources.fund_s_s_guarded_wallet +import bennu.composeapp.generated.resources.s_sats_arriving +import bennu.composeapp.generated.resources.spend_from_s_s_guarded_wallet import androidx.compose.foundation.layout.Row import com.machankura.bennu.compose.text.ProposedSpend import com.machankura.bennu.compose.ui.view.state.SpendRow @@ -37,6 +74,7 @@ import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.FormatListNumbered import androidx.compose.material.icons.filled.Visibility import androidx.compose.material3.Button +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon @@ -71,8 +109,29 @@ import bennu.composeapp.generated.resources.each_member_s_share_is_stored_unencr import bennu.composeapp.generated.resources.export_watch_only import bennu.composeapp.generated.resources.finding_the_group_s_coins import bennu.composeapp.generated.resources.group_wallet +import bennu.composeapp.generated.resources.s_onchain_wallet import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet import bennu.composeapp.generated.resources.open_a_group_wallet +import bennu.composeapp.generated.resources.open_a_guarded_wallet +import bennu.composeapp.generated.resources.a_subgroup +import bennu.composeapp.generated.resources.at_s +import bennu.composeapp.generated.resources.couldn_t_share_the_wallet +import bennu.composeapp.generated.resources.guarded_wallets +import bennu.composeapp.generated.resources.not_yet_shared_with_the_groups_above +import bennu.composeapp.generated.resources.s_sats_within_this_group_s_reach +import bennu.composeapp.generated.resources.share +import bennu.composeapp.generated.resources.spend +import bennu.composeapp.generated.resources.shared_with_the_groups_above +import bennu.composeapp.generated.resources.tell_the_groups_above +import bennu.composeapp.generated.resources.this_device_shares_these_on_its_own_when_it_can +import bennu.composeapp.generated.resources.wallets_of_groups_below_this_one +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow +import androidx.compose.foundation.lazy.LazyListScope +import bennu.composeapp.generated.resources.open_without_guardians +import bennu.composeapp.generated.resources.the_groups_above_this_one_have_agreed_to_guard_it +import bennu.composeapp.generated.resources.guarded_the_groups_above_this_one_can_spend +import com.machankura.bennu.compose.managers.GuardianDerivation import bennu.composeapp.generated.resources.opening_a_wallet_asks_the_group_to_agree import bennu.composeapp.generated.resources.receive_address import bennu.composeapp.generated.resources.received @@ -160,17 +219,60 @@ fun GroupWalletScreen( val couldNotOpen = stringResource(Res.string.couldn_t_ask_the_group_to_open_a_wallet) val sentAgain = stringResource(Res.string.sent_again) val couldNotBump = stringResource(Res.string.couldn_t_bump_the_fee) + val shared = stringResource(Res.string.shared_with_the_groups_above) + val couldNotShare = stringResource(Res.string.couldn_t_share_the_wallet) + // Behind the same two gates as the room's own send: a share to propose + // with, and a node to see the descendant's coins with. + val toGuardianSpend = { row: GuardedWalletRow -> + onNavigateToRoute( + GroupSendRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + guardedChatRoomId = row.wallet.descendantChatRoomId, + ) + ) + } + // Behind the room's own send's gates, since a funding is one: a share to + // propose with, and a node to see this group's coins with. + val toGuardianFund = { row: GuardedWalletRow -> + onNavigateToRoute( + GroupSendRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + fundChatRoomId = row.wallet.descendantChatRoomId, + ) + ) + } + // A member's wallets are gathered under them, and their header opens them: + // a person is someone to look at, not a room to go into. + val toPerson = { publicKey: HexKey -> + onNavigateToRoute(ProfilePreviewRoute(activeUserPublicKey = activeUserPublicKey, profilePublicKey = publicKey)) + } + val onShare = { shareable: GuardianManager.Shareable -> + groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) }) + } val toSession = { sessionId: String -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) } + // Named for its group once the room is known; a room with no subject, and + // the moment before it loads, fall back to the generic name. + val groupName = when (val state = groupWalletViewModel.groupWalletUIState) { + is GroupWalletUIState.NotOpened -> state.localChatRoom.chatRoom.subject + is GroupWalletUIState.Loaded -> state.localChatRoom.chatRoom.subject + else -> null + } + Scaffold( snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, topBar = { TopAppBar( title = { Text( - text = stringResource(Res.string.group_wallet), + text = groupName?.let { stringResource(Res.string.s_onchain_wallet, it) } + ?: stringResource(Res.string.group_wallet), maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -195,19 +297,26 @@ fun GroupWalletScreen( } is GroupWalletUIState.NotOpened -> { - EmptyState( - modifier = Modifier.padding(padding).readableContent(), + val notOpened = @Composable { modifier: Modifier -> EmptyState( + modifier = modifier, message = stringResource(Res.string.this_group_has_not_opened_a_wallet), icon = Icons.Default.AccountBalanceWallet, // Hidden rather than disabled, the way every gated way in // on the group's screens is: a device with no share cannot // propose, and a room with no key has nothing to open. - action = if (state.canSign && state.account != null) { + action = if (state.canSign && state.account != null && (state.offersPlain || state.guarded != null)) { { OpenWalletAction( isPending = groupWalletViewModel.isActionPending.value, - onOpen = { + guardedOffered = state.guarded != null, + plainOffered = state.offersPlain, + decided = (state.policy as? WalletPolicyReading.Decided)?.policy, + guardians = state.guarded?.account?.guardians.orEmpty(), + guardianNames = state.guardianNames, + chain = chain, + onOpen = { guarded -> groupWalletViewModel.openWallet( + guarded = guarded, onSuccess = { sessionId -> // Onto the session: the wallet does // not exist until a quorum signs. @@ -225,7 +334,31 @@ fun GroupWalletScreen( ) } } else null - ) + ) } + + if (state.guardedWallets.isEmpty() && state.shareable.isEmpty()) { + notOpened(Modifier.padding(padding).readableContent()) + } else { + // A group with no wallet of its own can still guard others', + // and still carry a descendant's upward. + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + item { notOpened(Modifier) } + guardianItems( + guardedWallets = state.guardedWallets, + shareable = state.shareable, + isPending = groupWalletViewModel.isActionPending.value, + onShare = onShare, + onSpend = if (state.canSign && wallets != null) toGuardianSpend else null, + // A group with no wallet of its own has nothing to fund with. + onFund = null, + onOpenPerson = toPerson, + ) + } + } } is GroupWalletUIState.Loaded -> { @@ -265,6 +398,11 @@ fun GroupWalletScreen( groupWalletViewModel.bumpFee(sessionId, onSuccess = toSession, onFailure = { notify(couldNotBump) }) } } else null, + isPending = groupWalletViewModel.isActionPending.value, + onShare = onShare, + onSpend = if (state.canSign && state.canWatch) toGuardianSpend else null, + onFund = if (state.canSign && state.canWatch) toGuardianFund else null, + onOpenPerson = toPerson, ) } } @@ -278,7 +416,18 @@ fun GroupWalletScreen( * an unencrypted share on a member's device means once there are coins behind it. */ @Composable -private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { +private fun OpenWalletAction( + isPending: Boolean, + guardedOffered: Boolean, + plainOffered: Boolean, + /** What the room's parent decided at its birth, or null when it left it to the room. */ + decided: SubgroupWalletPolicy?, + /** The guardians a guarded wallet would name, nearest first, each with its own delay. */ + guardians: List, + guardianNames: Map, + chain: Chain, + onOpen: (guarded: Boolean) -> Unit, +) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) @@ -292,10 +441,51 @@ private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) - Button(onClick = onOpen, enabled = !isPending) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.open_a_group_wallet)) + if (decided != null) { + // The parent decided at the room's birth, and its quorum signed it: + // one way in, and the line says whose decision it was. Every other + // member refuses the other statement, so offering it would only + // strand a quorum. See docs/subgroup-wallet-policy.md. + Text( + text = when (decided) { + SubgroupWalletPolicy.GUARDED -> stringResource(Res.string.the_group_above_decided_this_wallet_is_guarded) + SubgroupWalletPolicy.UNGUARDED -> stringResource(Res.string.the_group_above_decided_this_wallet_is_not_guarded) + }, + style = MaterialTheme.typography.bodyMedium, + ) + if (decided == SubgroupWalletPolicy.GUARDED) GuardianDelays(guardians, guardianNames, chain) + val guarded = decided == SubgroupWalletPolicy.GUARDED + if (guarded && guardedOffered || !guarded && plainOffered) { + Button(onClick = { onOpen(guarded) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(if (guarded) Res.string.open_a_guarded_wallet else Res.string.open_a_group_wallet)) + } + } + } else if (guardedOffered) { + // Undecided: a subgroup certified before parents decided. The default + // for one whose parent agreed to guard it, and the plain wallet beside + // it rather than hidden: being guarded is then the group's own choice, + // and its quorum signing the statement is it making that choice. + Text( + text = stringResource(Res.string.the_groups_above_this_one_have_agreed_to_guard_it), + style = MaterialTheme.typography.bodyMedium, + ) + GuardianDelays(guardians, guardianNames, chain) + Button(onClick = { onOpen(true) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_guarded_wallet)) + } + OutlinedButton(onClick = { onOpen(false) }, enabled = !isPending) { + Text(stringResource(Res.string.open_without_guardians)) + } + } else { + Button(onClick = { onOpen(false) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_group_wallet)) + } } } } @@ -310,6 +500,11 @@ private fun OpenWallet( onOpenSpend: (sessionId: String) -> Unit, onSendAgain: ((sessionId: String) -> Unit)?, onBump: ((sessionId: String) -> Unit)?, + isPending: Boolean, + onShare: (GuardianManager.Shareable) -> Unit, + onSpend: ((GuardedWalletRow) -> Unit)?, + onFund: ((GuardedWalletRow) -> Unit)?, + onOpenPerson: (HexKey) -> Unit, ) { val clipboardManager = LocalClipboardManager.current val addressCopied = stringResource(Res.string.address_copied) @@ -323,6 +518,19 @@ private fun OpenWallet( ) { item { BalanceCard(walletState) } + if (state.wallet.account.isGuarded) { + item { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text( + text = stringResource(Res.string.guarded_the_groups_above_this_one_can_spend), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + GuardianDelays(state.wallet.account.guardians, state.guardianNames, state.wallet.chain) + } + } + } + onSend?.let { send -> item { Button(onClick = send) { @@ -455,6 +663,16 @@ private fun OpenWallet( ) } } + + guardianItems( + guardedWallets = state.guardedWallets, + shareable = state.shareable, + isPending = isPending, + onShare = onShare, + onSpend = onSpend, + onFund = onFund, + onOpenPerson = onOpenPerson, + ) } } @@ -500,8 +718,266 @@ private fun SpendStatus.label() = when (this) { } /** Confirmed and on-the-way said apart: only the first can be spent by a send-all. */ +/** + * The guarded wallets of groups below this one, and the guarded statements this + * device can still carry to the groups above. Both under the room's own wallet, + * or in place of it for a group that has none. + */ +private fun LazyListScope.guardianItems( + guardedWallets: List, + shareable: List, + isPending: Boolean, + onShare: (GuardianManager.Shareable) -> Unit, + onSpend: ((GuardedWalletRow) -> Unit)?, + onFund: ((GuardedWalletRow) -> Unit)?, + onOpenPerson: (HexKey) -> Unit, +) { + if (guardedWallets.isNotEmpty()) { + item { + Text(text = stringResource(Res.string.guarded_wallets), style = MaterialTheme.typography.titleMedium) + } + item { + Text( + text = stringResource(Res.string.wallets_of_groups_below_this_one), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + // Subgroups' wallets, each a room; then members', gathered by person, so + // that one member's wallets under different groups below read as one + // person's. docs/member-wallet-guarding-group.md, D6. + val subgroups = guardedWallets.filter { it.wallet.subject is GuardianManager.GuardedSubject.Subgroup } + items(subgroups, key = { "guarded-" + it.wallet.statement.id }) { row -> + GuardedWalletCard(row = row, onSpend = onSpend, onFund = onFund) + } + val people = guardedWallets.byPerson() + if (people.isNotEmpty()) { + item { + Text(text = stringResource(Res.string.members_wallets), style = MaterialTheme.typography.titleSmall) + } + people.forEach { person -> + item(key = "person-" + person.ownerPublicKey) { + PersonHeader(person = person, onOpen = { onOpenPerson(person.ownerPublicKey) }) + } + items(person.rows, key = { "guarded-" + it.wallet.statement.id }) { row -> + GuardedWalletCard( + row = row, + onSpend = onSpend, + onFund = onFund, + // Under the header, so the cards read as the person's. + modifier = Modifier.padding(start = MaterialTheme.spacing.containerPadding), + ) + } + } + } + } + + if (shareable.isNotEmpty()) { + item { + Text(text = stringResource(Res.string.tell_the_groups_above), style = MaterialTheme.typography.titleMedium) + } + // What is left here is what the automatic forwarding could not send -- + // a notice lost on the wire, most often -- so the section says so, once. + // docs/guarded-wallet-forwarding.md, Phase 6. + item { + Text( + text = stringResource(Res.string.this_device_shares_these_on_its_own_when_it_can), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + items(shareable, key = { "shareable-" + it.statement.id }) { candidate -> + ListItem( + headlineContent = { + Text( + text = candidate.ownerPublicKey?.let { stringResource(Res.string.at_s, candidate.ownerName ?: it.take(8)) } + ?: candidate.name + ?: stringResource(Res.string.a_subgroup), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + supportingContent = { Text(stringResource(Res.string.not_yet_shared_with_the_groups_above)) }, + trailingContent = { + TextButton(onClick = { onShare(candidate) }, enabled = !isPending) { + Text(stringResource(Res.string.share)) + } + }, + ) + } + } +} + +/** + * Each guardian of a guarded wallet with its own delay, nearest first: + * *#Council: after 144 blocks, about 1 day*. One sentence with one number in it + * stopped being true once each group chose its own -- `docs/guardian-delay.md`. + */ @Composable -private fun BalanceCard(walletState: GroupWalletState?) { +private fun GuardianDelays( + guardians: List, + names: Map, + chain: Chain, +) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + guardians.forEach { guardian -> + Text( + text = stringResource( + Res.string.guardian_after, + names[guardian.chatRoomId] ?: stringResource(Res.string.a_group_above_this_one), + delayText(guardian.delay, chain), + ), + style = MaterialTheme.typography.bodyMedium, + ) + } + } +} + +/** + * One descendant's guarded wallet: its name and what is within reach, and under + * them the actions, in the card's own row rather than the list item's trailing + * slot. Two buttons there would leave the name -- the one thing that says which + * wallet this is -- a few characters at large text sizes, and a flow row wraps + * them instead. Each button names its wallet, since a screen reader hears every + * row's *Fund* and *Spend* alike. See `docs/guarded-wallet-funding.md`, Phase 5. + */ +@Composable +private fun GuardedWalletCard( + row: GuardedWalletRow, + onSpend: ((GuardedWalletRow) -> Unit)?, + onFund: ((GuardedWalletRow) -> Unit)?, + modifier: Modifier = Modifier, +) { + val name = guardedName(row.wallet.subject) + val member = row.wallet.subject as? GuardianManager.GuardedSubject.Member + val guardedBy = member?.let { guardedByLine(row.wallet, it) } + // A member's card sits under their header, so it is named by its label -- + // or, with none, by the group that guards it, which still tells two of one + // person's wallets apart. + val headline = when { + member == null -> name + else -> member.label ?: guardedBy.orEmpty() + } + OutlinedCard(modifier = modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + // Two lines, since the name is what says which wallet the buttons act on. + headlineContent = { Text(headline, maxLines = 2, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + val reach = row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) } + val arriving = row.arriving?.takeIf { it.sat > 0 }?.let { stringResource(Res.string.s_sats_arriving, it.grouped()) } + val amounts = when { + reach == null -> stringResource(Res.string.balance_not_known_yet) + arriving == null -> reach + else -> stringResource(Res.string.s_dot_s, reach, arriving) + } + Column { + // Which group below guards it, where the headline does not say. + if (member?.label != null && guardedBy != null) Text(guardedBy) + Text(amounts) + // This group's own leaf, which two of its descendants can have + // set differently. docs/guardian-delay.md. + Text(stringResource(Res.string.this_group_s_delay_in_this_wallet, delayText(row.wallet.delay, row.wallet.chain))) + } + }, + ) + if (onFund != null || onSpend != null) { + // Each names its wallet and not only its person: one member can have + // several here, and a screen reader hears every one's *Fund* alike. + val fundLabel = when { + member == null -> stringResource(Res.string.fund_s_s_guarded_wallet, name) + member.label != null -> stringResource(Res.string.fund_s_s_guarded_wallet_s, name, member.label) + else -> stringResource(Res.string.fund_s_s_wallet_guarded_by_s, name, guardianPhrase(row.wallet, member)) + } + val spendLabel = when { + member == null -> stringResource(Res.string.spend_from_s_s_guarded_wallet, name) + member.label != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet_s, name, member.label) + else -> stringResource(Res.string.spend_from_s_s_wallet_guarded_by_s, name, guardianPhrase(row.wallet, member)) + } + FlowRow( + modifier = Modifier.fillMaxWidth().padding( + start = MaterialTheme.spacing.containerPadding, + end = MaterialTheme.spacing.containerPadding, + bottom = MaterialTheme.spacing.compactPadding, + ), + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.targetGap, Alignment.End), + ) { + // Money in before money out, at equal weight: neither is the one + // every member wants, and a filled button would say it was. + onFund?.let { fund -> + TextButton(onClick = { fund(row) }, modifier = Modifier.semantics { contentDescription = fundLabel }) { + Text(stringResource(Res.string.fund)) + } + } + onSpend?.let { spend -> + TextButton(onClick = { spend(row) }, modifier = Modifier.semantics { contentDescription = spendLabel }) { + Text(stringResource(Res.string.spend)) + } + } + } + } + } +} + +/** + * One member, heading their wallets in an ancestor's list: how many this group + * guards, and under how many groups below it -- the summary that shows a person + * with wallets in more than one branch. Opens their profile. + */ +@Composable +private fun PersonHeader(person: PersonGuardedWallets, onOpen: () -> Unit) { + val name = stringResource(Res.string.at_s, person.ownerName ?: person.ownerPublicKey.take(8)) + val wallets = pluralStringResource(Res.plurals.n_wallets, person.rows.size, person.rows.size) + val groups = pluralStringResource(Res.plurals.guarded_by_n_groups, person.guardianCount, person.guardianCount) + ListItem( + modifier = Modifier.clickable(onClick = onOpen).minimumInteractiveComponentSize(), + // 40dp is the avatar's size, a dimension: M3's list item leading avatar. + leadingContent = { ProfileAvatar(size = 40.dp, publicKey = person.ownerPublicKey, picture = null, name = person.ownerName) }, + headlineContent = { Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { Text(stringResource(Res.string.s_comma_s, wallets, groups)) }, + ) +} + +/** + * The group that directly guards a member's wallet, as a phrase inside a + * sentence: *this group*, its name, or -- with no name this device can check -- + * where it sits, *a group below #P*. `docs/member-wallet-guarding-group.md`, D2. + */ +@Composable +internal fun guardianPhrase(wallet: GuardianManager.GuardedWallet, member: GuardianManager.GuardedSubject.Member): String = when { + wallet.isGuardedHere -> stringResource(Res.string.this_group) + member.guardianName != null -> member.guardianName + member.branchName != null -> stringResource(Res.string.a_group_below_s, member.branchName) + else -> stringResource(Res.string.a_group_below_this_one) +} + +/** + * *Guarded by #N*, or *Guarded by #M, below #P* where the group is further down + * than this one's own child -- the branch, so wallets from one part of the tree + * read as being from there. `docs/member-wallet-guarding-group.md`, D6. + */ +@Composable +internal fun guardedByLine(wallet: GuardianManager.GuardedWallet, member: GuardianManager.GuardedSubject.Member): String = + if (wallet.position >= 2 && member.guardianName != null && member.branchName != null) { + stringResource(Res.string.guarded_by_s_below_s, member.guardianName, member.branchName) + } else { + stringResource(Res.string.guarded_by_s, guardianPhrase(wallet, member)) + } + +/** + * A guarded wallet as an ancestor's list names it: a subgroup by the name its + * parent certified -- `#Translation` -- and a member by their profile's name -- + * `@alice` -- falling back to the start of their key. A person's name is theirs + * and live; the certificate fixes who they are, not what they are called. + */ +@Composable +internal fun guardedName(subject: GuardianManager.GuardedSubject): String = when (subject) { + is GuardianManager.GuardedSubject.Subgroup -> subject.name ?: stringResource(Res.string.a_subgroup) + is GuardianManager.GuardedSubject.Member -> stringResource(Res.string.at_s, subject.ownerName ?: subject.ownerPublicKey.take(8)) +} + +@Composable +internal fun BalanceCard(walletState: GroupWalletState?) { Card(modifier = Modifier.fillMaxWidth()) { Column( modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), @@ -528,7 +1004,7 @@ private fun BalanceCard(walletState: GroupWalletState?) { } @Composable -private fun CoinRow(utxo: GroupUtxo, confirmations: Int) { +internal fun CoinRow(utxo: GroupUtxo, confirmations: Int) { ListItem( leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, headlineContent = { Text(stringResource(Res.string.s_sats, utxo.amount.grouped())) }, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt new file mode 100644 index 00000000..d45bdd7c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt @@ -0,0 +1,154 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material.icons.filled.Send +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.couldn_t_send +import bennu.composeapp.generated.resources.send_from_your_guarded_wallet +import bennu.composeapp.generated.resources.sending_from_this_wallet_needs_its_key_and_a_node +import bennu.composeapp.generated.resources.sent +import bennu.composeapp.generated.resources.sign_and_send +import bennu.composeapp.generated.resources.signed_by_you_alone_and_sent_at_once +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.MemberSendViewModel +import com.machankura.bennu.compose.ui.view.state.MemberSendUIState +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import org.jetbrains.compose.resources.stringResource + +/** + * A spend from the member's own guarded wallet: the group's send form, and a + * button that signs with the member's key alone and sends. There is no quorum + * to stop a mistake after this, which the line above the button says. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MemberSendScreen( + activeUserPublicKey: HexKey, + walletId: String, + chain: Chain, + initialUIState: MemberSendUIState = MemberSendUIState.Loading, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + onNavigateBack: () -> Unit, +) { + val viewModel: MemberSendViewModel = viewModel( + factory = MemberSendViewModel.factory( + ownerPublicKey = activeUserPublicKey, + walletId = walletId, + chain = chain, + initialUIState = initialUIState, + memberWalletRepository = memberWalletRepository, + wallets = wallets, + ) + ) + + LaunchedEffect(true) { + if (initialUIState == MemberSendUIState.Loading) viewModel.initiate() + } + + // The caller's scope, so "sent" outlives the screen going back. + val notify = rememberNotifier(rememberCoroutineScope()) + val sent = stringResource(Res.string.sent) + val couldNotSend = stringResource(Res.string.couldn_t_send) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.send_from_your_guarded_wallet), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + // Nothing to retry: the wallet came from a navigation argument. + is MemberSendUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) + + MemberSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + MemberSendUIState.Unavailable -> EmptyState( + modifier = Modifier.padding(padding).readableContent(), + message = stringResource(Res.string.sending_from_this_wallet_needs_its_key_and_a_node), + icon = Icons.Default.AccountBalanceWallet, + ) + + is MemberSendUIState.Ready -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val preview = viewModel.preview() + + SpendForm( + addressField = viewModel.addressField, + amountField = viewModel.amountField, + feerateField = viewModel.feerateField, + sendEverything = viewModel.sendEverything, + spendable = viewModel.spendable(), + cap = GroupWalletRollout.memberCapFor(chain), + preview = preview, + amountProblem = preview?.takeIf { viewModel.isAboutTheAmount(it) }, + coinsKnown = state.walletState != null, + chain = chain, + ownWallet = true, + ) + + Text( + text = stringResource(Res.string.signed_by_you_alone_and_sent_at_once), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Button( + enabled = preview is GroupSpendBuilder.Result.Built && !viewModel.isActionPending.value, + onClick = { viewModel.send(onSent = { notify(sent); onNavigateBack() }, onFailure = { notify(couldNotSend) }) }, + ) { + Icon(Icons.Default.Send, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.sign_and_send)) + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletItems.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletItems.kt new file mode 100644 index 00000000..9b6bfeee --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletItems.kt @@ -0,0 +1,112 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_group +import bennu.composeapp.generated.resources.balance_not_known_yet +import bennu.composeapp.generated.resources.guarded_wallets +import bennu.composeapp.generated.resources.key_on_another_device +import bennu.composeapp.generated.resources.new_guarded_wallet +import bennu.composeapp.generated.resources.s_did_not_sign +import bennu.composeapp.generated.resources.s_dot_s +import bennu.composeapp.generated.resources.s_is_signing +import bennu.composeapp.generated.resources.s_sats +import bennu.composeapp.generated.resources.waiting_for_someone_in_s_to_put_it_to_the_group +import bennu.composeapp.generated.resources.you_have_no_guarded_wallets +import bennu.composeapp.generated.resources.you_re_no_longer_in_s +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.text.grouped +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.MemberWalletsViewModel +import org.jetbrains.compose.resources.stringResource + +/** + * A member's guarded wallets, on their own profile: one row per wallet, named + * for the group that guards it, and the way to ask for another. + * `docs/member-guarded-wallets.md`, Phase 8. + * + * Never published. A profile's kind 0 is public, and a member wallet's xpub + * never leaves an encryption. + */ +fun LazyListScope.memberWalletItems( + rows: List?, + onOpen: (walletId: String) -> Unit, + onNew: (() -> Unit)?, +) { + item { + Text( + modifier = Modifier.fillMaxWidth(), + text = stringResource(Res.string.guarded_wallets), + style = MaterialTheme.typography.titleMedium, + ) + } + + when { + rows == null -> Unit + rows.isEmpty() -> item { EmptyState(message = stringResource(Res.string.you_have_no_guarded_wallets), icon = Icons.Default.AccountBalanceWallet) } + else -> items(rows, key = { "member-wallet-" + it.wallet.walletId }) { row -> + ListItem( + modifier = Modifier.clickable { onOpen(row.wallet.walletId) }.minimumInteractiveComponentSize(), + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + headlineContent = { + val group = groupNameOf(row.wallet) + Text( + text = row.wallet.label?.let { stringResource(Res.string.s_dot_s, group, it) } ?: group, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + supportingContent = { Text(supportingLine(row)) }, + ) + } + } + + onNew?.let { new -> + item { + TextButton(onClick = new) { + Icon(Icons.Default.Add, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.new_guarded_wallet)) + } + } + } +} + +/** The guarding group as the member's rows name it: the room's name here, or a generic one. */ +@Composable +internal fun groupNameOf(wallet: MemberWalletManager.MemberWalletRow): String = + wallet.groupRoom?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: stringResource(Res.string.a_group) + +@Composable +private fun supportingLine(row: MemberWalletsViewModel.Row): String { + val group = groupNameOf(row.wallet) + if (!row.wallet.isMember) return stringResource(Res.string.you_re_no_longer_in_s, group) + val balance = row.walletState?.let { stringResource(Res.string.s_sats, it.confirmedBalance.grouped()) } + ?: stringResource(Res.string.balance_not_known_yet) + return when (row.wallet.state) { + MemberWalletManager.WalletState.ASKED -> stringResource(Res.string.waiting_for_someone_in_s_to_put_it_to_the_group, group) + MemberWalletManager.WalletState.SIGNING -> stringResource(Res.string.s_is_signing, group) + MemberWalletManager.WalletState.NOT_SIGNED -> stringResource(Res.string.s_did_not_sign, group) + MemberWalletManager.WalletState.OPEN -> balance + MemberWalletManager.WalletState.WATCH_ONLY -> stringResource(Res.string.s_dot_s, balance, stringResource(Res.string.key_on_another_device)) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletPolicyScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletPolicyScreen.kt new file mode 100644 index 00000000..e40514cf --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletPolicyScreen.kt @@ -0,0 +1,229 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_coin_the_member_moves_starts_waiting_again +import bennu.composeapp.generated.resources.after_s +import bennu.composeapp.generated.resources.ask_the_group +import bennu.composeapp.generated.resources.cancel +import bennu.composeapp.generated.resources.couldn_t_ask_the_group +import bennu.composeapp.generated.resources.doesn_t_guard_members_wallets +import bennu.composeapp.generated.resources.guards_members_wallets +import bennu.composeapp.generated.resources.how_long_before_this_group_can_take_a_member_s_coin +import bennu.composeapp.generated.resources.members_guarded_wallets +import bennu.composeapp.generated.resources.members_on_older_apps_can_only_be_guarded_at_12 +import bennu.composeapp.generated.resources.stop +import bennu.composeapp.generated.resources.stop_guarding_new_members_wallets_question +import bennu.composeapp.generated.resources.stop_guarding_new_wallets +import bennu.composeapp.generated.resources.stopped_guarding_new_members_wallets +import bennu.composeapp.generated.resources.wallets_already_guarded_keep_their_delay +import bennu.composeapp.generated.resources.wallets_already_guarded_stay_guarded +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.Route +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.GuardianDelayChooser +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.MemberWalletPolicyViewModel +import com.machankura.bennu.compose.ui.view.state.MemberWalletPolicyUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import org.jetbrains.compose.resources.stringResource + +/** + * Whether the group guards its members' wallets, at what delay, and closing it + * again -- `docs/member-wallet-delay.md`, Phase 6. + * + * What a change reaches is said before the button: only wallets asked for from + * now on, never one already guarded, and closing releases nothing. A device + * that cannot sign sees where the group stands and nothing to press. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MemberWalletPolicyScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialUIState: MemberWalletPolicyUIState = MemberWalletPolicyUIState.Loading, + chatRepository: ChatRepository, + memberWalletRepository: MemberWalletRepository, + frostSigningRepository: FrostSigningRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: MemberWalletPolicyViewModel = viewModel( + factory = MemberWalletPolicyViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialUIState = initialUIState, + chatRepository = chatRepository, + memberWalletRepository = memberWalletRepository, + frostSigningRepository = frostSigningRepository, + ) + ) + + LaunchedEffect(chatRoomId) { + if (initialUIState == MemberWalletPolicyUIState.Loading) viewModel.initiate() + } + + // Read above the handlers, which are not composable; the caller's scope, so + // the message outlives the screen moving onto the signing session. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAsk = stringResource(Res.string.couldn_t_ask_the_group) + val toSession = { sessionId: String -> + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) + } + var confirmingClose by remember { mutableStateOf(false) } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.members_guarded_wallets)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + MemberWalletPolicyUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + is MemberWalletPolicyUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = state.message, + // Reloading reads the group again, which is what failed. + onRetry = viewModel::initiate, + ) + + is MemberWalletPolicyUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + MemberWalletPolicyState(state.policy) + + if (state.canSign) { + GuardianDelayChooser( + title = stringResource(Res.string.how_long_before_this_group_can_take_a_member_s_coin), + consequence = stringResource(Res.string.a_coin_the_member_moves_starts_waiting_again), + input = viewModel.delay.input.value, + delay = viewModel.delay.delay(), + isCustom = viewModel.delay.isCustom.value, + problem = viewModel.delay.problem(), + onPreset = viewModel.delay::pick, + onCustom = viewModel.delay::useCustom, + onInput = viewModel.delay::type, + ) + Text( + text = stringResource(Res.string.wallets_already_guarded_keep_their_delay), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = stringResource(Res.string.members_on_older_apps_can_only_be_guarded_at_12), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + // Disabled, with the reason, while there is nothing to ask: + // a delay out of range, or the one the group already has. + val problem = viewModel.openProblem() + Button( + onClick = { viewModel.proposeOpen(onSuccess = toSession, onFailure = { notify(couldNotAsk) }) }, + enabled = problem == null && !viewModel.isActionPending.value, + ) { Text(stringResource(Res.string.ask_the_group)) } + if (problem != null && viewModel.delay.problem() == null) { + Text(text = problem, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + + if (viewModel.canClose()) { + OutlinedButton( + onClick = { confirmingClose = true }, + enabled = !viewModel.isActionPending.value, + ) { Text(stringResource(Res.string.stop_guarding_new_wallets)) } + } + } + } + } + } + } + + if (confirmingClose) { + AlertDialog( + onDismissRequest = { confirmingClose = false }, + title = { Text(stringResource(Res.string.stop_guarding_new_members_wallets_question)) }, + // What closing leaves alone, said where it is decided: the group's leaf + // is in every address of every wallet it already guards. + text = { Text(stringResource(Res.string.wallets_already_guarded_stay_guarded)) }, + confirmButton = { + TextButton(onClick = { + confirmingClose = false + viewModel.proposeClose(onSuccess = toSession, onFailure = { notify(couldNotAsk) }) + }) { Text(stringResource(Res.string.stop)) } + }, + dismissButton = { + TextButton(onClick = { confirmingClose = false }) { Text(stringResource(Res.string.cancel)) } + }, + ) + } +} + +/** + * Where the group stands on its members' wallets: guarding them after a delay, + * never having said so, or having stopped. Shared with the group's page. + */ +@Composable +internal fun MemberWalletPolicyState(policy: MemberWalletPolicyEvent.Policy?) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text( + text = stringResource( + when (policy) { + is MemberWalletPolicyEvent.Policy.Open -> Res.string.guards_members_wallets + is MemberWalletPolicyEvent.Policy.Closed -> Res.string.stopped_guarding_new_members_wallets + null -> Res.string.doesn_t_guard_members_wallets + } + ), + style = MaterialTheme.typography.titleMedium, + ) + if (policy is MemberWalletPolicyEvent.Policy.Open) { + Text( + text = stringResource(Res.string.after_s, delayText(policy.delay)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt new file mode 100644 index 00000000..58bb4f6a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt @@ -0,0 +1,429 @@ +package com.machankura.bennu.compose.ui.composable + +import com.machankura.bennu.compose.managers.MemberWalletManager +import bennu.composeapp.generated.resources.s_has_stopped_guarding_members_wallets_discard +import bennu.composeapp.generated.resources.s_has_changed_its_delay_since_you_asked +import bennu.composeapp.generated.resources.s_would_refuse_this_request_asked_before +import bennu.composeapp.generated.resources.s_would_refuse_this_request +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Send +import androidx.compose.material3.Button +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_group +import bennu.composeapp.generated.resources.address_copied +import bennu.composeapp.generated.resources.ask_again +import bennu.composeapp.generated.resources.cancel +import bennu.composeapp.generated.resources.change_descriptor +import bennu.composeapp.generated.resources.close +import bennu.composeapp.generated.resources.coins +import bennu.composeapp.generated.resources.copied +import bennu.composeapp.generated.resources.copy_address +import bennu.composeapp.generated.resources.couldn_t_ask_again +import bennu.composeapp.generated.resources.couldn_t_discard_the_wallet +import bennu.composeapp.generated.resources.discard +import bennu.composeapp.generated.resources.discard_this_wallet_question +import bennu.composeapp.generated.resources.discarding_forgets_its_key +import bennu.composeapp.generated.resources.export_key +import bennu.composeapp.generated.resources.export_this_wallet_s_key_question +import bennu.composeapp.generated.resources.finding_your_coins +import bennu.composeapp.generated.resources.copy +import bennu.composeapp.generated.resources.send +import bennu.composeapp.generated.resources.guarded_by_s +import bennu.composeapp.generated.resources.guarded_wallet +import bennu.composeapp.generated.resources.if_you_lose_this_device_those_groups_can_still_move_your_coins +import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet +import bennu.composeapp.generated.resources.receive_address +import bennu.composeapp.generated.resources.receive_descriptor +import bennu.composeapp.generated.resources.s_did_not_sign +import bennu.composeapp.generated.resources.s_is_signing +import bennu.composeapp.generated.resources.s_took_s_sats_in_s +import bennu.composeapp.generated.resources.show_key +import bennu.composeapp.generated.resources.taken_by_guardians +import bennu.composeapp.generated.resources.the_key_of_this_wallet_is_on_another_device +import bennu.composeapp.generated.resources.this_profile_cannot_watch_its_own_coins +import bennu.composeapp.generated.resources.waiting_for_someone_in_s_to_put_it_to_the_group +import bennu.composeapp.generated.resources.whoever_holds_these_descriptors_holds_the_coins +import bennu.composeapp.generated.resources.you_re_no_longer_in_s +import bennu.composeapp.generated.resources.your_spends +import bennu.composeapp.generated.resources.confirmed +import bennu.composeapp.generated.resources.in_the_mempool +import bennu.composeapp.generated.resources.sent_waiting_for_the_network +import com.machankura.bennu.compose.managers.MemberWalletManager.WalletState +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.text.grouped +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.QRCodeView +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.MemberWalletViewModel +import com.machankura.bennu.compose.ui.view.state.MemberWalletUIState +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.bip21Uri +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import org.jetbrains.compose.resources.stringResource + +/** + * One of the member's guarded wallets. + * + * Before a group has certified it, where the asking has got to and the two + * things the member can do about it: ask again, or discard the key -- which is + * safe exactly then, because no address was ever offered. Once certified, the + * wallet itself: balance, the address to be paid at, the coins, and every coin + * a guardian took, read off the chain. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MemberWalletScreen( + activeUserPublicKey: HexKey, + walletId: String, + initialUIState: MemberWalletUIState = MemberWalletUIState.Loading, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + /** The send form for this wallet, or null where there is none to offer. */ + onSend: ((walletId: String) -> Unit)? = null, + onNavigateBack: () -> Unit, +) { + val viewModel: MemberWalletViewModel = viewModel( + factory = MemberWalletViewModel.factory( + ownerPublicKey = activeUserPublicKey, + walletId = walletId, + initialUIState = initialUIState, + memberWalletRepository = memberWalletRepository, + wallets = wallets, + ) + ) + + LaunchedEffect(true) { + if (initialUIState == MemberWalletUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAskAgain = stringResource(Res.string.couldn_t_ask_again) + val couldNotDiscard = stringResource(Res.string.couldn_t_discard_the_wallet) + val addressCopied = stringResource(Res.string.address_copied) + val copied = stringResource(Res.string.copied) + val clipboardManager = LocalClipboardManager.current + + var confirmingDiscard by remember { mutableStateOf(false) } + var confirmingExport by remember { mutableStateOf(false) } + + val title = (viewModel.uiState as? MemberWalletUIState.Loaded)?.wallet?.label ?: stringResource(Res.string.guarded_wallet) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + MemberWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + // Nothing to retry: the wallet came from a navigation argument. + is MemberWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) + + is MemberWalletUIState.Loaded -> { + val wallet = state.wallet + val group = wallet.groupRoom?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: stringResource(Res.string.a_group) + val walletState = state.walletState + + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + item { Text(stringResource(Res.string.guarded_by_s, group), style = MaterialTheme.typography.titleMedium) } + item { + Text( + reachText(group, state.delays, wallet.account.chain), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (!wallet.isMember) item { Text(stringResource(Res.string.you_re_no_longer_in_s, group)) } + + when (wallet.state) { + WalletState.ASKED, WalletState.SIGNING, WalletState.NOT_SIGNED -> { + item { + Text( + stringResource( + when (wallet.state) { + WalletState.SIGNING -> Res.string.s_is_signing + WalletState.NOT_SIGNED -> Res.string.s_did_not_sign + else -> Res.string.waiting_for_someone_in_s_to_put_it_to_the_group + }, + group, + ) + ) + } + // Why the group would refuse the request as it stands, said + // before the button that fixes it. docs/member-wallet-delay.md. + wallet.refusedBecause?.let { why -> + item { + Text( + stringResource( + when (why) { + MemberWalletManager.Why.NO_POLICY -> Res.string.s_would_refuse_this_request_asked_before + MemberWalletManager.Why.DELAY_CHANGED -> Res.string.s_has_changed_its_delay_since_you_asked + MemberWalletManager.Why.CLOSED -> Res.string.s_has_stopped_guarding_members_wallets_discard + MemberWalletManager.Why.NOT_THE_GROUPS -> Res.string.s_would_refuse_this_request + }, + group, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + // A closed group takes no new request, so asking again + // could only fail; discarding is what is left. + if (wallet.state != WalletState.SIGNING && wallet.refusedBecause != MemberWalletManager.Why.CLOSED) { + item { + OutlinedButton( + onClick = { viewModel.askAgain(onAsked = {}, onFailure = { notify(couldNotAskAgain) }) }, + enabled = !viewModel.isActionPending.value, + ) { Text(stringResource(Res.string.ask_again)) } + } + } + if (wallet.state != WalletState.SIGNING) { + item { + TextButton(onClick = { confirmingDiscard = true }, enabled = !viewModel.isActionPending.value) { + Text(stringResource(Res.string.discard)) + } + } + } + } + + WalletState.OPEN, WalletState.WATCH_ONLY -> { + item { BalanceCard(walletState) } + + if (wallet.state == WalletState.WATCH_ONLY) { + item { + Text( + stringResource(Res.string.the_key_of_this_wallet_is_on_another_device), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + onSend?.takeIf { wallet.state == WalletState.OPEN && state.canWatch }?.let { send -> + item { SendButton(onClick = { send(wallet.walletId) }) } + } + + when { + !state.canWatch -> item { + Text( + stringResource(Res.string.this_profile_cannot_watch_its_own_coins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + walletState?.receiveAddress == null -> item { + LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_your_coins)) + } + + else -> { + val address = walletState.receiveAddress!! + item { + Card(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text(stringResource(Res.string.receive_address), style = MaterialTheme.typography.titleMedium) + QRCodeView(bip21Uri(address)) + SelectionContainer { Text(text = address, style = MaterialTheme.typography.bodyMedium) } + TextButton(onClick = { + clipboardManager.setText(buildAnnotatedString { append(address) }) + notify(addressCopied) + }) { + Icon(Icons.Default.ContentCopy, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.copy_address)) + } + } + } + } + + item { Text(stringResource(Res.string.coins), style = MaterialTheme.typography.titleMedium) } + if (walletState.utxos.isEmpty()) { + item { EmptyState(message = stringResource(Res.string.nothing_has_been_sent_to_this_wallet_yet)) } + } else { + items(walletState.utxos, key = { it.utxo.outPoint.toString() }) { utxo -> + CoinRow(utxo = utxo, confirmations = walletState.confirmations(utxo)) + } + } + } + } + + if (state.spends.isNotEmpty()) { + item { Text(stringResource(Res.string.your_spends), style = MaterialTheme.typography.titleMedium) } + items(state.spends, key = { "spend-" + it.txid }) { spend -> + ListItem( + headlineContent = { Text(spend.txid, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + stringResource( + when { + spend.confirmedAt != null -> Res.string.confirmed + spend.seenAt != null -> Res.string.in_the_mempool + else -> Res.string.sent_waiting_for_the_network + } + ) + ) + }, + ) + } + } + + if (state.taken.isNotEmpty()) { + item { Text(stringResource(Res.string.taken_by_guardians), style = MaterialTheme.typography.titleMedium) } + items(state.taken, key = { "taken-" + it.txid + it.guardianName }) { line -> + ListItem( + headlineContent = { + Text(stringResource(Res.string.s_took_s_sats_in_s, line.guardianName ?: stringResource(Res.string.a_group), line.amount.grouped(), line.txid)) + } + ) + } + } + + if (wallet.state == WalletState.OPEN) { + item { + TextButton(onClick = { confirmingExport = true }) { + Icon(Icons.Default.Key, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.export_key)) + } + } + } + } + } + + item { + Text( + stringResource(Res.string.if_you_lose_this_device_those_groups_can_still_move_your_coins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } + } + + if (confirmingDiscard) { + AlertDialog( + onDismissRequest = { confirmingDiscard = false }, + title = { Text(stringResource(Res.string.discard_this_wallet_question)) }, + text = { Text(stringResource(Res.string.discarding_forgets_its_key)) }, + confirmButton = { + TextButton(onClick = { + confirmingDiscard = false + viewModel.discard(onDiscarded = onNavigateBack, onFailure = { notify(couldNotDiscard) }) + }) { Text(stringResource(Res.string.discard)) } + }, + dismissButton = { TextButton(onClick = { confirmingDiscard = false }) { Text(stringResource(Res.string.cancel)) } }, + ) + } + + if (confirmingExport) { + AlertDialog( + onDismissRequest = { confirmingExport = false }, + title = { Text(stringResource(Res.string.export_this_wallet_s_key_question)) }, + text = { Text(stringResource(Res.string.whoever_holds_these_descriptors_holds_the_coins)) }, + confirmButton = { + TextButton(onClick = { + confirmingExport = false + viewModel.exportKey() + }) { Text(stringResource(Res.string.show_key)) } + }, + dismissButton = { TextButton(onClick = { confirmingExport = false }) { Text(stringResource(Res.string.cancel)) } }, + ) + } + + viewModel.exported?.let { (receive, change) -> + AlertDialog( + onDismissRequest = viewModel::hideKey, + title = { Text(stringResource(Res.string.export_key)) }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + listOf(Res.string.receive_descriptor to receive, Res.string.change_descriptor to change).forEach { (name, descriptor) -> + Text(stringResource(name), style = MaterialTheme.typography.titleSmall) + SelectionContainer { Text(descriptor, style = MaterialTheme.typography.bodySmall) } + TextButton(onClick = { + clipboardManager.setText(buildAnnotatedString { append(descriptor) }) + notify(copied) + }) { + Icon(Icons.Default.ContentCopy, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.copy)) + } + } + } + }, + confirmButton = { TextButton(onClick = viewModel::hideKey) { Text(stringResource(Res.string.close)) } }, + ) + } +} + +@Composable +private fun SendButton(onClick: () -> Unit) { + Button(onClick = onClick) { + Icon(Icons.Default.Send, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.send)) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt new file mode 100644 index 00000000..be392384 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt @@ -0,0 +1,252 @@ +package com.machankura.bennu.compose.ui.composable + +import bennu.composeapp.generated.resources.this_group_has_stopped_guarding_members_wallets +import bennu.composeapp.generated.resources.this_group_doesn_t_guard_members_wallets +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material.icons.filled.Groups +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +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.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_group +import bennu.composeapp.generated.resources.a_wallet_only_you_can_spend_from_guarded_by_s +import bennu.composeapp.generated.resources.ask_s +import bennu.composeapp.generated.resources.ask_the_group_for_its_key +import bennu.composeapp.generated.resources.asked_for_the_group_s_key +import bennu.composeapp.generated.resources.asked_s_to_guard_a_wallet +import bennu.composeapp.generated.resources.choose_a_group_to_guard_it +import bennu.composeapp.generated.resources.couldn_t_ask_the_group_to_guard_a_wallet +import bennu.composeapp.generated.resources.if_you_lose_this_device_those_groups_can_still_move_your_coins +import bennu.composeapp.generated.resources.label_optional +import bennu.composeapp.generated.resources.member_wallets_are_not_offered_on_this_network +import bennu.composeapp.generated.resources.members_of_those_groups_will_see_this_wallet +import bennu.composeapp.generated.resources.new_guarded_wallet +import bennu.composeapp.generated.resources.only_a_group_can_guard_a_wallet +import bennu.composeapp.generated.resources.s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you +import bennu.composeapp.generated.resources.s_and_the_group_above_it_can_take_any_coin_without_asking_you +import bennu.composeapp.generated.resources.s_can_take_any_coin_without_asking_you +import bennu.composeapp.generated.resources.this_device_does_not_know_what_this_group_signs_with +import bennu.composeapp.generated.resources.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet +import bennu.composeapp.generated.resources.this_profile_cannot_sign_a_request +import bennu.composeapp.generated.resources.this_profile_cannot_watch_its_own_coins +import bennu.composeapp.generated.resources.none_of_your_groups_guards_members_wallets_yet +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.NewMemberWalletViewModel +import com.machankura.bennu.compose.ui.view.state.NewMemberWalletUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import org.jetbrains.compose.resources.stringResource + +/** + * Asking a group to guard a wallet only this member can spend from. + * + * A consent screen first and a form second: what the member gives up -- the + * groups that can take their coins, and see them -- is said before the one + * button, in the words `docs/member-guarded-wallets.md` uses. Nothing leaves the + * device until that button: the key is made, the leaves worked out and the key + * stored, and only then is the group asked. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun NewMemberWalletScreen( + activeUserPublicKey: HexKey, + chatRoomId: String?, + chain: Chain, + canWatch: Boolean, + initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading, + memberWalletRepository: MemberWalletRepository, + onNavigateBack: () -> Unit, +) { + val viewModel: NewMemberWalletViewModel = viewModel( + factory = NewMemberWalletViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + chain = chain, + canWatch = canWatch, + initialUIState = initialUIState, + memberWalletRepository = memberWalletRepository, + ) + ) + + LaunchedEffect(true) { + if (initialUIState == NewMemberWalletUIState.Loading) viewModel.initiate() + } + + // Read above the handlers: the notifier and the strings are composable and + // an onClick is not. The caller's scope, so "asked" outlives the screen + // navigating away. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAsk = stringResource(Res.string.couldn_t_ask_the_group_to_guard_a_wallet) + val fallbackName = stringResource(Res.string.a_group) + val chosenName = (viewModel.uiState as? NewMemberWalletUIState.Chosen)?.room?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: fallbackName + val asked = stringResource(Res.string.asked_s_to_guard_a_wallet, chosenName) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.new_guarded_wallet)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + NewMemberWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + // Nothing to retry: the group came from a navigation argument. + is NewMemberWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) + + is NewMemberWalletUIState.Picking -> if (state.groups.isEmpty()) { + EmptyState( + modifier = Modifier.padding(padding).readableContent(), + message = stringResource(Res.string.none_of_your_groups_guards_members_wallets_yet), + icon = Icons.Default.Groups, + ) + } else { + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + item { + Text(stringResource(Res.string.choose_a_group_to_guard_it), style = MaterialTheme.typography.titleMedium) + } + items(state.groups, key = { it.room.chatRoom.id }) { choice -> + ListItem( + modifier = Modifier.clickable { viewModel.pick(choice.room.chatRoom.id) }.minimumInteractiveComponentSize(), + leadingContent = { Icon(Icons.Default.Groups, contentDescription = Decorative) }, + headlineContent = { + Text(choice.room.chatRoom.subject?.takeIf { it.isNotBlank() } ?: fallbackName, maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + supportingContent = choice.refusal?.let { refusal -> { Text(refusalText(refusal)) } }, + ) + } + } + } + + is NewMemberWalletUIState.Chosen -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Text( + text = stringResource(Res.string.a_wallet_only_you_can_spend_from_guarded_by_s, chosenName), + style = MaterialTheme.typography.titleLarge, + ) + + state.delays?.let { delays -> Text(reachText(chosenName, delays, chain), style = MaterialTheme.typography.bodyLarge) } + Text(stringResource(Res.string.members_of_those_groups_will_see_this_wallet), style = MaterialTheme.typography.bodyLarge) + Text( + stringResource(Res.string.if_you_lose_this_device_those_groups_can_still_move_your_coins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + when (val refusal = state.refusal) { + null -> { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + value = viewModel.label.value, + onValueChange = viewModel::setLabel, + label = { Text(stringResource(Res.string.label_optional)) }, + singleLine = true, + ) + Button( + onClick = { viewModel.ask(onAsked = { notify(asked); onNavigateBack() }, onFailure = { notify(couldNotAsk) }) }, + enabled = !viewModel.isActionPending.value, + ) { + Text(stringResource(Res.string.ask_s, chosenName)) + } + } + + MemberWalletManager.Refusal.KEY_UNKNOWN -> { + Text(refusalText(refusal), color = MaterialTheme.colorScheme.onSurfaceVariant) + if (state.askedForKey) { + Text(stringResource(Res.string.asked_for_the_group_s_key), color = MaterialTheme.colorScheme.onSurfaceVariant) + } else { + TextButton(onClick = viewModel::askForGroupKey) { Text(stringResource(Res.string.ask_the_group_for_its_key)) } + } + } + + else -> Text(refusalText(refusal), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + } + } +} + +/** + * Who can take the member's coins, and after how long: the group alone, the + * group and its parent, or the group and N above it, [delays] nearest first. + * Each guardian's own, since every group above chose its own -- + * `docs/guardian-delay.md`. + */ +@Composable +internal fun reachText(groupName: String, delays: List, chain: Chain?): String = when (delays.size) { + 0 -> "" + 1 -> stringResource(Res.string.s_can_take_any_coin_without_asking_you, groupName, delayText(delays[0], chain)) + 2 -> stringResource( + Res.string.s_and_the_group_above_it_can_take_any_coin_without_asking_you, + groupName, delayText(delays[0], chain), delayText(delays[1], chain), + ) + else -> stringResource( + Res.string.s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you, + groupName, delayText(delays[0], chain), delays.size - 1, delayText(delays.drop(1).min(), chain), + ) +} + +@Composable +private fun refusalText(refusal: MemberWalletManager.Refusal): String = stringResource( + when (refusal) { + MemberWalletManager.Refusal.CANNOT_SIGN -> Res.string.this_profile_cannot_sign_a_request + MemberWalletManager.Refusal.NOT_A_GROUP -> Res.string.only_a_group_can_guard_a_wallet + MemberWalletManager.Refusal.KEY_UNKNOWN -> Res.string.this_device_does_not_know_what_this_group_signs_with + MemberWalletManager.Refusal.GUARDIANS_UNREADABLE -> Res.string.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet + MemberWalletManager.Refusal.NOT_ON_THIS_NETWORK -> Res.string.member_wallets_are_not_offered_on_this_network + MemberWalletManager.Refusal.CANNOT_WATCH -> Res.string.this_profile_cannot_watch_its_own_coins + MemberWalletManager.Refusal.NOT_OFFERED -> Res.string.this_group_doesn_t_guard_members_wallets + MemberWalletManager.Refusal.CLOSED -> Res.string.this_group_has_stopped_guarding_members_wallets + } +) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreen.kt index 087150f4..7300f628 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreen.kt @@ -1,5 +1,25 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.ui.view.model.PersonGuardedWalletsViewModel +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute +import bennu.composeapp.generated.resources.wallets_your_groups_guard +import bennu.composeapp.generated.resources.guarded_by_s +import bennu.composeapp.generated.resources.a_group +import bennu.composeapp.generated.resources.a_group_below_s +import bennu.composeapp.generated.resources.another_group +import bennu.composeapp.generated.resources.guardian_after +import bennu.composeapp.generated.resources.spend_from_s_as_s +import bennu.composeapp.generated.resources.the_wallet_guarded_by_s +import com.machankura.bennu.compose.ui.composable.widgets.delayText +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import bennu.composeapp.generated.resources.spend +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material3.ListItem +import androidx.compose.material3.Icon +import com.machankura.bennu.compose.ui.composable.widgets.Decorative import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize @@ -14,7 +34,6 @@ import androidx.compose.material3.BottomAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.LoadingIndicator -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost @@ -46,7 +65,6 @@ import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative import com.machankura.bennu.compose.ui.composable.widgets.EmptyState import com.machankura.bennu.compose.ui.composable.widgets.ErrorState import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator @@ -91,7 +109,16 @@ fun ProfilePreviewScreen( chatRepository: ChatRepository, onStartChat: (Route) -> Unit, onNavigateBack: () -> Unit, + // The person's guarded wallets that this profile's groups guard + // (docs/member-guarded-wallets.md, Phase 11), and where a spend from one goes. + memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, + onNavigateToRoute: (Route) -> Unit = {}, ) { + val personWalletsViewModel: PersonGuardedWalletsViewModel = viewModel( + factory = PersonGuardedWalletsViewModel.factory(ownerPublicKey = profilePublicKey, memberWalletRepository = memberWalletRepository), + ) + LaunchedEffect(true) { personWalletsViewModel.initiate() } + val profilePreviewViewModel: ProfilePreviewViewModel = viewModel( factory = ProfilePreviewViewModel.factory( activeUserPublicKey = activeUserPublicKey, @@ -187,6 +214,24 @@ fun ProfilePreviewScreen( onRetry = { profilePreviewViewModel.retry() }, ) } + + // One's own wallets are listed on one's own profile, with their + // keys; this is the guardians' view of somebody else's. + if (profilePublicKey != activeUserPublicKey && personWalletsViewModel.rows.isNotEmpty()) { + GuardedByYourGroups( + wallets = personWalletsViewModel.rows, + onSpend = { holder -> + onNavigateToRoute( + GroupSendRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = holder.wallet.ancestorChatRoomId, + relayHint = null, + guardedChatRoomId = holder.wallet.descendantChatRoomId, + ) + ) + }, + ) + } } } @@ -223,6 +268,58 @@ fun ProfilePreviewScreen( } } +/** + * The person's guarded wallets as this profile's groups hold them: one entry per + * wallet, saying which group directly guards it, and under it each group here + * holding a leaf in it, with that leaf's delay and -- where this device holds a + * share of that group's key -- the way to spend through it, which is the + * guardian spend the group's wallet screen already offers. + * `docs/member-wallet-guarding-group.md`, D7. + */ +@Composable +private fun GuardedByYourGroups( + wallets: List, + onSpend: (MemberWalletManager.GuardedHere) -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(stringResource(Res.string.wallets_your_groups_guard), style = MaterialTheme.typography.titleMedium) + wallets.forEach { wallet -> + val guardian = wallet.guardianName + ?: wallet.below?.let { stringResource(Res.string.a_group_below_s, it) } + ?: stringResource(Res.string.another_group) + val guardedBy = stringResource(Res.string.guarded_by_s, guardian) + ListItem( + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + // Named by its label, or with none by the group that guards it. + headlineContent = { Text(wallet.label ?: guardedBy) }, + supportingContent = wallet.label?.let { { Text(guardedBy) } }, + ) + wallet.holders.forEach { holder -> + val holderName = holder.holderName ?: stringResource(Res.string.a_group) + val spendLabel = stringResource( + Res.string.spend_from_s_as_s, + wallet.label ?: stringResource(Res.string.the_wallet_guarded_by_s, guardian), + holderName, + ) + ListItem( + // Under its wallet, so the holders read as the wallet's. + modifier = Modifier.padding(start = MaterialTheme.spacing.containerPadding), + headlineContent = { + Text(stringResource(Res.string.guardian_after, holderName, delayText(holder.wallet.delay, holder.wallet.chain))) + }, + trailingContent = if (holder.canSpend) { + { + TextButton(onClick = { onSpend(holder) }, modifier = Modifier.semantics { contentDescription = spendLabel }) { + Text(stringResource(Res.string.spend)) + } + } + } else null, + ) + } + } + } +} + /** * Who this is: leading-aligned, because rows with an avatar align to a leading edge * and centring is for a block that is the only thing on the screen, which this is diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt deleted file mode 100644 index 0dd670a3..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt +++ /dev/null @@ -1,423 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupEventProposal -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.text.ProposedEvent -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.ProposeGroupEventViewModel -import com.machankura.bennu.compose.ui.view.state.ProposeGroupEventUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_post_needs_something_to_say -import bennu.composeapp.generated.resources.an_event_is_a_json_object -import bennu.composeapp.generated.resources.an_event_needs_a_kind -import bennu.composeapp.generated.resources.content_must_be_text -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_event -import bennu.composeapp.generated.resources.eg_kind_1_tags_content -import bennu.composeapp.generated.resources.kind_n -import bennu.composeapp.generated.resources.kind_n_has_nowhere_to_go_on_this_screen -import bennu.composeapp.generated.resources.paste_an_unsigned_event_for_the_group_to_sign -import bennu.composeapp.generated.resources.propose_event -import bennu.composeapp.generated.resources.tags_must_be_a_list_of_lists_of_strings -import bennu.composeapp.generated.resources.that_is_not_json -import bennu.composeapp.generated.resources.the_content_is_not_a_profile -import bennu.composeapp.generated.resources.the_group_signs_an_event_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_an_event -import bennu.composeapp.generated.resources.unsigned_event -import bennu.composeapp.generated.resources.what_the_group_would_sign -import org.jetbrains.compose.resources.stringResource - -/** - * An unsigned event, pasted, for the group to sign. - * - * The typed editors each build one kind of statement; this takes any of the - * kinds the group's screen can show, as JSON, the way another tool prints one. - * Above the paste is what the group would be signing, read back the way the - * signing screen will describe it, so a member sees "Post · gm" rather than a - * wall of brackets before deciding -- and sees why the group will - * not be asked when the paste is something it could never show. - * - * The byline is the group's, as on the post composer and for the same reason: - * whatever is pasted goes out in the group's name, and a paste that names some - * other `pubkey` goes out in the group's name anyway. The explanatory line says - * so, because a paste with a `pubkey` in it is the one case where a member could - * reasonably expect otherwise. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun ProposeGroupEventScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialProposeGroupEventUIState: ProposeGroupEventUIState = ProposeGroupEventUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val proposeGroupEventViewModel: ProposeGroupEventViewModel = viewModel( - factory = ProposeGroupEventViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialProposeGroupEventUIState = initialProposeGroupEventUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in the click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_event) - - ScreenStateTransition(proposeGroupEventViewModel.proposeGroupEventUIState) { uiState -> - when (val proposeGroupEventUIState = uiState) { - is ProposeGroupEventUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState(message = proposeGroupEventUIState.message, onRetry = null) - } - - is ProposeGroupEventUIState.Loaded -> { - val eventFieldState = rememberTextFieldState() - val canSign = proposeGroupEventUIState.canSign - - // Read on every change. A paste is a few kilobytes at most and the - // reading is one JSON parse, so this is cheaper than the debounce - // that would hide the answer for a beat after the paste. - val json = eventFieldState.text.toString() - val reading = remember(json) { - json.takeIf { it.isNotBlank() }?.let(GroupEventProposal::read) - } - - // imePadding: this screen is a text field the size of the screen, - // and without it the software keyboard covers what is being pasted. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(text = stringResource(Res.string.propose_event)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_event), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose event") }, - enabled = canSign, - onClick = { - proposeGroupEventViewModel.proposeEvent( - localChatRoom = proposeGroupEventUIState.localChatRoom, - json = eventFieldState.text.toString(), - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. Nothing has been - // signed yet -- the event lands when - // a quorum signs -- so landing on a - // screen that does not show it would - // read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // The reason is already under the paste; - // pressing the button anyway is answered - // rather than ignored, and the paste - // stays. Same on a failure to propose. - onRefused = {}, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - // Whose name this goes out in, said before anything is - // pasted. It is the group's, whatever the paste says. - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - ProfileAvatar( - size = MaterialTheme.spacing.space500, - publicKey = chatRoomId, - picture = proposeGroupEventUIState.groupNostrProfile?.picture(), - name = proposeGroupEventUIState.groupNostrProfile?.name() - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - Text( - text = proposeGroupEventUIState.groupNostrProfile?.name() - ?: proposeGroupEventUIState.localChatRoom.chatRoom.subject - ?: chatRoomId.take(16), - style = MaterialTheme.typography.titleSmall, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.paste_an_unsigned_event_for_the_group_to_sign - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - Text( - text = stringResource( - Res.string.the_group_signs_an_event_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_an_event - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - when (reading) { - null -> Unit - is GroupEventProposal.Ready -> ProposalPreview(reading) - is GroupEventProposal.Refused -> RefusalNotice(reading) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth().weight(1f) - .background(BottomAppBarDefaults.containerColor), - state = eventFieldState, - // The paste grows into the screen rather than scrolling - // inside three lines, and is set in a monospace face: - // it is JSON, and a bracket that does not line up is - // the kind of thing a member is looking for in it. - lineLimits = TextFieldLineLimits.MultiLine(), - textStyle = TextStyle(fontFamily = FontFamily.Monospace), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - label = { Text(stringResource(Res.string.unsigned_event)) }, - placeholder = { - Text( - text = stringResource(Res.string.eg_kind_1_tags_content), - fontFamily = FontFamily.Monospace - ) - }, - isError = reading is GroupEventProposal.Refused - ) - } - } - } - - ProposeGroupEventUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - Text( - text = stringResource(Res.string.propose_event), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialProposeGroupEventUIState == ProposeGroupEventUIState.Loading) { - proposeGroupEventViewModel.initiateProposeGroupEvent() - } - } -} - -/** - * What the group would sign, said the way the signing screen will say it. - * - * `ProposedEvent.summarize` rather than a description of this screen's own, so - * that what a member reads here before proposing is word for word what every - * other member reads before signing. Two descriptions of one event would drift. - */ -@Composable -private fun ProposalPreview(ready: GroupEventProposal.Ready) { - val summary = ProposedEvent.summarize(ready.preview()) - - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = stringResource(Res.string.what_the_group_would_sign), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Text( - text = stringResource(Res.string.kind_n, ready.kind.toString()) + " · " + summary.label, - style = MaterialTheme.typography.titleSmall - ) - - // Capped, because a kind:1's detail is the whole post and the paste - // under this card is the thing the screen is for. - Text( - text = summary.detail, - style = MaterialTheme.typography.bodyMedium, - maxLines = 6, - overflow = TextOverflow.Ellipsis - ) - } - } -} - -/** - * Why the group will not be asked, under the paste it is about. - * - * Named rather than silent: a button that does nothing for a paste it refuses is - * indistinguishable from a missed tap. - */ -@Composable -private fun RefusalNotice(refused: GroupEventProposal.Refused) { - Text( - text = when (refused) { - GroupEventProposal.Refused.NotJson -> stringResource(Res.string.that_is_not_json) - GroupEventProposal.Refused.NotAnObject -> stringResource(Res.string.an_event_is_a_json_object) - GroupEventProposal.Refused.NoKind -> stringResource(Res.string.an_event_needs_a_kind) - is GroupEventProposal.Refused.KindNotAccepted -> stringResource( - Res.string.kind_n_has_nowhere_to_go_on_this_screen, - refused.kind.toString(), - GroupEventProposal.ACCEPTED_KINDS.sorted().joinToString() - ) - GroupEventProposal.Refused.TagsMalformed -> - stringResource(Res.string.tags_must_be_a_list_of_lists_of_strings) - GroupEventProposal.Refused.ContentNotText -> stringResource(Res.string.content_must_be_text) - GroupEventProposal.Refused.ProfileUnreadable -> - stringResource(Res.string.the_content_is_not_a_profile) - GroupEventProposal.Refused.PostBlank -> stringResource(Res.string.a_post_needs_something_to_say) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) -} - -@ConformancePreviews -@Composable -private fun ProposeGroupEventScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - ProposeGroupEventScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialProposeGroupEventUIState = ProposeGroupEventUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A group that can sign, so the screen renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt index 6b5de38e..ec17dce2 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt @@ -32,6 +32,9 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable +import androidx.compose.material3.TextButton +import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute +import bennu.composeapp.generated.resources.start_the_key_ceremony import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -223,6 +226,25 @@ fun SelectChatRoomTypeScreen( text = stringResource(Res.string.was_created_but_its_shared_key_ceremony, name), style = MaterialTheme.typography.bodyMedium ) + + // Straight to the one screen that starts a group's own + // ceremony, rather than leaving the member to find it + // through the group's details. + selectChatRoomTypeViewModel.createdChatRoomId.value?.let { createdChatRoomId -> + TextButton( + modifier = Modifier.padding(horizontal = MaterialTheme.spacing.space100), + onClick = { + onNavigateToRoute( + CreateSharedKeyRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = createdChatRoomId, + ) + ) + } + ) { + Text(stringResource(Res.string.start_the_key_ceremony)) + } + } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt index 8eebdb79..0a3275cf 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt @@ -1,5 +1,25 @@ package com.machankura.bennu.compose.ui.composable +import bennu.composeapp.generated.resources.a_coin_the_subgroup_moves_starts_waiting_again +import bennu.composeapp.generated.resources.how_long_before_this_group_can_spend_a_coin +import com.machankura.bennu.compose.ui.composable.widgets.GuardianDelayChooser +import com.machankura.bennu.compose.ui.view.state.onlyGuarded +import com.machankura.bennu.compose.ui.view.state.canGuard +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import bennu.composeapp.generated.resources.this_group_s_guardian_keys_can_t_be_read +import bennu.composeapp.generated.resources.this_group_is_guarded_so_its_subgroups_are_too +import bennu.composeapp.generated.resources.only_the_subgroup_can_spend_from_its_wallet +import bennu.composeapp.generated.resources.this_group_and_the_d_above_it_can_spend +import bennu.composeapp.generated.resources.this_group_can_spend_its_coins_once +import bennu.composeapp.generated.resources.unguarded_wallet +import bennu.composeapp.generated.resources.guarded_wallet +import bennu.composeapp.generated.resources.the_subgroup_s_wallet +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.Role +import androidx.compose.material3.RadioButton +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -70,9 +90,10 @@ import com.machankura.bennu.compose.ui.view.model.SelectSubgroupAdminsViewModel import com.machankura.bennu.compose.ui.view.state.SelectSubgroupAdminsUIState /** - * Picks who runs a subgroup, what it is called, and on what quorum. + * Picks who runs a subgroup, what it is called, on what quorum, and whether its + * wallet is guarded. * - * The three things that cannot be changed later, gathered before anything is + * The four things that cannot be changed later, gathered before anything is * published -- see `SelectSubgroupAdminsViewModel` for why the threshold in * particular has nowhere else to live. */ @@ -81,6 +102,8 @@ import com.machankura.bennu.compose.ui.view.state.SelectSubgroupAdminsUIState fun SelectSubgroupAdminsScreen( activeUserPublicKey: HexKey, parentChatRoomId: String, + /** A failed subgroup ceremony to start from; see `SelectSubgroupAdminsRoute.retrying`. */ + retrying: String? = null, initialUIState: SelectSubgroupAdminsUIState = SelectSubgroupAdminsUIState.Loading, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, @@ -92,6 +115,7 @@ fun SelectSubgroupAdminsScreen( factory = SelectSubgroupAdminsViewModel.factory( activeUserPublicKey = activeUserPublicKey, parentChatRoomId = parentChatRoomId, + retrying = retrying, initialUIState = initialUIState, activeIdentityStateFlow = activeIdentityStateFlow, chatRepository = chatRepository, @@ -271,6 +295,34 @@ fun SelectSubgroupAdminsScreen( onQuorumChange = viewModel::setThreshold ) } + + item { + WalletPolicyChooser( + policy = viewModel.walletPolicy.value, + parentGuardianCount = state.parentGuardians?.size ?: 0, + onlyGuarded = state.onlyGuarded, + canGuard = state.canGuard, + onPolicyChange = viewModel::setWalletPolicy + ) + } + + // The parent's own leaf's delay, and only for a guarded + // subgroup: docs/guardian-delay.md. + if (viewModel.walletPolicy.value == SubgroupWalletPolicy.GUARDED && state.canGuard) { + item { + GuardianDelayChooser( + title = stringResource(Res.string.how_long_before_this_group_can_spend_a_coin), + consequence = stringResource(Res.string.a_coin_the_subgroup_moves_starts_waiting_again), + input = viewModel.guardianDelayInput.value, + delay = viewModel.guardianDelay(), + isCustom = viewModel.isCustomDelay.value, + problem = viewModel.guardianDelayProblem(), + onPreset = viewModel::setGuardianDelay, + onCustom = viewModel::useCustomDelay, + onInput = viewModel::setGuardianDelayInput, + ) + } + } } } } @@ -328,6 +380,92 @@ private fun QuorumStepper( } } +/** + * Whether the subgroup's wallet is guarded -- `docs/subgroup-wallet-policy.md`. + * + * Settled here for the reason the threshold is: it rides the proposal, every + * admin is shown it before joining, and the parent's quorum signs it into the + * certificate, so there is no later screen where it could be changed. + * + * Under a guarded parent both rows still show, with *unguarded* disabled and its + * reason in place of its description. Hiding it would make the picker look like + * an older build's, where nobody decided anything; showing it says a decision was + * made, and by whom. + */ +@Composable +private fun WalletPolicyChooser( + policy: SubgroupWalletPolicy, + parentGuardianCount: Int, + onlyGuarded: Boolean, + canGuard: Boolean, + onPolicyChange: (SubgroupWalletPolicy) -> Unit, +) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(top = MaterialTheme.spacing.space50) + .selectableGroup(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50) + ) { + Text( + text = stringResource(Res.string.the_subgroup_s_wallet), + style = MaterialTheme.typography.titleSmall + ) + + WalletPolicyRow( + title = stringResource(Res.string.guarded_wallet), + // Names the reach the parent is actually granting: itself, and each + // ancestor whose key its own certificate passes on. + description = if (!canGuard) { + stringResource(Res.string.this_group_s_guardian_keys_can_t_be_read) + } else if (parentGuardianCount == 0) { + stringResource(Res.string.this_group_can_spend_its_coins_once) + } else { + stringResource(Res.string.this_group_and_the_d_above_it_can_spend, parentGuardianCount) + }, + isSelected = policy == SubgroupWalletPolicy.GUARDED, + isEnabled = canGuard, + onSelect = { onPolicyChange(SubgroupWalletPolicy.GUARDED) } + ) + WalletPolicyRow( + title = stringResource(Res.string.unguarded_wallet), + description = if (onlyGuarded) { + stringResource(Res.string.this_group_is_guarded_so_its_subgroups_are_too) + } else { + stringResource(Res.string.only_the_subgroup_can_spend_from_its_wallet) + }, + isSelected = policy == SubgroupWalletPolicy.UNGUARDED, + isEnabled = !onlyGuarded, + onSelect = { onPolicyChange(SubgroupWalletPolicy.UNGUARDED) } + ) + } +} + +@Composable +private fun WalletPolicyRow( + title: String, + description: String, + isSelected: Boolean, + isEnabled: Boolean, + onSelect: () -> Unit, +) { + // The card is the target, as the admin rows above are, and the radio button + // beside the title only says which one is chosen. + Card( + modifier = Modifier.fillMaxWidth().semantics { role = Role.RadioButton; selected = isSelected }, + onClick = onSelect, + enabled = isEnabled + ) { + ListItem( + leadingContent = { + RadioButton(selected = isSelected, onClick = null, enabled = isEnabled) + }, + headlineContent = { Text(title) }, + supportingContent = { Text(description) } + ) + } +} + @ConformancePreviews @Composable private fun SelectSubgroupAdminsScreenPreview() { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt deleted file mode 100644 index d6c751fb..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslateChunkScreen.kt +++ /dev/null @@ -1,275 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Add -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.Card -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.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ImplementationPendingRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.TranslateChunkViewModel -import com.machankura.bennu.compose.ui.view.state.TranslateChunkUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.enter_the_translation_for_this_chunk -import bennu.composeapp.generated.resources.original -import bennu.composeapp.generated.resources.propose_translation -import bennu.composeapp.generated.resources.translate_chunk -import bennu.composeapp.generated.resources.translated_text -import bennu.composeapp.generated.resources.translation -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TranslateChunkScreen( - activeUserPublicKey: HexKey, - translationChapterId: String, - chunkId: String, - chatRoomId: String, - relayHint: String?, - initialTranslateChunkUIState: TranslateChunkUIState = TranslateChunkUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val translateChunkViewModel: TranslateChunkViewModel = viewModel( - factory = TranslateChunkViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chunkId = chunkId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslateChunkUIState = initialTranslateChunkUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(translateChunkViewModel.translateChunkUIState) { uiState -> - when (val translateChunkUIState = uiState) { - is TranslateChunkUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = translateChunkUIState.message) - } - } - - is TranslateChunkUIState.Loaded -> { - val translationFieldState = rememberTextFieldState(translateChunkUIState.existingTranslationText) - - // imePadding: this screen has a text field, and without it the software - // keyboard covers whatever is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.translate_chunk)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_translation), - icon = { Icon(Icons.Default.Add, contentDescription = "Propose translation") }, - enabled = translateChunkUIState.canSign, - onClick = { - translateChunkViewModel.proposeTranslation( - localChatRoom = translateChunkUIState.localChatRoom, - originalChunk = translateChunkUIState.originalChunk, - translationField = translationFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back to - // the chapter table. Nothing has been - // translated yet -- the chunk is - // translated when enough members sign -- - // so a table still showing it untranslated - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { - onNavigateToRoute.invoke( - ImplementationPendingRoute("Failed translation") - ) - } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier - .padding(innerPadding) - .readableContent() - .fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (!translateChunkUIState.canSign) { - Text( - text = "This group has no shared key, so it cannot sign a " + - "translation. Run a shared key ceremony first.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) - } - - Text( - text = stringResource(Res.string.original), - style = MaterialTheme.typography.labelMedium - ) - Card { - Text( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - text = translateChunkUIState.originalChunk.text, - style = MaterialTheme.typography.bodyMedium - ) - } - - Text( - text = stringResource(Res.string.translation), - style = MaterialTheme.typography.labelMedium - ) - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = translationFieldState, - label = { Text(stringResource(Res.string.translated_text)) }, - placeholder = { Text(stringResource(Res.string.enter_the_translation_for_this_chunk)) }, - ) - } - } - } - - TranslateChunkUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.translate_chunk), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialTranslateChunkUIState == TranslateChunkUIState.Loading) { - translateChunkViewModel.initiateTranslateChunk() - } - } -} - -@ConformancePreviews -@Composable -private fun TranslateChunkScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - TranslateChunkScreen( - activeUserPublicKey = "", - translationChapterId = "translationChapterId", - chunkId = "chunkId", - chatRoomId = "chatRoomId", - relayHint = null, - initialTranslateChunkUIState = TranslateChunkUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "chatRoomId", - userPublicKey = "", - subject = "Message title", - description = "See something. Say somethin", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = null - ), - ), - originalChunk = MantraChunk( - id = "chunkId", - chapterId = "chapterId", - publicKey = "author", - text = "When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow.", - index = 0, - wordCount = 0, - characterCount = 0, - signature = "", - chatRoomId = "chatRoomId" - ), - existingTranslationText = "", - canSign = true - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt deleted file mode 100644 index 2e04ac4e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationArtifactVersionDetailScreen.kt +++ /dev/null @@ -1,310 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Article -import androidx.compose.material.icons.filled.PlaylistAdd -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationChapterRoute -import com.machankura.bennu.compose.ui.composable.widgets.DetailRow -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.TranslationArtifactVersionDetailViewModel -import com.machankura.bennu.compose.ui.view.state.TranslationArtifactVersionDetailUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.chapters -import bennu.composeapp.generated.resources.details -import bennu.composeapp.generated.resources.no_chapters -import bennu.composeapp.generated.resources.propose -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_so_it_cannot -import bennu.composeapp.generated.resources.translation_detail -import bennu.composeapp.generated.resources.chapter -import bennu.composeapp.generated.resources.chunks_translated -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TranslationArtifactVersionDetailScreen( - activeUserPublicKey: HexKey, - translationArtifactVersionId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationArtifactVersionDetailUIState: TranslationArtifactVersionDetailUIState = TranslationArtifactVersionDetailUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val translationDetailViewModel: TranslationArtifactVersionDetailViewModel = viewModel( - factory = TranslationArtifactVersionDetailViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - translationArtifactVersionId = translationArtifactVersionId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationArtifactVersionDetailUIState = initialTranslationArtifactVersionDetailUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - ScreenStateTransition(translationDetailViewModel.translationDetailUIState) { uiState -> - when (val translationDetailUIState = uiState) { - is TranslationArtifactVersionDetailUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = translationDetailUIState.message) - } - } - - is TranslationArtifactVersionDetailUIState.Loaded -> { - val translation = translationDetailUIState.translation - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(translation.name) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - // Chapters the source version has and this translation - // does not. Above the list rather than after it: a chapter - // that is not here is invisible from a list of the ones - // that are. - val localChatRoom = translationDetailUIState.localChatRoom - val missingChapters = translationDetailUIState.missingChapters - - if (missingChapters.isNotEmpty()) { - item { - Card { - ListItem( - leadingContent = { - Icon( - Icons.Default.PlaylistAdd, - contentDescription = "Chapters missing from this translation" - ) - }, - headlineContent = { - Text( - "${missingChapters.size} " + - (if (missingChapters.size == 1) "chapter is" else "chapters are") + - " not in this translation yet" - ) - }, - supportingContent = { - Text( - if (!translationDetailUIState.canSign) { - stringResource(Res.string.this_group_has_no_shared_key_so_it_cannot) - } else { - "They were signed into the artifact after this " + - "translation. Ask the group to add them so they " + - "can be translated." - } - ) - }, - trailingContent = { - TextButton( - enabled = localChatRoom != null && - translationDetailUIState.canSign && - !translationDetailViewModel.isActionPending.value, - onClick = { - if (localChatRoom == null) return@TextButton - - translationDetailViewModel.catchUpMissingChapters( - localChatRoom = localChatRoom, - missingChapters = missingChapters, - onSuccess = { sessionId -> - onNavigateToRoute.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = {} - ) - } - ) { - Text(stringResource(Res.string.propose)) - } - } - ) - } - } - - item { HorizontalDivider() } - } - - // Chapters with translation progress - item { - Text( - text = stringResource(Res.string.chapters), - style = MaterialTheme.typography.labelMedium - ) - } - if (translationDetailUIState.chapters.isEmpty()) { - item { Text(stringResource(Res.string.no_chapters)) } - } else { - items( - items = translationDetailUIState.chapters, - key = { progress -> progress.chapter.id } - ) { progress -> - Card( - onClick = { - onNavigateToRoute.invoke( - TranslationChapterRoute( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = progress.chapter.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - ListItem( - leadingContent = { - Icon( - Icons.Default.Article, - contentDescription = "Chapter" - ) - }, - headlineContent = { Text(stringResource(Res.string.chapter, progress.chapter.index)) }, - supportingContent = { - Text(stringResource(Res.string.chunks_translated, progress.translatedChunks, progress.totalChunks)) - } - ) - } - } - } - - item { HorizontalDivider() } - - // Details - item { - Text( - text = stringResource(Res.string.details), - style = MaterialTheme.typography.labelMedium - ) - } - item { - Card { - DetailRow(label = "Name", value = translation.name) - DetailRow(label = "Dialect", value = translation.dialectId) - DetailRow(label = "Visibility", value = translation.visibility) - DetailRow(label = "License", value = translation.license) - DetailRow(label = "Source version", value = translation.artifactVersionId) - DetailRow(label = "Author", value = translation.publicKey) - DetailRow(label = "Created", value = translation.createdAt.toString()) - } - } - } - } - } - - TranslationArtifactVersionDetailUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.translation_detail), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialTranslationArtifactVersionDetailUIState == TranslationArtifactVersionDetailUIState.Loading) { - translationDetailViewModel.initiateTranslationArtifactVersionDetail() - } - } -} - -@ConformancePreviews -@Composable -private fun TranslationArtifactVersionDetailScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - TranslationArtifactVersionDetailScreen( - activeUserPublicKey = "", - translationArtifactVersionId = "translationId", - chatRoomId = "chatRoomId", - relayHint = null, - initialTranslationArtifactVersionDetailUIState = TranslationArtifactVersionDetailUIState.Loaded( - translation = MantraTranslationArtifactVersion( - id = "translationId", - publicKey = "author", - artifactVersionId = "versionId", - dialectId = "dialectId", - name = "Sesotho", - visibility = "private", - license = "cc", - signature = "", - chatRoomId = "chatRoomId" - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt deleted file mode 100644 index 2c1a0b88..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/TranslationChapterScreen.kt +++ /dev/null @@ -1,279 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.IntrinsicSize -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ChevronRight -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.VerticalDivider -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslateChunkRoute -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.TranslationChapterViewModel -import com.machankura.bennu.compose.ui.view.state.ChunkTranslationPair -import com.machankura.bennu.compose.ui.view.state.TranslationChapterUIState -import com.machankura.bennu.compose.ui.theme.spacing -import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource -import bennu.composeapp.generated.resources.chapter_translation -import bennu.composeapp.generated.resources.this_chapter_has_no_chunks -import androidx.compose.material3.SnackbarHost -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TranslationChapterScreen( - activeUserPublicKey: HexKey, - translationChapterId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationChapterUIState: TranslationChapterUIState = TranslationChapterUIState.Loading, - mantraRepository: MantraRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val translationChapterViewModel: TranslationChapterViewModel = viewModel( - factory = TranslationChapterViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationChapterUIState = initialTranslationChapterUIState, - mantraRepository = mantraRepository, - ) - ) - - ScreenStateTransition(translationChapterViewModel.translationChapterUIState) { uiState -> - when (val translationChapterUIState = uiState) { - is TranslationChapterUIState.Error -> { - Column( - modifier = Modifier.fillMaxWidth(), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = translationChapterUIState.message) - } - } - - is TranslationChapterUIState.Loaded -> { - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.chapter_translation)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { innerPadding -> - LazyColumn( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - // Header row: dialect names. - item { - TableRow( - left = { - Text( - text = translationChapterUIState.originalDialectName, - fontWeight = FontWeight.Bold - ) - }, - right = { - Text( - text = translationChapterUIState.translationDialectName, - fontWeight = FontWeight.Bold - ) - }, - ) - HorizontalDivider() - } - - if (translationChapterUIState.rows.isEmpty()) { - item { - Box( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - contentAlignment = Alignment.Center - ) { - Text(stringResource(Res.string.this_chapter_has_no_chunks)) - } - } - } else { - items( - items = translationChapterUIState.rows, - key = { pair -> pair.originalChunk.id } - ) { pair -> - ChunkTranslationRow( - pair = pair, - onClick = { - onNavigateToRoute.invoke( - TranslateChunkRoute( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chunkId = pair.originalChunk.id, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - HorizontalDivider() - } - } - } - } - } - - TranslationChapterUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space250) - ) { - Spacer(modifier = Modifier.weight(1f)) - Text( - text = stringResource(Res.string.chapter_translation), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - LoadingDataIndicator(fillScreen = false) - Spacer(modifier = Modifier.weight(2f)) - } - } - } - } - - LaunchedEffect(true) { - if (initialTranslationChapterUIState == TranslationChapterUIState.Loading) { - translationChapterViewModel.initiateTranslationChapter() - } - } -} - -@Composable -private fun ChunkTranslationRow( - pair: ChunkTranslationPair, - onClick: () -> Unit, -) { - val translated = pair.translationChunk?.text?.takeIf { it.isNotBlank() } - TableRow( - left = { Text(pair.originalChunk.text) }, - // The whole translation cell opens the chunk translation editor. When - // there is no translation yet, the original text is shown greyed out as - // a placeholder. It stays plain text, laid out like the original cell - // beside it, rather than a button with its own shape and padding. - rightModifier = Modifier.minimumInteractiveComponentSize() - .clickable(onClick = onClick), - right = { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - modifier = Modifier.weight(1f), - text = translated ?: pair.originalChunk.text, - color = if (translated != null) { - MaterialTheme.colorScheme.onSurface - } else { - MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) - } - ) - Icon( - Icons.Default.ChevronRight, - contentDescription = "Translate this chunk", - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - }, - ) -} - -@Composable -private fun TableRow( - left: @Composable () -> Unit, - right: @Composable () -> Unit, - rightModifier: Modifier = Modifier, -) { - Row( - modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min) - ) { - Box(modifier = Modifier.weight(1f).padding(MaterialTheme.spacing.space150)) { left() } - VerticalDivider(modifier = Modifier.fillMaxHeight()) - Box(modifier = Modifier.weight(1f).then(rightModifier).padding(MaterialTheme.spacing.space150)) { right() } - } -} - -@ConformancePreviews -@Composable -private fun TranslationChapterScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - TranslationChapterScreen( - activeUserPublicKey = "", - translationChapterId = "translationChapterId", - chatRoomId = "chatRoomId", - relayHint = null, - initialTranslationChapterUIState = TranslationChapterUIState.Loaded( - originalDialectName = "English", - translationDialectName = "Sesotho", - rows = listOf( - ChunkTranslationPair( - originalChunk = sampleChunk("c1", "When he was nearly thirteen, my brother Jem got his arm badly broken."), - translationChunk = null - ), - ChunkTranslationPair( - originalChunk = sampleChunk("c2", "When enough years had gone by to enable us to look back on them..."), - translationChunk = null - ), - ) - ), - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {} - ) - } - } -} - -private fun sampleChunk(id: String, text: String) = MantraChunk( - id = id, - chapterId = "chapterId", - publicKey = "author", - text = text, - index = 0, - wordCount = 0, - characterCount = 0, - signature = "", - chatRoomId = "chatRoomId" -) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 4707a5a3..658732b2 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -21,6 +21,8 @@ import com.machankura.bennu.compose.ui.composable.IcebergCeremonyScreen import com.machankura.bennu.compose.database.repository.DatabaseGroupLightningRepository import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.wallet.GroupChainClients +import com.machankura.bennu.compose.ui.composable.MemberWalletPolicyScreen +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute import com.machankura.bennu.compose.ui.composable.GroupSendScreen import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.fillMaxSize @@ -61,19 +63,12 @@ import com.machankura.bennu.compose.ui.composable.ChatRoomDetailScreen import com.machankura.bennu.compose.ui.composable.ChatRoomMessagingScreen import com.machankura.bennu.compose.ui.composable.CreateProfileScreen import com.machankura.bennu.compose.ui.composable.DkgJoinApprovalScreen +import com.machankura.bennu.compose.ui.composable.CreateSharedKeyScreen import com.machankura.bennu.compose.ui.composable.DkgRitualScreen import com.machankura.bennu.compose.ui.composable.DkgRound1ApprovalScreen import com.machankura.bennu.compose.ui.composable.DkgRound2ApprovalScreen -import com.machankura.bennu.compose.ui.composable.EditGroupNostrProfileScreen -import com.machankura.bennu.compose.ui.composable.AddGroupPostScreen -import com.machankura.bennu.compose.ui.composable.BroadcastGroupSignedEventScreen -import com.machankura.bennu.compose.ui.composable.ProposeGroupEventScreen -import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen -import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen -import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupWalletScreen import com.machankura.bennu.compose.ui.composable.GroupWalletAddressesScreen -import com.machankura.bennu.compose.ui.composable.GroupPostsScreen import com.machankura.bennu.compose.ui.composable.HomeScreen import com.machankura.bennu.compose.ui.composable.ImplementationPendingScreen import com.machankura.bennu.compose.ui.composable.KeyPackageManagementScreen @@ -107,6 +102,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomDeta import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgJoinApprovalRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRitualRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRound1ApprovalRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRound2ApprovalRoute @@ -164,42 +160,22 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.repository.DatabaseMantraRepository -import com.machankura.bennu.compose.ui.composable.AddArtifactScreen -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddArtifactRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddDialectRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroupEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.NewMemberWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberSendRoute +import com.machankura.bennu.compose.ui.composable.MemberSendScreen +import com.machankura.bennu.compose.ui.composable.MemberWalletScreen +import com.machankura.bennu.compose.ui.composable.NewMemberWalletScreen +import com.machankura.bennu.compose.database.repository.DatabaseMemberWalletRepository import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddChapterRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddTranslationRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ArtifactDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ChapterDetailRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslateChunkRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationChapterRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.TranslationArtifactVersionDetailRoute -import com.machankura.bennu.compose.ui.composable.ArtifactDetailScreen -import com.machankura.bennu.compose.ui.composable.AddChapterScreen -import com.machankura.bennu.compose.ui.composable.AddDialectScreen import com.machankura.bennu.compose.ui.composable.FrostSigningScreen import com.machankura.bennu.compose.ui.composable.ProposalListScreen -import com.machankura.bennu.compose.ui.composable.AddTranslationArtifactVersionScreen -import com.machankura.bennu.compose.ui.composable.ChapterDetailScreen -import com.machankura.bennu.compose.ui.composable.TranslateChunkScreen -import com.machankura.bennu.compose.ui.composable.TranslationChapterScreen -import com.machankura.bennu.compose.ui.composable.TranslationArtifactVersionDetailScreen @Composable fun BennuNavHost( @@ -266,14 +242,15 @@ fun BennuNavHost( ) } - val databaseMarmotRepository = remember { - DatabaseMarmotRepository( + val databaseMemberWalletRepository = remember { + DatabaseMemberWalletRepository( database = auxDatabaseManager.auxDatabase, - applicationIOScope + activeIdentity = sovereignWalletViewModel.activeIdentity, ) } - val databaseMantraRepository = remember { - DatabaseMantraRepository( + + val databaseMarmotRepository = remember { + DatabaseMarmotRepository( database = auxDatabaseManager.auxDatabase, applicationIOScope ) @@ -703,6 +680,7 @@ fun BennuNavHost( SelectSubgroupAdminsScreen( activeUserPublicKey = route.activeUserPublicKey, parentChatRoomId = route.parentChatRoomId, + retrying = route.retrying, activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, chatRepository = databaseChatRepository, dkgRepository = databaseDkgRepository, @@ -775,6 +753,32 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + CreateSharedKeyScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, + chatRepository = databaseChatRepository, + dkgRepository = databaseDkgRepository, + // Replaces this screen with the ceremony, whether it was just + // opened or was already there, so back from the ceremony goes + // wherever the member came from rather than to a second offer. + onCeremonyOpened = { dkgSessionId -> + navController.navigate( + DkgRitualRoute( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + dkgSessionId = dkgSessionId + ) + ) { + popUpTo { inclusive = true } + } + }, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1048,6 +1052,8 @@ fun BennuNavHost( ) }, signOut = signOutOfReadOnlyIdentity, + memberWalletRepository = databaseMemberWalletRepository, + wallets = groupOnchainWallets, ) } composable { backStackEntry -> @@ -1204,7 +1210,7 @@ fun BennuNavHost( relayHint = route.relayHint, nostrRepository = databaseNostrRepository, chatRepository = databaseChatRepository, - mantraRepository = databaseMantraRepository, + memberWalletRepository = databaseMemberWalletRepository, onNavigateToRoute = { actionRoute -> navController.navigate( route = actionRoute @@ -1267,99 +1273,6 @@ fun BennuNavHost( }, ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddArtifactScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - mantraRepository = databaseMantraRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this add screen so back returns to the group rather - // than to a form whose proposal has already gone out. - navController.navigate( - route = signingRoute - ) { - popUpTo(route) { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddDialectScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - nostrRepository = databaseNostrRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this add screen so back returns to the group rather - // than to a form whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupNostrProfileScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupRelaysScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1379,6 +1292,67 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + MemberWalletScreen( + activeUserPublicKey = route.activeUserPublicKey, + walletId = route.walletId, + memberWalletRepository = databaseMemberWalletRepository, + wallets = groupOnchainWallets, + onSend = { walletId -> + navController.navigate(route = MemberSendRoute(activeUserPublicKey = route.activeUserPublicKey, walletId = walletId)) + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + MemberSendScreen( + activeUserPublicKey = route.activeUserPublicKey, + walletId = route.walletId, + chain = NodeParamsManager.chain, + memberWalletRepository = databaseMemberWalletRepository, + wallets = groupOnchainWallets, + onNavigateBack = { + navController.popBackStack() + } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + MemberWalletPolicyScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + memberWalletRepository = databaseMemberWalletRepository, + frostSigningRepository = databaseFrostSigningRepository, + onNavigateToRoute = { actionRoute -> + navController.navigate(route = actionRoute) + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + NewMemberWalletScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chain = NodeParamsManager.chain, + canWatch = groupOnchainWallets != null, + memberWalletRepository = databaseMemberWalletRepository, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1402,6 +1376,8 @@ fun BennuNavHost( chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, wallets = groupOnchainWallets, + guardedChatRoomId = route.guardedChatRoomId, + fundChatRoomId = route.fundChatRoomId, onNavigateToRouteAndPopUpInclusive = { signingRoute -> // Replace the form so back returns to the wallet rather // than to a spend that has already been proposed. @@ -1414,134 +1390,6 @@ fun BennuNavHost( } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupPostsScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - EditGroupNostrProfileScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the form so back returns to the group rather than - // to an edit whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - EditGroupRelaysScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the editor so back returns to the group rather - // than to lists whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddGroupPostScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the composer so back returns to the group rather - // than to a draft whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - BroadcastGroupSignedEventScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - signedEventId = route.signedEventId, - chatRepository = databaseChatRepository, - // Handed the pool itself rather than a queue to write to, - // as the entries screen is for its "Broadcast all": a - // group-signed event must not become a `NostrEvent` row, and - // the queue hangs off one. See - // `BroadcastGroupSignedEventViewModel`. - publishTransport = synchronizationViewModel.relaysSocketManager, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - ProposeGroupEventScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the paste so back returns to the group rather - // than to an event whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1573,170 +1421,6 @@ fun BennuNavHost( initialFilter = route.filter ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - ArtifactDetailScreen( - activeUserPublicKey = route.activeUserPublicKey, - artifactId = route.artifactId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - ChapterDetailScreen( - activeUserPublicKey = route.activeUserPublicKey, - chapterId = route.chapterId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - TranslationArtifactVersionDetailScreen( - activeUserPublicKey = route.activeUserPublicKey, - translationArtifactVersionId = route.translationArtifactVersionId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - TranslationChapterScreen( - activeUserPublicKey = route.activeUserPublicKey, - translationChapterId = route.translationChapterId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - TranslateChunkScreen( - activeUserPublicKey = route.activeUserPublicKey, - translationChapterId = route.translationChapterId, - chunkId = route.chunkId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this editor so back returns to the chapter table - // rather than to a form whose proposal has already gone out. - // The table itself is left alone: nothing is translated until - // the group signs, so there is nothing new for it to show. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddTranslationArtifactVersionScreen( - activeUserPublicKey = route.activeUserPublicKey, - artifactId = route.artifactId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this screen so back returns to the artifact rather - // than to a form whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddChapterScreen( - activeUserPublicKey = route.activeUserPublicKey, - artifactId = route.artifactId, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - mantraRepository = databaseMantraRepository, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace this add screen so back returns to the artifact - // rather than to a form whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateToRoute = { actionRoute -> - navController.navigate( - route = actionRoute - ) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1833,6 +1517,8 @@ fun BennuNavHost( profilePublicKey = route.profilePublicKey, nostrRepository = databaseNostrRepository, chatRepository = databaseChatRepository, + memberWalletRepository = databaseMemberWalletRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, // The room replaces the preview, as it replaces the profile detail // above: back from a chat is the list, not the person it was started // from. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt deleted file mode 100755 index 5c481e8f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddArtifactRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddArtifactRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt deleted file mode 100644 index fc2619ed..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddGroupPostRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt deleted file mode 100644 index ecaaa079..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddTranslationRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddTranslationRoute( - val activeUserPublicKey: String, - val artifactId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt deleted file mode 100644 index 64d9574e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ArtifactDetailRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class ArtifactDetailRoute( - val activeUserPublicKey: String, - val artifactId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt deleted file mode 100644 index 7268d494..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class BroadcastGroupSignedEventRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String?, - /** The `GroupSignedEvent` to send, which is also the event id the group signed. */ - val signedEventId: String, -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt deleted file mode 100644 index 605e6395..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ChapterDetailRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class ChapterDetailRoute( - val activeUserPublicKey: String, - val chapterId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt new file mode 100644 index 00000000..6e81c652 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt @@ -0,0 +1,19 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * Starting a NIP-17 group's own key ceremony, and nothing else. + * + * The one place a group that has no key yet asks for one. Group creation and + * the subgroup picker start their own ceremonies because they already know what + * each is for; this is for a group that exists and has none. The ceremony screen + * that follows only ever shows a ceremony -- it used to offer to start one too, + * from the same button the approvals used, which is how a member joining a + * subgroup's ceremony opened a second. See docs/ceremony-creation.md. + */ +@Serializable +data class CreateSharedKeyRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgJoinApprovalRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgJoinApprovalRoute.kt index 64e5e00d..b757b139 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgJoinApprovalRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgJoinApprovalRoute.kt @@ -14,6 +14,6 @@ import kotlinx.serialization.Serializable data class DkgJoinApprovalRoute( val activeUserPublicKey: String, val chatRoomId: String, - /** The ceremony being approved; null takes the room's newest. */ - val dkgSessionId: String? = null + /** The ceremony being approved. Required, for the reason `DkgRitualRoute`'s is. */ + val dkgSessionId: String ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRitualRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRitualRoute.kt index bb4763fb..1da46e3b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRitualRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRitualRoute.kt @@ -3,7 +3,7 @@ package com.machankura.bennu.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable /** - * The shared-key ceremony for one NIP-17 group. + * One shared-key ceremony, shown and never started. * * Deliberately says nothing about *what the ceremony is for*. A subgroup's * ceremony grows the ladder by a rung -- the parent's birth certificate -- and @@ -17,13 +17,15 @@ data class DkgRitualRoute( val activeUserPublicKey: String, val chatRoomId: String, /** - * Which of the room's ceremonies to show, when the caller knows. + * Which of the room's ceremonies to show. Required: this screen shows a + * ceremony and never offers to start one, so a caller without a ceremony to + * name is asking to start one and goes to `CreateSharedKeyRoute` instead. * - * A room can hold more than one -- a subgroup whose admins are the whole - * group runs in the room the group's own ceremony ran in -- so "the room's - * ceremony" does not name one thing. A transcript line knows which it is - * about and passes it; a caller with only a room passes null and gets the - * newest, which is the best answer available to it. + * A room can hold more than one -- a parent's room hosts every subgroup + * ceremony the group runs -- so "the room's ceremony" does not name one + * thing, and falling back to the newest is how a second, whole-room ceremony + * once ended up on the screen in place of a subgroup's. See + * docs/ceremony-creation.md. */ - val dkgSessionId: String? = null + val dkgSessionId: String ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound1ApprovalRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound1ApprovalRoute.kt index f3c18ea2..ec2fbc97 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound1ApprovalRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound1ApprovalRoute.kt @@ -14,6 +14,6 @@ import kotlinx.serialization.Serializable data class DkgRound1ApprovalRoute( val activeUserPublicKey: String, val chatRoomId: String, - /** The ceremony being approved; null takes the room's newest. */ - val dkgSessionId: String? = null + /** The ceremony being approved. Required, for the reason `DkgRitualRoute`'s is. */ + val dkgSessionId: String ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound2ApprovalRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound2ApprovalRoute.kt index cf55bccc..be82d781 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound2ApprovalRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/DkgRound2ApprovalRoute.kt @@ -14,6 +14,6 @@ import kotlinx.serialization.Serializable data class DkgRound2ApprovalRoute( val activeUserPublicKey: String, val chatRoomId: String, - /** The ceremony being approved; null takes the room's newest. */ - val dkgSessionId: String? = null + /** The ceremony being approved. Required, for the reason `DkgRitualRoute`'s is. */ + val dkgSessionId: String ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt deleted file mode 100644 index 18cb2495..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class EditGroupNostrProfileRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt deleted file mode 100644 index 771dd52e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class EditGroupRelaysRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt deleted file mode 100644 index 06f3254c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * What the group says about itself on nostr, as the group signed it. - * - * The group's screen names the profile in a row; this is where it is read, with - * the broadcast under it and, for a member holding a share of the key, the way - * into the editor. One of the three screens the group's signed work is split - * across -- see [GroupRelaysRoute] and [GroupPostsRoute] -- each pushed from its - * row on the group's screen. - */ -@Serializable -data class GroupNostrProfileRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt deleted file mode 100644 index be352f7f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * What the group has said publicly, as itself, newest first, with a broadcast - * under each post and the way into the composer for a member holding a share - * of the key. - */ -@Serializable -data class GroupPostsRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt deleted file mode 100644 index a76a9a86..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * Where the group has said it lives on nostr: its four relay lists, as the - * group signed them, with a broadcast under each one it has agreed and the way - * into the editor for a member holding a share of the key. - */ -@Serializable -data class GroupRelaysRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt index b09b665d..2b9776b8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt @@ -2,12 +2,22 @@ package com.machankura.bennu.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable -/** The form a member proposes a spend from the group's wallet with. */ +/** + * The form a member proposes a spend from the group's wallet with -- or, with + * [guardedChatRoomId], from that descendant's guarded wallet, through the + * group's guardian leaf. + * + * [fundChatRoomId] is where the coins go instead of where they come from: the + * descendant whose guarded wallet a send from the group's own wallet pays. A + * route naming both is not one the form opens -- `docs/guarded-wallet-funding.md`, D6. + */ @Serializable data class GroupSendRoute( val activeUserPublicKey: String, val chatRoomId: String, val relayHint: String?, + val guardedChatRoomId: String? = null, + val fundChatRoomId: String? = null, /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ val chain: String? = null, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberSendRoute.kt similarity index 56% rename from composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt rename to composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberSendRoute.kt index 6ef108c4..116b0ad3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddDialectRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberSendRoute.kt @@ -2,9 +2,9 @@ package com.machankura.bennu.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable +/** The form a member sends from their own guarded wallet with, signing alone. */ @Serializable -data class AddDialectRoute( +data class MemberSendRoute( val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? + val walletId: String, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt similarity index 51% rename from composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt rename to composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt index c6d2dfa8..237bfd83 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddChapterRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt @@ -2,10 +2,12 @@ package com.machankura.bennu.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable +/** + * Whether the group [chatRoomId] guards its members' wallets, at what delay, + * and closing it again -- `docs/member-wallet-delay.md`, Phase 6. + */ @Serializable -data class AddChapterRoute( +data class MemberWalletPolicyRoute( val activeUserPublicKey: String, - val artifactId: String, val chatRoomId: String, - val relayHint: String? ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletRoute.kt new file mode 100644 index 00000000..df587573 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletRoute.kt @@ -0,0 +1,14 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * One of the active member's guarded wallets: its balance, where to be paid, + * its coins, what its guardians took, and -- while no group has certified it -- + * where the asking has got to. `docs/member-guarded-wallets.md`, Phase 8. + */ +@Serializable +data class MemberWalletRoute( + val activeUserPublicKey: String, + val walletId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/NewMemberWalletRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/NewMemberWalletRoute.kt new file mode 100644 index 00000000..8e1d9446 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/NewMemberWalletRoute.kt @@ -0,0 +1,14 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * Asking a group to guard a wallet only the active member can spend from -- + * `docs/member-guarded-wallets.md`, Phase 6. With [chatRoomId] the group is + * already chosen; without it the screen offers the groups this profile is in. + */ +@Serializable +data class NewMemberWalletRoute( + val activeUserPublicKey: String, + val chatRoomId: String? = null, +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt deleted file mode 100644 index 82c810ba..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** The untyped way into a group's signed statements: an unsigned event, pasted. */ -@Serializable -data class ProposeGroupEventRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectSubgroupAdminsRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectSubgroupAdminsRoute.kt index 4a15b10e..ffab974d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectSubgroupAdminsRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/SelectSubgroupAdminsRoute.kt @@ -16,5 +16,12 @@ import kotlinx.serialization.Serializable data class SelectSubgroupAdminsRoute( val activeUserPublicKey: String, val parentChatRoomId: String, - val relayHint: String? = null + val relayHint: String? = null, + /** + * A failed subgroup ceremony this is trying again, whose name, admins and + * quorum the picker starts from. Every one of them can still be changed, and + * every refusal runs again: a retry is a new ceremony, not the old one + * resumed. + */ + val retrying: String? = null, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt deleted file mode 100644 index f377c1ae..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslateChunkRoute.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class TranslateChunkRoute( - val activeUserPublicKey: String, - val translationChapterId: String, - val chunkId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt deleted file mode 100644 index c3150b4c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationArtifactVersionDetailRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class TranslationArtifactVersionDetailRoute( - val activeUserPublicKey: String, - val translationArtifactVersionId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt deleted file mode 100644 index 8133a75b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/TranslationChapterRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class TranslationChapterRoute( - val activeUserPublicKey: String, - val translationChapterId: String, - val chatRoomId: String, - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DelayText.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DelayText.kt new file mode 100644 index 00000000..ef7458aa --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DelayText.kt @@ -0,0 +1,46 @@ +package com.machankura.bennu.compose.ui.composable.widgets + +import androidx.compose.runtime.Composable +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.about_n_days +import bennu.composeapp.generated.resources.about_n_hours +import bennu.composeapp.generated.resources.about_n_minutes +import bennu.composeapp.generated.resources.about_n_months +import bennu.composeapp.generated.resources.about_n_years +import bennu.composeapp.generated.resources.blocks_and_about +import bennu.composeapp.generated.resources.n_blocks +import com.machankura.bennu.compose.text.BlockDuration +import com.machankura.bennu.compose.text.groupedBlocks +import fr.acinq.bitcoin.Chain +import org.jetbrains.compose.resources.pluralStringResource +import org.jetbrains.compose.resources.stringResource + +/** + * A guardian's delay as a member reads it: *144 blocks, about 1 day*. + * `docs/guardian-delay.md`, D5. + * + * Blocks only on regtest, whose blocks come when somebody mines one, so a time + * there would be wrong. [chain] is null where a delay is for no network in + * particular -- a birth certificate is not -- and then the estimate is + * mainnet's, as every network but regtest shares its target. + */ +@Composable +fun delayText(blocks: Long, chain: Chain? = null): String { + val count = pluralStringResource(Res.plurals.n_blocks, blocks.toInt(), blocks.groupedBlocks()) + if (chain == Chain.Regtest) return count + return stringResource(Res.string.blocks_and_about, count, approximateDuration(blocks)) +} + +/** *about 1 day*: [BlockDuration.approximate] in words. */ +@Composable +fun approximateDuration(blocks: Long): String { + val approximate = BlockDuration.approximate(blocks) + val plural = when (approximate.unit) { + BlockDuration.Unit.MINUTES -> Res.plurals.about_n_minutes + BlockDuration.Unit.HOURS -> Res.plurals.about_n_hours + BlockDuration.Unit.DAYS -> Res.plurals.about_n_days + BlockDuration.Unit.MONTHS -> Res.plurals.about_n_months + BlockDuration.Unit.YEARS -> Res.plurals.about_n_years + } + return pluralStringResource(plural, approximate.count, approximate.count) +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt deleted file mode 100644 index bfb75ffc..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/DetailRow.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.widgets - -import androidx.compose.material3.ListItem -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable - -/** A labelled value row for detail screens (label above, value below). */ -@Composable -fun DetailRow(label: String, value: String) { - ListItem( - overlineContent = { Text(label) }, - headlineContent = { Text(value) } - ) -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/GuardianDelayChooser.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/GuardianDelayChooser.kt new file mode 100644 index 00000000..96137ae7 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/GuardianDelayChooser.kt @@ -0,0 +1,109 @@ +package com.machankura.bennu.compose.ui.composable.widgets + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.delay_custom +import bennu.composeapp.generated.resources.delay_in_blocks +import bennu.composeapp.generated.resources.delay_longest +import bennu.composeapp.generated.resources.delay_one_day +import bennu.composeapp.generated.resources.delay_one_hour +import bennu.composeapp.generated.resources.delay_one_month +import bennu.composeapp.generated.resources.delay_one_week +import bennu.composeapp.generated.resources.delay_six_months +import bennu.composeapp.generated.resources.delay_two_hours +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.GuardianDelayInput +import org.jetbrains.compose.resources.stringResource + +/** + * How long a coin waits before a group can take it through its own leaf: in a + * guarded subgroup's wallet (`docs/guardian-delay.md`) or in the wallets it + * guards for its members (`docs/member-wallet-delay.md`). Presets for what + * people mean, and a field for the exact number of blocks, which says what it + * works out to while it is typed. + * + * The words are the caller's -- [title], and [consequence], the trade a long + * delay makes -- because *the subgroup* and *the member* differ. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun GuardianDelayChooser( + title: String, + consequence: String, + input: String, + delay: Long?, + isCustom: Boolean, + problem: String?, + onPreset: (Long) -> Unit, + onCustom: () -> Unit, + onInput: (String) -> Unit, +) { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall + ) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + GuardianDelayInput.PRESETS.forEach { preset -> + FilterChip( + selected = !isCustom && delay == preset, + onClick = { onPreset(preset) }, + label = { Text(presetLabel(preset)) } + ) + } + FilterChip( + selected = isCustom, + onClick = onCustom, + label = { Text(stringResource(Res.string.delay_custom)) } + ) + } + if (isCustom) { + OutlinedTextField( + value = input, + onValueChange = onInput, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + label = { Text(stringResource(Res.string.delay_in_blocks)) }, + isError = problem != null, + supportingText = { Text(problem ?: delay?.let { delayText(it) }.orEmpty()) } + ) + } else if (delay != null && problem == null) { + Text(text = delayText(delay), style = MaterialTheme.typography.bodyMedium) + } + Text( + text = consequence, + style = MaterialTheme.typography.bodySmall + ) + } +} + +/** What a preset chip calls its delay: the time it was chosen to be, not its estimate. */ +@Composable +private fun presetLabel(blocks: Long): String = when (blocks) { + 6L -> stringResource(Res.string.delay_one_hour) + 12L -> stringResource(Res.string.delay_two_hours) + 144L -> stringResource(Res.string.delay_one_day) + 1_008L -> stringResource(Res.string.delay_one_week) + 4_320L -> stringResource(Res.string.delay_one_month) + 26_280L -> stringResource(Res.string.delay_six_months) + else -> stringResource(Res.string.delay_longest) +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt deleted file mode 100644 index d227381c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.widgets - -import androidx.compose.runtime.Composable -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.relay_accepted -import bennu.composeapp.generated.resources.relay_could_not_send -import bennu.composeapp.generated.resources.relay_no_answer -import bennu.composeapp.generated.resources.relay_rejected -import bennu.composeapp.generated.resources.relay_sending -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome - -/** - * One relay's answer to a broadcast, in the words both screens that show one - * use for it: the row under a relay on `BroadcastGroupSignedEventScreen`, and - * the line under an entry that "Broadcast all" sent. - * - * A rejection and a failure carry the relay's own reason, because "blocked: - * not on the allow list" is something a member can act on and a red icon is - * not. One spelling for both screens, so a relay's answer reads the same - * whichever button sent to it. - */ -@Composable -fun RelayOutcome.label(): String = when (this) { - RelayOutcome.Sending -> stringResource(Res.string.relay_sending) - RelayOutcome.Accepted -> stringResource(Res.string.relay_accepted) - is RelayOutcome.Rejected -> stringResource(Res.string.relay_rejected, reason) - is RelayOutcome.Failed -> stringResource(Res.string.relay_could_not_send, reason) - RelayOutcome.NoAnswer -> stringResource(Res.string.relay_no_answer) -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt deleted file mode 100644 index dcbe5d5e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.widgets.buttons - -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.width -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.CellTower -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.broadcast -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.theme.spacing - -/** - * The way into `BroadcastGroupSignedEventScreen`, drawn the same under every - * event the group signed -- its profile, each relay list, each post, each schema - * and each entry -- so that it reads as one action on whichever screen it sits. - * - * Behind no gate anywhere it appears: sending what the group has already signed - * takes no share of the key, since the signature on it is the group's whoever - * repeats it. Only *making* a statement is gated, and that is the caller's - * concern. The icon is decorative because the label is beside it. - */ -@Composable -fun BroadcastButton(onClick: () -> Unit) { - TextButton(onClick = onClick) { - Icon(Icons.Default.CellTower, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.broadcast)) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt index dbe89ca0..c946d5ab 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -16,6 +16,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet import androidx.compose.material.icons.filled.AccountTree import bennu.composeapp.generated.resources.open import bennu.composeapp.generated.resources.the_group_has_its_key_finish_setting_it_up @@ -110,7 +111,7 @@ import com.machankura.bennu.compose.ui.composable.widgets.ErrorState @Composable fun ChatTranscript( viewModel: ChatMessageListViewModel, - onOpenSharedKey: (dkgSessionId: String?) -> Unit, + onOpenSharedKey: (dkgSessionId: String) -> Unit, /** Opens the Lightning wallet key ceremony an [ChatMessage.ICEBERG_TYPES] line is about. */ onOpenIcebergCeremony: (sessionId: String?) -> Unit = {}, /** @@ -267,9 +268,13 @@ fun ChatTranscript( // The line knows which ceremony it is // about; the room does not. Passing it is // what stops a subgroup's request opening - // the group's own finished ceremony. - onClick = { - onOpenSharedKey(localChatMessage.chatMessage.dkgSessionId) + // the group's own finished ceremony. A + // line that names none opens nothing: the + // ceremony screen shows the ceremony it is + // named, and guessing one is how a + // subgroup's got buried under another. + onClick = localChatMessage.chatMessage.dkgSessionId?.let { dkgSessionId -> + { onOpenSharedKey(dkgSessionId) } } ) return@items @@ -356,15 +361,11 @@ fun ChatTranscript( return@items } - // The group's own profile, signed. Same treatment - // and for the same reason: nobody said it. Answered - // and settled because it reports rather than asks -- - // a quorum has already signed by the time this line - // exists. - // - // It leads nowhere. What a reader wants from one is - // the profile, and the nostr profile section of the - // group's detail screen is where that lives. + // Something the group signed. Same treatment and for + // the same reason: nobody said it. Answered and + // settled because it reports rather than asks -- a + // quorum has already signed by the time this line + // exists. It leads nowhere. if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { RitualNotice( localChatMessage = localChatMessage, @@ -806,7 +807,8 @@ private fun RitualNotice( localChatMessage: LocalChatMessage, isAnswered: Boolean, isSettled: Boolean, - onClick: () -> Unit, + /** Null for a line that names no ceremony, which then opens nothing. */ + onClick: (() -> Unit)?, ) { val chatMessage = localChatMessage.chatMessage @@ -861,6 +863,7 @@ private fun RitualNotice( // path, so they get separate icons -- the whole reason both lines exist is // to be able to see that the first happened and the second did not. ChatMessage.TYPE_SUBGROUP_CERTIFIED -> Icons.Default.AccountTree + ChatMessage.TYPE_MEMBER_WALLET_REQUESTED, ChatMessage.TYPE_MEMBER_WALLET_GUARDED -> Icons.Default.AccountBalanceWallet ChatMessage.TYPE_MEMBER_INVITED -> Icons.Default.PersonAdd ChatMessage.TYPE_MEMBER_INVITE_SENT -> Icons.Default.Upload ChatMessage.TYPE_MEMBER_INVITE_FAILED -> Icons.Default.ErrorOutline @@ -898,7 +901,7 @@ private fun RitualNotice( modifier = Modifier .fillMaxWidth() .minimumInteractiveComponentSize() - .clickable(onClick = onClick) + .clickable(enabled = onClick != null) { onClick?.invoke() } .padding(horizontal = MaterialTheme.spacing.space250, vertical = MaterialTheme.spacing.space125), horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), verticalAlignment = Alignment.CenterVertically diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt index efbf4e97..8c4a36c5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt @@ -56,10 +56,8 @@ fun ProfileAvatar( /** * The same avatar for a subject that has no `Profile` row. * - * A group's is the case in hand: its kind:0 is signed by the group and kept as a - * `GroupSignedEvent`, which is not a `NostrEvent` and so cannot have a `Profile` - * hanging off it -- see `GroupNostrProfile`. The picture and the name are all this - * ever wanted from a profile, so they are what it takes. + * The picture and the name are all this ever wanted from a profile, so they are + * what it takes. * * [name] only reaches the content description. The tint behind a missing picture * comes from [publicKey], which is what keeps the same subject the same colour diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt deleted file mode 100644 index bad5507c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddArtifactViewModel.kt +++ /dev/null @@ -1,186 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.runtime.MutableState -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.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.NostrRepository -import co.touchlab.kermit.Logger -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.AddArtifactUIState - -class AddArtifactViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddArtifactUIState: AddArtifactUIState, - val nostrRepository: NostrRepository, - val chatRepository: ChatRepository, - val mantraRepository: MantraRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addArtifactUIState: AddArtifactUIState by mutableStateOf(initialAddArtifactUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateChatRoomDetail() { - logger.d("compressed (most likely chat room): $chatRoomId") - // Get ChatRoomById - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addArtifactUIState = if (localChatRoom == null) { - // Initiate new chat... and navigate to new chat... - AddArtifactUIState.Error("Couldn't find the chat room") - } else { - AddArtifactUIState.Loaded( - localChatRoom = localChatRoom, - dialects = mantraRepository.getDialects(localChatRoom.chatRoom.id), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign an artifact into its library. - * - * The artifact is not created here and does not exist yet. What goes out is - * a proposal to sign it, and the artifact appears -- on every member's - * device at once, authored by this room's own key rather than by whoever - * typed it -- when enough members have signed. That author is the room's id: - * signing runs at the path the room was derived at, so an artifact says - * which library it belongs to simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. A library is the group's, so the second is the honest one. - * - * Two events, one session: the artifact and the version it starts life with, - * which a chapter later hangs off. All-or-nothing, which is right here -- - * an artifact with no version is inert, since nothing can attach to it. - */ - fun addArtifact( - localChatRoom: LocalChatRoom, - nameField: TextFieldState, - urlField: TextFieldState, - versionLabelField: TextFieldState, - dialectId: HexKey?, - visibility: String = MantraRepository.DEFAULT_VISIBILITY, - license: String = MantraRepository.DEFAULT_LICENSE, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val name = nameField.text.toString() - val url = urlField.text.toString() - val versionLabel = versionLabelField.text.toString() - - // An artifact requires an existing source dialect; they are signed into - // existence from the group detail screen, not here. - if (name.isBlank() || url.isBlank() || versionLabel.isBlank() || dialectId.isNullOrBlank()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - // The label rides on the artifact and the version is signed beside - // it, in the same batch. A first version proposed on its own would - // cost a second quorum for one form, which is why it used to be - // derived on arrival instead; a batch costs one quorum, so the row a - // chapter hangs off can carry the group's signature rather than - // being rebuilt from the artifact by every device that holds it. - val artifactEventTemplate = ArtifactEvent.build( - name = name, - url = url, - visibility = visibility, - license = license, - dialectId = dialectId, - versionLabel = versionLabel, - ) - - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - lead = artifactEventTemplate, - // The version names the artifact it is of, and that id is a - // hash over the group's key at the room's path -- neither of - // which this screen knows or should. The artifact comes back - // built, and the version is read off the label it declares. - dependents = ArtifactVersionEvent::initialVersionOf - ) - }.onFailure { error -> - logger.e("Failed to propose an artifact for signing", error) - }.getOrNull() - - if (session != null) { - nameField.clearText() - urlField.clearText() - versionLabelField.clearText() - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AddArtifactViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddArtifactUIState: AddArtifactUIState = AddArtifactUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - mantraRepository: MantraRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddArtifactViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddArtifactUIState = initialAddArtifactUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - mantraRepository = mantraRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt deleted file mode 100644 index 4411786d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddChapterViewModel.kt +++ /dev/null @@ -1,291 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.runtime.MutableState -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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.managers.TranslationScaffold -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.text.Markdown -import com.machankura.bennu.compose.ui.view.state.AddChapterUIState - -class AddChapterViewModel( - val artifactId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddChapterUIState: AddChapterUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addChapterUIState: AddChapterUIState by mutableStateOf(initialAddChapterUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateAddChapter() { - viewModelScope.launch(Dispatchers.IO) { - val artifact = mantraRepository.getArtifact(artifactId) - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addChapterUIState = when { - artifact == null -> AddChapterUIState.Error("Couldn't find the artifact") - localChatRoom == null -> AddChapterUIState.Error("Couldn't find the chat room") - else -> AddChapterUIState.Loaded( - localChatRoom = localChatRoom, - artifact = artifact, - // Chapters attach to an artifact version; use the latest one. - artifactVersion = mantraRepository.getArtifactVersions(artifactId).firstOrNull(), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign a chapter, and every chunk it splits into, in one - * session. - * - * Nothing is created here. What goes out is a proposal to sign the lot, and - * the chapter and its chunks appear on every member's device at once, - * authored by this room's own key rather than by whoever pasted the text, - * when enough members have signed. That author is the room's id: signing - * runs at the path the room was derived at, so a chapter says which group's - * artifact it belongs to simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. The text everyone will translate from is the group's, so - * the second is the honest one. - * - * The chunks travel as their own events rather than being split back out of - * the signed chapter on each device, so that each one carries the group's - * signature over its own text -- a translation is of a chunk, and a chunk - * that can be checked on its own is worth more than one that can only be - * checked by re-deriving it. What it costs is [MAX_CHUNKS_PER_CHAPTER]: the - * batch is capped, the chapter takes one of its places, and a chapter with - * more paragraphs than the rest cannot be proposed at all. - */ - fun addChapter( - localChatRoom: LocalChatRoom, - artifactVersion: MantraArtifactVersion, - nameField: TextFieldState, - originalTextField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val name = nameField.text.toString() - val originalText = originalTextField.text.toString() - val paragraphs = Markdown.splitParagraphs(originalText) - - // The cap is the group's, not this screen's, and proposing past it - // throws rather than failing softly. The form says so as it is typed; - // this is the check that has to hold when it does not. - if (name.isBlank() || paragraphs.isEmpty() || paragraphs.size > MAX_CHUNKS_PER_CHAPTER) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - // Where this chapter sits in the version, read now rather than - // derived on arrival: the index is signed into the event, and a - // device applying it cannot recount from a version other members - // may have added to in a different order. The scaffolding proposed - // below is placed at the same one, so a translation chapter agrees - // with the chapter it stands for. - val chapterIndex = mantraRepository.getChaptersForArtifactVersion(artifactVersion.id).size - - val chapterEventTemplate = ChapterEvent.build( - artifactVersionId = artifactVersion.id, - name = name, - originalText = originalText, - index = chapterIndex, - wordCount = Markdown.wordCount(originalText), - characterCount = Markdown.characterCount(originalText), - ) - - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - lead = chapterEventTemplate, - // A chunk names the chapter it belongs to, and that id is a - // hash over the group's key at the room's path -- neither of - // which this screen knows or should. The chapter comes back - // built, and the chunks are cut from the text it carries. - dependents = ChunkEvent::splitOf - ) - }.onFailure { error -> - logger.e("Failed to propose a chapter for signing", error) - }.getOrNull() - - if (session != null) { - // Before navigating, not after: the route this screen sits on - // is popped on success, which clears this view model and takes - // `viewModelScope` with it. Scaffolding launched afterwards - // would be cancelled somewhere in the middle. - scaffoldIntoTranslations( - localChatRoom = localChatRoom, - artifactVersion = artifactVersion, - chapterIndex = chapterIndex, - chapterSessionId = session.id, - ) - - nameField.clearText() - originalTextField.clearText() - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - /** - * Asks the group to scaffold this chapter into every translation of the - * version, in sessions of their own. - * - * Its own session rather than more items on the chapter's, because the two - * would otherwise compete for one batch: a chapter is capped at - * [MAX_CHUNKS_PER_CHAPTER] paragraphs, and every dialect the group works in - * would take one of those places away. How long a chapter may be and how - * many languages it is read in have nothing to do with each other, and a - * shared cap would make the first move whenever somebody else did the - * second. - * - * Sessions run independently -- every message carries the session it - * belongs to, and each mints its own nonce material -- so a second one - * opened here costs the admins another approval and nothing else. - * - * **What a separate session gives up.** A batch is all-or-nothing; two - * sessions are not. If the chapter fails to reach a quorum while this one - * succeeds, these are valid signatures over rows naming a chapter nobody - * has: they fail a foreign key on the way in, are logged by - * `applySignedEvent`, and never become rows. Harmless, and not recoverable - * either -- a re-proposed chapter is a different id -- so the catch-up on - * the translation is what fills the gap afterwards. - * - * The chapter is named as the group will author it: [chapterSessionId]'s - * first item is the unsigned chapter, whose id is the hash its signers are - * putting their shares behind, and it is settled at proposal time rather - * than when the quorum arrives. - * - * Failure here is logged and swallowed. The chapter has already been - * proposed and is the thing that was asked for; losing it because its - * scaffolding could not be opened would be the wrong way round. - */ - private suspend fun scaffoldIntoTranslations( - localChatRoom: LocalChatRoom, - artifactVersion: MantraArtifactVersion, - chapterIndex: Int, - chapterSessionId: String, - ) { - runCatching { - val translations = mantraRepository - .getTranslationsForArtifactVersion(artifactVersion.id) - .ifEmpty { return@runCatching } - - val chapter = frostSigningRepository - .unsignedEvents(frostSigningRepository.getItems(chapterSessionId)) - .firstOrNull() ?: return@runCatching - - // One session per MAX_BATCH_SIZE translations. A group with more - // dialects than a batch holds is not a group this should refuse; - // it is one that answers twice. - translations.chunked(FrostSigningManager.MAX_BATCH_SIZE).forEach { batch -> - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = batch.map { it.id }, - chapters = listOf( - TranslationScaffold.SourceChapter( - id = chapter.id, - index = chapterIndex, - ) - ), - createdAt = chapter.createdAt, - ) - ) - } - }.onFailure { error -> - logger.e( - "Proposed the chapter but could not ask for it in this version's translations", - error - ) - } - } - - companion object { - private const val TAG = "AddChapterViewModel" - - /** - * The most paragraphs a chapter can be proposed with. - * - * A chapter is signed together with a chunk per paragraph, and the - * session signs at most [FrostSigningManager.MAX_BATCH_SIZE] events. The - * chapter is one of them, so the paragraphs get the rest. A longer - * chapter has to be split into two, which is a real limit and belongs in - * front of whoever is typing rather than in a failure afterwards. - */ - const val MAX_CHUNKS_PER_CHAPTER: Int = FrostSigningManager.MAX_BATCH_SIZE - 1 - - fun factory( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddChapterUIState: AddChapterUIState = AddChapterUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddChapterViewModel( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddChapterUIState = initialAddChapterUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt deleted file mode 100644 index 4e693c7d..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddDialectViewModel.kt +++ /dev/null @@ -1,164 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.clearText -import androidx.compose.runtime.MutableState -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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.NostrRepository -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.ui.view.state.AddDialectUIState - -class AddDialectViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddDialectUIState: AddDialectUIState, - val nostrRepository: NostrRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addDialectUIState: AddDialectUIState by mutableStateOf(initialAddDialectUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * Whether this group holds a key it can sign with. - * - * Read before the form is offered: a group without one cannot make a dialect - * this way at all, and a button that always fails is worse than no button. - */ - suspend fun canSign(): Boolean = frostSigningRepository.canSign(chatRoomId) - - fun initiateAddDialect() { - logger.d("compressed (most likely chat room): $chatRoomId") - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addDialectUIState = if (localChatRoom == null) { - AddDialectUIState.Error("Couldn't find the chat room") - } else { - AddDialectUIState.Loaded( - localChatRoom = localChatRoom, - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign a new dialect into existence. - * - * The dialect is not created here and does not exist yet. What goes out is a - * proposal to sign it, and the dialect appears -- on every member's device at - * once, authored by this room's own key rather than by whoever typed it -- - * when enough members have signed. That author is the room's id: signing runs - * at the path the room was derived at, so a dialect says which room made it - * simply by being signed. - * - * That is the difference from submitting one. A submission says "I am putting - * this in front of the group" and the group's only recourse afterwards is - * social. A signature is the group saying it, and it takes a quorum to say. - */ - fun addDialect( - localChatRoom: LocalChatRoom, - nameField: TextFieldState, - countryField: TextFieldState, - languageField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val name = nameField.text.toString() - val country = countryField.text.toString() - val language = languageField.text.toString() - - if (name.isBlank() || country.isBlank() || language.isBlank()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val dialectEventTemplate = DialectEvent.build( - name = name, - country = country, - language = language, - ) - - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = dialectEventTemplate.kind, - tags = dialectEventTemplate.tags, - content = dialectEventTemplate.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a dialect for signing", error) - }.getOrNull() - - if (session != null) { - nameField.clearText() - countryField.clearText() - languageField.clearText() - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AddDialectViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddDialectUIState: AddDialectUIState = AddDialectUIState.Loading, - nostrRepository: NostrRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddDialectViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddDialectUIState = initialAddDialectUIState, - nostrRepository = nostrRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt deleted file mode 100644 index 5adc8b61..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt +++ /dev/null @@ -1,154 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -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.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.AddGroupPostUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * Asks the group to say something publicly, in its own name. - * - * The post is not written here and does not exist yet. What goes out is a proposal - * to sign one, and the post appears -- on every member's device at once, authored by - * the room's own key rather than by whoever typed it -- when enough members have - * signed. That author is the room's id: signing runs at the path the room was - * derived at, so a post says which group made it simply by being signed. - * - * That is the difference from a message in the room. A message is a member speaking - * where the group can hear; this is the group speaking where anyone can, and it - * takes a quorum to say. - */ -class AddGroupPostViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddGroupPostUIState: AddGroupPostUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addGroupPostUIState: AddGroupPostUIState by mutableStateOf(initialAddGroupPostUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateAddGroupPost() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addGroupPostUIState = if (localChatRoom == null) { - AddGroupPostUIState.Error("Couldn't find the chat room") - } else { - AddGroupPostUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room has no key of its own to sign as, so it has no - // identity to post under -- the same condition the group detail - // screen gates the entry point on. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Opens a session over one kind:1 authored by the group. - * - * Refuses a blank draft rather than proposing it: a quorum signing an empty note - * would put a post on the record that renders as nothing and cannot be told from - * a broken one -- and kind:1 is not replaceable, so there is no un-saying it. - * `GroupPost.newestFirstAmong` drops blanks on the way back out too, which is - * the second line of the same defence. - * - * The draft is not cleared on success. This screen is replaced by the signing - * session, and on the failure path the words are the thing worth keeping. - */ - fun proposePost( - localChatRoom: LocalChatRoom, - noteField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onEmpty: () -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. Posts accumulate rather than replace, so a - // second session over the same words is a second post on the record forever. - if (isActionPending.value) return - - val note = noteField.text.toString().trim() - if (note.isBlank()) { - onEmpty.invoke() - return - } - - isActionPending.value = true - - val template = GroupPost.template(note) - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a post for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AddGroupPostViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddGroupPostUIState: AddGroupPostUIState = AddGroupPostUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddGroupPostViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddGroupPostUIState = initialAddGroupPostUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt deleted file mode 100644 index 0f7693f5..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddTranslationArtifactVersionViewModel.kt +++ /dev/null @@ -1,260 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.managers.TranslationScaffold -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.AddTranslationArtifactVersionUIState - -class AddTranslationArtifactVersionViewModel( - val artifactId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState by mutableStateOf(initialAddTranslationArtifactVersionUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateAddTranslation() { - viewModelScope.launch(Dispatchers.IO) { - val artifact = mantraRepository.getArtifact(artifactId) - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - // Translations attach to an artifact version; use the latest one. - val artifactVersion = mantraRepository.getArtifactVersions(artifactId).firstOrNull() - - addTranslationArtifactVersionUIState = if (artifact == null || localChatRoom == null) { - AddTranslationArtifactVersionUIState.Error("Couldn't find the artifact") - } else { - AddTranslationArtifactVersionUIState.Loaded( - artifact = artifact, - localChatRoom = localChatRoom, - dialects = mantraRepository.getDialects(chatRoomId), - artifactVersion = artifactVersion, - chapters = artifactVersion - ?.let { mantraRepository.getChaptersForArtifactVersion(it.id) } - .orEmpty(), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign a translation of the artifact, and a translation - * chapter for every chapter it has, in one session. - * - * Nothing is created here. What goes out is a proposal to sign the lot, and - * the translation and its chapters appear on every member's device at once, - * authored by this room's own key rather than by whoever picked the dialect, - * when enough members have signed. That author is the room's id: signing - * runs at the path the room was derived at, so a translation says which - * group's artifact it belongs to simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. A translation is what the group's readers will read the - * artifact as, so the second is the honest one. - * - * The chapters travel with it rather than being scaffolded on each device, - * for the same reason the chapter's chunks do: a translation chapter that - * carries the group's signature can be checked by anybody holding it, and a - * translation with no chapters is one nobody can start translating. What it - * costs is [MAX_CHAPTERS_PER_TRANSLATION]: the batch is capped, the - * translation takes one of its places, and an artifact with more chapters - * than the rest cannot be translated in one session at all. - */ - fun addTranslation( - localChatRoom: LocalChatRoom, - artifact: MantraArtifact, - artifactVersion: MantraArtifactVersion, - dialect: MantraDialect, - chapters: List, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val translationEventTemplate = TranslationArtifactVersionEvent.build( - artifactVersionId = artifactVersion.id, - dialectId = dialect.id, - // The translation is named after its dialect, and inherits the - // source artifact's visibility and license: it is the same work - // in another tongue, not a new one to license afresh. - name = dialect.name, - visibility = artifact.visibility, - license = artifact.license, - ) - - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - lead = translationEventTemplate, - // A translation chapter names the translation it belongs to, - // and that id is a hash over the group's key at the room's - // path -- neither of which this screen knows or should. The - // translation comes back built, and the chapters are laid - // out against it. - dependents = { translation -> - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = chapters.take(MAX_CHAPTERS_PER_TRANSLATION) - .map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - } - ) - }.onFailure { error -> - logger.e("Failed to propose a translation for signing", error) - }.getOrNull() - - if (session != null) { - // Before navigating, not after: the route this screen sits on - // is popped on success, which clears this view model and takes - // `viewModelScope` with it. - scaffoldRemainingChapters( - localChatRoom = localChatRoom, - chapters = chapters.drop(MAX_CHAPTERS_PER_TRANSLATION), - translationSessionId = session.id, - ) - - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - /** - * Asks the group for the chapters that did not fit the translation's own - * session, in sessions of their own. - * - * The alternative was refusing to translate an artifact of more than - * [MAX_CHAPTERS_PER_TRANSLATION] chapters at all, which is a cap on how - * long a book may be dressed up as a cap on a batch. A group with a longer - * one answers more than once instead. - * - * The translation is named as the group will author it: the first item of - * [translationSessionId] is the unsigned translation, and its id is settled - * at proposal time rather than when the quorum arrives. - * - * These carry the same cost as any second session, and the same one the - * chapter side carries: if the translation itself fails to reach a quorum - * these are valid signatures over rows naming a translation nobody has. - * They fail a foreign key on the way in, are logged, and never become rows - * -- and the catch-up on the translation is what fills the gap afterwards. - */ - private suspend fun scaffoldRemainingChapters( - localChatRoom: LocalChatRoom, - chapters: List, - translationSessionId: String, - ) { - if (chapters.isEmpty()) return - - runCatching { - val translation = frostSigningRepository - .unsignedEvents(frostSigningRepository.getItems(translationSessionId)) - .firstOrNull() ?: return@runCatching - - chapters.chunked(FrostSigningManager.MAX_BATCH_SIZE).forEach { batch -> - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = batch.map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - ) - } - }.onFailure { error -> - logger.e( - "Proposed the translation but could not ask for the chapters past the first session", - error - ) - } - } - - companion object { - private const val TAG = "AddTranslationViewModel" - - /** - * How many chapters ride in the translation's own session. - * - * The translation is signed together with a chapter apiece, and a - * session signs at most [FrostSigningManager.MAX_BATCH_SIZE] events. The - * translation is one of them, so the chapters get the rest. - * - * A cap on the session, not on the work: an artifact with more chapters - * than this is not refused, it is proposed in more than one session. A - * limit whoever is looking at the screen can do nothing about is not a - * limit worth telling them to work around. - */ - const val MAX_CHAPTERS_PER_TRANSLATION: Int = FrostSigningManager.MAX_BATCH_SIZE - 1 - - fun factory( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialAddTranslationArtifactVersionUIState: AddTranslationArtifactVersionUIState = AddTranslationArtifactVersionUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddTranslationArtifactVersionViewModel( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddTranslationArtifactVersionUIState = initialAddTranslationArtifactVersionUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt deleted file mode 100644 index 926dd046..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ArtifactDetailViewModel.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.machankura.bennu.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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.ArtifactDetailUIState - -class ArtifactDetailViewModel( - val artifactId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialArtifactDetailUIState: ArtifactDetailUIState, - val mantraRepository: MantraRepository, -): ViewModel() { - - var artifactDetailUIState: ArtifactDetailUIState by mutableStateOf(initialArtifactDetailUIState) - private set - - private val logger = Logger.withTag(TAG) - - fun initiateArtifactDetail() { - logger.d("initiateArtifactDetail: $artifactId") - viewModelScope.launch(Dispatchers.IO) { - val artifact = mantraRepository.getArtifact(artifactId) - - artifactDetailUIState = if (artifact == null) { - ArtifactDetailUIState.Error("Couldn't find the artifact") - } else { - ArtifactDetailUIState.Loaded( - artifact = artifact, - versions = mantraRepository.getArtifactVersions(artifactId), - chapters = mantraRepository.getChaptersForArtifact(artifactId), - translations = mantraRepository.getTranslationsForArtifact(artifactId), - ) - } - } - } - - companion object { - private const val TAG = "ArtifactDetailViewModel" - - fun factory( - activeUserPublicKey: HexKey, - artifactId: String, - chatRoomId: String, - relayHint: String?, - initialArtifactDetailUIState: ArtifactDetailUIState = ArtifactDetailUIState.Loading, - mantraRepository: MantraRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - ArtifactDetailViewModel( - activeUserPublicKey = activeUserPublicKey, - artifactId = artifactId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialArtifactDetailUIState = initialArtifactDetailUIState, - mantraRepository = mantraRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt deleted file mode 100644 index 86c5e8f7..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ /dev/null @@ -1,485 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateListOf -import androidx.compose.runtime.mutableStateMapOf -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 com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.Job -import kotlinx.coroutines.TimeoutCancellationException -import kotlinx.coroutines.flow.take -import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeout -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.relays.RelayPool -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState -import kotlin.time.Duration.Companion.milliseconds - -/** - * One event the group signed, sent to the relays a member picks. - * - * Signing and sending are two acts here, on purpose. `FrostSigningManager.complete` - * files what a quorum signed and applies it locally, and nothing leaves the device; - * this is the second act, taken by a member, one event at a time, to relays they - * can see and change before pressing the button. What goes on the wire is the - * event exactly as the group signed it -- the signature is the group's, so any - * member holding the event can send it and no share of the key is needed. - * - * The send itself, [sendToRelays], is also what the entries screen's "Broadcast - * all" uses, one entry after another and each to the relays [defaultRelaysFor] - * would have seeded here; what is this screen's is the list the member edits - * and the rows that show each relay's answer. - * - * ### Why not the broadcast queue - * - * Everything the app publishes as itself goes through `BroadcastNostrEventRequest`, - * which is durable, retried and drained in the background. It is not used here - * because it hangs off a `NostrEvent` row, and a row for the group's event is - * more than a queue entry: the home feed selects by kind, so the group's post - * would appear in it as if it were anybody's; and the sync loop offers every - * local event id to the relays it reconciles with, so the event would reach - * relays this screen never named. `GroupSignedEvent` explains at length why it is - * not a `NostrEvent`; this keeps that true. The cost is that a broadcast is only - * as durable as the button press -- what each relay said is shown, and a relay - * that did not answer is sent to again by pressing again. - * - * ### Where the relays come from - * - * [defaultRelaysFor]: the group's own General list where it has agreed one, the - * app's publish set where it has not, plus the indexers for a relay list, minus - * anything the group has blocked. The member can add and remove before sending, and the - * seeded list is a suggestion rather than a rule. - */ -class BroadcastGroupSignedEventViewModel( - val chatRoomId: String, - val signedEventId: HexKey, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialBroadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState, - val chatRepository: ChatRepository, - val publishTransport: EventPublishTransport, -): ViewModel() { - - var broadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState by mutableStateOf( - initialBroadcastGroupSignedEventUIState - ) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * The relays the event will be sent to, in the order they are shown. - * - * Held on the view model rather than in the composition, like the relay - * editor's working copy, so a rotation does not empty the list. - */ - val relays = mutableStateListOf() - - /** - * What each relay said the last time the button was pressed. - * - * Keyed by relay rather than kept as a list, because a relay removed after it - * answered takes its answer with it, and one added afterwards has none until - * the next press. - */ - val outcomes = mutableStateMapOf() - - /** - * Why the last add did not happen, or null. Cleared by the next keystroke. - * - * The same two refusals as the relay editor's, for the same reason: an add - * button that does nothing for a URL it refuses is indistinguishable from a - * missed tap. - */ - var addFailure: AddFailure? by mutableStateOf(null) - private set - - /** - * How the last press went, or null before the first one. - * - * Shown on the screen rather than flashed in a snackbar, because it is the - * answer the member came for and it should still be there after the rows - * under it have been read. Cleared when the next press starts. - */ - var lastBroadcast: BroadcastSummary? by mutableStateOf(null) - private set - - private var isSeeded = false - - /** [accepted] of [asked] relays said OK. */ - data class BroadcastSummary(val accepted: Int, val asked: Int) - - enum class AddFailure { - /** Not a `wss://` URL, or one pointing at this machine. */ - NotARelay, - - /** Already in the list, which is a no-op rather than a mistake. */ - AlreadyListed, - } - - /** One relay's answer to one press of the button. */ - sealed interface RelayOutcome { - /** Asked, and not yet answered. */ - data object Sending : RelayOutcome - - /** The relay's OK: it holds the event now, or already did. */ - data object Accepted : RelayOutcome - - /** The relay answered and said no, in its own words. */ - data class Rejected(val reason: String) : RelayOutcome - - /** The relay could not be asked: no connection, or one that dropped. */ - data class Failed(val reason: String) : RelayOutcome - - /** Asked, and still unanswered when the whole broadcast ran out of time. */ - data object NoAnswer : RelayOutcome - } - - fun initiateBroadcastGroupSignedEvent() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - val signedEvent = chatRepository.groupSignedEvent(chatRoomId, signedEventId) - - broadcastGroupSignedEventUIState = when { - localChatRoom == null -> - BroadcastGroupSignedEventUIState.Error("Couldn't find the chat room") - - signedEvent == null -> - BroadcastGroupSignedEventUIState.Error( - "This device doesn't hold that signed event" - ) - - // The group's wallet statement carries its xpub: on a relay it is - // every address and the whole balance, to anyone. - signedEvent.kind in GroupWalletStatementEvent.NEVER_BROADCAST -> - BroadcastGroupSignedEventUIState.Error( - "The group's wallet stays inside the group" - ) - - else -> BroadcastGroupSignedEventUIState.Loaded( - localChatRoom = localChatRoom, - signedEvent = signedEvent, - relayLists = chatRepository.groupRelayLists(chatRoomId), - ) - } - } - } - - /** - * Fills the list from what the group has said, once. - * - * Called from the screen rather than from the loader, for the reason the - * relay editor's `seedWorkingCopy` gives: a preview and a layout test hand a - * loaded state straight in. Once and only once, so a member who emptied the - * list on purpose does not find it refilled by a state the view model re-emits. - */ - fun seedRelays( - relayLists: List, - kind: Kind, - ) { - if (isSeeded) return - isSeeded = true - - relays.addAll(defaultRelaysFor(relayLists, kind)) - } - - fun clearAddFailure() { - addFailure = null - } - - /** - * Adds [url] to the list, or says why it did not. - * - * True when the row appeared, which is the caller's cue to clear the field. - */ - fun addRelay(url: String): Boolean { - val relayUrl = GroupRelaySet.relayUrlOrNull(url) ?: run { - addFailure = AddFailure.NotARelay - return false - } - - if (relayUrl in relays) { - addFailure = AddFailure.AlreadyListed - return false - } - - relays.add(relayUrl) - addFailure = null - return true - } - - fun removeRelay(relayUrl: NormalizedRelayUrl) { - relays.remove(relayUrl) - outcomes.remove(relayUrl) - } - - /** - * Sends [signedEvent] to every relay in the list and records what each said. - * - * The send itself is [sendToRelays], which the entries screen's - * "Broadcast all" shares; what is this screen's is the state around it. - * Each answer lands in [outcomes] as it arrives, so the rows fill in one - * by one rather than all at the end, and [lastBroadcast] sums it up once - * every row has settled. - * - * [onNoRelays] instead of a send to nobody: an empty list is a question - * rather than a mistake, and the pool would otherwise fall back to the - * *member's* relays, which is not what an empty list on this screen means. - * - * Returns the send, for a caller that has to wait for it, and null when - * nothing was sent. - */ - fun broadcast( - signedEvent: GroupSignedEvent, - onNoRelays: () -> Unit, - ): Job? { - // Guard against double submits. A second press while the first is out - // would answer each relay's OK twice and count it twice. - if (isActionPending.value) return null - - val targets = relays.toList() - if (targets.isEmpty()) { - onNoRelays.invoke() - return null - } - - isActionPending.value = true - lastBroadcast = null - outcomes.clear() - targets.forEach { outcomes[it] = RelayOutcome.Sending } - - return viewModelScope.launch(Dispatchers.IO) { - val settled = sendToRelays(publishTransport, signedEvent, targets) { relay, outcome -> - outcomes[relay] = outcome - } - - lastBroadcast = BroadcastSummary( - accepted = settled.count { it.value == RelayOutcome.Accepted }, - asked = targets.size, - ) - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "BroadcastGroupSignedEventViewModel" - - private val logger = Logger.withTag(TAG) - - /** - * A ceiling on the whole broadcast, past the pool's own per-relay wait, - * so a socket that opens and then says nothing cannot hold the button - * down forever. The same bound the queue drainer puts on one attempt. - */ - val BROADCAST_TIMEOUT = (RelayPool.PUBLISH_TIMEOUT * 2).milliseconds - - /** - * Sends [signedEvent] to [targets] and says what each relay answered. - * - * One call to the pool for the whole list, which opens a socket to any - * relay it does not hold and answers once per relay -- an OK, a - * rejection with the relay's reason, or the error that stopped it being - * asked. Each answer goes to [onOutcome] as it arrives, so a caller - * showing rows can fill them in one by one rather than all at the end; - * a relay that has not answered when the whole thing runs out of time - * is marked so, which is different from having been refused, and one - * the pool refused to ask at all is marked failed with the pool's reason. - * - * Returns once every relay has settled, with the answers in the order - * [targets] gave them. Shared by the one-event screen and the entries - * screen's "Broadcast all", so that what a relay's answer becomes is - * decided in one place. - */ - suspend fun sendToRelays( - publishTransport: EventPublishTransport, - signedEvent: GroupSignedEvent, - targets: List, - onOutcome: (NormalizedRelayUrl, RelayOutcome) -> Unit = { _, _ -> }, - ): Map { - // The second line of the refusal the loader makes, for the callers that - // never pass through it -- "Broadcast all" among them. - require(signedEvent.kind !in GroupWalletStatementEvent.NEVER_BROADCAST) { - "kind ${signedEvent.kind} never leaves the group" - } - - val outcomes = mutableMapOf() - - fun settle(relay: NormalizedRelayUrl, outcome: RelayOutcome) { - outcomes[relay] = outcome - onOutcome(relay, outcome) - } - - try { - withTimeout(BROADCAST_TIMEOUT) { - publishTransport.publishEvent( - nostrEvent = wireEventOf(signedEvent), - relays = targets.map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), - ) - // One answer per relay is all the pool ever gives, and the - // flow underneath never completes on its own. - .take(targets.size) - .collect { result -> - outcomeOf(targets, result)?.let { (relay, outcome) -> settle(relay, outcome) } - } - } - } catch (e: TimeoutCancellationException) { - // Ordinary: a relay that never answers is what the timeout is - // for. The relays still unanswered are settled below. - logger.w("Broadcast of ${signedEvent.id} ran out of time") - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - // The pool refused the whole call rather than one relay's part of - // it, so every relay that was waiting gets the same answer. - logger.e("Broadcast of ${signedEvent.id} failed before any relay answered", e) - targets.forEach { relay -> - if (relay !in outcomes) settle(relay, RelayOutcome.Failed(e.message ?: "Could not send")) - } - } - - targets.forEach { relay -> - if (relay !in outcomes) settle(relay, RelayOutcome.NoAnswer) - } - - return targets.associateWith { outcomes.getValue(it) } - } - - /** - * One relay's answer, against the relay that was asked. - * - * Matched by host rather than by string, because the pool names a relay - * by the URL it first opened a socket with, and that may carry a - * trailing slash the caller's spelling does not. Null for an answer - * from a relay nobody asked, which is logged and dropped. - */ - private fun outcomeOf( - targets: List, - result: NostrPublishResult, - ): Pair? { - val answered = NormalizedRelayUrl(result.relayUrl).displayUrl() - val relay = targets.firstOrNull { it.displayUrl() == answered } ?: run { - logger.w("Answer from ${result.relayUrl}, which was not asked") - return null - } - - val error = result.error - val ok = result.result as? NostrIncomingMessage.OkMessage - - return relay to when { - // The pool wraps a relay's ["OK", id, false, reason] in this one - // exception type and nothing else in it, so the message is the - // relay's reason in the relay's words. - error is NostrPublishException -> RelayOutcome.Rejected(error.message ?: "Rejected") - error != null -> RelayOutcome.Failed(error.message ?: "Could not send") - ok?.success == true -> RelayOutcome.Accepted - else -> RelayOutcome.Failed("No OK from the relay") - } - } - - /** - * The event as the pool wants it, and nothing more. - * - * A `NostrEvent` built to be serialised and dropped -- it is never - * written to the table, which is the whole point of this screen sending - * directly rather than through the queue. The seven fields are the ones - * the id was hashed over, so what goes out is what the group signed. - */ - fun wireEventOf(signedEvent: GroupSignedEvent): NostrEvent = NostrEvent( - id = signedEvent.id, - pubKey = signedEvent.publicKey, - kind = signedEvent.kind, - tags = signedEvent.tags, - content = signedEvent.content, - sig = signedEvent.signature, - createdAt = signedEvent.createdAt, - ) - - /** - * Where an event of [kind] should go, before the member has said otherwise. - * - * The group's General list is the answer NIP-65 gives -- its write relays, - * where it has agreed any -- and the app's own publish set stands in for a - * group that has not, since a list of nothing would make the button a - * no-op on every group until somebody edits it. A relay list goes to the - * indexers as well: the list says where to find the group, so sending it - * only to the relays it names is circular -- a reader who already knew - * those relays would not need the list. - * - * And nothing goes to a relay the group has blocked, whatever the other - * lists say; that is what a blocked list is for. - */ - fun defaultRelaysFor( - relayLists: List, - kind: Kind, - ): List { - val general = relayLists.firstOrNull { it.set == GroupRelaySet.General } - ?.relays.orEmpty() - .filter { it.write } - .map { it.url } - - val where = general.ifEmpty { Relays.eventPublishRelaySet.toList() } - - val indexers = if (kind in GroupRelaySet.KINDS) { - Relays.DefaultIndexerRelayList.toList() - } else { - emptyList() - } - - val blocked = relayLists.firstOrNull { it.set == GroupRelaySet.Blocked } - ?.relays.orEmpty() - .map { it.url } - .toSet() - - return (where + indexers).distinct().filterNot { it in blocked } - } - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - signedEventId: HexKey, - initialBroadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState = - BroadcastGroupSignedEventUIState.Loading, - chatRepository: ChatRepository, - publishTransport: EventPublishTransport, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - BroadcastGroupSignedEventViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = signedEventId, - initialBroadcastGroupSignedEventUIState = initialBroadcastGroupSignedEventUIState, - chatRepository = chatRepository, - publishTransport = publishTransport, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt deleted file mode 100644 index 62ad9653..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChapterDetailViewModel.kt +++ /dev/null @@ -1,72 +0,0 @@ -package com.machankura.bennu.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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.ChapterDetailUIState - -class ChapterDetailViewModel( - val chapterId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialChapterDetailUIState: ChapterDetailUIState, - val mantraRepository: MantraRepository, -): ViewModel() { - - var chapterDetailUIState: ChapterDetailUIState by mutableStateOf(initialChapterDetailUIState) - private set - - private val logger = Logger.withTag(TAG) - - fun initiateChapterDetail() { - logger.d("initiateChapterDetail: $chapterId") - viewModelScope.launch(Dispatchers.IO) { - val chapter = mantraRepository.getChapter(chapterId) - - chapterDetailUIState = if (chapter == null) { - ChapterDetailUIState.Error("Couldn't find the chapter") - } else { - ChapterDetailUIState.Loaded( - chapter = chapter, - chunks = mantraRepository.getChunksForChapter(chapterId), - ) - } - } - } - - companion object { - private const val TAG = "ChapterDetailViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chapterId: String, - chatRoomId: String, - relayHint: String?, - initialChapterDetailUIState: ChapterDetailUIState = ChapterDetailUIState.Loading, - mantraRepository: MantraRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - ChapterDetailViewModel( - activeUserPublicKey = activeUserPublicKey, - chapterId = chapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialChapterDetailUIState = initialChapterDetailUIState, - mantraRepository = mantraRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt index 3b9e247f..fadac727 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt @@ -204,6 +204,7 @@ class ChatMessageListViewModel( observeProposalsAwaitingYou() observeCeremoniesAwaitingYou() askForGroupHistory() + forwardGuardedWallets() resumeSigningSessions() } @@ -313,6 +314,22 @@ class ChatMessageListViewModel( } } + /** + * Tells the groups above this one about every guarded wallet it holds that + * they have not heard of: the catch-up behind the arrival triggers, which + * covers a wallet that arrived while this device was offline, one the + * elected device never sent, and every one filed before forwarding existed. + * `docs/guarded-wallet-forwarding.md`, D5. A Marmot room only -- a guardian + * is a group with a key, and a group with a key has an MLS room. + */ + private fun forwardGuardedWallets() { + if (localChatRoom.chatRoom.mlsGroupState == null) return + viewModelScope.launch(Dispatchers.IO) { + runCatching { chatRepository.forwardGuardedWallets(localChatRoom.chatRoom.id) } + .onFailure { logger.w(throwable = it) { "Could not tell the groups above about this group's guarded wallets" } } + } + } + /** * Lets this room's answered signing sessions take any step they are able to. * diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt index 39c5adf2..68bb49af 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -14,7 +14,6 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.HomeRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route @@ -26,6 +25,9 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch import com.machankura.bennu.compose.database.model.types.MarmotReindexReport +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.vitorpamplona.quartz.nip01Core.core.Event class ChatRoomDetailViewModel( val chatRoomId: String, @@ -34,7 +36,8 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState: ChatRoomDetailUIState, val nostrRepository: NostrRepository, val chatRepository: ChatRepository, - val mantraRepository: MantraRepository, + /** The member wallets this group guards -- `docs/member-guarded-wallets.md`. The no-op lists none. */ + val memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, ): ViewModel() { var chatRoomDetailUIState: ChatRoomDetailUIState by mutableStateOf(initialChatRoomDetailUIState) @@ -89,29 +92,63 @@ class ChatRoomDetailViewModel( val isDisbanded = group?.currentGroupState()?.isDisbanded == true val canGovern = group != null && group.isLocalAdmin() && !isDisbanded && localChatRoom.chatRoom.leftGroupAt == null + // A direct chat is a Marmot room of two with no key, and not a group + // that guards anybody's wallet: no section, no button. + // docs/member-wallet-delay.md. + val couldGuard = memberWalletRepository.couldGuard(chatRoomId) + ChatRoomDetailUIState.Loaded( localChatRoom = localChatRoom, groupKeyState = chatRepository.groupKeyState(chatRoomId), signedGroupKeyStateEvent = chatRepository.signedGroupKeyStateEvent(chatRoomId), subgroups = chatRepository.subgroupsOf(chatRoomId), parentChatRoomId = chatRepository.parentOf(chatRoomId), - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - groupRelayLists = chatRepository.groupRelayLists(chatRoomId), - groupPosts = chatRepository.groupPosts(chatRoomId), + walletPolicy = chatRepository.walletPolicyOf(chatRoomId), + guardianDelay = chatRepository.guardiansOf(chatRoomId)?.firstOrNull()?.delay, groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain), testNetworkWallet = if (GroupLightningRollout.ENABLED && GroupLightningRollout.NETWORK != NodeParamsManager.chain) { chatRepository.groupWallet(chatRoomId, GroupLightningRollout.NETWORK) } else null, lightningParticipants = if (GroupLightningRollout.ENABLED) chatRepository.lightningParticipants(chatRoomId, GroupLightningRollout.NETWORK) else emptySet(), - canEditNostrProfile = canSign, canAddSubgroup = canSign, canGovern = canGovern, isDisbanded = isDisbanded, + memberWallets = memberWalletRepository.memberWalletsOf(chatRoomId), + // Offered wherever the new-wallet screen could get somewhere: + // a group, a profile that signs, a network it is open on. A key + // this device does not know yet is that screen's to ask for. + canAskForMemberWallet = !isDisbanded && couldGuard && memberWalletRepository.refusal(chatRoomId, NodeParamsManager.chain).let { + it == null || it == MemberWalletManager.Refusal.KEY_UNKNOWN + }, + canSponsor = canSign, + memberWalletPolicy = memberWalletRepository.policyOf(chatRoomId), + // Everybody in a Marmot group sees whether it guards members' + // wallets; only a signer is offered to change it. + showsMemberWalletPolicy = !isDisbanded && couldGuard, ) } } } + /** + * Puts a member's request for a guarded wallet to the group, as this device: + * a signing session over the certificate it asks for, which proposing counts + * as approving. [onSuccess] gets the session, for the screen to move onto. + */ + fun putToGroup(request: Event, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + if (isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { memberWalletRepository.putToGroup(chatRoomId, request) } + .onFailure { logger.e("Couldn't put a member's wallet to $chatRoomId", it) } + .getOrNull() + viewModelScope.launch(Dispatchers.Main) { + isActionPending.value = false + if (session != null) onSuccess(session.id) else onFailure() + } + } + } + /** * Removes [memberPublicKey] as an admin, and reloads the screen. The commit is * applied when a relay accepts it, so the member's row stays until then; the @@ -224,7 +261,7 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading, nostrRepository: NostrRepository, chatRepository: ChatRepository, - mantraRepository: MantraRepository, + memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, ): ViewModelProvider.Factory = viewModelFactory { initializer { ChatRoomDetailViewModel( @@ -234,7 +271,7 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState = initialChatRoomDetailUIState, nostrRepository = nostrRepository, chatRepository = chatRepository, - mantraRepository = mantraRepository, + memberWalletRepository = memberWalletRepository, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModel.kt new file mode 100644 index 00000000..be4898e6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModel.kt @@ -0,0 +1,184 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +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.IO +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import com.machankura.bennu.compose.database.model.types.ChatRoomType +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.managers.ChillDkgRitualManager +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState +import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState.Refused.Reason + +/** + * Starts a NIP-17 group's own key ceremony. + * + * Everything about *starting* that the ceremony screen used to carry: the + * quorum, the size check, and the proposal. The ceremony screen only shows one + * now, so nothing it draws can be mistaken for a way to open another. + * + * The refusals are made here rather than by hiding a button, so the screen can + * say why, and `ChillDkgRitualManager.proposeRitual` makes the Marmot one again + * underneath -- a screen not drawing something is not a guard. + */ +class CreateSharedKeyViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + initialUIState: CreateSharedKeyUIState, + val activeIdentityStateFlow: StateFlow, + val chatRepository: ChatRepository, + val dkgRepository: DkgRepository, +) : ViewModel() { + + var uiState: CreateSharedKeyUIState by mutableStateOf(initialUIState) + private set + + private val logger = Logger.withTag(TAG) + + val isActionPending: MutableState = mutableStateOf(false) + + /** + * The quorum the ceremony will generate a key for. Pre-filled with the same + * majority default the group-creation screen offers. + */ + val threshold: MutableState = mutableStateOf(ChatRoomType.MINIMUM_QUORUM) + + fun initiate() { + uiState = CreateSharedKeyUIState.Loading + + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (localChatRoom == null) { + uiState = CreateSharedKeyUIState.Error(CreateSharedKeyUIState.Error.Reason.ROOM_NOT_FOUND) + return@launch + } + + if (ChillDkgRitualManager.isMarmotRoom(localChatRoom)) { + uiState = CreateSharedKeyUIState.Refused(Reason.MARMOT_ROOM) + return@launch + } + + if (!ChillDkgRitualManager.canRunRitual(localChatRoom)) { + uiState = CreateSharedKeyUIState.Refused(Reason.TOO_FEW_MEMBERS) + return@launch + } + + // The room's own, which in a NIP-17 room is every ceremony it holds: + // subgroups run in their parent's Marmot room. A finished one counts -- + // the group has its key, and the ceremony screen is where the next step + // after it is offered. + val own = dkgRepository.observeLatestSessionForChatRoom(chatRoomId, parentChatRoomId = null) + .first() + if (own != null && own.stage != DkgRitualStage.FAILED) { + uiState = CreateSharedKeyUIState.Existing(own.id) + return@launch + } + + val participantCount = ChillDkgRitualManager.memberPublicKeys(localChatRoom).size + threshold.value = ChatRoomType.defaultQuorum(participantCount) + .coerceIn(quorumRange(participantCount)) + + uiState = CreateSharedKeyUIState.Loaded( + localChatRoom = localChatRoom, + participantCount = participantCount, + ) + } + } + + fun quorumRange(): IntRange { + val loaded = uiState as? CreateSharedKeyUIState.Loaded + ?: return ChatRoomType.quorumRange(ChatRoomType.MINIMUM_QUORUM) + + return quorumRange(loaded.participantCount) + } + + // Below the minimum the range runs backwards and is empty, which `coerceIn` + // rejects outright. There is no ceremony to run at that size either. + private fun quorumRange(participantCount: Int): IntRange = + ChatRoomType.quorumRange(maxOf(participantCount, ChatRoomType.MINIMUM_QUORUM)) + + fun setThreshold(value: Int) { + if (isActionPending.value) return + + threshold.value = value.coerceIn(quorumRange()) + } + + /** + * Opens the ceremony, making this device its coordinator, and hands over to + * the screen that shows it. + */ + fun create(onCreated: (dkgSessionId: String) -> Unit) { + if (isActionPending.value) return + + val loaded = uiState as? CreateSharedKeyUIState.Loaded ?: return + + val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey + if (nostrPrivateKey == null) { + uiState = CreateSharedKeyUIState.Error(CreateSharedKeyUIState.Error.Reason.NO_KEYS) + return + } + + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + // A ceremony somebody else opened since this screen loaded comes back + // here rather than a second one -- `proposeRitual` checks again. + val session = dkgRepository.proposeRitual( + localChatRoom = loaded.localChatRoom, + userPublicKey = activeUserPublicKey, + nostrPrivateKey = nostrPrivateKey.value.toByteArray(), + threshold = threshold.value + ) + + isActionPending.value = false + + if (session == null) { + logger.e("Failed to start a key ceremony in $chatRoomId") + uiState = CreateSharedKeyUIState.Error(CreateSharedKeyUIState.Error.Reason.NOT_STARTED) + return@launch + } + + withContext(Dispatchers.Main) { onCreated(session.id) } + } + } + + companion object { + private const val TAG = "CreateSharedKeyViewModel" + + fun factory( + chatRoomId: String, + activeUserPublicKey: HexKey, + initialUIState: CreateSharedKeyUIState = CreateSharedKeyUIState.Loading, + activeIdentityStateFlow: StateFlow, + chatRepository: ChatRepository, + dkgRepository: DkgRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + CreateSharedKeyViewModel( + chatRoomId = chatRoomId, + activeUserPublicKey = activeUserPublicKey, + initialUIState = initialUIState, + activeIdentityStateFlow = activeIdentityStateFlow, + chatRepository = chatRepository, + dkgRepository = dkgRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt index 0929979d..8d14e090 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt @@ -10,9 +10,7 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.machankura.bennu.compose.database.model.types.DkgApprovalStep -import com.machankura.bennu.compose.database.model.types.DkgRitualStage import com.machankura.bennu.compose.database.model.types.FrostSigningStage -import com.machankura.bennu.compose.database.model.types.ChatRoomType import com.machankura.bennu.compose.managers.ChillDkgRitualManager import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SharedKeyDerivation @@ -35,25 +33,42 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind import com.machankura.bennu.compose.identity.Identity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO -import kotlinx.coroutines.Job +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.mapLatest +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalFrostSigningSession import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch /** - * Watches a group's ChillDKG ritual, and opens one on request. + * Watches one ChillDKG ritual, and the steps that follow it. * * Nothing here drives the protocol — the ritual advances in * [ChillDkgRitualManager] as messages arrive on the inbound path, so this only * has to read the session and show it moving. + * + * It never opens one. That is `CreateSharedKeyViewModel`'s job for a group's own + * key, and the subgroup picker's for a subgroup's: a screen that showed a + * ceremony and offered to start one from the same button is how a member + * approving a subgroup's ceremony opened a second -- see + * docs/ceremony-creation.md. */ +@OptIn(ExperimentalCoroutinesApi::class) class DkgRitualViewModel( val chatRoomId: String, val activeUserPublicKey: HexKey, - /** - * The ceremony to show, when the caller knew which. Null falls back to the - * room's newest -- see [DkgRitualRoute.dkgSessionId]. - */ - val dkgSessionId: String? = null, + /** The ceremony to show -- see [DkgRitualRoute.dkgSessionId]. */ + val dkgSessionId: String, initialDkgRitualUIState: DkgRitualUIState, val activeIdentityStateFlow: StateFlow, val chatRepository: ChatRepository, @@ -67,73 +82,24 @@ class DkgRitualViewModel( val isActionPending: MutableState = mutableStateOf(false) - /** Watches the current session's messages; replaced whenever the session changes. */ - private var messageObserver: Job? = null - - /** Watches the room's signing sessions, which is where the key state is agreed. */ - private var keyStateObserver: Job? = null - - /** Watches the parent certifying this subgroup; re-pointed as the purpose is learned. */ - private var certificateObserver: Job? = null + /** Whether [initiate] has run. The view model's to decide, not the screen's. */ + private var initiated = false /** - * The parent [observeCertificate] is currently watching, so a re-emission of - * the same session does not tear the watchers down and stand them up again. + * Members the admin room is waiting on for a key package. The one part of the + * state an action writes rather than a flow, so it is a flow too, and goes + * through the same single write as everything else. */ - private var watchedParentChatRoomId: HexKey? = null - - /** The ceremony [observeForCeremony] is currently watching. */ - private var watchedSessionId: String? = null - - /** - * The quorum the ritual will generate a key for. Pre-filled with the same - * majority default the group-creation screen offers. - * - * TODO: the quorum chosen at creation time is not persisted on ChatRoom, so - * it cannot be read back here. Storing it there would let this default to - * what the group was actually promised rather than re-deriving it. - */ - val threshold: MutableState = mutableStateOf(ChatRoomType.MINIMUM_QUORUM) - - /** - * Whether this device can open a ceremony right now. - * - * Any member may: ChillDKG gives the coordinator no say in the outcome, and a - * NIP-17 room records no creator to reserve the job for. What rules it out is - * a ceremony already running, or a group too small to split a key across. - */ - fun canStartRitual(): Boolean { - val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return false - - if (loaded.session != null && loaded.session.stage != DkgRitualStage.FAILED) return false - - // Not just the ceremony on screen. A room can hold more than one, and this - // screen exists to offer one to a room that has none -- so a room with a - // ceremony running under a different purpose must not be offered another, - // whatever this screen happens to be showing. - if (loaded.roomHasCeremony) return false - - return ChillDkgRitualManager.canRunRitual(loaded.localChatRoom) - } - - fun quorumRange(): IntRange { - val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded - ?: return ChatRoomType.quorumRange(ChatRoomType.MINIMUM_QUORUM) - - // Below the minimum the range runs backwards and is empty, which `coerceIn` - // rejects outright. There is no ritual to run at that size either. - return ChatRoomType.quorumRange( - maxOf(loaded.participantCount, ChatRoomType.MINIMUM_QUORUM) - ) - } - - fun setThreshold(value: Int) { - if (isActionPending.value) return - - threshold.value = value.coerceIn(quorumRange()) - } + private val adminGroupBlockedOn = MutableStateFlow>(emptyList()) fun initiate() { + // The screen asks every time it comes back into view -- returning from an + // approval screen, say -- and starting again used to reset the state to + // "no ceremony" and stack a second set of watchers on the first. The + // first run's watchers are still running, so there is nothing to start. + if (initiated) return + initiated = true + viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) if (localChatRoom == null) { @@ -141,210 +107,193 @@ class DkgRitualViewModel( return@launch } - dkgRitualUIState = DkgRitualUIState.Loaded(localChatRoom = localChatRoom) - threshold.value = ChatRoomType - .defaultQuorum(ChillDkgRitualManager.memberPublicKeys(localChatRoom).size) - .coerceIn(quorumRange()) + // One writer. Every part of the screen used to be its own coroutine + // reading the state, copying one field and writing it back, and one + // that read before another wrote put the other's field back the way it + // was -- which could leave the screen with no ceremony on it, offering + // to start one. Now each part is a flow and the state is built from all + // of them at once. + ceremonyState(localChatRoom).collect { state -> + // An action that failed has said so; a later emission must not + // paper over it. + if (dkgRitualUIState is DkgRitualUIState.Error) return@collect - observeKeyState() + dkgRitualUIState = state + } + } + } - // Room-scoped, deliberately. Only the member who opened a subgroup - // arrives here knowing it is one -- everybody else reaches this screen - // from the room, through the transcript's ritual notice or the group's - // details, neither of which has a purpose to hand it. Filtering by one - // here left every other member looking at a room whose ceremony had - // started and being told none had. - // - // So the purpose is read off the session rather than required to open - // it. `getLatestSessionFor` is still scoped where scoping is the - // question being asked -- "may I open another" -- in `proposeRitual` - // and `refuseCeremonyRoom`. - // The named ceremony where the caller knew which, and the room's - // newest otherwise. A room holds more than one the moment a subgroup's - // admins are the whole group, and then "the room's newest" is whichever - // ceremony was opened last -- routinely the group's own, already - // finished, while the subgroup's request goes unanswered underneath it. - val sessions = dkgSessionId - ?.let { dkgRepository.observeSessionById(it) } - ?: dkgRepository.observeLatestSessionForChatRoom(chatRoomId) + /** + * The whole screen as one flow, so no part of it can overwrite another. + * + * The purpose -- a group's own key or a subgroup's -- is read off the + * session rather than handed in, because only the member who opened a + * subgroup arrives knowing it is one; everybody else comes from a transcript + * line that names the ceremony and nothing more. + */ + private fun ceremonyState(localChatRoom: LocalChatRoom): Flow { + val sessions = dkgRepository.observeSessionById(dkgSessionId) - // Whether the room has any ceremony at all, which is a different - // question from which one is being shown -- see - // `DkgRitualUIState.roomHasCeremony`. - launch { - dkgRepository.observeLatestSessionForChatRoom(chatRoomId).collect { newest -> - val current = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return@collect - - dkgRitualUIState = current.copy( - roomHasCeremony = newest != null && newest.stage != DkgRitualStage.FAILED - ) + // The session in which the group agrees what its admin room will sign + // with. Matched on the ceremony the state names, not on being the newest + // key state in the room: a subgroup's ceremony runs in its parent's room, + // and so does every other subgroup's, so the newest one there is as + // likely a sibling's as this one's. + val keyStateSession = dkgRepository.observeSigningSessions(chatRoomId) + .map { sessions -> + sessions.firstCarrying(GroupKeyStateEvent.KIND) { + GroupKeyStateEvent.parseDkgSessionId(it.tags) == dkgSessionId } } - sessions.collect { session -> - val loaded = (dkgRitualUIState as? DkgRitualUIState.Loaded) - ?: DkgRitualUIState.Loaded(localChatRoom = localChatRoom) + // Everything about one ceremony, re-pointed when the ceremony, its + // purpose or its key changes -- which for a member arriving cold is at + // most twice, the key arriving as the ceremony finishes -- and not on + // every change to the session row. + val parts = sessions + .map { Triple(it?.id, it?.parentChatRoomId, it?.thresholdPublicKey) } + .distinctUntilChanged() + .flatMapLatest { (sessionId, parent, key) -> ceremonyParts(sessionId, parent, key) } - // The session is the only thing that knows what the ceremony is - // for. The route used to carry it too, which was right for the one - // member who opened the subgroup and null for everybody else. - val parent = session?.parentChatRoomId + return combine( + sessions, + parts, + keyStateSession, + adminGroupBlockedOn, + ) { session, ceremony, keyState, blockedOn -> + Snapshot(session, ceremony, keyState, blockedOn) + } + // The parts lag the session by one emission when the ceremony changes; + // a state that drew one ceremony's counts under another's name is the + // thing this is here to stop. + .filter { it.ceremony.sessionId == it.session?.id } + .mapLatest { snapshot -> + // A ceremony this device has no row for. Every way here names one + // the device recorded -- a transcript line it wrote, or one it has + // just opened -- so this is a bug to say out loud rather than an + // empty screen to fill with an offer. + val session = snapshot.session + ?: return@mapLatest DkgRitualUIState.Error("Couldn't find this key ceremony") + val ceremony = snapshot.ceremony - dkgRitualUIState = loaded.copy( + DkgRitualUIState.Loaded( + localChatRoom = localChatRoom, session = session, - parentChatRoomId = parent, - pendingApproval = session?.let { dkgRepository.pendingApproval(it) } + hostKeyParticipants = ceremony.hostKeyParticipants, + round1Participants = ceremony.round1Participants, + round2Participants = ceremony.round2Participants, + // Computed here, before the one write, rather than read and + // written around a suspension: whether round 1 can be asked + // for depends on how many host keys have arrived, which only + // the messages flow sees. + pendingApproval = dkgRepository.pendingApproval(session), + adminGroupBlockedOn = snapshot.adminGroupBlockedOn, + keyStateSession = snapshot.keyStateSession, + isKeyStateSigned = ceremony.isKeyStateSigned, + parentChatRoomId = session.parentChatRoomId, + isCertified = ceremony.isCertified, + certificateSession = ceremony.certificateSession, ) + } + } - // Re-point the per-ceremony watchers whenever the ceremony or its - // purpose changes, which for a member arriving cold is once. - // Everything downstream of this -- the key state, the certificate - // -- is about one ceremony, and the room cannot say which. - if (session?.id != watchedSessionId || parent != watchedParentChatRoomId) { - watchedSessionId = session?.id - watchedParentChatRoomId = parent - observeForCeremony(session?.id, parent) - } + /** + * One ceremony's messages, whether its key state has been signed, and -- for + * a subgroup -- whether its parent has certified it. + * + * The certificate is read off the *parent's* signed events and sessions + * rather than this room's: it is made where the parent's key can sign it, + * which is never the ceremony's room. An ordinary ceremony passes no parent + * and gets nothing watched there, which is exactly right. + * + * The parent's room holds a certificate session for every subgroup it has + * been asked about, so the one shown is the one naming [thresholdPublicKey]. + * Taking the newest regardless is how a parent's second subgroup opened on + * its first one's finished certificate, with the button to ask for its own + * already disabled. Before the ceremony has a key there is nothing to have + * certified, and no session is this one's. + */ + private fun ceremonyParts( + sessionId: String?, + parentChatRoomId: HexKey?, + thresholdPublicKey: HexKey?, + ): Flow { + if (sessionId == null) return flowOf(CeremonyParts(sessionId = null)) - // Re-point the message watcher at whatever session is current. An - // abandoned ritual's counts must not keep ticking over the new one. - messageObserver?.cancel() - if (session != null) { - messageObserver = viewModelScope.launch(Dispatchers.IO) { - dkgRepository.observeMessages(session.id).collect { messages -> - val current = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return@collect + val certified = parentChatRoomId + ?.let { parent -> dkgRepository.observeBirthCertificate(sessionId, parent).map { it != null } } + ?: flowOf(false) - fun senders(kind: Kind) = messages - .filter { it.kind == kind } - .map { it.participantPublicKey } - .toSet() - - dkgRitualUIState = current.copy( - hostKeyParticipants = senders(DkgRitualEvents.HOST_KEY), - round1Participants = senders(DkgRitualEvents.ROUND_1), - round2Participants = senders(DkgRitualEvents.ROUND_2), - // Recomputed here as well as on the session, because - // whether round 1 can be asked for depends on how many - // host keys have arrived, which only this flow sees. - pendingApproval = current.session - ?.let { dkgRepository.pendingApproval(it) } - ) - } + val certificateSession = parentChatRoomId + ?.takeIf { thresholdPublicKey != null } + ?.let { parent -> + dkgRepository.observeSigningSessions(parent).map { sessions -> + sessions.firstCarrying(SubgroupBirthCertificateEvent.KIND) { + SubgroupBirthCertificateEvent.parseThresholdPublicKey(it.tags) + .equals(thresholdPublicKey, ignoreCase = true) } } } + ?: flowOf(null) + + return combine( + dkgRepository.observeMessages(sessionId), + // Asked by ceremony rather than by room: the room holds however many + // ceremonies it holds, and the answer is about this one's key. + dkgRepository.observeSignedGroupKeyState(sessionId).map { it != null }, + certified, + certificateSession, + ) { messages, isKeyStateSigned, isCertified, certificate -> + fun senders(kind: Kind) = messages + .filter { it.kind == kind } + .map { it.participantPublicKey } + .toSet() + + CeremonyParts( + sessionId = sessionId, + hostKeyParticipants = senders(DkgRitualEvents.HOST_KEY), + round1Participants = senders(DkgRitualEvents.ROUND_1), + round2Participants = senders(DkgRitualEvents.ROUND_2), + isKeyStateSigned = isKeyStateSigned, + isCertified = isCertified, + certificateSession = certificate, + ) } } /** - * Follows the group agreeing what its admin room will sign with. - * - * Nothing here watches a [GroupKeyState] row, because there is no room yet - * for one to belong to -- being able to follow this before the room exists - * is the point. What is watched instead is the session, for how the signing - * is going, and the signed event, for whether it finished. - * - * The room a ceremony runs in signs nothing else, so the newest session in - * it is the key state's -- but it is matched on the kind it carries anyway, - * so a room that one day signs something else does not confuse the two. + * The newest signing session carrying an event of [kind] that is [about] + * this ceremony, if there is one. */ - private fun observeKeyState() { - keyStateObserver?.cancel() - keyStateObserver = viewModelScope.launch(Dispatchers.IO) { - // Two flows because they answer two questions off two tables. How - // the signing is going is the session row; whether it finished is - // the signed event, and only that second one can be asked at all - // before there is a room -- which is the whole point of asking it. - launch { - dkgRepository.observeSigningSessions(chatRoomId).collect { sessions -> - val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return@collect - - dkgRitualUIState = loaded.copy( - keyStateSession = sessions.firstOrNull { local -> - local.items.any { item -> - runCatching { - Event.fromJson(item.unsignedEventJson).kind - }.getOrNull() == GroupKeyStateEvent.KIND - } - }?.session - ) - } + private fun List.firstCarrying( + kind: Kind, + about: (Event) -> Boolean, + ): FrostSigningSession? = + firstOrNull { local -> + local.items.any { item -> + runCatching { Event.fromJson(item.unsignedEventJson) } + .getOrNull() + ?.let { it.kind == kind && about(it) } == true } + }?.session + /** What [ceremonyParts] knows about the ceremony named by [sessionId]. */ + private data class CeremonyParts( + val sessionId: String?, + val hostKeyParticipants: Set = emptySet(), + val round1Participants: Set = emptySet(), + val round2Participants: Set = emptySet(), + val isKeyStateSigned: Boolean = false, + val isCertified: Boolean = false, + val certificateSession: FrostSigningSession? = null, + ) - } - } - - /** - * Follows one ceremony: whether its key state has been signed, and -- for a - * subgroup -- whether its parent has certified it. - * - * Off the *parent's* signed events and sessions rather than this room's: the - * certificate is made where the parent's key can sign it, which is never the - * ceremony's room. - * - * Started from the session collector rather than at init, because a member - * who did not open the subgroup has no idea it is one until the proposal they - * were sent turns up. Cancelled and restarted on a change, the way the - * message watcher is -- an ordinary ceremony passes null and gets nothing - * watched, which is exactly right. - */ - private fun observeForCeremony(dkgSessionId: String?, parentChatRoomId: HexKey?) { - certificateObserver?.cancel() - - if (dkgSessionId == null) { - dkgRitualUIState = (dkgRitualUIState as? DkgRitualUIState.Loaded) - ?.copy(isKeyStateSigned = false, isCertified = false, certificateSession = null) - ?: dkgRitualUIState - return - } - - certificateObserver = viewModelScope.launch(Dispatchers.IO) { - // Whether the group has agreed what the room this ceremony's key - // derives will sign with. Asked by ceremony rather than by room: the - // room holds however many ceremonies it holds, and the answer is - // about this one's key. - launch { - dkgRepository.observeSignedGroupKeyState(dkgSessionId).collect { state -> - val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return@collect - - dkgRitualUIState = loaded.copy(isKeyStateSigned = state != null) - } - } - - if (parentChatRoomId == null) { - dkgRitualUIState = (dkgRitualUIState as? DkgRitualUIState.Loaded) - ?.copy(isCertified = false, certificateSession = null) - ?: dkgRitualUIState - return@launch - } - - launch { - dkgRepository.observeBirthCertificate(dkgSessionId, parentChatRoomId) - .collect { certificate -> - val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return@collect - - dkgRitualUIState = loaded.copy(isCertified = certificate != null) - } - } - - launch { - dkgRepository.observeSigningSessions(parentChatRoomId).collect { sessions -> - val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return@collect - - dkgRitualUIState = loaded.copy( - certificateSession = sessions.firstOrNull { local -> - local.items.any { item -> - runCatching { - Event.fromJson(item.unsignedEventJson).kind - }.getOrNull() == SubgroupBirthCertificateEvent.KIND - } - }?.session - ) - } - } - } - } + private data class Snapshot( + val session: DkgSession?, + val ceremony: CeremonyParts, + val keyStateSession: FrostSigningSession?, + val adminGroupBlockedOn: List, + ) /** * Asks the group to sign what its admin room will sign with. @@ -354,13 +303,13 @@ class DkgRitualViewModel( * ceremony's coordinator, who is also the member who will create the room. * * Nothing here waits for the answer: the signing runs on arriving messages - * like everything else, and the screen follows it through [observeKeyState]. + * like everything else, and the screen follows it through [ceremonyState]. */ fun proposeKeyState() { if (isActionPending.value) return val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return - val session = loaded.session ?: return + val session = loaded.session if (session.thresholdPublicKey == null) return // Nothing to ask for, and nobody to ask twice. A failed session is the @@ -416,7 +365,7 @@ class DkgRitualViewModel( * does by construction -- they are a parent admin, that is how they got here. * * Nothing waits for the answer. The session runs on arriving messages like - * every other, and [observeKeyState] follows it. + * every other, and [ceremonyState] follows it. */ fun proposeBirthCertificate() { if (isActionPending.value) return @@ -426,7 +375,7 @@ class DkgRitualViewModel( // any of the subgroup's admins -- see `SubgroupManager` -- and they reach // this screen from the room, with no route to have told them anything. val parent = loaded.parentChatRoomId ?: return - val session = loaded.session ?: return + val session = loaded.session if (session.thresholdPublicKey == null) return // Nothing to ask for, and nobody to ask twice. A failed session is the @@ -466,36 +415,21 @@ class DkgRitualViewModel( } } - /** Opens a ritual, making this device its coordinator, and publishes the proposal. */ - fun startRitual() { + /** + * Ends this ceremony for everyone in it. The screen asks the member to confirm + * first; the session flow delivers the failed row, so nothing is set here. + */ + fun abandon() { if (isActionPending.value) return val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return - - val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey - if (nostrPrivateKey == null) { - dkgRitualUIState = DkgRitualUIState.Error("Couldn't read your keys. Please try again.") - return - } + if (!loaded.canAbandon) return isActionPending.value = true viewModelScope.launch(Dispatchers.IO) { - val session = dkgRepository.proposeRitual( - localChatRoom = loaded.localChatRoom, - userPublicKey = activeUserPublicKey, - nostrPrivateKey = nostrPrivateKey.value.toByteArray(), - threshold = threshold.value - ) - + dkgRepository.abandon(loaded.localChatRoom, loaded.session.id) isActionPending.value = false - - if (session == null) { - logger.e("Failed to start DKG ritual for $chatRoomId") - dkgRitualUIState = DkgRitualUIState.Error("Couldn't start the key ceremony. Please try again.") - } - // On success the session flow above delivers the new row; no need to - // set it here and risk racing the observer. } } @@ -505,12 +439,17 @@ class DkgRitualViewModel( * Takes the step rather than reading it back from the state so a screen opened * for one step cannot approve a different one it has since moved on to — the * manager checks it against the ritual again and ignores a mismatch. + * + * [onApproved] runs once the approval has been sent, not when the button is + * pressed. The approval screens close on it, and closing one clears this view + * model and cancels its scope -- so closing first could cut the publish off, + * and on the last approval of a round nothing arrives afterwards to resume it. */ - fun approve(step: DkgApprovalStep) { + fun approve(step: DkgApprovalStep, onApproved: () -> Unit = {}) { if (isActionPending.value) return val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return - val session = loaded.session ?: return + val session = loaded.session val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey if (nostrPrivateKey == null) { @@ -531,6 +470,8 @@ class DkgRitualViewModel( isActionPending.value = false // The session flow delivers the updated row and with it the next pending // step, so nothing is set here. + + withContext(Main) { onApproved() } } } @@ -559,7 +500,7 @@ class DkgRitualViewModel( if (isActionPending.value) return val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return - val session = loaded.session ?: return + val session = loaded.session val thresholdPublicKey = session.thresholdPublicKey ?: return // The screen offers nothing until the group has signed, so this is a @@ -594,7 +535,7 @@ class DkgRitualViewModel( ?: if (subgroupParent != null) "Subgroup" else "Group" isActionPending.value = true - dkgRitualUIState = loaded.copy(adminGroupBlockedOn = emptyList()) + adminGroupBlockedOn.value = emptyList() viewModelScope.launch(Dispatchers.IO) { val outcome = chatRepository.createMarmotGroup( @@ -621,15 +562,13 @@ class DkgRitualViewModel( // Named rather than counted. A member cannot publish a key // package on somebody else's behalf, so the only useful thing // to say is whose door to knock on. - dkgRitualUIState = loaded.copy( - adminGroupBlockedOn = outcome.missing.map { publicKey -> - loaded.ritualMembers - .firstOrNull { it.participant.participantPublicKey == publicKey } - ?.profile - ?.humanReadableNameOrPubkey() - ?: publicKey.take(12) - } - ) + adminGroupBlockedOn.value = outcome.missing.map { publicKey -> + loaded.ritualMembers + .firstOrNull { it.participant.participantPublicKey == publicKey } + ?.profile + ?.humanReadableNameOrPubkey() + ?: publicKey.take(12) + } } is MarmotGroupCreation.Outcome.Failed -> { @@ -659,13 +598,6 @@ class DkgRitualViewModel( } } - override fun onCleared() { - messageObserver?.cancel() - keyStateObserver?.cancel() - certificateObserver?.cancel() - super.onCleared() - } - companion object { private const val TAG = "DkgRitualViewModel" @@ -675,7 +607,7 @@ class DkgRitualViewModel( fun factory( chatRoomId: String, activeUserPublicKey: HexKey, - dkgSessionId: String? = null, + dkgSessionId: String, initialDkgRitualUIState: DkgRitualUIState = DkgRitualUIState.Loading, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt deleted file mode 100644 index 8467072f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt +++ /dev/null @@ -1,161 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -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.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupNostrProfileUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * Asks the group to sign what it says about itself on nostr. - * - * The room's id is the pubkey the group signs as, so the kind:0 this proposes is - * the profile the rest of nostr would read for that key -- authored by the group - * rather than by whoever filled the form in. Nothing is saved when the button is - * pressed: what goes out is a proposal, and the profile changes on every member's - * device at once when a quorum has signed it. - */ -class EditGroupNostrProfileViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var editGroupNostrProfileUIState: EditGroupNostrProfileUIState by mutableStateOf( - initialEditGroupNostrProfileUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateEditGroupNostrProfile() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - editGroupNostrProfileUIState = if (localChatRoom == null) { - EditGroupNostrProfileUIState.Error("Couldn't find the chat room") - } else { - EditGroupNostrProfileUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room has no key of its own to sign as, so it has no - // nostr identity to describe -- the same condition the group - // detail screen gates the entry point on. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Opens a session over one kind:0 for the group's own key. - * - * A blank field is not a field left alone: it clears what the group had said, - * because that is the only way to unsay it. [GroupNostrProfile.template] hands - * every field to `MetadataEvent`, whose rule for these arguments is that empty - * deletes the key -- and it builds on the group's newest profile, so a field - * this form does not offer is carried across rather than wiped. - * - * The fields are not cleared on success, unlike the add forms': a profile is - * standing state rather than a thing being added, and this screen is replaced - * by the signing session anyway. - */ - fun proposeNostrProfile( - localChatRoom: LocalChatRoom, - groupNostrProfile: GroupNostrProfile?, - nameField: TextFieldState, - aboutField: TextFieldState, - pictureField: TextFieldState, - websiteField: TextFieldState, - nip05Field: TextFieldState, - lud16Field: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits from repeated taps. A second session over a - // second kind:0 would leave the group's profile decided by whichever - // quorum finished last. - if (isActionPending.value) return - isActionPending.value = true - - val template = GroupNostrProfile.template( - latest = groupNostrProfile, - name = nameField.text.toString().trim(), - about = aboutField.text.toString().trim(), - picture = pictureField.text.toString().trim(), - website = websiteField.text.toString().trim(), - nip05 = nip05Field.text.toString().trim(), - lud16 = lud16Field.text.toString().trim(), - ) - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a nostr profile for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "EditGroupNostrProfileViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState = - EditGroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - EditGroupNostrProfileViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupNostrProfileUIState = initialEditGroupNostrProfileUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt deleted file mode 100644 index 909fc16b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt +++ /dev/null @@ -1,299 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateMapOf -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.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupRelaysUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * The group's relay lists, edited locally and proposed together. - * - * Nothing here is saved. The working copy lives in [working] until the button is - * pressed, and what the button does is open one signing session over the sets that - * changed -- so the group's relay lists change on every member's device at once, - * when a quorum has signed, or not at all. - * - * ### Why one session rather than one per set - * - * Wisp publishes a tab at a time because a person's client signs for itself and - * there is nothing to coordinate. Here every signature costs a quorum's attention, - * and four separate sessions for one sitting at one screen would ask for it four - * times over what is plainly a single decision: where this group lives. - * - * The batch carries **only the sets that differ**, which is what keeps that honest. - * Re-signing a list nobody touched would put a second, identical statement on the - * record with a newer timestamp -- harmless, since these are replaceable, and still - * a lie about when the group last decided anything. - * - * `FrostSigningManager` documents the cost of batching: a batch is all-or-nothing - * and so only as available as its worst item. These four items are the same size, - * the same shape and signed by the same quorum in the same second, so there is no - * worst one to be dragged down by. - */ -class EditGroupRelaysViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialEditGroupRelaysUIState: EditGroupRelaysUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var editGroupRelaysUIState: EditGroupRelaysUIState by mutableStateOf( - initialEditGroupRelaysUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * The working copy: what the lists would be if the group agreed. - * - * A snapshot map so the editor recomposes as rows are added and removed, and - * held on the view model rather than in the composition so that switching tabs - * -- which is a pager page changing -- does not throw away an edit. - */ - val working = mutableStateMapOf>() - - /** Which set the editor is showing, and so what the add field adds to. */ - var selectedSet: GroupRelaySet by mutableStateOf(GroupRelaySet.entries.first()) - private set - - /** - * Why the last add did not happen, or null. Cleared by the next keystroke. - * - * Named rather than silent: Wisp's add button does nothing at all for a URL it - * refuses, and "nothing happened" is indistinguishable from a missed tap. - */ - var addFailure: AddFailure? by mutableStateOf(null) - private set - - enum class AddFailure { - /** Not a `wss://` URL, or one pointing at this machine. */ - NotARelay, - - /** Already in this set, which is a no-op rather than a mistake. */ - AlreadyListed, - } - - fun initiateEditGroupRelays() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - editGroupRelaysUIState = if (localChatRoom == null) { - EditGroupRelaysUIState.Error("Couldn't find the chat room") - } else { - EditGroupRelaysUIState.Loaded( - localChatRoom = localChatRoom, - signed = chatRepository.groupRelayLists(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Fills the working copy from what the group signed, leaving edits alone. - * - * A set the group has agreed starts at its list; one it has not starts at the - * set's defaults, which is what puts this build's own relay in front of a group - * setting up for the first time rather than an empty list. See - * `GroupRelaySet.defaults`. - * - * Called from the screen rather than from [initiateEditGroupRelays], because - * the loader is not the only way a loaded state arrives -- a preview and a - * layout test both hand one straight in, and seeding only on the load path gave - * both of them an editor with nothing in it while the app worked fine. The - * screen has the state either way. - * - * **Only fills what is missing**, so running again after the member has typed - * something does not undo it. That matters because the effect that calls this - * is keyed on a state the view model can re-emit. - */ - fun seedWorkingCopy(signed: List) { - signed.forEach { list -> - if (list.set in working) return@forEach - - working[list.set] = if (list.isAgreed) list.relays else list.set.defaults() - } - } - - fun selectSet(set: GroupRelaySet) { - selectedSet = set - addFailure = null - } - - fun clearAddFailure() { - addFailure = null - } - - fun relaysOf(set: GroupRelaySet): List = working[set] ?: emptyList() - - /** - * Adds [url] to the selected set, or says why it did not. - * - * True when the row appeared, which is the caller's cue to clear the field. - */ - fun addRelay(url: String): Boolean { - val relayUrl = GroupRelaySet.relayUrlOrNull(url) ?: run { - addFailure = AddFailure.NotARelay - return false - } - - val current = relaysOf(selectedSet) - if (current.any { it.url == relayUrl }) { - addFailure = AddFailure.AlreadyListed - return false - } - - working[selectedSet] = current + GroupRelay(relayUrl) - addFailure = null - return true - } - - fun removeRelay(set: GroupRelaySet, relay: GroupRelay) { - working[set] = relaysOf(set).filterNot { it.url == relay.url } - } - - /** - * Turns a NIP-65 marker on or off, refusing to turn off the last one. - * - * A relay that is neither read nor write has no tag in NIP-65 -- see - * `GroupRelaySet.template` -- so the state does not exist to be put the group's - * signature on. What it would mean is that the relay is not in the list, and - * removing it is the row's own button. - */ - fun toggleRead(set: GroupRelaySet, relay: GroupRelay) = - toggle(set, relay) { it.copy(read = !it.read) } - - fun toggleWrite(set: GroupRelaySet, relay: GroupRelay) = - toggle(set, relay) { it.copy(write = !it.write) } - - private fun toggle( - set: GroupRelaySet, - relay: GroupRelay, - change: (GroupRelay) -> GroupRelay, - ) { - working[set] = relaysOf(set).map { - if (it.url != relay.url) return@map it - - change(it).takeIf { changed -> changed.read || changed.write } ?: it - } - } - - /** - * The sets whose working copy says something different to what the group - * signed, in the order the editor shows them. - * - * Order-sensitive on purpose. A relay list is written in the order it is read - * back, and a member who moved a relay to the front meant to; comparing as sets - * would call that no change and quietly refuse to propose it. - * - * A set the group has never agreed counts as changed as soon as it holds - * anything, so a first-time group's seeded defaults are a real proposal rather - * than an accident, and an empty one it has never agreed counts as unchanged -- - * there is nothing to say. - */ - fun changedSets(signed: List): List = - signed.filter { list -> relaysOf(list.set) != list.relays } - .filterNot { list -> !list.isAgreed && relaysOf(list.set).isEmpty() } - .map { it.set } - - /** - * Opens one session over every set that changed. - * - * [onNothingToPropose] rather than a session over nothing: - * `proposeSigningBatch` refuses an empty batch outright, and a member who has - * changed nothing is asking a question rather than making a mistake. - */ - fun proposeRelayLists( - localChatRoom: LocalChatRoom, - signed: List, - onSuccess: (sessionId: String) -> Unit, - onNothingToPropose: () -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. Two sessions over two versions of one relay - // list would leave the group's answer decided by whichever quorum finished - // last. - if (isActionPending.value) return - - val changed = changedSets(signed) - if (changed.isEmpty()) { - onNothingToPropose.invoke() - return - } - - isActionPending.value = true - - val templates = changed.map { set -> set.template(relaysOf(set)) } - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = templates, - ) - }.onFailure { error -> - logger.e("Failed to propose relay lists for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "EditGroupRelaysViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupRelaysUIState: EditGroupRelaysUIState = - EditGroupRelaysUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - EditGroupRelaysViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupRelaysUIState = initialEditGroupRelaysUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt deleted file mode 100644 index b5b27846..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.machankura.bennu.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 kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupNostrProfileUIState - -/** - * The group's nostr profile, read once for the screen that shows it. - * - * One read rather than a watch, the way the group's screen reads it: a profile - * changes when a quorum signs a new one, which lands as a group event this - * device processes, and the screen is re-entered -- and re-read -- on the way - * back from the signing session that made it. - */ -class GroupNostrProfileViewModel( - val chatRoomId: String, - initialGroupNostrProfileUIState: GroupNostrProfileUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupNostrProfileUIState: GroupNostrProfileUIState by mutableStateOf( - initialGroupNostrProfileUIState - ) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupNostrProfileUIState = if (localChatRoom == null) { - GroupNostrProfileUIState.Error("Couldn't find the group") - } else { - GroupNostrProfileUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room is excluded by the first half: it has no key - // of its own to sign as, so nothing to hold a share of. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupNostrProfileUIState: GroupNostrProfileUIState = - GroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupNostrProfileViewModel( - chatRoomId = chatRoomId, - initialGroupNostrProfileUIState = initialGroupNostrProfileUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt deleted file mode 100644 index e3c282ae..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.machankura.bennu.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 kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupPostsUIState - -/** - * The group's posts, read once for the screen that shows them, with the - * profile that bylines them. One read rather than a watch, for the reason - * `GroupNostrProfileViewModel` gives. - */ -class GroupPostsViewModel( - val chatRoomId: String, - initialGroupPostsUIState: GroupPostsUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupPostsUIState: GroupPostsUIState by mutableStateOf(initialGroupPostsUIState) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupPostsUIState = if (localChatRoom == null) { - GroupPostsUIState.Error("Couldn't find the group") - } else { - GroupPostsUIState.Loaded( - localChatRoom = localChatRoom, - groupPosts = chatRepository.groupPosts(chatRoomId), - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupPostsUIState: GroupPostsUIState = GroupPostsUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupPostsViewModel( - chatRoomId = chatRoomId, - initialGroupPostsUIState = initialGroupPostsUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt deleted file mode 100644 index c3c4a5ea..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt +++ /dev/null @@ -1,62 +0,0 @@ -package com.machankura.bennu.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 kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupRelaysUIState - -/** - * The group's relay lists, read once for the screen that shows them. One read - * rather than a watch, for the reason `GroupNostrProfileViewModel` gives. - */ -class GroupRelaysViewModel( - val chatRoomId: String, - initialGroupRelaysUIState: GroupRelaysUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupRelaysUIState: GroupRelaysUIState by mutableStateOf(initialGroupRelaysUIState) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupRelaysUIState = if (localChatRoom == null) { - GroupRelaysUIState.Error("Couldn't find the group") - } else { - GroupRelaysUIState.Loaded( - localChatRoom = localChatRoom, - groupRelayLists = chatRepository.groupRelayLists(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupRelaysUIState: GroupRelaysUIState = GroupRelaysUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupRelaysViewModel( - chatRoomId = chatRoomId, - initialGroupRelaysUIState = initialGroupRelaysUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt index 5bd754c8..4c5ba66a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt @@ -1,6 +1,9 @@ package com.machankura.bennu.compose.ui.view.model import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.database.model.GroupSignedEvent import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import androidx.compose.runtime.MutableState @@ -17,6 +20,7 @@ import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.FrostSigningRepository import com.machankura.bennu.compose.text.SatsInput import com.machankura.bennu.compose.text.parseSats +import com.machankura.bennu.compose.ui.view.state.FundingTarget import com.machankura.bennu.compose.ui.view.state.GroupSendUIState import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupSpendBuilder @@ -29,6 +33,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -49,6 +54,10 @@ class GroupSendViewModel( val chatRepository: ChatRepository, val frostSigningRepository: FrostSigningRepository, private val wallets: GroupOnchainWallets?, + /** The descendant whose guarded wallet this form spends from, or null for the room's own. */ + val guardedChatRoomId: String? = null, + /** The descendant whose guarded wallet this form pays, or null for a payment to a typed address. */ + val fundChatRoomId: String? = null, ): ViewModel() { private val logger = Logger.withTag(TAG) @@ -72,9 +81,29 @@ class GroupSendViewModel( return@launch } - val wallet = chatRepository.groupWallet(chatRoomId, chain) + // Spending from one descendant's wallet into another's is a decision + // of its own, not one this form makes -- docs/guarded-wallet-funding.md, D6. + if (guardedChatRoomId != null && fundChatRoomId != null) { + groupSendUIState = GroupSendUIState.Unavailable + return@launch + } + + // A descendant's guarded wallet, as this room was told it, with the + // group as its guardian -- or the room's own wallet. + val heldByRoom = if (guardedChatRoomId != null || fundChatRoomId != null) chatRepository.guardedWallets(chatRoomId) else emptyList() + fun held(descendant: String?) = descendant?.let { + heldByRoom.firstOrNull { wallet -> wallet.descendantChatRoomId.equals(it, ignoreCase = true) && wallet.chain == chain } + } + val guarded = held(guardedChatRoomId) + // The wallet a send from the room's own pays, when it funds one. + val funded = held(fundChatRoomId) + val wallet = when { + guardedChatRoomId == null -> chatRepository.groupWallet(chatRoomId, chain) + guarded == null -> null + else -> GroupWallet(GroupSignedEvent.fromEvent(guarded.statement, chatRoomId = guarded.descendantChatRoomId), guarded.account) + } val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) - if (wallet == null || !canSign || wallets == null) { + if (wallet == null || !canSign || wallets == null || (fundChatRoomId != null && funded == null)) { groupSendUIState = GroupSendUIState.Unavailable return@launch } @@ -85,6 +114,8 @@ class GroupSendViewModel( walletState = null, reserved = frostSigningRepository.reservedOutPoints(chatRoomId), reservedChange = frostSigningRepository.reservedChangeIndices(chatRoomId, wallet.account), + spender = guarded?.spender() ?: GroupSpend.Spender.Owner, + funding = funded?.let { FundingTarget(it, walletState = null, reserved = frostSigningRepository.reservedFundingIndices(chatRoomId, it.account)) }, ) groupSendUIState = ready @@ -94,7 +125,7 @@ class GroupSendViewModel( } } - follow(ready, wallets.walletFor(wallet.account).state) + follow(ready, wallets.walletFor(wallet.account).state, funded?.let { wallets.walletFor(it.account).state }) } } @@ -109,18 +140,35 @@ class GroupSendViewModel( * One state from both, as the wallet screen does, so no frame shows new * coins against old reservations. Apart from [initiate] so that it can be * followed without an Electrum client. + * + * A send that funds a descendant's wallet follows [fundingState] too, and + * the addresses the room's open fundings hold: if the address it was going + * to pay is paid or taken while the form is open, the next one is shown. */ @OptIn(ExperimentalCoroutinesApi::class) - internal fun follow(ready: GroupSendUIState.Ready, chainState: Flow) { + internal fun follow( + ready: GroupSendUIState.Ready, + chainState: Flow, + fundingState: Flow? = null, + ) { val account = ready.wallet.account + val fundedAccount = ready.funding?.wallet?.account val reservations = frostSigningRepository.observeGroupTransactions(chatRoomId).mapLatest { - frostSigningRepository.reservedOutPoints(chatRoomId) to - frostSigningRepository.reservedChangeIndices(chatRoomId, account) + Triple( + frostSigningRepository.reservedOutPoints(chatRoomId), + frostSigningRepository.reservedChangeIndices(chatRoomId, account), + fundedAccount?.let { frostSigningRepository.reservedFundingIndices(chatRoomId, it) }.orEmpty(), + ) } watching?.cancel() watching = viewModelScope.launch(Dispatchers.IO) { - combine(chainState, reservations) { state, (reserved, reservedChange) -> - ready.copy(walletState = state, reserved = reserved, reservedChange = reservedChange) + combine(chainState, fundingState ?: flowOf(null), reservations) { state, funded, (reserved, reservedChange, reservedFunding) -> + ready.copy( + walletState = state, + reserved = reserved, + reservedChange = reservedChange, + funding = ready.funding?.copy(walletState = funded, reserved = reservedFunding), + ) }.collect { groupSendUIState = it } } } @@ -129,9 +177,20 @@ class GroupSendViewModel( fun amount(): SatsInput = parseSats(amountField.text) /** The confirmed coins no open spend holds, summed, or null before Electrum has answered. */ + /** + * How long a coin has to have waited before this group, as a guardian, can + * spend it -- its own leaf's delay -- or null when the group spends its own + * wallet. `docs/guardian-delay.md`. + */ + fun guardianDelay(): Long? { + val state = groupSendUIState as? GroupSendUIState.Ready ?: return null + val guardian = state.spender as? GroupSpend.Spender.Guardian ?: return null + return state.wallet.account.guardians.getOrNull(guardian.position)?.delay + } + fun spendable(): Satoshi? { val state = groupSendUIState as? GroupSendUIState.Ready ?: return null - return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved) } + return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved, state.spender) } } /** @@ -168,12 +227,17 @@ class GroupSendViewModel( } val feerate = feerateField.text.toString().trim().toLongOrNull()?.takeIf { it > 0 } ?: return null - val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null + // A funding pays the address its target chose, never one typed: the + // title says whose wallet it is, and a typed one would make that a claim. + val destination = when (val funding = state.funding) { + null -> GroupSpendBuilder.Destination.Address(addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null) + else -> GroupSpendBuilder.Destination.Funding(funding.wallet.account, funding.address?.derivation ?: return null) + } val built = if (amount == null) { - GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved) + GroupSpendBuilder.sendAll(walletState, destination, feerate, state.reserved, state.spender) } else { - GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange) + GroupSpendBuilder.send(walletState, destination, amount, feerate, state.reserved, state.reservedChange, state.spender) } return GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(chain)) } @@ -186,12 +250,21 @@ class GroupSendViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSpend( - localChatRoom = state.localChatRoom, - userPublicKey = activeUserPublicKey, - psbt = built.psbt, - chain = chain, - ) + when (val descendant = guardedChatRoomId.takeIf { state.spender is GroupSpend.Spender.Guardian }) { + null -> frostSigningRepository.proposeSpend( + localChatRoom = state.localChatRoom, + userPublicKey = activeUserPublicKey, + psbt = built.psbt, + chain = chain, + ) + else -> frostSigningRepository.proposeGuardianSpend( + localChatRoom = state.localChatRoom, + userPublicKey = activeUserPublicKey, + psbt = built.psbt, + descendantChatRoomId = descendant, + chain = chain, + ) + } }.onFailure { logger.e("Failed to propose a spend from $chatRoomId", it) }.getOrNull() withContext(Dispatchers.Main) { @@ -212,11 +285,13 @@ class GroupSendViewModel( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, wallets: GroupOnchainWallets?, + guardedChatRoomId: String? = null, + fundChatRoomId: String? = null, ): ViewModelProvider.Factory = viewModelFactory { initializer { GroupSendViewModel( activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState, - chatRepository, frostSigningRepository, wallets, + chatRepository, frostSigningRepository, wallets, guardedChatRoomId, fundChatRoomId, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index c6d95d12..a4975f44 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.ui.view.model +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.subgroup.isDecided +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.ui.view.state.SpendRow import com.machankura.bennu.compose.ui.view.state.SpendStatus @@ -7,8 +10,15 @@ import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.machankura.bennu.compose.wallet.GroupTransactionWatcher +import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.distinctUntilChangedBy +import com.machankura.bennu.compose.managers.GroupWalletDerivation import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -71,13 +81,40 @@ class GroupWalletViewModel( val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) val wallet = chatRepository.groupWallet(chatRoomId, chain) + val guarded = chatRepository.guardedWallets(chatRoomId).filter { it.chain == chain } + // The catch-up first, so what the screen offers to share is only what + // could not be sent. docs/guarded-wallet-forwarding.md, Phase 4. + chatRepository.forwardGuardedWallets(chatRoomId) + val shareable = chatRepository.shareableGuardedWallets(chatRoomId, chain) + val guardedRows = guarded.map { GuardedWalletRow(it, walletState = null) } + + watching?.cancel() if (wallet == null) { - groupWalletUIState = GroupWalletUIState.NotOpened( + // What the room's parent decided at its birth: a decided policy + // leaves one way in, and an undecided or absent one both, as + // before policies. docs/subgroup-wallet-policy.md. + val policy = chatRepository.walletPolicyOf(chatRoomId) + val offersGuarded = !policy.isDecided(SubgroupWalletPolicy.UNGUARDED) && + GroupWalletRollout.offersGuardiansOn(chain) + val notOpened = GroupWalletUIState.NotOpened( localChatRoom = localChatRoom, account = chatRepository.groupWalletAccount(chatRoomId, chain), canSign = canSign, - ) + guarded = if (offersGuarded) { + chatRepository.groupWalletGuardedOpening(chatRoomId, chain) + } else null, + policy = policy, + offersPlain = !policy.isDecided(SubgroupWalletPolicy.GUARDED), + guardedWallets = guardedRows, + shareable = shareable, + ).let { it.copy(guardianNames = namesOf(it.guarded?.account?.guardians.orEmpty())) } + groupWalletUIState = notOpened + if (guarded.isNotEmpty()) { + watching = viewModelScope.launch(Dispatchers.IO) { + guardedStates(guarded).collect { rows -> groupWalletUIState = notOpened.copy(guardedWallets = rows) } + } + } return@launch } @@ -87,23 +124,97 @@ class GroupWalletViewModel( walletState = null, canWatch = wallets != null, canSign = canSign, + guardedWallets = guardedRows, + shareable = shareable, + guardianNames = namesOf(wallet.account.guardians), ) groupWalletUIState = loaded - // The chain and the room's spends, as one state: either changing - // redraws the screen, and neither may overwrite the other. + // The chain, the room's spends and the wallets it guards, as one + // state: any of them changing redraws the screen, and none may + // overwrite another. val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null) - watching?.cancel() + noticeGuardianSpends(wallet.account) watching = viewModelScope.launch(Dispatchers.IO) { - combine(chainState, frostSigningRepository.observeGroupTransactions(chatRoomId)) { state, transactions -> - state to transactions.map { rowOf(it) } - }.collect { (state, rows) -> - groupWalletUIState = loaded.copy(walletState = state, spends = rows) + combine( + chainState, + frostSigningRepository.observeGroupTransactions(chatRoomId), + guardedStates(guarded), + ) { state, transactions, guardedWallets -> + Triple(state, transactions.map { rowOf(it) }, guardedWallets) + }.collect { (state, rows, guardedWallets) -> + groupWalletUIState = loaded.copy(walletState = state, spends = rows, guardedWallets = guardedWallets) } } } } + /** + * Each guarded wallet with what the chain says of it, on the identity's own + * Electrum client -- or with nothing, for a profile that cannot watch. + */ + /** + * What this device calls each of [guardians]' rooms, for the ones it holds: + * the wallet screen lists each guardian with its own delay, and a room id is + * not a name. A guardian whose room this device does not have is left out, + * and the screen says *a group above this one*. + */ + private suspend fun namesOf(guardians: List): Map = + guardians.mapNotNull { guardian -> + chatRepository.getChatRoomByIdentifier(guardian.chatRoomId)?.chatRoom?.subject?.let { guardian.chatRoomId to it } + }.toMap() + + private suspend fun guardedStates(guarded: List): Flow> { + val wallets = wallets + if (wallets == null || guarded.isEmpty()) return flowOf(guarded.map { GuardedWalletRow(it, walletState = null) }) + + val states = guarded.map { wallet -> wallets.walletFor(wallet.account).state.map { GuardedWalletRow(wallet, it) } } + return combine(states) { it.toList() } + } + + private var noticing: Job? = null + + /** + * For a guarded wallet: each time its coins change, reads the chain for + * spends a guardian made from it and writes the transcript line for any that + * has none -- the group's only notice, since nobody in it signed them. + */ + private suspend fun noticeGuardianSpends(account: GroupWalletDerivation.Account) { + val wallets = wallets ?: return + if (!account.isGuarded) return + val onchain = wallets.walletFor(account) + + noticing?.cancel() + noticing = viewModelScope.launch(Dispatchers.IO) { + onchain.state + .distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint }.toSet() } + .collect { state -> chatRepository.recordGuardianSpends(chatRoomId, wallets.guardianSpends(state)) } + } + } + + /** + * Tells the groups above about [shareable]'s guarded wallet: one notice into + * each of their rooms this device is in. What is told stays told, so the + * row goes from the screen once it is sent. + */ + fun share(shareable: GuardianManager.Shareable, onShared: () -> Unit, onFailure: () -> Unit) { + if (isActionPending.value) return + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val told = chatRepository.shareGuardedWallet(shareable, activeUserPublicKey) + if (told > 0) { + groupWalletUIState = when (val state = groupWalletUIState) { + is GroupWalletUIState.Loaded -> state.copy(shareable = state.shareable - shareable) + is GroupWalletUIState.NotOpened -> state.copy(shareable = state.shareable - shareable) + else -> state + } + } + withContext(Dispatchers.Main) { if (told > 0) onShared() else onFailure() } + isActionPending.value = false + } + } + /** Checked once per session: the PSBT is write-once, so what it says cannot change. */ private val checkedSpends = mutableMapOf() private val checkedSweeps = mutableMapOf() @@ -144,9 +255,15 @@ class GroupWalletViewModel( } isActionPending.value = true + // A guardian's spend is bumped as one: the same leaf, the same descendant. + val guardedChatRoomId = state.spends.first { it.transaction.frostSigningSessionId == sessionId }.transaction.guardedChatRoomId + viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSpend(state.localChatRoom, activeUserPublicKey, built.psbt, chain) + when (guardedChatRoomId) { + null -> frostSigningRepository.proposeSpend(state.localChatRoom, activeUserPublicKey, built.psbt, chain) + else -> frostSigningRepository.proposeGuardianSpend(state.localChatRoom, activeUserPublicKey, built.psbt, guardedChatRoomId, chain) + } }.onFailure { logger.e("Failed to bump $sessionId", it) }.getOrNull() withContext(Dispatchers.Main) { @@ -162,17 +279,28 @@ class GroupWalletViewModel( * Never batched with anything, for the reason `GroupWalletStatementEvent` * gives -- every spend is opened against this, and it should never be as * available as its worst co-passenger. + * + * [guarded] opens the guarded account the room's certificate grants instead + * of the plain one: the statement then names the guardians and carries the + * certificate, and the group's quorum signing it is the group agreeing to be + * guarded. */ - fun openWallet(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + fun openWallet(guarded: Boolean = false, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { val state = groupWalletUIState as? GroupWalletUIState.NotOpened ?: return - val account = state.account ?: return + val template = if (guarded) { + val opening = state.guarded ?: return + GroupWalletStatementEvent.template(opening.account, opening.certificate) + } else { + // Not under a parent that decided this wallet is guarded: no state + // offers it, and every other member would refuse it anyway. + if (!state.offersPlain) return + GroupWalletStatementEvent.template(state.account ?: return) + } // A second statement for the same account is harmless -- the same values // under the same `d` tag -- but it is a second quorum asked for nothing. if (isActionPending.value) return isActionPending.value = true - val template = GroupWalletStatementEvent.template(account) - viewModelScope.launch(Dispatchers.IO) { val session = runCatching { frostSigningRepository.proposeSigning( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GuardianDelayInput.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GuardianDelayInput.kt new file mode 100644 index 00000000..66f7999e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GuardianDelayInput.kt @@ -0,0 +1,70 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.text.groupedBlocks + +/** + * A guardian delay as somebody is choosing it -- a preset, or blocks typed -- + * for the two screens that choose one: the subgroup picker + * (`docs/guardian-delay.md`) and the group's member-wallet policy + * (`docs/member-wallet-delay.md`). + * + * Holds the text as typed and never clamps it, so the field can say *at most + * 65,535 blocks* about the number somebody actually entered. + */ +class GuardianDelayInput(initial: Long = GuardianDerivation.DEFAULT_DELAY) { + /** The delay, in blocks, as typed or picked. */ + val input: MutableState = mutableStateOf(initial.toString()) + + /** Whether the delay is being typed rather than picked from a preset. */ + val isCustom: MutableState = mutableStateOf(initial !in PRESETS) + + /** Picks a preset. */ + fun pick(blocks: Long) { + isCustom.value = false + input.value = blocks.toString() + } + + /** Switches to typing, starting from the delay already chosen. */ + fun useCustom() { + isCustom.value = true + } + + /** What was typed, digits only, kept as typed. */ + fun type(value: String) { + input.value = value.filter { it in '0'..'9' }.take(MAX_DIGITS) + } + + /** Starts again from [blocks]: a preset as its chip, anything else in the field. */ + fun reset(blocks: Long) { + input.value = blocks.toString() + isCustom.value = blocks !in PRESETS + } + + /** The delay typed or picked, or null while the field holds no number. */ + fun delay(): Long? = input.value.toLongOrNull() + + /** Why the delay cannot be used, or null when it can. */ + fun problem(): String? { + val delay = delay() ?: return "Give the delay in blocks." + return when { + delay < GuardianDerivation.MIN_DELAY -> "A delay is at least ${GuardianDerivation.MIN_DELAY} blocks." + delay > GuardianDerivation.MAX_DELAY -> "A delay is at most ${GuardianDerivation.MAX_DELAY.groupedBlocks()} blocks." + else -> null + } + } + + companion object { + /** + * The delays offered as chips, in blocks -- `docs/guardian-delay.md`, D4: + * an hour, two (the default), a day, a week, a month, six months, and the + * longest a leaf can carry. + */ + val PRESETS: List = listOf(6L, 12L, 144L, 1_008L, 4_320L, 26_280L, GuardianDerivation.MAX_DELAY) + + /** Enough digits for anything past the ceiling, so the field can say so. */ + private const val MAX_DIGITS = 7 + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt new file mode 100644 index 00000000..04ff5fa1 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt @@ -0,0 +1,186 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import androidx.compose.runtime.MutableState +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.machankura.bennu.compose.database.model.MemberWalletSpend +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.text.SatsInput +import com.machankura.bennu.compose.text.parseSats +import com.machankura.bennu.compose.ui.view.state.MemberSendUIState +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Satoshi +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlin.time.Clock + +/** + * A spend from the member's own guarded wallet, built as they type and signed + * alone when they ask. + * + * The group's send form, read the same way -- the preview is the spend, so the + * fee shown is the fee paid -- with one difference that matters: there is no + * quorum after this. Pressing the button signs and broadcasts. + */ +class MemberSendViewModel( + private val ownerPublicKey: HexKey, + val walletId: String, + val chain: Chain, + initialUIState: MemberSendUIState, + private val memberWalletRepository: MemberWalletRepository, + private val wallets: GroupOnchainWallets?, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + var uiState: MemberSendUIState by mutableStateOf(initialUIState) + private set + + val addressField = TextFieldState() + val amountField = TextFieldState() + val feerateField = TextFieldState() + val sendEverything: MutableState = mutableStateOf(false) + + val isActionPending: MutableState = mutableStateOf(false) + + private var watching: Job? = null + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val wallet = memberWalletRepository.walletOf(ownerPublicKey, walletId) + if (wallet == null) { + uiState = MemberSendUIState.Error("Couldn't find this wallet") + return@launch + } + if (wallet.state != MemberWalletManager.WalletState.OPEN || wallets == null) { + uiState = MemberSendUIState.Unavailable + return@launch + } + + val ready = MemberSendUIState.Ready(wallet = wallet, walletState = null) + uiState = ready + + wallets.suggestedFeeratePerVbyte(chain)?.let { suggested -> + withContext(Dispatchers.Main) { + if (feerateField.text.isEmpty()) feerateField.setTextAndPlaceCursorAtEnd(suggested.toString()) + } + } + + watching?.cancel() + watching = viewModelScope.launch(Dispatchers.IO) { + combine(wallets.walletFor(wallet.account).state, memberWalletRepository.observeSpends(walletId)) { state, spends -> + val (reserved, reservedChange) = reservationsOf(spends, ready) + ready.copy(walletState = state, reserved = reserved, reservedChange = reservedChange) + }.collect { uiState = it } + } + } + } + + /** + * What the member's own spends still on their way hold: their coins, and the + * change they pay back to. Electrum stops listing a coin once a spend of it + * is in the mempool, so this matters for the moment between signing and the + * server hearing of it -- a second send then would spend the same coin. + */ + private fun reservationsOf(spends: List, ready: MemberSendUIState.Ready): Pair, Set> { + val open = spends.filter { it.seenAt == null && it.replacedByTxid == null } + .mapNotNull { GroupSpend.decode(it.psbt) } + .mapNotNull { (GroupSpend.check(it, ready.wallet.account) as? GroupSpend.Result.Ok)?.checked } + return open.flatMap { spend -> spend.inputs.map { it.outPoint } }.toSet() to + open.flatMap { spend -> spend.outputs.mapNotNull { it.change?.index } }.toSet() + } + + fun amount(): SatsInput = parseSats(amountField.text) + + fun spendable(): Satoshi? { + val state = uiState as? MemberSendUIState.Ready ?: return null + return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved, GroupSpend.Spender.Owner) } + } + + fun isAboutTheAmount(result: GroupSpendBuilder.Result?): Boolean = + !sendEverything.value && ( + result is GroupSpendBuilder.Result.InvalidAmount || + result is GroupSpendBuilder.Result.OverCap || + result == GroupSpendBuilder.Result.NotEnough || + result == GroupSpendBuilder.Result.BelowDust + ) + + /** The spend the form describes, or null while it is incomplete -- the same build the group's form makes. */ + fun preview(): GroupSpendBuilder.Result? { + val state = uiState as? MemberSendUIState.Ready ?: return null + val walletState = state.walletState ?: return null + + val amount = if (sendEverything.value) { + null + } else { + when (val input = amount()) { + SatsInput.Empty -> return null + is SatsInput.Sats -> input.amount + else -> return GroupSpendBuilder.Result.InvalidAmount(input) + } + } + val feerate = feerateField.text.toString().trim().toLongOrNull()?.takeIf { it > 0 } ?: return null + val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null + + val built = if (amount == null) { + GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved) + } else { + GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange) + } + return GroupSpendBuilder.capped(built, GroupWalletRollout.memberCapFor(chain)) + } + + /** Signs what the form describes and hands it to Electrum. [onSent] when it went, [onFailure] when it did not. */ + fun send(onSent: () -> Unit, onFailure: () -> Unit) { + val built = preview() as? GroupSpendBuilder.Result.Built ?: return + val wallets = wallets ?: return + if (isActionPending.value) return + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val sent = runCatching { + val signed = memberWalletRepository.signSpend(walletId, built.psbt) + wallets.broadcast(signed, chain) + memberWalletRepository.recordChain(signed.txid.toString(), confirmations = null, broadcastAt = Clock.System.now()) + }.onFailure { logger.e("Couldn't send from wallet $walletId", it) }.isSuccess + + withContext(Dispatchers.Main) { + isActionPending.value = false + if (sent) onSent() else onFailure() + } + } + } + + companion object { + private const val TAG = "MemberSendViewModel" + + fun factory( + ownerPublicKey: HexKey, + walletId: String, + chain: Chain, + initialUIState: MemberSendUIState = MemberSendUIState.Loading, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { MemberSendViewModel(ownerPublicKey, walletId, chain, initialUIState, memberWalletRepository, wallets) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModel.kt new file mode 100644 index 00000000..dd904701 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModel.kt @@ -0,0 +1,142 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +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.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.MemberWalletPolicyUIState +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * Whether a group guards its members' wallets, at what delay, and closing it + * again -- `docs/member-wallet-delay.md`, Phase 6. + * + * Proposes a policy the way opening a wallet proposes a statement: a signing + * session in the group's room, which proposing counts as approving. Nothing + * changes until a quorum signs, and every policy reaches only the wallets asked + * for after it -- one already guarded keeps its delay, and closing never + * releases it. + */ +class MemberWalletPolicyViewModel( + private val activeUserPublicKey: HexKey, + private val chatRoomId: String, + initialUIState: MemberWalletPolicyUIState, + private val chatRepository: ChatRepository, + private val memberWalletRepository: MemberWalletRepository, + private val frostSigningRepository: FrostSigningRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + var uiState: MemberWalletPolicyUIState by mutableStateOf(initialUIState) + private set + + val isActionPending: MutableState = mutableStateOf(false) + + /** The delay being chosen, starting from the group's own or the default. */ + val delay = GuardianDelayInput() + + /** Whether [initiate] has set [delay] from the group's policy, which it does once. */ + private var started = false + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (room == null) { + uiState = MemberWalletPolicyUIState.Error("Couldn't find the group") + return@launch + } + val policy = memberWalletRepository.policyOf(chatRoomId) + val canSign = room.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) + if (!started) { + started = true + delay.reset((policy as? MemberWalletPolicyEvent.Policy.Open)?.delay ?: GuardianDerivation.DEFAULT_DELAY) + } + uiState = MemberWalletPolicyUIState.Loaded(room, policy, canSign) + } + } + + /** + * Why opening at the chosen delay cannot be proposed, or null when it can: + * a delay out of range, or the delay the group already has -- a quorum + * asked to restate itself is asked for nothing. + */ + fun openProblem(): String? { + delay.problem()?.let { return it } + val loaded = uiState as? MemberWalletPolicyUIState.Loaded ?: return "Still loading" + if (!loaded.canSign) return "This device can't put a change to the group." + val current = (loaded.policy as? MemberWalletPolicyEvent.Policy.Open)?.delay + if (current == delay.delay()) return "That is already this group's delay." + return null + } + + /** Whether closing can be proposed: only a group that is open. */ + fun canClose(): Boolean = (uiState as? MemberWalletPolicyUIState.Loaded)?.let { it.isOpen && it.canSign } == true + + /** Asks the group to guard members' wallets at the chosen delay. */ + fun proposeOpen(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + if (openProblem() != null) return + propose(MemberWalletPolicyEvent.open(delay.delay() ?: return), onSuccess, onFailure) + } + + /** Asks the group to stop guarding new members' wallets. */ + fun proposeClose(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + if (!canClose()) return + propose(MemberWalletPolicyEvent.closed(), onSuccess, onFailure) + } + + private fun propose(template: EventTemplate<*>, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val loaded = uiState as? MemberWalletPolicyUIState.Loaded ?: return + if (isActionPending.value) return + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + frostSigningRepository.proposeSigning( + localChatRoom = loaded.localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + ) + }.onFailure { logger.e("Failed to propose a member-wallet policy for $chatRoomId", it) }.getOrNull() + + withContext(Dispatchers.Main) { + isActionPending.value = false + if (session != null) onSuccess(session.id) else onFailure() + } + } + } + + companion object { + private const val TAG = "MemberWalletPolicyViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialUIState: MemberWalletPolicyUIState = MemberWalletPolicyUIState.Loading, + chatRepository: ChatRepository, + memberWalletRepository: MemberWalletRepository, + frostSigningRepository: FrostSigningRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + MemberWalletPolicyViewModel(activeUserPublicKey, chatRoomId, initialUIState, chatRepository, memberWalletRepository, frostSigningRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt new file mode 100644 index 00000000..41253f85 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt @@ -0,0 +1,160 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +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.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.MemberWalletUIState +import com.machankura.bennu.compose.ui.view.state.TakenLine +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChangedBy +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Transaction +import kotlin.time.Clock +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * One of the member's guarded wallets: read once for where the asking has got + * to, then -- for a certified wallet on a profile that can watch the chain -- + * watched for its coins, and searched for what its guardians took. + * + * Addresses are offered only once a group has certified the wallet: a wallet + * nobody has agreed to guard should not be handed out to be paid. + */ +class MemberWalletViewModel( + private val ownerPublicKey: HexKey, + walletId: String, + initialUIState: MemberWalletUIState, + private val memberWalletRepository: MemberWalletRepository, + private val wallets: GroupOnchainWallets?, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + /** + * The wallet on screen. Moves when asking again had to make a new request + * under the group's newest policy, with a new key, in place of this one -- + * `docs/member-wallet-delay.md`, Phase 5. + */ + var walletId: String = walletId + private set + + var uiState: MemberWalletUIState by mutableStateOf(initialUIState) + private set + + val isActionPending: MutableState = mutableStateOf(false) + + /** The exported descriptors while they are being shown, and only then. */ + var exported: Pair? by mutableStateOf(null) + private set + + private var watching: Job? = null + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val wallet = memberWalletRepository.walletOf(ownerPublicKey, walletId) + if (wallet == null) { + uiState = MemberWalletUIState.Error("Couldn't find this wallet") + return@launch + } + val loaded = MemberWalletUIState.Loaded(wallet = wallet, canWatch = wallets != null) + uiState = loaded + + watching?.cancel() + if (!wallet.isCertified || wallets == null) return@launch + watching = viewModelScope.launch(Dispatchers.IO) { + var taken = emptyList() + combine( + wallets.walletFor(wallet.account).state + .distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint } to state.tipHeight }, + memberWalletRepository.observeSpends(walletId), + ) { state, spends -> state to spends } + .collect { (state, spends) -> + uiState = loaded.copy(walletState = state, taken = taken, spends = spends) + follow(spends, wallet.account.chain) + // History, not a watch: a device asleep when a guardian took a + // coin still finds it, since the chain keeps the record. + taken = wallets.guardianSpends(state).map { spend -> + TakenLine(spend.txid.toString(), memberWalletRepository.roomName(spend.guardian.chatRoomId), spend.amount) + } + uiState = loaded.copy(walletState = state, taken = taken, spends = spends) + } + } + } + } + + /** + * Asks the chain where each of the member's unsettled spends has got to, + * and sends again any Electrum has not heard of. There is no session for + * `GroupTransactionWatcher` to follow, so the wallet screen follows its own + * spends while it is open -- the economy the guardian-spend notice makes: a + * device that never opens the screen writes nothing, and the chain keeps the + * record for the next one that does. + */ + private suspend fun follow(spends: List, chain: Chain) { + val wallets = wallets ?: return + spends.filter { it.confirmedAt == null && it.replacedByTxid == null }.forEach { spend -> + val tx = runCatching { Transaction.read(spend.signedTransaction) }.getOrNull() ?: return@forEach + val confirmations = wallets.confirmationsOf(tx, chain) + val resent = if (confirmations == null) { + runCatching { wallets.broadcast(tx, chain) }.getOrNull()?.let { Clock.System.now() } + } else null + memberWalletRepository.recordChain(spend.txid, confirmations, broadcastAt = resent) + } + } + + fun askAgain(onAsked: () -> Unit, onFailure: () -> Unit) = act(onAsked, onFailure) { + walletId = memberWalletRepository.askAgain(walletId) + initiate() + } + + fun discard(onDiscarded: () -> Unit, onFailure: () -> Unit) = act(onDiscarded, onFailure) { + memberWalletRepository.discard(walletId) + } + + fun exportKey() { + viewModelScope.launch(Dispatchers.IO) { exported = memberWalletRepository.exportKey(walletId) } + } + + fun hideKey() { + exported = null + } + + private fun act(onDone: () -> Unit, onFailure: () -> Unit, action: suspend () -> Unit) { + if (isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val done = runCatching { action() }.onFailure { logger.e("Couldn't act on wallet $walletId", it) }.isSuccess + withContext(Dispatchers.Main) { + isActionPending.value = false + if (done) onDone() else onFailure() + } + } + } + + companion object { + private const val TAG = "MemberWalletViewModel" + + fun factory( + ownerPublicKey: HexKey, + walletId: String, + initialUIState: MemberWalletUIState = MemberWalletUIState.Loading, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { MemberWalletViewModel(ownerPublicKey, walletId, initialUIState, memberWalletRepository, wallets) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt new file mode 100644 index 00000000..a6d97d86 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt @@ -0,0 +1,70 @@ +package com.machankura.bennu.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.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch + +/** + * A member's guarded wallets, as their profile lists them: each one's state, + * and -- for the ones a group has certified, on a profile that can watch the + * chain -- its balance. + */ +class MemberWalletsViewModel( + private val ownerPublicKey: HexKey, + private val memberWalletRepository: MemberWalletRepository, + private val wallets: GroupOnchainWallets?, +) : ViewModel() { + /** One wallet and, once the chain has answered, its coins. */ + data class Row(val wallet: MemberWalletManager.MemberWalletRow, val walletState: GroupWalletState?) + + /** Null until the first read. */ + var rows: List? by mutableStateOf(null) + private set + + private var watching: Job? = null + + /** Reads the list again: called each time the profile is shown, since a certificate can arrive while it is not. */ + fun refresh() { + viewModelScope.launch(Dispatchers.IO) { + val found = memberWalletRepository.walletsOf(ownerPublicKey) + rows = found.map { Row(it, walletState = null) } + + watching?.cancel() + val watched = found.filter { it.isCertified } + if (wallets == null || watched.isEmpty()) return@launch + watching = viewModelScope.launch(Dispatchers.IO) { + val states = found.map { wallet -> + if (wallet.isCertified) wallets.walletFor(wallet.account).state else flowOf(null) + } + combine(states) { it.toList() }.collect { current -> + rows = found.zip(current) { wallet, state -> Row(wallet, state) } + } + } + } + } + + companion object { + fun factory( + ownerPublicKey: HexKey, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { MemberWalletsViewModel(ownerPublicKey, memberWalletRepository, wallets) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt new file mode 100644 index 00000000..b84d07b8 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt @@ -0,0 +1,139 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +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.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.GroupChoice +import com.machankura.bennu.compose.ui.view.state.NewMemberWalletUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * Asking a group to guard a wallet only this member can spend from. + * + * The screen offers nothing that would be refused. Every refusal is read before + * the button is drawn and again inside `MemberWalletManager.request`, the way + * the subgroup picker refuses: the screen keeps a member out of a dead end, the + * manager keeps a bug out of the room. + * + * [canWatch] is whether this profile has an Electrum client: one without could + * not see its own coins, so it is not offered a wallet it cannot see (D3). + */ +class NewMemberWalletViewModel( + val activeUserPublicKey: HexKey, + private val chatRoomId: String?, + private val chain: Chain, + private val canWatch: Boolean, + initialUIState: NewMemberWalletUIState, + private val memberWalletRepository: MemberWalletRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + var uiState: NewMemberWalletUIState by mutableStateOf(initialUIState) + private set + + val label: MutableState = mutableStateOf("") + + val isActionPending: MutableState = mutableStateOf(false) + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + uiState = when (val chosen = chatRoomId) { + null -> NewMemberWalletUIState.Picking( + memberWalletRepository.groupsOf(activeUserPublicKey) + .map { GroupChoice(it, refusal(it.chatRoom.id)) } + // A group that has never opened to its members' wallets, or + // has closed, is not a choice, so it is not on the list. A + // group whose key -- and so whose policy -- this device has + // not been told yet stays, with the button that asks: it may + // well be open. docs/member-wallet-delay.md. + .filter { it.refusal !in NOT_A_CHOICE } + ) + else -> choose(chosen) ?: NewMemberWalletUIState.Error("Couldn't find the group") + } + } + } + + fun pick(chatRoomId: String) { + viewModelScope.launch(Dispatchers.IO) { + uiState = choose(chatRoomId) ?: NewMemberWalletUIState.Error("Couldn't find the group") + } + } + + private suspend fun choose(chatRoomId: String): NewMemberWalletUIState.Chosen? { + val room = memberWalletRepository.groupsOf(activeUserPublicKey).firstOrNull { it.chatRoom.id == chatRoomId } ?: return null + return NewMemberWalletUIState.Chosen( + room = room, + refusal = refusal(chatRoomId), + reach = memberWalletRepository.reachOf(chatRoomId), + delays = memberWalletRepository.delaysOf(chatRoomId), + ) + } + + private suspend fun refusal(chatRoomId: String): MemberWalletManager.Refusal? = + memberWalletRepository.refusal(chatRoomId, chain) + ?: if (!canWatch) MemberWalletManager.Refusal.CANNOT_WATCH else null + + fun askForGroupKey() { + val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return + viewModelScope.launch(Dispatchers.IO) { + memberWalletRepository.askForGroupKey(chosen.room.chatRoom.id) + uiState = chosen.copy(askedForKey = true) + } + } + + fun setLabel(value: String) { + label.value = value.take(LABEL_LENGTH) + } + + /** Asks the chosen group; [onAsked] gets the group's name, [onFailure] runs when it could not. */ + fun ask(onAsked: () -> Unit, onFailure: () -> Unit) { + val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return + if (chosen.refusal != null || isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val asked = runCatching { + memberWalletRepository.request(chosen.room.chatRoom.id, chain, label.value.takeIf { it.isNotBlank() }) + }.onFailure { logger.e("Couldn't ask ${chosen.room.chatRoom.id} to guard a wallet", it) }.isSuccess + withContext(Dispatchers.Main) { + isActionPending.value = false + if (asked) onAsked() else onFailure() + } + } + } + + companion object { + /** Refusals that say a group is not guarding members' wallets, rather than that this device cannot ask yet. */ + private val NOT_A_CHOICE = setOf(MemberWalletManager.Refusal.NOT_OFFERED, MemberWalletManager.Refusal.CLOSED) + + private const val TAG = "NewMemberWalletViewModel" + + /** The longest label a request carries -- `MemberWalletRequestEvent.MAX_LABEL_LENGTH`. */ + const val LABEL_LENGTH = 64 + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String?, + chain: Chain, + canWatch: Boolean, + initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading, + memberWalletRepository: MemberWalletRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + NewMemberWalletViewModel(activeUserPublicKey, chatRoomId, chain, canWatch, initialUIState, memberWalletRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/PersonGuardedWalletsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/PersonGuardedWalletsViewModel.kt new file mode 100644 index 00000000..283ed521 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/PersonGuardedWalletsViewModel.kt @@ -0,0 +1,41 @@ +package com.machankura.bennu.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.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch + +/** + * A person's guarded wallets as the groups this profile is in guard them -- + * the person's page's *Wallets your groups guard*, one entry per wallet and + * each with the groups that hold a leaf in it. Where a group's page lists a + * member's wallet, its row leads here, since a person is someone to look at, + * not a room to go into. + */ +class PersonGuardedWalletsViewModel( + private val ownerPublicKey: HexKey, + private val memberWalletRepository: MemberWalletRepository, +) : ViewModel() { + /** One per wallet, each with the groups here holding a leaf in it. */ + var rows: List by mutableStateOf(emptyList()) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { rows = MemberWalletManager.byWallet(memberWalletRepository.guardedByGroupsHere(ownerPublicKey)) } + } + + companion object { + fun factory(ownerPublicKey: HexKey, memberWalletRepository: MemberWalletRepository): ViewModelProvider.Factory = viewModelFactory { + initializer { PersonGuardedWalletsViewModel(ownerPublicKey, memberWalletRepository) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt deleted file mode 100644 index 29607e18..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt +++ /dev/null @@ -1,158 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -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.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupEventProposal -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.ProposeGroupEventUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * Asks the group to sign an event a member pasted. - * - * Nothing is built here; the paste is the event. What this decides is whether - * the group should be asked at all -- `GroupEventProposal.read` refuses a paste - * the group's screen could never show, so a quorum is not spent on an event that - * would be signed, filed and seen by nobody -- and it hands the kind, tags and - * content to the same `proposeSigning` every typed editor uses. The author and - * the time are the session's to fill in, which is how a pasted `pubkey` or - * `created_at` comes to be ignored: they are never passed along. - * - * Where the event lands is decided by nothing here. `FrostSigningManager.complete` - * files every signed event as a `GroupSignedEvent`, and the group's screen reads - * its profile, posts, relay lists and schemas off those by kind. A pasted kind 0 - * becomes the profile the same way a kind 0 from the profile form does, because - * by the time either is signed there is no telling them apart. - */ -class ProposeGroupEventViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialProposeGroupEventUIState: ProposeGroupEventUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var proposeGroupEventUIState: ProposeGroupEventUIState by mutableStateOf( - initialProposeGroupEventUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateProposeGroupEvent() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - proposeGroupEventUIState = if (localChatRoom == null) { - ProposeGroupEventUIState.Error("Couldn't find the chat room") - } else { - ProposeGroupEventUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room has no key of its own to sign as, so it has no - // statements to make -- the same condition the group detail - // screen gates the entry point on. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Opens a session over the pasted event, or says why not. - * - * [onRefused] carries the reading's own reason, which the screen has been - * showing under the paste all along; it is repeated here so pressing the - * button on a refused paste is answered rather than ignored. Both refusals - * and a failed proposal stay on the paste: the JSON is the thing worth - * keeping. - */ - fun proposeEvent( - localChatRoom: LocalChatRoom, - json: String, - onSuccess: (sessionId: String) -> Unit, - onRefused: (GroupEventProposal.Refused) -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. A pasted kind:1 accumulates like any - // other post, so a second session over the same paste is a second post - // on the record forever. - if (isActionPending.value) return - - val ready = when (val reading = GroupEventProposal.read(json)) { - is GroupEventProposal.Ready -> reading - is GroupEventProposal.Refused -> { - onRefused.invoke(reading) - return - } - } - - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = ready.kind, - tags = ready.tags, - content = ready.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a pasted kind ${ready.kind} event for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "ProposeGroupEventViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialProposeGroupEventUIState: ProposeGroupEventUIState = - ProposeGroupEventUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - ProposeGroupEventViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialProposeGroupEventUIState = initialProposeGroupEventUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt index 9e3a5e17..8166d4d0 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.ui.view.model +import com.machankura.bennu.compose.ui.view.state.canGuard +import com.machankura.bennu.compose.ui.view.state.onlyGuarded +import com.machankura.bennu.compose.database.model.subgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.isDecided +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf @@ -16,6 +21,7 @@ import com.machankura.bennu.compose.identity.Identity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import com.machankura.bennu.compose.database.model.types.ChatRoomType @@ -27,9 +33,12 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.Route import com.machankura.bennu.compose.ui.view.state.SelectSubgroupAdminsUIState /** - * Who runs a subgroup, what it is called, and on what quorum. + * Who runs a subgroup, what it is called, on what quorum, and whether its wallet + * is guarded. * - * All three are settled here and nowhere else. The name and the admin set are + * All four are settled here and nowhere else. The wallet policy rides the + * proposal like the threshold and is signed into the birth certificate by the + * parent's quorum -- `docs/subgroup-wallet-policy.md`. The name and the admin set are * carried into the birth certificate, so they are what the parent's admins will * be asked to approve; the threshold cannot move afterwards at all, because * ChillDKG hashes it and the host keys into the session identity, so `t` is fixed @@ -49,6 +58,8 @@ import com.machankura.bennu.compose.ui.view.state.SelectSubgroupAdminsUIState class SelectSubgroupAdminsViewModel( val activeUserPublicKey: HexKey, val parentChatRoomId: String, + /** A failed subgroup ceremony to start from; see `SelectSubgroupAdminsRoute.retrying`. */ + val retrying: String? = null, initialUIState: SelectSubgroupAdminsUIState, val activeIdentityStateFlow: StateFlow, val chatRepository: ChatRepository, @@ -78,6 +89,30 @@ class SelectSubgroupAdminsViewModel( val threshold: MutableState = mutableStateOf(ChatRoomType.MINIMUM_QUORUM) + /** + * What the subgroup's wallet is to be -- `docs/subgroup-wallet-policy.md`. + * Guarded unless the coordinator says otherwise, and only ever guarded under a + * parent that is guarded itself: [setWalletPolicy] will not move it, so the + * state never holds a choice the screen shows as disabled. + */ + val walletPolicy: MutableState = mutableStateOf(SubgroupWalletPolicy.GUARDED) + + /** + * How long a coin in a guarded subgroup's wallet waits before this group can + * take it -- `docs/guardian-delay.md`. The parent's own leaf only: each + * ancestor above keeps the delay it chose. + */ + private val delay = GuardianDelayInput() + + /** The delay as typed; see [GuardianDelayInput]. */ + val guardianDelayInput: MutableState get() = delay.input + + /** Whether the delay is being typed rather than picked from a preset. */ + val isCustomDelay: MutableState get() = delay.isCustom + + /** Whether [retrying] has been read into the form, which happens once. */ + private var prefilled = false + fun initiate() { viewModelScope.launch(Dispatchers.IO) { val parentRoom = chatRepository.getChatRoomByIdentifier(parentChatRoomId) @@ -92,15 +127,66 @@ class SelectSubgroupAdminsViewModel( .distinctBy { it.participant.participantPublicKey } .filterNot { it.participant.participantPublicKey == activeUserPublicKey } + // The parent's own wallet policy and guardians, read once: whether it + // may make an unguarded child at all, and whether it can grant a + // guarded one anything. + val parentPolicy = chatRepository.walletPolicyOf(parentChatRoomId) + val parentGuardians = chatRepository.guardiansOf(parentChatRoomId) + uiState = SelectSubgroupAdminsUIState.Loaded( parentRoom = parentRoom, candidates = candidates, + parentPolicy = parentPolicy, + parentGuardians = parentGuardians, ) + // A parent that cannot grant keys can only make an unguarded child, + // and one that is guarded can only make a guarded one. + if (parentGuardians == null) walletPolicy.value = SubgroupWalletPolicy.UNGUARDED + if (parentPolicy.isDecided(SubgroupWalletPolicy.GUARDED)) walletPolicy.value = SubgroupWalletPolicy.GUARDED + + // Before the key-package lookup, so anybody who can no longer be + // welcomed is unpicked by the same rule as a fresh pick would be. + prefillFromRetry(candidates.map { it.participant.participantPublicKey }.toSet()) + resolveKeyPackages(candidates.map { it.participant.participantPublicKey }) } } + /** + * Starts the form from the failed ceremony this is trying again. + * + * Only from one that was this parent's subgroup, and only admins who are + * still in the parent: the ceremony recorded who it was with, and the + * parent's membership may have moved since. Once, because the screen asks + * to start again every time it comes back into view and a member's edits + * must not be put back. + */ + private suspend fun prefillFromRetry(candidates: Set) { + val sessionId = retrying ?: return + if (prefilled) return + prefilled = true + + val failed = dkgRepository.observeSessionById(sessionId).first() ?: return + if (failed.parentChatRoomId != parentChatRoomId) return + + name.value = failed.subject.orEmpty() + + selectedPublicKeys.clear() + selectedPublicKeys.addAll( + failed.participantPublicKeySet().orEmpty() + .filter { it != activeUserPublicKey && it in candidates } + ) + + threshold.value = failed.threshold.coerceIn(quorumRange()) + + // Through the setter, so a policy the parent no longer allows -- the + // failed ceremony can predate the parent's own certificate -- is pulled + // back the way the threshold is pulled into its range. + failed.subgroupWalletPolicy?.let(::setWalletPolicy) + failed.guardianDelay?.let(delay::reset) + } + /** * Asks every candidate's key package up front. * @@ -150,6 +236,44 @@ class SelectSubgroupAdminsViewModel( name.value = value } + /** + * Chooses the subgroup's wallet policy. *Unguarded* under a guarded parent is + * ignored -- D4 -- and so is *guarded* under a parent that cannot grant keys. + */ + fun setWalletPolicy(value: SubgroupWalletPolicy) { + if (isActionPending.value) return + + val loaded = uiState as? SelectSubgroupAdminsUIState.Loaded ?: return + if (value == SubgroupWalletPolicy.UNGUARDED && loaded.onlyGuarded) return + if (value == SubgroupWalletPolicy.GUARDED && !loaded.canGuard) return + + walletPolicy.value = value + } + + /** Picks a preset delay. */ + fun setGuardianDelay(blocks: Long) { + if (isActionPending.value) return + delay.pick(blocks) + } + + /** Switches to typing a delay, starting from the one already chosen. */ + fun useCustomDelay() { + if (isActionPending.value) return + delay.useCustom() + } + + /** What was typed as the delay, kept as typed. */ + fun setGuardianDelayInput(value: String) { + if (isActionPending.value) return + delay.type(value) + } + + /** The delay typed or picked, or null while the field holds no number. */ + fun guardianDelay(): Long? = delay.delay() + + /** Why the delay cannot be used, or null when it can. */ + fun guardianDelayProblem(): String? = delay.problem() + /** The subgroup's admins: everyone ticked, plus the coordinator. */ fun adminCount(): Int = selectedPublicKeys.size + 1 @@ -173,6 +297,19 @@ class SelectSubgroupAdminsViewModel( if (name.value.isBlank()) return "Give the subgroup a name." + // The policy before the admins and before the key-package lookup, which it + // does not wait on: an answer here sends the coordinator back + // to a choice, not to a person. Checked again on confirm, so a state that + // got past the screen is stopped before a ceremony is proposed. + if (walletPolicy.value == SubgroupWalletPolicy.UNGUARDED && loaded.onlyGuarded) { + return "This group is guarded, so its subgroups are too." + } + if (walletPolicy.value == SubgroupWalletPolicy.GUARDED && !loaded.canGuard) { + return "This group's own guardian keys can't be read, so it can't guard a subgroup." + } + if (walletPolicy.value == SubgroupWalletPolicy.GUARDED) guardianDelayProblem()?.let { return it } + + if (loaded.isResolvingKeyPackages) return "Checking who can be added…" val unreachable = selectedPublicKeys.filter { it in loaded.withoutKeyPackage } @@ -245,7 +382,14 @@ class SelectSubgroupAdminsViewModel( // coordinator is added by `proposeRitual`: opening a ceremony is // being in it, and is not theirs to tick. participantPublicKeys = selectedPublicKeys.toSet(), - subject = name.value.trim() + subject = name.value.trim(), + // Carried on the proposal so every admin is told at the join gate, + // and on the session so whoever proposes the certificate proposes + // it under the same one. + walletPolicy = walletPolicy.value, + // The parent's own leaf, and only for a guarded subgroup. + // docs/guardian-delay.md. + guardianDelay = guardianDelay().takeIf { walletPolicy.value == SubgroupWalletPolicy.GUARDED } ) isActionPending.value = false @@ -265,14 +409,6 @@ class SelectSubgroupAdminsViewModel( // arrive -- which is now literally the same place every other // admin answers from, through the ritual notices that name their // own ceremony. - // - // Sending them to the shared-key screen instead was actively - // harmful: that screen's job is to *offer* a ceremony to a room - // that has none, so the coordinator arrived at a "Start key - // ceremony" button seconds after starting one, and pressing it - // opened a second -- for no subgroup, so `proposeRitual`'s guard - // did not recognise it as a duplicate -- which then buried the - // subgroup's under the room's newest. onNavigateToRoute( ChatRoomMessagingRoute( activeUserPublicKey = activeUserPublicKey, @@ -285,11 +421,15 @@ class SelectSubgroupAdminsViewModel( } companion object { + /** The delays the picker offers: [GuardianDelayInput.PRESETS]. */ + val DELAY_PRESETS: List get() = GuardianDelayInput.PRESETS + private const val TAG = "SelectSubgroupAdminsViewModel" fun factory( activeUserPublicKey: HexKey, parentChatRoomId: String, + retrying: String? = null, initialUIState: SelectSubgroupAdminsUIState = SelectSubgroupAdminsUIState.Loading, activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, @@ -299,6 +439,7 @@ class SelectSubgroupAdminsViewModel( SelectSubgroupAdminsViewModel( activeUserPublicKey = activeUserPublicKey, parentChatRoomId = parentChatRoomId, + retrying = retrying, initialUIState = initialUIState, activeIdentityStateFlow = activeIdentityStateFlow, chatRepository = chatRepository, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt deleted file mode 100644 index 38e195ca..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslateChunkViewModel.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.TranslateChunkUIState - -class TranslateChunkViewModel( - val translationChapterId: String, - val chunkId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialTranslateChunkUIState: TranslateChunkUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var translateChunkUIState: TranslateChunkUIState by mutableStateOf(initialTranslateChunkUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateTranslateChunk() { - viewModelScope.launch(Dispatchers.IO) { - val originalChunk = mantraRepository.getChunk(chunkId) - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - translateChunkUIState = when { - originalChunk == null -> TranslateChunkUIState.Error("Couldn't find the chunk") - localChatRoom == null -> TranslateChunkUIState.Error("Couldn't find the chat room") - else -> TranslateChunkUIState.Loaded( - localChatRoom = localChatRoom, - originalChunk = originalChunk, - // What the group has already signed for this chunk, so a - // retranslation starts from it rather than from nothing. - existingTranslationText = mantraRepository - .getTranslationChunks(translationChapterId) - .firstOrNull { it.chunkId == chunkId } - ?.text - .orEmpty(), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to sign this chunk's translation. - * - * The translation is not saved here and does not exist yet. What goes out is - * a proposal to sign it, and the translated chunk appears -- on every - * member's device at once, authored by this room's own key rather than by - * whoever typed it -- when enough members have signed. That author is the - * room's id: signing runs at the path the room was derived at, so a - * translated chunk says which group rendered it simply by being signed. - * - * That is the difference from submitting one. A submission says "I am - * putting this in front of the group" and the group's only recourse - * afterwards is social. A signature is the group saying it, and it takes a - * quorum to say. What a chunk means in another tongue is a claim the group - * is making about somebody else's words, so the second is the honest one. - * - * A retranslation goes the same way: the event carries a different text and - * so a different id, and it replaces the one the group signed before rather - * than editing it -- there is nothing here to edit, since the old text is - * already signed. - */ - fun proposeTranslation( - localChatRoom: LocalChatRoom, - originalChunk: MantraChunk, - translationField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - val text = translationField.text.toString() - if (text.isBlank()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated FAB taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val translationChunkEventTemplate = TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = originalChunk.id, - // The translation sits where the chunk it translates sits. Read - // off the source rather than counted here: a chapter is - // translated a chunk at a time and in no particular order, so - // counting what is translated so far would number them by who - // got there first. - index = originalChunk.index, - text = text, - ) - - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = translationChunkEventTemplate.kind, - tags = translationChunkEventTemplate.tags, - content = translationChunkEventTemplate.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a translation for signing", error) - }.getOrNull() - - if (session != null) { - viewModelScope.launch(Dispatchers.Main) { - onSuccess.invoke(session.id) - } - } else { - viewModelScope.launch(Dispatchers.Main) { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "TranslateChunkViewModel" - - fun factory( - activeUserPublicKey: HexKey, - translationChapterId: String, - chunkId: String, - chatRoomId: String, - relayHint: String?, - initialTranslateChunkUIState: TranslateChunkUIState = TranslateChunkUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - TranslateChunkViewModel( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chunkId = chunkId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslateChunkUIState = initialTranslateChunkUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt deleted file mode 100644 index 1ef0431c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationArtifactVersionDetailViewModel.kt +++ /dev/null @@ -1,172 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -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 com.vitorpamplona.quartz.utils.TimeUtils -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.managers.TranslationScaffold -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.TranslationChapterProgress -import com.machankura.bennu.compose.ui.view.state.TranslationArtifactVersionDetailUIState - -class TranslationArtifactVersionDetailViewModel( - val translationArtifactVersionId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialTranslationArtifactVersionDetailUIState: TranslationArtifactVersionDetailUIState, - val mantraRepository: MantraRepository, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var translationDetailUIState: TranslationArtifactVersionDetailUIState by mutableStateOf(initialTranslationArtifactVersionDetailUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateTranslationArtifactVersionDetail() { - logger.d("initiateTranslationArtifactVersionDetail: $translationArtifactVersionId") - viewModelScope.launch(Dispatchers.IO) { - val translation = mantraRepository.getTranslation(translationArtifactVersionId) - - translationDetailUIState = if (translation == null) { - TranslationArtifactVersionDetailUIState.Error("Couldn't find the translation") - } else { - val translationChapters = mantraRepository.getTranslationChapters(translationArtifactVersionId) - val chapters = translationChapters.map { chapter -> - val chunks = mantraRepository.getTranslationChunks(chapter.id) - TranslationChapterProgress( - chapter = chapter, - totalChunks = chunks.size, - translatedChunks = chunks.count { it.text.isNotBlank() }, - ) - } - - TranslationArtifactVersionDetailUIState.Loaded( - translation = translation, - chapters = chapters, - localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId), - missingChapters = TranslationScaffold.chaptersMissingFrom( - translationChapters = translationChapters, - sourceChapters = mantraRepository - .getChaptersForArtifactVersion(translation.artifactVersionId), - ), - canSign = frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Asks the group to put the chapters this translation is missing into it. - * - * The scaffolding a chapter is signed with covers the translations that - * existed when it was proposed, and the scaffolding a translation is signed - * with covers the chapters that existed when *it* was proposed. Two things - * proposed at the same moment see neither the other, and a session that - * fails to reach a quorum leaves nothing behind to try again with. Neither - * is a bug that can be designed out of a snapshot taken at proposal time -- - * so this is the pass that reconciles them, run when somebody notices. - * - * It proposes only what is missing, matched on the source chapter each - * translation chapter names, so running it on a translation that is already - * complete proposes nothing rather than a second copy of everything. - */ - fun catchUpMissingChapters( - localChatRoom: LocalChatRoom, - missingChapters: List, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - if (missingChapters.isEmpty()) { - onFailure.invoke() - return - } - - // Guard against double submits from repeated taps. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - // One timestamp for the lot, so a catch-up reads as the one act it - // is rather than as chapters that happen to share a minute. - val createdAt = TimeUtils.now() - - val sessions = runCatching { - // One session per MAX_BATCH_SIZE chapters. A translation far - // enough behind to need more than a batch holds is not one to - // refuse; it is one the group answers for more than once. - missingChapters.chunked(FrostSigningManager.MAX_BATCH_SIZE).mapNotNull { batch -> - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationArtifactVersionId), - chapters = batch.map(TranslationScaffold.SourceChapter::of), - createdAt = createdAt, - ) - ) - } - }.onFailure { error -> - logger.e("Failed to propose this translation's missing chapters", error) - }.getOrNull().orEmpty() - - // The first, because it is the one that opened; the rest are in the - // room's session list beside it. - val session = sessions.firstOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) onSuccess.invoke(session.id) else onFailure.invoke() - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "TranslationArtifactVersionDetailViewModel" - - fun factory( - activeUserPublicKey: HexKey, - translationArtifactVersionId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationArtifactVersionDetailUIState: TranslationArtifactVersionDetailUIState = TranslationArtifactVersionDetailUIState.Loading, - mantraRepository: MantraRepository, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - TranslationArtifactVersionDetailViewModel( - activeUserPublicKey = activeUserPublicKey, - translationArtifactVersionId = translationArtifactVersionId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationArtifactVersionDetailUIState = initialTranslationArtifactVersionDetailUIState, - mantraRepository = mantraRepository, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt deleted file mode 100644 index 8a61891e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/TranslationChapterViewModel.kt +++ /dev/null @@ -1,98 +0,0 @@ -package com.machankura.bennu.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.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.MantraRepository -import com.machankura.bennu.compose.ui.view.state.ChunkTranslationPair -import com.machankura.bennu.compose.ui.view.state.TranslationChapterUIState - -class TranslationChapterViewModel( - val translationChapterId: String, - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialTranslationChapterUIState: TranslationChapterUIState, - val mantraRepository: MantraRepository, -): ViewModel() { - - var translationChapterUIState: TranslationChapterUIState by mutableStateOf(initialTranslationChapterUIState) - private set - - private val logger = Logger.withTag(TAG) - - fun initiateTranslationChapter() { - logger.d("initiateTranslationChapter: $translationChapterId") - viewModelScope.launch(Dispatchers.IO) { - val translationChapter = mantraRepository.getTranslationChapter(translationChapterId) - val sourceChapter = translationChapter?.let { mantraRepository.getChapter(it.chapterId) } - - translationChapterUIState = if (translationChapter == null || sourceChapter == null) { - TranslationChapterUIState.Error("Couldn't find the translation chapter") - } else { - // Original dialect: source chapter -> version -> artifact -> dialect. - val originalDialectName = mantraRepository.getArtifactVersion(sourceChapter.artifactVersionId) - ?.let { mantraRepository.getArtifact(it.artifactId) } - ?.let { mantraRepository.getDialect(it.dialectId) } - ?.name ?: "Original" - - // Translation dialect: translation version -> dialect. - val translationDialectName = mantraRepository.getTranslation(translationChapter.translationArtifactVersionId) - ?.let { mantraRepository.getDialect(it.dialectId) } - ?.name ?: "Translation" - - // Pair each original chunk with its translation chunk (by chunkId). - val translationChunksByChunkId = mantraRepository - .getTranslationChunks(translationChapter.id) - .associateBy { it.chunkId } - - val rows = mantraRepository.getChunksForChapter(sourceChapter.id).map { originalChunk -> - ChunkTranslationPair( - originalChunk = originalChunk, - translationChunk = translationChunksByChunkId[originalChunk.id], - ) - } - - TranslationChapterUIState.Loaded( - originalDialectName = originalDialectName, - translationDialectName = translationDialectName, - rows = rows, - ) - } - } - } - - companion object { - private const val TAG = "TranslationChapterViewModel" - - fun factory( - activeUserPublicKey: HexKey, - translationChapterId: String, - chatRoomId: String, - relayHint: String?, - initialTranslationChapterUIState: TranslationChapterUIState = TranslationChapterUIState.Loading, - mantraRepository: MantraRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - TranslationChapterViewModel( - activeUserPublicKey = activeUserPublicKey, - translationChapterId = translationChapterId, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialTranslationChapterUIState = initialTranslationChapterUIState, - mantraRepository = mantraRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt deleted file mode 100755 index 4de694a1..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddArtifactUIState.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddArtifactUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val dialects: List = emptyList(), - - /** - * Whether the group holds a shared key. An artifact is signed into - * existence now rather than submitted, so a group without one cannot - * add one here at all. - */ - val canSign: Boolean = false, - ): AddArtifactUIState - - data class Error( - val message: String - ): AddArtifactUIState - - data object Loading: AddArtifactUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt deleted file mode 100644 index 89ff2ca2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddChapterUIState.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddChapterUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val artifact: MantraArtifact, - - /** - * The version the chapter would attach to: the artifact's latest. - * - * Null on an artifact that has none, which is one nothing can be added - * to -- a chapter hangs off a version rather than off an artifact. - */ - val artifactVersion: MantraArtifactVersion? = null, - - /** - * Whether the group holds a shared key. A chapter is signed into - * existence now rather than submitted, so a group without one cannot - * add one here at all. - */ - val canSign: Boolean = false, - ): AddChapterUIState - - data class Error( - val message: String - ): AddChapterUIState - - data object Loading: AddChapterUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt deleted file mode 100644 index 21951d3a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddDialectUIState.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddDialectUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - - /** - * Whether the group holds a shared key. A dialect is signed into - * existence now rather than submitted, so a group without one cannot - * make one here at all. - */ - val canSign: Boolean = false, - ): AddDialectUIState - - data class Error( - val message: String - ): AddDialectUIState - - data object Loading: AddDialectUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt deleted file mode 100644 index 0c499154..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface AddGroupPostUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * Who the group says it is, for the byline over the draft. - * - * A post is signed by the group and read as the group, so the composer - * shows whose voice is being written in -- which is not the member typing. - * Null in a group that has not described itself, and the byline falls back - * to the room. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the draft writable and the button inert, for the same reason - * the other two editors do: reading and composing cost nothing, and only a - * share-holder can open the session that would sign it. - */ - val canSign: Boolean = false, - ): AddGroupPostUIState - - data class Error( - val message: String - ): AddGroupPostUIState - - data object Loading: AddGroupPostUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt deleted file mode 100644 index 36edc1c9..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddTranslationArtifactVersionUIState.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface AddTranslationArtifactVersionUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val artifact: MantraArtifact, - - /** - * The dialects this room has signed into existence. A translation is - * into one of them and only one of them: an invented dialect is a - * dialect nobody agreed to, and the room already has a screen for - * asking the group for a new one. - */ - val dialects: List = emptyList(), - - /** - * The version being translated: the artifact's latest. - * - * Null on an artifact that has none, which is one there is nothing to - * translate -- a translation is of a version rather than of an artifact. - */ - val artifactVersion: MantraArtifactVersion? = null, - - /** - * The chapters of that version, which the translation is laid out - * against: a translation chapter each, signed in the same session. - * - * Held here rather than re-read when proposing, so that the count the - * form shows is the count the group is asked to sign. - */ - val chapters: List = emptyList(), - - /** - * Whether the group holds a shared key. A translation is signed into - * existence now rather than submitted, so a group without one cannot - * start one here at all. - */ - val canSign: Boolean = false, - ): AddTranslationArtifactVersionUIState - - data class Error( - val message: String - ): AddTranslationArtifactVersionUIState - - data object Loading: AddTranslationArtifactVersionUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt deleted file mode 100644 index 468ed2d2..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ArtifactDetailUIState.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion - -sealed interface ArtifactDetailUIState { - data class Loaded( - val artifact: MantraArtifact, - val versions: List = emptyList(), - val chapters: List = emptyList(), - val translations: List = emptyList(), - ): ArtifactDetailUIState - - data class Error( - val message: String - ): ArtifactDetailUIState - - data object Loading: ArtifactDetailUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt deleted file mode 100644 index a9b4b6b0..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelayList - -sealed interface BroadcastGroupSignedEventUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** The event to send, as the group signed it. What goes on the wire is this, byte for byte. */ - val signedEvent: GroupSignedEvent, - /** - * Where the group has said it lives, which is what the relay picker starts - * from: the General list's write relays when the group has agreed one, and - * never a relay the group has blocked. See - * `BroadcastGroupSignedEventViewModel.defaultRelaysFor`. - */ - val relayLists: List = emptyList(), - ): BroadcastGroupSignedEventUIState - - data class Error( - val message: String - ): BroadcastGroupSignedEventUIState - - data object Loading: BroadcastGroupSignedEventUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt deleted file mode 100644 index 33b9d74b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChapterDetailUIState.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk - -sealed interface ChapterDetailUIState { - data class Loaded( - val chapter: MantraChapter, - val chunks: List = emptyList(), - ): ChapterDetailUIState - - data class Error( - val message: String - ): ChapterDetailUIState - - data object Loading: ChapterDetailUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt index 78b57943..070c1081 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -1,14 +1,14 @@ package com.machankura.bennu.compose.ui.view.state +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList sealed interface ChatRoomDetailUIState { data class Loaded( @@ -51,44 +51,19 @@ sealed interface ChatRoomDetailUIState { */ val parentChatRoomId: HexKey? = null, /** - * The kind:0 the group signed about itself, or null while it has signed - * none. - * - * Its row sits under the room's identity and above its work, because that - * is what it is: the name and the picture the rest of nostr sees on the - * key the signing key row names. The row shows the name and the address; - * the profile itself is read on `GroupNostrProfileScreen`. Null is an - * ordinary state and the row says so -- a group has an identity from the - * moment it has a key and describes it whenever somebody gets round to it. + * What [parentChatRoomId] decided about this room's wallet at its birth, + * or null for a room with no certificate. Shown on the parent row, + * because it is a fact about where the room came from. */ - val groupNostrProfile: GroupNostrProfile? = null, + val walletPolicy: WalletPolicyReading? = null, /** - * Where the group has said it lives on nostr, one entry per relay set. - * - * Beside the profile because they are the same kind of fact -- the group's - * own account of itself, signed by the group -- and read in the same breath - * by anybody checking whether the group is reachable. The row counts how - * many the group has agreed; the lists are read on `GroupRelaysScreen`. - * - * Empty only in a room that has none of this to say. Every other case has - * four entries, some of them unsigned; see `ChatRepository.groupRelayLists`. + * The delay [parentChatRoomId] gave its own leaf in this room's wallet, + * or null for a room whose certificate grants no keys. */ - val groupRelayLists: List = emptyList(), - /** - * What the group has said publicly, as itself, newest first. - * - * Under the relay lists because it is the thing they are *for*: the profile - * says who the group is, the relay lists say where to find it, and these - * are what a reader would find there. The row counts them; they are read - * on `GroupPostsScreen`. Empty in a group that has said nothing, which is - * every group until somebody proposes one. - */ - val groupPosts: List = emptyList(), + val guardianDelay: Long? = null, /** * The wallet this group has opened on the app's network, or null for one - * it has not. Under the identity block because it is not part of the - * group's account of itself on nostr -- nobody outside the room reads it -- - * and the row says only whether it is open; the coins are read on + * it has not. The row says only whether it is open; the coins are read on * `GroupWalletScreen`. */ val groupWallet: GroupWallet? = null, @@ -100,21 +75,6 @@ sealed interface ChatRoomDetailUIState { val testNetworkWallet: GroupWallet? = null, /** Who holds a share of the group's Lightning wallet key, so removing one of them can say what it leaves. */ val lightningParticipants: Set = emptySet(), - /** - * Whether this device could sign an event for the group, which on this - * screen gates the paste at the end of the identity block. Each of the - * three screens the rows open reads the same capability for its own gate. - * - * The same capability [canAddSubgroup] wants, and wanted for the same - * reason: proposing anything in the group's name is a signature by the - * group, and `FrostSigningManager.proposeSigningBatch` throws for a - * device holding no share of the key. It is not about permission -- any - * member with a share may propose -- and the quorum is what decides. - * - * A NIP-17 room is excluded by the same condition, since it has no key of - * its own to sign as and so no nostr identity to describe. - */ - val canEditNostrProfile: Boolean = false, /** * Whether this device could open a subgroup here at all. * @@ -141,6 +101,24 @@ sealed interface ChatRoomDetailUIState { * and nobody rejoins, so every write entrance is hidden and the room says so. */ val isDisbanded: Boolean = false, + /** + * The member wallets this group guards, and the requests for one still + * waiting for a signer -- `docs/member-guarded-wallets.md`. Its own + * section, never mixed into [subgroups]: a row here is a person. + */ + val memberWallets: List = emptyList(), + /** Whether this profile could ask this group to guard a wallet for it. */ + val canAskForMemberWallet: Boolean = false, + /** Whether this device holds a share, and so can put a member's request to the group. */ + val canSponsor: Boolean = false, + /** + * Whether this group guards its members' wallets, and at what delay -- + * its newest member-wallet policy, or null for one it never signed. + * `docs/member-wallet-delay.md`. + */ + val memberWalletPolicy: MemberWalletPolicyEvent.Policy? = null, + /** Whether to show that at all: a Marmot group, still going. */ + val showsMemberWalletPolicy: Boolean = false, ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CreateSharedKeyUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CreateSharedKeyUIState.kt new file mode 100644 index 00000000..3942a9b9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CreateSharedKeyUIState.kt @@ -0,0 +1,40 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom + +sealed interface CreateSharedKeyUIState { + /** The room, and how many people a ceremony in it would be split across. */ + data class Loaded( + val localChatRoom: LocalChatRoom, + val participantCount: Int, + ) : CreateSharedKeyUIState + + /** + * The group already has a ceremony that has not failed -- running, or finished + * with a key. The screen hands over to it rather than offering a second: a + * second is another participant set for every member to reconcile, and the key + * the first produced would be left with nothing pointing at it. + */ + data class Existing(val dkgSessionId: String) : CreateSharedKeyUIState + + /** This room cannot hold a ceremony of its own, and the screen says why. */ + data class Refused(val reason: Reason) : CreateSharedKeyUIState { + enum class Reason { + /** + * A Marmot room's id is derived from the key it already has, so a key + * of its own is one it could never answer to. It hosts its subgroups' + * ceremonies, which are started from the subgroup picker. + */ + MARMOT_ROOM, + + /** A key held by one person is just a key. */ + TOO_FEW_MEMBERS, + } + } + + data class Error(val reason: Reason) : CreateSharedKeyUIState { + enum class Reason { ROOM_NOT_FOUND, NO_KEYS, NOT_STARTED } + } + + data object Loading : CreateSharedKeyUIState +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/DkgRitualUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/DkgRitualUIState.kt index 5d5e2761..f1313293 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/DkgRitualUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/DkgRitualUIState.kt @@ -7,14 +7,19 @@ import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant import com.machankura.bennu.compose.database.model.types.DkgApprovalStep +import com.machankura.bennu.compose.database.model.types.DkgRitualStage import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.machankura.bennu.compose.managers.ChillDkgRitualManager sealed interface DkgRitualUIState { data class Loaded( val localChatRoom: LocalChatRoom, - /** Null until somebody opens a ritual. */ - val session: DkgSession? = null, + /** + * The ceremony this screen was named. Never absent once loaded: the screen + * shows a ceremony and does not offer to start one, so there is no state + * in which it has none to show -- see docs/ceremony-creation.md. + */ + val session: DkgSession, /** * Who has published each round's message, for the progress ladder. * @@ -63,18 +68,6 @@ sealed interface DkgRitualUIState { * signed first. It is what gates creating the room. */ val isKeyStateSigned: Boolean = false, - /** - * Whether this room already holds a ceremony that has not failed -- - * whichever one [session] happens to be showing. - * - * Two different questions, and conflating them opened a second ceremony - * in a room that already had one. [session] is the ceremony being looked - * at; this is whether the room has any. `proposeRitual`'s guard is scoped - * by purpose, so a room holding a subgroup's ceremony would happily take - * a second one for no subgroup -- and then "the room's newest ceremony" - * is the new empty one and the subgroup's is buried under it. - */ - val roomHasCeremony: Boolean = false, /** * The group this ceremony is making a subgroup of, or null for an * ordinary one. @@ -124,9 +117,7 @@ sealed interface DkgRitualUIState { .distinctBy { it.participant.participantPublicKey } .associateBy { it.participant.participantPublicKey } - val participants = session - ?.let { ChillDkgRitualManager.participantsOf(it, localChatRoom) } - ?: roomMembers.keys + val participants = ChillDkgRitualManager.participantsOf(session, localChatRoom) return (participants + hostKeyParticipants + round1Participants + round2Participants) .map { publicKey -> @@ -142,13 +133,20 @@ sealed interface DkgRitualUIState { } /** - * The `n` of the t-of-n. Counted over people, not participant rows — a room - * can hold the same member twice — and taken from the session once one - * exists, because that is the count every device agreed to run the ritual on. + * Whether this member can end the ceremony for everyone: while it is still + * running, and only if they are in it. See `ChillDkgRitualManager.abandon`. + */ + val canAbandon: Boolean + get() = session.stage != DkgRitualStage.COMPLETE && + session.stage != DkgRitualStage.FAILED && + session.userPublicKey in ChillDkgRitualManager.participantsOf(session, localChatRoom) + + /** + * The `n` of the t-of-n, as the session has it, because that is the count + * every device agreed to run the ritual on. */ val participantCount: Int - get() = session?.participantCount - ?: ChillDkgRitualManager.memberPublicKeys(localChatRoom).size + get() = session.participantCount } data class Error( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt deleted file mode 100644 index a2a39725..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface EditGroupNostrProfileUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * What the group has already said about itself, or null the first time. - * - * The form starts from it, and so does the event: an edit is built with - * `MetadataEvent.updateFromPast` so a field this app does not offer survives - * being edited rather than being dropped by it. See - * [GroupNostrProfile.template]. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the form readable and the button inert, which is the honest - * shape: the profile is worth reading either way, and a member without a - * share cannot open a session for one. See - * `ChatRoomDetailUIState.canEditNostrProfile`. - */ - val canSign: Boolean = false, - ): EditGroupNostrProfileUIState - - data class Error( - val message: String - ): EditGroupNostrProfileUIState - - data object Loading: EditGroupNostrProfileUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt deleted file mode 100644 index e957ce76..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelayList - -sealed interface EditGroupRelaysUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * What the group has signed for each set, which is what an edit is measured - * against. - * - * Kept beside the working copy rather than replaced by it, because the - * button only proposes the sets that actually differ -- and "differ" needs - * both halves. See `EditGroupRelaysViewModel.changedSets`. - */ - val signed: List = emptyList(), - /** - * Whether this device holds a share of the group's key. - * - * False leaves the lists readable and the button inert: where the group - * says it lives is worth reading whoever is looking, and proposing a change - * to it is a signature only a share-holder can start. - */ - val canSign: Boolean = false, - ): EditGroupRelaysUIState - - data class Error( - val message: String - ): EditGroupRelaysUIState - - data object Loading: EditGroupRelaysUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt deleted file mode 100644 index d4a47e41..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface GroupNostrProfileUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * The kind:0 the group signed about itself, or null while it has signed - * none. - * - * Null is an ordinary state and the screen says so -- a group has an - * identity from the moment it has a key and describes it whenever - * somebody gets round to it. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the profile readable and hides the way into the editor: - * proposing one is a signature by the group, and - * `FrostSigningManager.proposeSigningBatch` throws for a device holding - * no share. It is not about permission -- any member with a share may - * propose -- and the quorum is what decides. - */ - val canSign: Boolean = false, - ): GroupNostrProfileUIState - - data class Error( - val message: String - ): GroupNostrProfileUIState - - data object Loading: GroupNostrProfileUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt deleted file mode 100644 index a4d93d9e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost - -sealed interface GroupPostsUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * What the group has said publicly, as itself, newest first. Empty in - * a group that has said nothing, which is every group until somebody - * proposes a post. - */ - val groupPosts: List = emptyList(), - /** - * The group's profile, for the byline on every post. - * - * Read alongside the posts because a post is the one thing here a - * reader might otherwise attribute to whichever member proposed it, - * and the group's own name and picture are what say it was the group. - * Null where the group has not described itself, and the byline falls - * back to the key. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the posts readable and hides the way into the composer, - * for the reason `GroupNostrProfileUIState.Loaded.canSign` gives. - */ - val canSign: Boolean = false, - ): GroupPostsUIState - - data class Error( - val message: String - ): GroupPostsUIState - - data object Loading: GroupPostsUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt deleted file mode 100644 index cd2a0e14..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelayList - -sealed interface GroupRelaysUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * Where the group has said it lives on nostr, one entry per relay set. - * - * Empty only in a room that has none of this to say. Every other case - * has four entries, some of them unsigned; see - * `ChatRepository.groupRelayLists`. - */ - val groupRelayLists: List = emptyList(), - /** - * Whether this device holds a share of the group's key. - * - * False leaves the lists readable and hides the way into the editor, - * for the reason `GroupNostrProfileUIState.Loaded.canSign` gives. - */ - val canSign: Boolean = false, - ): GroupRelaysUIState - - data class Error( - val message: String - ): GroupRelaysUIState - - data object Loading: GroupRelaysUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt index 6b2fef1a..82dc3523 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt @@ -1,7 +1,10 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.wallet.GroupAddress import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.GroupWalletState import fr.acinq.bitcoin.OutPoint @@ -18,6 +21,14 @@ sealed interface GroupSendUIState { val reserved: Set, /** The change indices open spends already pay back to, which a new one pays past. */ val reservedChange: Set = emptySet(), + /** + * Who would sign: the room's own group, or -- spending from a descendant's + * guarded wallet -- the group as that wallet's guardian. [wallet] is then + * the descendant's. + */ + val spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + /** The descendant's guarded wallet this send pays, or null for a send to a typed address. */ + val funding: FundingTarget? = null, ): GroupSendUIState /** A room this device cannot propose from -- no wallet, no share, or no node. */ @@ -27,3 +38,21 @@ sealed interface GroupSendUIState { data object Loading: GroupSendUIState } + +/** + * A descendant's guarded wallet a send funds, with where it is up to: its chain + * state as this device watches it, and the receive indices the room's open + * fundings already hold. See `docs/guarded-wallet-funding.md`. + */ +data class FundingTarget( + val wallet: GuardianManager.GuardedWallet, + /** Null until Electrum has answered for the descendant's addresses. */ + val walletState: GroupWalletState?, + val reserved: Set = emptySet(), +) { + /** The address the send pays, moving on whenever the one before it is paid or held. */ + val address: GroupAddress? get() = walletState?.fundingAddress(reserved) + + /** Electrum has answered, and open fundings hold every address the wallet watches. */ + val allHeld: Boolean get() = walletState?.receiveAddress != null && address == null +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt index 303c923f..3e35453b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt @@ -1,13 +1,19 @@ package com.machankura.bennu.compose.ui.view.state +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager +import fr.acinq.bitcoin.Satoshi +import fr.acinq.lightning.utils.sum import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.wallet.GroupWalletState import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.vitorpamplona.quartz.nip01Core.core.HexKey sealed interface GroupWalletUIState { /** @@ -17,11 +23,30 @@ sealed interface GroupWalletUIState { * at all -- there is nothing to open then. [canSign] gates the way in, for * the reason every proposing screen gives: `proposeSigning` throws for a * device holding no share. + * + * [guarded] is the guarded account a subgroup could open instead, when its + * birth certificate grants it guardian keys and guarded wallets are offered + * on this network -- see `docs/group-wallet-guardians.md`. + * + * [policy] is what the room's own certificate decided about its wallet, or + * null for a room with none -- `docs/subgroup-wallet-policy.md`. A decided + * policy leaves one way in: [guarded] alone for *guarded*, the plain + * [account] alone for *unguarded*, which [offersPlain] and [guarded] say. */ data class NotOpened( val localChatRoom: LocalChatRoom, val account: GroupWalletDerivation.Account?, val canSign: Boolean, + val guarded: GroupWalletManager.GuardedOpening? = null, + val policy: WalletPolicyReading? = null, + /** What this device calls each guardian's room, by room id, for the ones it holds. */ + val guardianNames: Map = emptyMap(), + /** Whether a plain wallet may be opened: false only when the parent decided this one is guarded. */ + val offersPlain: Boolean = true, + /** Guarded wallets of groups below this one. A group with no wallet of its own can still guard others'. */ + val guardedWallets: List = emptyList(), + /** Guarded statements this device can carry to the groups above. */ + val shareable: List = emptyList(), ): GroupWalletUIState /** @@ -39,6 +64,12 @@ sealed interface GroupWalletUIState { val canSign: Boolean, /** The room's spends, newest first. */ val spends: List = emptyList(), + /** Guarded wallets of groups below this one. */ + val guardedWallets: List = emptyList(), + /** Guarded statements this device can carry to the groups above. */ + val shareable: List = emptyList(), + /** What this device calls each guardian's room, by room id, for the ones it holds. */ + val guardianNames: Map = emptyMap(), ): GroupWalletUIState data class Error( @@ -48,6 +79,75 @@ sealed interface GroupWalletUIState { data object Loading: GroupWalletUIState } +/** A descendant's guarded wallet, as an ancestor's wallet screen lists it. */ +data class GuardedWalletRow( + val wallet: GuardianManager.GuardedWallet, + /** Null before Electrum's first answer, and for a profile that cannot watch the chain. */ + val walletState: GroupWalletState?, +) { + /** + * What this group could spend now: coins confirmed at least as deep as its + * own leaf's lock -- not the default's, since the group that granted the + * leaf chose it. Null while the chain is not known. + */ + val withinReach: Satoshi? + get() = walletState?.let { state -> + state.utxos.filter { state.confirmations(it) >= wallet.delay }.map { it.amount }.sum() + } + + /** + * Coins in the wallet not yet within reach: in the mempool, or confirmed + * less deeply than this group's own leaf's lock, the same one [withinReach] + * counts past. What a funding looks like for the two + * hours after it lands -- without it, [withinReach] would make the money + * look gone. Every such coin, whoever paid it, which is all this group can + * know. Null while the chain is not known. + */ + val arriving: Satoshi? + get() = walletState?.let { state -> + state.utxos.filter { state.confirmations(it) < wallet.delay }.map { it.amount }.sum() + } +} + +/** + * One member's wallets as an ancestor's list gathers them, so a group can see + * at a glance that one person has several, guarded by different groups below + * it. `docs/member-wallet-guarding-group.md`, D6. + */ +data class PersonGuardedWallets( + val ownerPublicKey: HexKey, + /** The member's profile name on this device, or null. */ + val ownerName: String?, + /** Nearest first, then by the guarding group's name: wallets from one branch sit together. */ + val rows: List, +) { + /** How many groups below this one directly guard these wallets. */ + val guardianCount: Int get() = rows.map { it.wallet.directGuardianChatRoomId.lowercase() }.distinct().size +} + +/** + * The member wallets among these rows, by person, people by name and then key. + * Subgroups' wallets are left out: a row there is a room, not a person. + */ +fun List.byPerson(): List = + mapNotNull { row -> (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.let { it to row } } + .groupBy { (member, _) -> member.ownerPublicKey.lowercase() } + .map { (_, owned) -> + val member = owned.first().first + PersonGuardedWallets( + ownerPublicKey = member.ownerPublicKey, + ownerName = owned.firstNotNullOfOrNull { (it, _) -> it.ownerName }, + rows = owned.map { it.second }.sortedWith( + compareBy( + { it.wallet.position }, + { (it.wallet.subject as GuardianManager.GuardedSubject.Member).guardianName?.lowercase() ?: it.wallet.directGuardianChatRoomId }, + { (it.wallet.subject as GuardianManager.GuardedSubject.Member).label?.lowercase() }, + ) + ), + ) + } + .sortedWith(compareBy({ it.ownerName?.lowercase() ?: it.ownerPublicKey }, { it.ownerPublicKey })) + /** Where one of the room's spends has got to, as one fact a member reads. */ enum class SpendStatus { WAITING_FOR_SIGNATURES, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberSendUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberSendUIState.kt new file mode 100644 index 00000000..8bf3fd34 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberSendUIState.kt @@ -0,0 +1,24 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.wallet.GroupWalletState +import fr.acinq.bitcoin.OutPoint + +sealed interface MemberSendUIState { + data object Loading : MemberSendUIState + + data class Error(val message: String) : MemberSendUIState + + /** A wallet this device can spend from: certified, its key here, and a node to see the coins with. */ + data object Unavailable : MemberSendUIState + + data class Ready( + val wallet: MemberWalletManager.MemberWalletRow, + /** Null until Electrum answers. */ + val walletState: GroupWalletState?, + /** The coins the member's own unsettled spends hold, which a new one leaves alone. */ + val reserved: Set = emptySet(), + /** The change indices those spends pay back to, which a new one pays past. */ + val reservedChange: Set = emptySet(), + ) : MemberSendUIState +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletPolicyUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletPolicyUIState.kt new file mode 100644 index 00000000..c327b17b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletPolicyUIState.kt @@ -0,0 +1,23 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent + +sealed interface MemberWalletPolicyUIState { + data object Loading : MemberWalletPolicyUIState + + data class Error(val message: String) : MemberWalletPolicyUIState + + /** + * The group, and what it says about its members' wallets now: [policy] is + * its newest, open or closed, or null for one it never signed. [canSign] is + * whether this device can put a change to the group. + */ + data class Loaded( + val localChatRoom: LocalChatRoom, + val policy: MemberWalletPolicyEvent.Policy?, + val canSign: Boolean, + ) : MemberWalletPolicyUIState { + val isOpen: Boolean get() = policy is MemberWalletPolicyEvent.Policy.Open + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt new file mode 100644 index 00000000..ea2ddb31 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt @@ -0,0 +1,36 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.wallet.GroupWalletState +import fr.acinq.bitcoin.Satoshi + +sealed interface MemberWalletUIState { + data object Loading : MemberWalletUIState + + data class Error(val message: String) : MemberWalletUIState + + data class Loaded( + val wallet: MemberWalletManager.MemberWalletRow, + /** Null before Electrum's first answer, for a wallet no group has certified, and for a profile that cannot watch the chain. */ + val walletState: GroupWalletState? = null, + /** Whether this profile has an Electrum client to watch the chain with. */ + val canWatch: Boolean, + /** What the wallet's guardians took from it, read off the chain: never stored, found again on each look. */ + val taken: List = emptyList(), + /** The spends the member signed from it, newest first. */ + val spends: List = emptyList(), + /** How many groups guard it, for the line under the title. */ + val reach: Int = wallet.account.guardians.size, + /** Each guardian's delay, nearest first: the leaves the wallet's addresses carry. */ + val delays: List = wallet.account.guardians.map { it.delay }, + ) : MemberWalletUIState +} + +/** One guardian spend from a member's wallet, named for the group that made it. */ +data class TakenLine( + val txid: String, + /** The guardian's room name on this device, or null when this device is not in it. */ + val guardianName: String?, + val amount: Satoshi, +) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/NewMemberWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/NewMemberWalletUIState.kt new file mode 100644 index 00000000..c2c16683 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/NewMemberWalletUIState.kt @@ -0,0 +1,37 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.MemberWalletManager + +sealed interface NewMemberWalletUIState { + data object Loading : NewMemberWalletUIState + + data class Error(val message: String) : NewMemberWalletUIState + + /** + * No group chosen yet: every group this profile is in that guards members' + * wallets, or may -- one whose key this device does not know yet -- each + * with why it cannot guard a wallet now, if it cannot. + */ + data class Picking(val groups: List) : NewMemberWalletUIState + + /** + * A group chosen. [refusal] null means it can be asked, and [reach] is how + * many groups the wallet would be guarded by -- the group and every group + * above it whose key it passes down. + */ + data class Chosen( + val room: LocalChatRoom, + val refusal: MemberWalletManager.Refusal?, + val reach: Int?, + /** Each guardian's delay, nearest first, as [reach] counts them; null while the group's key is unknown. */ + val delays: List? = null, + /** The member already asked the group for its key, and is waiting on an answer. */ + val askedForKey: Boolean = false, + ) : NewMemberWalletUIState +} + +data class GroupChoice( + val room: LocalChatRoom, + val refusal: MemberWalletManager.Refusal?, +) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt deleted file mode 100644 index 6e867343..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface ProposeGroupEventUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * Who the group says it is, for the byline over the paste. - * - * Whatever is pasted goes out signed by the group and read as the group, - * so the screen shows whose name it will carry -- which is not the - * member pasting it, and not whatever `pubkey` the paste may name. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the paste writable and the button inert, for the same - * reason the typed editors do: reading and checking cost nothing, and - * only a share-holder can open the session that would sign it. - */ - val canSign: Boolean = false, - ): ProposeGroupEventUIState - - data class Error( - val message: String - ): ProposeGroupEventUIState - - data object Loading: ProposeGroupEventUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/SelectSubgroupAdminsUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/SelectSubgroupAdminsUIState.kt index e64974d1..ff5cecf0 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/SelectSubgroupAdminsUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/SelectSubgroupAdminsUIState.kt @@ -1,5 +1,9 @@ package com.machankura.bennu.compose.ui.view.state +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.subgroup.isDecided +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant @@ -29,9 +33,29 @@ sealed interface SelectSubgroupAdminsUIState { val withoutKeyPackage: Set = emptySet(), /** Null while the lookup is still out; a set once it has settled. */ val isResolvingKeyPackages: Boolean = true, + /** + * What the parent's own certificate says of its wallet, or null for a + * parent with none. A parent decided *guarded* can only make guarded + * subgroups -- `docs/subgroup-wallet-policy.md`, D4. + */ + val parentPolicy: WalletPolicyReading? = null, + /** + * The guardian keys the parent's own certificate grants it, or null when + * they do not read -- in which case it cannot grant a child any, and a + * guarded subgroup is refused here rather than after a ceremony. + */ + val parentGuardians: List? = emptyList(), ): SelectSubgroupAdminsUIState data class Error(val message: String): SelectSubgroupAdminsUIState data object Loading: SelectSubgroupAdminsUIState } + +/** Whether this parent may only make guarded subgroups. */ +val SelectSubgroupAdminsUIState.Loaded.onlyGuarded: Boolean + get() = parentPolicy.isDecided(SubgroupWalletPolicy.GUARDED) + +/** Whether this parent can grant a child guardian keys at all. */ +val SelectSubgroupAdminsUIState.Loaded.canGuard: Boolean + get() = parentGuardians != null diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt deleted file mode 100644 index b6281d6c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslateChunkUIState.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -sealed interface TranslateChunkUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - val originalChunk: MantraChunk, - val existingTranslationText: String = "", - - /** - * Whether the group holds a shared key. A translation is signed into - * existence now rather than saved, so a group without one cannot - * translate a chunk here at all. - */ - val canSign: Boolean = false, - ): TranslateChunkUIState - - data class Error( - val message: String - ): TranslateChunkUIState - - data object Loading: TranslateChunkUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt deleted file mode 100644 index 3d67b44a..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationArtifactVersionDetailUIState.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom - -/** A translation chapter with how many of its chunks have been translated. */ -data class TranslationChapterProgress( - val chapter: MantraTranslationChapter, - val totalChunks: Int, - val translatedChunks: Int, -) - -sealed interface TranslationArtifactVersionDetailUIState { - data class Loaded( - val translation: MantraTranslationArtifactVersion, - val chapters: List = emptyList(), - - /** - * The room this translation belongs to, which is who would sign the - * chapters it is missing. Null when it cannot be read, which is a - * translation nothing can be proposed for. - */ - val localChatRoom: LocalChatRoom? = null, - - /** - * Chapters of the source version this translation has nothing for. - * - * A translation covers the chapters that existed when it was proposed, - * and a chapter signed afterwards is scaffolded into it by a session of - * that chapter's own -- which the two can miss, by being proposed at the - * same moment or by one of them not reaching a quorum. This is what is - * left over when they do, and it is shown rather than inferred because - * a chapter nobody can translate is invisible from the translation. - */ - val missingChapters: List = emptyList(), - - /** Whether the group holds a shared key, without which nothing can be proposed. */ - val canSign: Boolean = false, - ): TranslationArtifactVersionDetailUIState - - data class Error( - val message: String - ): TranslationArtifactVersionDetailUIState - - data object Loading: TranslationArtifactVersionDetailUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt deleted file mode 100644 index 0f2b8a08..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/TranslationChapterUIState.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraTranslationChunk - -/** - * An original chunk paired with its translation chunk. [translationChunk] is - * null (or has blank text) when the chunk hasn't been translated yet, in which - * case the UI shows the original text as a greyed-out placeholder. - */ -data class ChunkTranslationPair( - val originalChunk: MantraChunk, - val translationChunk: MantraTranslationChunk?, -) - -sealed interface TranslationChapterUIState { - data class Loaded( - val originalDialectName: String, - val translationDialectName: String, - val rows: List = emptyList(), - ): TranslationChapterUIState - - data class Error( - val message: String - ): TranslationChapterUIState - - data object Loading: TranslationChapterUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt index 6b51bf65..b7294d5e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt @@ -230,6 +230,35 @@ data class GroupWalletState( } } + /** + * The receive address an ancestor pays when it funds this wallet: the lowest + * unused index from [GroupOnchainWallet.ADDRESSES_AHEAD] past the current one + * that [reserved] -- the indices open fundings already pay -- does not hold, + * and that the wallet watches. Null before Electrum has answered, for the + * reason [receiveAddress] is, and when every such index is held. + * + * Not the current address: the wallet's own members are handing that one + * out, and every device computes the same one. Starting at the top of the + * address list's window and going up keeps an ancestor out of their way. + * See `docs/guarded-wallet-funding.md`, D2. + */ + fun fundingAddress(reserved: Set = emptySet()): GroupAddress? { + val current = receive.firstUnusedDerivedAddress?.second?.index ?: return null + val window = (current + GroupOnchainWallet.ADDRESSES_AHEAD) until (current + GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt()) + val (address, index) = receive.addresses.entries + .filterNot { it.value.alreadyUsed } + .mapNotNull { (address, addressState) -> addressState.meta.indexOrNull?.let { address to it } } + .filter { (_, index) -> index in window && index.toLong() !in reserved } + .minByOrNull { (_, index) -> index } + ?: return null + return GroupAddress( + derivation = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()), + address = address, + status = GroupAddress.Status.NEXT, + balance = Satoshi(0), + ) + } + /** Whether Electrum has answered for any change address yet: before it has, there is no next one to name. */ val changeKnown: Boolean get() = change.addresses.values.any { !it.alreadyUsed } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt index a66a76aa..5900cd28 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt @@ -2,6 +2,12 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation import fr.acinq.bitcoin.Chain +import com.machankura.bennu.compose.managers.GuardianManager +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.byteVector32 import fr.acinq.lightning.blockchain.electrum.IElectrumClient import fr.acinq.lightning.blockchain.fee.FeeratePerByte import kotlinx.coroutines.CoroutineScope @@ -30,9 +36,14 @@ class GroupOnchainWallets( private val mutex = Mutex() private val wallets = mutableMapOf() - /** The wallet watching [account], made the first time it is asked for. Keyed by xpub, which names one account of one group on one network. */ + /** + * The wallet watching [account], made the first time it is asked for. Keyed + * by its receive descriptor, which names one account of one group on one + * network *and* the guardians in its addresses -- an xpub alone would hand a + * guarded account the plain one's addresses. + */ suspend fun walletFor(account: GroupWalletDerivation.Account): GroupOnchainWallet = mutex.withLock { - wallets.getOrPut(account.xpub) { GroupOnchainWallet(account, clients.clientFor(account.chain), scope) } + wallets.getOrPut(account.receiveDescriptor) { GroupOnchainWallet(account, clients.clientFor(account.chain), scope) } } /** @@ -43,6 +54,62 @@ class GroupOnchainWallets( suspend fun suggestedFeeratePerVbyte(chain: Chain): Long? = clients.clientFor(chain).estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1) + /** Transactions fetched for [guardianSpends], which never change once mined or seen. */ + private val transactions = mutableMapOf() + + /** + * Every spend a guardian of [state]'s account made from it, read off the + * history of each address the wallet has used. Empty for an unguarded + * account, and for whatever Electrum cannot answer right now -- the next look + * asks again. + * + * History rather than a watch on coins disappearing: a device asleep when the + * coin moved still finds it, since the chain keeps the record and nothing + * here has to have been running at the time. + */ + suspend fun guardianSpends(state: GroupWalletState): List { + val account = state.account + if (!account.isGuarded) return emptyList() + val electrum = clients.clientFor(account.chain) + + val used = listOf(GroupWalletDerivation.RECEIVE to state.receive, GroupWalletDerivation.CHANGE to state.change) + .flatMap { (branch, wallet) -> + wallet.addresses.values.filter { it.alreadyUsed }.mapNotNull { address -> + address.meta.indexOrNull?.let { GroupWalletDerivation.derive(account, branch, it.toLong()) } + } + } + val ours = used.associateBy { it.pubkeyScript } + + val history = used.flatMap { derived -> + runCatching { electrum.getScriptHashHistory(Crypto.sha256(derived.pubkeyScript).byteVector32().reversed()) } + .getOrDefault(emptyList()) + .map { it.txid } + }.distinct().mapNotNull { txid -> transactionOf(txid, electrum) } + + val coins = history.flatMap { tx -> + tx.txOut.mapIndexedNotNull { index, out -> ours[out.publicKeyScript]?.let { OutPoint(tx, index.toLong()) to (out to it) } } + }.toMap() + + return history.flatMap { GuardianManager.takenIn(it, account, coins) } + } + + private suspend fun transactionOf(txid: TxId, electrum: IElectrumClient): Transaction? = + mutex.withLock { transactions[txid] } + ?: runCatching { electrum.getTx(txid) }.getOrNull()?.also { tx -> mutex.withLock { transactions[txid] = tx } } + + /** + * Hands [tx] to Electrum -- for a spend a member signed alone, which has no + * session for `GroupTransactionWatcher` to follow. Electrum reports success + * whatever the server said, so this is not evidence it reached the network: + * [confirmationsOf] is. + */ + suspend fun broadcast(tx: Transaction, chain: Chain) { + clients.clientFor(chain).broadcastTransaction(tx) + } + + /** How deep [tx] is on [chain]: 0 in the mempool, null while Electrum has not heard of it or cannot be asked. */ + suspend fun confirmationsOf(tx: Transaction, chain: Chain): Int? = runCatching { clients.clientFor(chain).getConfirmations(tx) }.getOrNull() + suspend fun stop() = mutex.withLock { wallets.values.forEach { it.stop() } wallets.clear() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt index f27490c5..17378609 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt @@ -2,15 +2,23 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.KeyPath import fr.acinq.bitcoin.OutPoint import fr.acinq.bitcoin.Satoshi import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.ScriptWitness import fr.acinq.bitcoin.SigHash import fr.acinq.bitcoin.Transaction import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.frost.TweakCache import fr.acinq.bitcoin.psbt.Input import fr.acinq.bitcoin.psbt.Psbt import fr.acinq.bitcoin.psbt.TaprootBip32DerivationPath @@ -38,6 +46,16 @@ import kotlin.io.encoding.Base64 * is what lets a member with no node of their own, and so no way to look a coin * up, still sign safely: the worst a lying proposer gets is a transaction nobody * can mine. + * + * ### Two ways to sign a coin + * + * The wallet's own group signs each input on its address's key path. An + * ancestor of a guarded wallet signs through its leaf instead -- a [Spender.Guardian] + * -- and then every input's sighash is BIP342's over that leaf, its sequence is + * the leaf's lock, its signature verifies against the leaf key, and its witness + * is the leaf and its control block. Everything else above holds unchanged: the + * coins are still the descendant's, at places under its account, and each claim + * is still rederived rather than believed. See `docs/group-wallet-guardians.md`. */ object GroupSpend { /** @@ -65,6 +83,30 @@ object GroupSpend { */ const val MAX_FEERATE_SAT_PER_VBYTE: Long = 2_000L + /** Who signs a spend's inputs. */ + sealed interface Spender { + /** The wallet's own group, on each address's key path. */ + data object Owner : Spender + + /** + * An ancestor of a guarded wallet, through its leaf: the guardian at + * [position] in the account's guardians, whose key is [thresholdPublicKey] + * walked down [lineage] -- `GuardianDerivation.signingCache`. + * + * [thresholdPublicKey] is null for a builder, which needs the leaf and + * never the key that signs it; [check] refuses without it. + */ + data class Guardian( + val position: Int, + val lineage: List, + val thresholdPublicKey: HexKey? = null, + /** The guarded wallet's founding name, for the words a spend is shown in. */ + val name: String? = null, + /** A member's label for the wallet, where they gave one: one person can have several. */ + val label: String? = null, + ) : Spender + } + /** One input, and what its signature has to be over and verify against. */ data class SpentInput( val index: Int, @@ -72,7 +114,19 @@ object GroupSpend { val txOut: TxOut, val derivation: GroupWalletDerivation.Derived, val sighash: ByteVector32, - ) + /** The leaf a guardian signs through, or null for a key-path input. */ + val leaf: ScriptTree.Leaf? = null, + /** The key the input's signature verifies against: the address's output key, or the leaf key. */ + val signingKey: XonlyPublicKey = derivation.outputKey, + /** The cache a session signs this input with. */ + val cache: TweakCache = derivation.cache, + ) { + /** The input's witness around [signature]. */ + fun witness(signature: ByteVector64): ScriptWitness = when (leaf) { + null -> Script.witnessKeyPathPay2tr(signature) + else -> Script.witnessScriptPathPay2tr(derivation.internalKey, leaf, ScriptWitness(listOf(signature)), derivation.tree!!) + } + } /** One output, and -- when its claim to be the wallet's own derives -- where under the account it is. */ data class CheckedOutput( @@ -91,8 +145,19 @@ object GroupSpend { val outputs: List, /** `Σ inputs − Σ outputs`, believable for the reason the object's kdoc gives. */ val fee: Satoshi, - /** The finished transaction's weight. Exact before signing: a default-sighash key-path witness is always 64 bytes. */ + /** + * The finished transaction's weight. Exact before signing: a default-sighash + * signature is always 64 bytes, and a guardian's leaf and control block are + * known before it signs. + */ val weight: Int, + val spender: Spender = Spender.Owner, + /** + * The payments that fund a descendant's guarded wallet, each claim derived + * again -- [fundingsOf]. Empty until a caller holding the room's guarded + * wallets has read them, which [check] alone cannot. + */ + val fundings: List = emptyList(), ) { val tx: Transaction get() = psbt.global.tx @@ -106,6 +171,10 @@ object GroupSpend { /** Every spent output, in input order: what every sighash and `correctlySpends` take. */ val spentOutputs: List get() = inputs.map { it.txOut } + + /** [tx] with each input's witness around its signature, in input order. */ + fun witnessed(signatures: List): Transaction = + signatures.foldIndexed(tx) { index, partial, signature -> partial.updateWitness(index, inputs[index].witness(signature)) } } sealed interface Result { @@ -113,14 +182,73 @@ object GroupSpend { data class Refused(val reason: String) : Result } + /** A payment into a descendant's guarded wallet, at [derived] under its account -- the claim, derived again. */ + data class Funding( + val outputIndex: Int, + val wallet: GuardianManager.GuardedWallet, + val derived: GroupWalletDerivation.Derived, + ) + + sealed interface FundingReading { + data class Ok(val fundings: List) : FundingReading + data class Refused(val reason: String) : FundingReading + } + + /** + * Which of [checked]'s payments fund one of [guarded] -- the descendants' + * guarded wallets the room holds -- read off each payment's derivation and + * derived again, the way change is. `docs/guarded-wallet-funding.md`, D4: + * + * - a claim under a wallet in [guarded] that derives to the payment's script + * is a funding; + * - a claim under a wallet in [guarded] that does not -- another index, + * another branch, another key -- refuses the spend, so no proposer can put + * a descendant's name on a payment to an address it does not own; + * - a claim under any other account is not this device's to check, and the + * payment is read as the bare address it is. + * + * Fingerprints are four bytes, so every held wallet sharing one is tried + * before a claim is refused. + */ + fun fundingsOf(checked: Checked, guarded: List): FundingReading { + val fundings = checked.payments.mapNotNull { payment -> + val paths = checked.psbt.outputs[payment.index].taprootDerivationPaths + val (internalKey, path, candidates) = paths.entries.firstNotNullOfOrNull { (internalKey, path) -> + guarded.filter { it.chain == checked.account.chain && isOurs(path, it.account) } + .takeIf { it.isNotEmpty() } + ?.let { Triple(internalKey, path, it) } + } ?: return@mapNotNull null + + val (branch, index) = path.keyPath.path.takeIf { it.size == 2 && path.leaves.isEmpty() } + ?: return FundingReading.Refused("output ${payment.index} claims a place in a guarded wallet that is not one") + if (branch != GroupWalletDerivation.RECEIVE || index !in 0L..MAX_ADDRESS_INDEX) { + return FundingReading.Refused("output ${payment.index} claims $branch/$index, which is not a receive address") + } + candidates.firstNotNullOfOrNull { wallet -> + GroupWalletDerivation.derive(wallet.account, branch, index) + .takeIf { it.pubkeyScript == payment.txOut.publicKeyScript && it.internalKey == internalKey } + ?.let { Funding(payment.index, wallet, it) } + } ?: return FundingReading.Refused( + "output ${payment.index} claims $branch/$index of ${candidates.first().displayName ?: "a subgroup"}'s guarded wallet, which is not where it pays" + ) + } + return FundingReading.Ok(fundings) + } + /** * The checks a member makes before signing, in the order `docs/group-chain-wallet.md` * numbers them, against [account] -- which comes from the room's verified - * statement and never from the proposal. + * statement and never from the proposal -- as [spender] would sign it. */ - fun check(psbt: Psbt, account: GroupWalletDerivation.Account): Result { + fun check(psbt: Psbt, account: GroupWalletDerivation.Account, spender: Spender = Spender.Owner): Result { val tx = psbt.global.tx + // A guardian's leaf, and what it locks: every one of its inputs carries + // exactly that lock, and it signs as the key its walk reaches. + val guardian = spender as? Spender.Guardian + val delay = guardian?.let { account.guardians.getOrNull(it.position)?.delay ?: return Result.Refused("names a guardian this wallet does not have") } + if (guardian != null && guardian.thresholdPublicKey == null) return Result.Refused("has no key to sign a guardian's leaf with") + // 4. Bounded, before any per-input work. if (tx.txIn.isEmpty()) return Result.Refused("spends nothing") if (tx.txIn.size > MAX_INPUTS) return Result.Refused("spends ${tx.txIn.size} coins, more than the $MAX_INPUTS one spend may sign") @@ -128,6 +256,7 @@ object GroupSpend { if (tx.version != 2L) return Result.Refused("is version ${tx.version}, not 2") if (tx.lockTime != 0L) return Result.Refused("has a lock time") if (tx.txIn.any { it.sequence > MAX_SEQUENCE }) return Result.Refused("cannot be replaced: a sequence is above ${MAX_SEQUENCE}") + if (delay != null && tx.txIn.any { it.sequence != delay }) return Result.Refused("has an input whose sequence is not its leaf's lock of $delay blocks") if (tx.txIn.map { it.outPoint }.toSet().size != tx.txIn.size) return Result.Refused("spends one coin twice") // 2 and 3. Every input is the group's, at a key path, under the default sighash. @@ -157,19 +286,42 @@ object GroupSpend { val spentOutputs = claimed.map { it.second } val inputs = claimed.map { (index, txOut, derivation) -> - SpentInput( - index = index, - outPoint = tx.txIn[index].outPoint, - txOut = txOut, - derivation = derivation, - sighash = tx.hashForSigningTaprootKeyPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT), - ) + if (guardian == null) { + SpentInput( + index = index, + outPoint = tx.txIn[index].outPoint, + txOut = txOut, + derivation = derivation, + sighash = tx.hashForSigningTaprootKeyPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT), + ) + } else { + val leaf = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)[guardian.position] + val signing = GuardianDerivation.signingCache( + guardian.thresholdPublicKey!!, guardian.lineage, account.chain, account.account, derivation.change, derivation.index, + ) + // The leaf in the descendant's address, and the key this group's + // walk reaches, have to be one key -- or this group would sign for + // a leaf it cannot spend. + if (leaf.script != ByteVector(Script.write(GuardianDerivation.leafScript(signing.leafKey, delay!!)))) { + return Result.Refused("input $index's leaf is not this group's to sign") + } + SpentInput( + index = index, + outPoint = tx.txIn[index].outPoint, + txOut = txOut, + derivation = derivation, + sighash = tx.hashForSigningTaprootScriptPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT, leaf.hash()), + leaf = leaf, + signingKey = signing.leafKey, + cache = signing.cache, + ) + } } // 5. Change is change only if it derives. val outputs = psbt.outputs.mapIndexed { index, output -> val txOut = tx.txOut[index] - val ours = output.taprootDerivationPaths.values.filter { it.masterKeyFingerprint == account.fingerprint } + val ours = output.taprootDerivationPaths.values.filter { isOurs(it, account) } val change = if (ours.isEmpty()) { null } else { @@ -186,12 +338,12 @@ object GroupSpend { // 6. A sane fee. val fee = spentOutputs.map { it.amount }.sum() - tx.txOut.map { it.amount }.sum() if (fee.sat <= 0) return Result.Refused("pays out more than it spends") - val weight = witnessed(tx, List(tx.txIn.size) { ByteVector64.Zeroes }).weight() + val weight = inputs.fold(tx) { partial, input -> partial.updateWitness(input.index, input.witness(ByteVector64.Zeroes)) }.weight() if (fee.sat > MAX_FEERATE_SAT_PER_VBYTE * vbytes(weight)) { return Result.Refused("pays a fee of ${fee.sat} sats, over $MAX_FEERATE_SAT_PER_VBYTE sats per byte") } - return Result.Ok(Checked(account = account, psbt = psbt, inputs = inputs, outputs = outputs, fee = fee, weight = weight)) + return Result.Ok(Checked(account = account, psbt = psbt, inputs = inputs, outputs = outputs, fee = fee, weight = weight, spender = spender)) } /** @@ -204,10 +356,23 @@ object GroupSpend { fun claimedChangeIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set = psbt.outputs .flatMap { it.taprootDerivationPaths.values } - .filter { it.masterKeyFingerprint == account.fingerprint } + .filter { isOurs(it, account) } .mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.CHANGE }?.get(1) } .toSet() + /** + * The receive indices under [account] -- a descendant's guarded wallet -- + * that [psbt]'s outputs claim to fund: what an open funding holds, so the + * next one pays a different address. Claims, as [claimedChangeIndices] are, + * for the same reason. See `docs/guarded-wallet-funding.md`. + */ + fun claimedFundingIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set = + psbt.outputs + .flatMap { it.taprootDerivationPaths.values } + .filter { isOurs(it, account) } + .mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.RECEIVE }?.get(1) } + .toSet() + /** * The one derivation under [account] a PSBT field names, or null when it names * none, several, or one this wallet will not walk. @@ -219,7 +384,7 @@ object GroupSpend { paths: Map, account: GroupWalletDerivation.Account, ): GroupWalletDerivation.Derived? { - val (internalKey, path) = paths.entries.singleOrNull { it.value.masterKeyFingerprint == account.fingerprint } + val (internalKey, path) = paths.entries.singleOrNull { isOurs(it.value, account) } ?.toPair() ?: return null if (path.leaves.isNotEmpty()) return null @@ -230,16 +395,34 @@ object GroupSpend { return GroupWalletDerivation.derive(account, change, index).takeIf { it.internalKey == internalKey } } + /** + * Whether [path] names [account] as its master key. + * + * Compared as an unsigned 32-bit value. bitcoin-kmp reads a taproot + * derivation's fingerprint back from a serialised PSBT as a *signed* int, so + * an account whose fingerprint has its top bit set -- half of them -- would + * write `3578966523` and read back `-716000773`, and every member but the + * proposer would refuse every spend from that wallet as not its own. + */ + private fun isOurs(path: TaprootBip32DerivationPath, account: GroupWalletDerivation.Account): Boolean = + (path.masterKeyFingerprint and 0xFFFFFFFFL) == account.fingerprint + /** * The PSBT a proposer sends: [tx] with every input's spent output and * derivation, and every change output's derivation, so that a signer is * *told* what is change -- and [check] is how they decide whether to believe it. + * + * A [funding] output -- one paying a descendant's guarded wallet -- carries + * its derivation the same way, under the descendant's account rather than + * this one, so it is never mistaken for change and a signer holding that + * wallet can derive it again. See `docs/guarded-wallet-funding.md`. */ fun psbtOf( tx: Transaction, spent: List>, change: Map, account: GroupWalletDerivation.Account, + funding: Map> = emptyMap(), ): Psbt { require(spent.size == tx.txIn.size) { "one spent output per input" } @@ -252,11 +435,13 @@ object GroupSpend { ).right ?: throw IllegalArgumentException("could not describe input $index") } - return change.entries.fold(withInputs) { psbt, (index, derivation) -> + val outputs = change.mapValues { (_, derivation) -> account to derivation } + funding + return outputs.entries.fold(withInputs) { psbt, (index, claim) -> + val (owner, derivation) = claim psbt.updateWitnessOutput( outputIndex = index, taprootInternalKey = derivation.internalKey, - taprootDerivationPaths = mapOf(derivation.internalKey to pathOf(derivation, account)), + taprootDerivationPaths = mapOf(derivation.internalKey to pathOf(derivation, owner)), ).right ?: throw IllegalArgumentException("could not describe output $index") } } @@ -274,6 +459,21 @@ object GroupSpend { partial.updateWitness(index, Script.witnessKeyPathPay2tr(signature)) } + /** + * The witness a guardian puts on [derivation]'s coin around [signature]: its + * leaf in that address, and the control block that proves the leaf is there. + * What a builder weighs a guardian spend by, before anybody signs. + */ + fun guardianWitness( + account: GroupWalletDerivation.Account, + derivation: GroupWalletDerivation.Derived, + position: Int, + signature: ByteVector64 = ByteVector64.Zeroes, + ): ScriptWitness { + val leaf = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)[position] + return Script.witnessScriptPathPay2tr(derivation.internalKey, leaf, ScriptWitness(listOf(signature)), derivation.tree!!) + } + fun encode(psbt: Psbt): String = Base64.Default.encode(Psbt.write(psbt).toByteArray()) fun decode(content: String): Psbt? = diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt index 8024178f..35627cec 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt @@ -22,11 +22,33 @@ import fr.acinq.lightning.utils.sum * proposal is already spending. Two proposals over one coin are not dangerous -- * only one can confirm, and each has its own nonces -- but the second is a quorum * asked for nothing. + * + * A guardian building a spend from a descendant's guarded wallet -- a + * [GroupSpend.Spender.Guardian] -- takes only coins its leaf's lock has already + * let go of, puts that lock on every input, and weighs each input by its leaf + * and control block. Its change, if any, goes back to the descendant. + * + * A spend can also *fund* a descendant's guarded wallet: a [Destination.Funding] + * pays the receive address `GroupWalletState.fundingAddress` chose, and the PSBT + * says so on that output, in the derivation field change already uses, so every + * signer can derive it again. See `docs/guarded-wallet-funding.md`. */ object GroupSpendBuilder { /** Phoenix's floor, kept: an output below it is one no node will relay. */ val DUST: Satoshi = Satoshi(546) + /** Where a spend's payment goes. */ + sealed interface Destination { + /** What the member typed: whatever it is, it is not the group's to vouch for. */ + data class Address(val address: String) : Destination + + /** + * A descendant's guarded wallet, at [derived] under its [account] -- the + * receive address `GroupWalletState.fundingAddress` chose. + */ + data class Funding(val account: GroupWalletDerivation.Account, val derived: GroupWalletDerivation.Derived) : Destination + } + sealed interface Result { data class Built( val psbt: Psbt, @@ -35,6 +57,8 @@ object GroupSpendBuilder { val change: Satoshi?, /** What [fee] holds beyond the feerate: change too small to send back, paid to the miner instead. */ val absorbed: Satoshi = Satoshi(0), + /** The guarded wallet the payment funds, or null for a payment to a typed address. */ + val funded: Destination.Funding? = null, ) : Result data object NotAnAddress : Result data object NothingToSpend : Result @@ -61,17 +85,33 @@ object GroupSpendBuilder { if (cap != null && result is Result.Built && result.amount > cap) Result.OverCap(cap) else result /** Every confirmed, unreserved coin, to [address], less the fee. */ - fun sendAll(state: GroupWalletState, address: String, feeratePerVbyte: Long, reserved: Set): Result { - val script = scriptOf(state, address) ?: return Result.NotAnAddress - val coins = spendable(state, reserved).ifEmpty { return Result.NothingToSpend } + fun sendAll( + state: GroupWalletState, + address: String, + feeratePerVbyte: Long, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): Result = sendAll(state, Destination.Address(address), feeratePerVbyte, reserved, spender) + + /** Every confirmed, unreserved coin, to [destination], less the fee. */ + fun sendAll( + state: GroupWalletState, + destination: Destination, + feeratePerVbyte: Long, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): Result { + val script = scriptOf(state, destination) ?: return Result.NotAnAddress + val funded = destination as? Destination.Funding + val coins = spendable(state, reserved, spender).ifEmpty { return Result.NothingToSpend } val total = coins.map { it.amount }.sum() - val fee = feeOf(coins, listOf(script), feeratePerVbyte) + val fee = feeOf(state, coins, listOf(script), feeratePerVbyte, spender) val amount = total - fee if (amount < DUST) return Result.BelowDust - val tx = transaction(coins, listOf(TxOut(amount, script))) - return Result.Built(psbtOf(state, tx, coins, change = emptyMap()), amount, fee, change = null) + val tx = transaction(state, coins, listOf(TxOut(amount, script)), spender) + return Result.Built(psbtOf(state, tx, coins, change = emptyMap(), funded), amount, fee, change = null, funded = funded) } /** @@ -86,10 +126,23 @@ object GroupSpendBuilder { feeratePerVbyte: Long, reserved: Set, reservedChange: Set = emptySet(), + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): Result = send(state, Destination.Address(address), amount, feeratePerVbyte, reserved, reservedChange, spender) + + /** [amount] to [destination], as [send] to an address does. */ + fun send( + state: GroupWalletState, + destination: Destination, + amount: Satoshi, + feeratePerVbyte: Long, + reserved: Set, + reservedChange: Set = emptySet(), + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, ): Result { - val script = scriptOf(state, address) ?: return Result.NotAnAddress + val script = scriptOf(state, destination) ?: return Result.NotAnAddress + val funded = destination as? Destination.Funding if (amount < DUST) return Result.BelowDust - val coins = spendable(state, reserved).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend } + val coins = spendable(state, reserved, spender).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend } if (!state.changeKnown) return Result.FindingChange val changeIndex = state.nextChangeIndex(reservedChange) ?: return Result.TooManyOpen @@ -99,21 +152,22 @@ object GroupSpendBuilder { for (coin in coins) { chosen += coin val total = chosen.map { it.amount }.sum() - val withChange = feeOf(chosen, listOf(script, change.pubkeyScript), feeratePerVbyte) + val withChange = feeOf(state, chosen, listOf(script, change.pubkeyScript), feeratePerVbyte, spender) val leftover = total - amount - withChange if (leftover >= DUST) { - val tx = transaction(chosen, listOf(TxOut(amount, script), TxOut(leftover, change.pubkeyScript))) - return Result.Built(psbtOf(state, tx, chosen, mapOf(1 to change)), amount, withChange, leftover) + val tx = transaction(state, chosen, listOf(TxOut(amount, script), TxOut(leftover, change.pubkeyScript)), spender) + return Result.Built(psbtOf(state, tx, chosen, mapOf(1 to change), funded), amount, withChange, leftover, funded = funded) } // Enough to pay without change: the remainder, under dust, goes to fees. - val withoutChange = feeOf(chosen, listOf(script), feeratePerVbyte) + val withoutChange = feeOf(state, chosen, listOf(script), feeratePerVbyte, spender) if (total - amount >= withoutChange) { - val tx = transaction(chosen, listOf(TxOut(amount, script))) + val tx = transaction(state, chosen, listOf(TxOut(amount, script)), spender) return Result.Built( - psbtOf(state, tx, chosen, emptyMap()), amount, total - amount, change = null, + psbtOf(state, tx, chosen, emptyMap(), funded), amount, total - amount, change = null, absorbed = total - amount - withoutChange, + funded = funded, ) } } @@ -136,50 +190,104 @@ object GroupSpendBuilder { if (reduced < DUST) return Result.NotEnough val tx = spend.tx.copy(txOut = spend.tx.txOut.mapIndexed { index, out -> if (index == target.index) out.copy(amount = reduced) else out }) + // A funding keeps its claim, or the bump would read as a payment to a bare address. val psbt = GroupSpend.psbtOf( tx, spend.inputs.map { it.txOut to it.derivation }, spend.outputs.mapNotNull { output -> output.change?.let { output.index to it } }.toMap(), spend.account, + funding = spend.fundings.associate { it.outputIndex to (it.wallet.account to it.derived) }, ) return Result.Built( psbt = psbt, amount = if (target.isChange) spend.amountSent else reduced, fee = fee, change = if (target.isChange) reduced else null, + funded = spend.fundings.singleOrNull()?.let { Destination.Funding(it.wallet.account, it.derived) }, ) } - /** The coins a new spend may use: confirmed, and held by no open spend. */ - fun spendable(state: GroupWalletState, reserved: Set): List = - state.utxos.filter { it.isConfirmed && it.utxo.outPoint !in reserved } + /** + * The coins a new spend may use: confirmed -- for a guardian, as deep as its + * leaf's lock -- and held by no open spend. + */ + fun spendable( + state: GroupWalletState, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): List { + val lock = lockOf(state, spender) + return state.utxos.filter { + it.isConfirmed && (lock == null || state.confirmations(it) >= lock) && it.utxo.outPoint !in reserved + } + } /** * What [spendable] adds up to: the most a form can offer, before the fee. * Less than the wallet's confirmed balance by whatever open spends hold. */ - fun spendableBalance(state: GroupWalletState, reserved: Set): Satoshi = - spendable(state, reserved).map { it.amount }.sum() + fun spendableBalance( + state: GroupWalletState, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): Satoshi = spendable(state, reserved, spender).map { it.amount }.sum() - private fun scriptOf(state: GroupWalletState, address: String): ByteVector? = - Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, address.trim()).right + /** The relative lock a guardian's inputs carry, or null for the wallet's own group. */ + private fun lockOf(state: GroupWalletState, spender: GroupSpend.Spender): Long? = + (spender as? GroupSpend.Spender.Guardian)?.let { state.account.guardians[it.position].delay } + + /** + * What [destination] pays: a typed address's script, or the funded wallet's + * own derivation -- never a string round trip, so a funding is always an + * address. Null for text that is not an address on this network, and for a + * funding on another network. + */ + private fun scriptOf(state: GroupWalletState, destination: Destination): ByteVector? = when (destination) { + is Destination.Address -> Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, destination.address.trim()).right ?.let { ByteVector(Script.write(it)) } + is Destination.Funding -> destination.derived.pubkeyScript.takeIf { destination.account.chain == state.account.chain } + } - private fun transaction(coins: List, outputs: List) = Transaction( + private fun transaction(state: GroupWalletState, coins: List, outputs: List, spender: GroupSpend.Spender) = Transaction( version = 2, - // Replaceable, so a stuck spend can be bumped by a new proposal. - txIn = coins.map { TxIn(it.utxo.outPoint, ByteVector.empty, GroupSpend.MAX_SEQUENCE) }, + // Replaceable, so a stuck spend can be bumped by a new proposal -- and a + // guardian's lock is far below the replaceable ceiling, so its is too. + txIn = coins.map { TxIn(it.utxo.outPoint, ByteVector.empty, lockOf(state, spender) ?: GroupSpend.MAX_SEQUENCE) }, txOut = outputs, lockTime = 0, ) - /** The fee at [feeratePerVbyte] for spending [coins] to [scripts]: exact, because every witness is 64 bytes. */ - private fun feeOf(coins: List, scripts: List, feeratePerVbyte: Long): Satoshi { - val tx = transaction(coins, scripts.map { TxOut(Satoshi(0), it) }) - val weight = GroupSpend.witnessed(tx, List(coins.size) { ByteVector64.Zeroes }).weight() + /** + * The fee at [feeratePerVbyte] for spending [coins] to [scripts]: exact, + * because every signature is 64 bytes and a guardian's leaf and control + * block are known before anybody signs. + */ + private fun feeOf( + state: GroupWalletState, + coins: List, + scripts: List, + feeratePerVbyte: Long, + spender: GroupSpend.Spender, + ): Satoshi { + val tx = transaction(state, coins, scripts.map { TxOut(Satoshi(0), it) }, spender) + val weight = when (spender) { + GroupSpend.Spender.Owner -> GroupSpend.witnessed(tx, List(coins.size) { ByteVector64.Zeroes }) + is GroupSpend.Spender.Guardian -> coins.foldIndexed(tx) { index, partial, coin -> + partial.updateWitness(index, GroupSpend.guardianWitness(state.account, coin.derivation, spender.position)) + } + }.weight() return Satoshi(feeratePerVbyte * ((weight + 3) / 4)) } - private fun psbtOf(state: GroupWalletState, tx: Transaction, coins: List, change: Map) = - GroupSpend.psbtOf(tx, coins.map { it.utxo.txOut to it.derivation }, change, state.account) + /** The payment is always output 0, so a funding's claim goes there. */ + private fun psbtOf( + state: GroupWalletState, + tx: Transaction, + coins: List, + change: Map, + funded: Destination.Funding?, + ) = GroupSpend.psbtOf( + tx, coins.map { it.utxo.txOut to it.derivation }, change, state.account, + funding = funded?.let { mapOf(0 to (it.account to it.derived)) }.orEmpty(), + ) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt index dc2bae31..d90d6f7e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt @@ -5,7 +5,10 @@ import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import fr.acinq.bitcoin.Crypto import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.byteVector32 import fr.acinq.lightning.blockchain.electrum.IElectrumClient import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -35,6 +38,15 @@ import kotlin.time.Instant * sent again every [REBROADCAST_AFTER], which is what `IElectrumClient` asks of * its callers. A confirmation goes through [FrostSigningManager.recordConfirmed], * which settles every other spend of the same coins. + * + * A spend Electrum has not heard of may have lost its coins. Only the group can + * spend a plain wallet's coins, so there the loser is always another of the + * room's own spends and the winner's confirmation settles it. A guarded wallet's + * coins have a second spender, in another room: so an unseen spend asks the + * chain whether its coins are still there, and one taken by a *confirmed* + * transaction it is not goes through [FrostSigningManager.recordReplaced]. A + * conflict still in the mempool settles nothing -- ours may yet be the one that + * confirms. */ class GroupTransactionWatcher( private val database: BennuDatabase, @@ -111,8 +123,12 @@ class GroupTransactionWatcher( database.groupTransactionDao().upsert(row) } - // Null while disconnected, or while Electrum has not heard of it. - val confirmations = electrum.getConfirmations(signed) ?: return + // Null while disconnected, or while Electrum has not heard of it -- which + // is also what a spend whose coins somebody else took looks like. + val confirmations = electrum.getConfirmations(signed) ?: run { + conflictOf(row, signed)?.let { FrostSigningManager.recordReplaced(database, row.frostSigningSessionId, it.toString()) } + return + } if (row.seenAt == null) { row = row.copy(seenAt = now()) database.groupTransactionDao().upsert(row) @@ -122,6 +138,35 @@ class GroupTransactionWatcher( } } + /** + * A confirmed transaction other than [signed] that spent one of its coins, or + * null when every coin is still unspent, or was only taken by something + * unconfirmed, or the chain cannot be asked right now. + * + * Read per coin off the address it is at: is it still unspent there, and if + * not, which transaction in that address's history spent it. The address is + * the spent output's script, which the proposed PSBT carries for every input. + */ + private suspend fun conflictOf(transaction: GroupTransaction, signed: Transaction): TxId? { + val psbt = GroupSpend.decode(transaction.psbt) ?: return null + val electrum = electrumFor(transaction) ?: return null + + signed.txIn.forEachIndexed { index, input -> + val txOut = (psbt.inputs.getOrNull(index) as? fr.acinq.bitcoin.psbt.Input.WitnessInput)?.txOut ?: return@forEachIndexed + val scriptHash = Crypto.sha256(txOut.publicKeyScript).byteVector32().reversed() + + val unspent = electrum.getScriptHashUnspents(scriptHash) + .any { it.txid == input.outPoint.txid && it.outputIndex.toLong() == input.outPoint.index } + if (unspent) return@forEachIndexed + + electrum.getScriptHashHistory(scriptHash) + .filter { it.blockHeight > 0 && it.txid != signed.txid } + .firstOrNull { item -> electrum.getTx(item.txid)?.txIn?.any { it.outPoint == input.outPoint } == true } + ?.let { return it.txid } + } + return null + } + companion object { val POLL: Duration = 30.seconds val REBROADCAST_AFTER: Duration = 10.minutes diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt index 94020bed..b125f0f7 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt @@ -29,4 +29,53 @@ object GroupWalletRollout { val MAINNET_CAP: Satoshi = Satoshi(100_000) fun capFor(chain: Chain): Satoshi? = MAINNET_CAP.takeIf { chain.isMainnet() } + + /** + * Whether a subgroup is offered a guarded wallet on mainnet -- + * `docs/group-wallet-guardians.md`. Test networks were offered one from the + * start. On: lifted by decision, ahead of the signet run its own condition + * named -- a guardian spend made by a real three-level hierarchy. What it + * still leaves open is the mixed-version risk: a member on a build that + * predates guarded statements sees no wallet, and can open a plain one whose + * addresses the rest do not watch. Every guardian spend on mainnet is held to + * [MAINNET_CAP] like any other. + */ + const val GUARDIANS_ON_MAINNET: Boolean = true + + fun offersGuardiansOn(chain: Chain): Boolean = GUARDIANS_ON_MAINNET || !chain.isMainnet() + + /** + * Whether a member is offered a guarded wallet of their own on mainnet -- + * `docs/member-guarded-wallets.md`, D8. Test networks were offered one from + * the start. On: lifted by decision, ahead of the signet run its own + * condition named -- a three-level hierarchy watching one member's wallet, + * and its root making a guardian spend from it -- as [GUARDIANS_ON_MAINNET] + * was. What it still leaves open is the mixed-version risk: a signer on a + * build that predates member wallets is shown a certificate it cannot check. + * + * The entrances only. A device with it shut still accepts, shows and signs + * a certificate somebody else asked for. + */ + const val MEMBER_WALLETS_ON_MAINNET: Boolean = true + + fun offersMemberWalletsOn(chain: Chain): Boolean = MEMBER_WALLETS_ON_MAINNET || !chain.isMainnet() + + /** + * Whether a device tells the groups above about a guarded wallet on its own + * -- as the wallet arrives, and as a group's chat or wallet screen opens -- + * rather than only when somebody taps *Share*. + * `docs/guarded-wallet-forwarding.md`, D8. A behaviour that sends messages + * without a person, so it has a switch for the release it first ships in. + * The button does not read it. + */ + const val FORWARDS_GUARDED_WALLETS: Boolean = true + + /** + * The most a member's own spend from their guarded wallet may send on + * [chain]: [MAINNET_CAP] on mainnet, as every other spend is. The gate + * lifted before the run that was to lift the cap with it, and the member's + * spend is signed by a path no group spend goes through, so the cap stays + * until that run has been made. + */ + fun memberCapFor(chain: Chain): Satoshi? = capFor(chain) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt index 64f19c13..f6752e9d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt @@ -92,7 +92,7 @@ object CoSigningWire { @Serializable data class Input(val txid: String, val index: Long, val amountSat: Long, val script: String) - /** Kind 30341, from the operator. [kind] is a [fr.acinq.lightning.crypto.IcebergRoundTwoRequest.Kind] name. */ + /** Kind 30358, from the operator. [kind] is a [fr.acinq.lightning.crypto.IcebergRoundTwoRequest.Kind] name. */ @Serializable data class SigningRequest( val wallet: String, @@ -111,15 +111,15 @@ object CoSigningWire { val context: Context? = null, ) - /** Kind 30342: a co-signer saw [messageHash] under [label], and will sign nothing else under it. */ + /** Kind 30359: a co-signer saw [messageHash] under [label], and will sign nothing else under it. */ @Serializable data class Echo(val wallet: String, val requestId: String, val label: String, val messageHash: String) - /** Kind 30343: round-one contributions for consecutive pool counters from [from]. */ + /** Kind 30360: round-one contributions for consecutive pool counters from [from]. */ @Serializable data class NonceBatch(val wallet: String, val from: Long, val contributions: List) - /** Kind 30344: one co-signer's round-two answer. */ + /** Kind 30361: one co-signer's round-two answer. */ @Serializable data class SignatureShareMessage(val wallet: String, val requestId: String, val label: String, val share: String) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt index bcc6388c..b7108502 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt @@ -34,7 +34,7 @@ object WalletWire { ) /** - * Kind 30345: the operator's claim about the wallet, sent when something changes and every few + * Kind 30362: the operator's claim about the wallet, sent when something changes and every few * minutes while the node runs. [assignments] is the round-one pool's assignments, so an operator * elected after this one can sign under the verification nonces this one published. */ @@ -55,11 +55,11 @@ object WalletWire { val inboundMsat: Long get() = channels.sumOf { it.theirsMsat } } - /** Kind 30347: a member asks the operator for an invoice. */ + /** Kind 30364: a member asks the operator for an invoice. */ @Serializable data class InvoiceRequest(val wallet: String, val requestId: String, val amountMsat: Long? = null, val description: String) - /** Kind 30348: the operator's answer, addressed to the whole room by [requestId]. */ + /** Kind 30365: the operator's answer, addressed to the whole room by [requestId]. */ @Serializable data class InvoiceReply(val wallet: String, val requestId: String, val bolt11: String) } diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/database/model/RumorIdAgreementTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/database/model/RumorIdAgreementTest.kt deleted file mode 100644 index d897746c..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/database/model/RumorIdAgreementTest.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.test.Test -import kotlin.test.assertEquals -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactIdTag - -/** - * The row on disk and the payload on the wire have to be the same event. - * - * `MantraDao` writes an entity whose id comes from `MantraX.fromXEventTemplate`, - * and separately builds the rumor it submits with `rumorOf`, which hashes the - * template itself. Both are supposed to produce one id. Nothing checks that they - * do, and nothing would notice if they stopped: - * - * - the submission would carry a `payloadId` naming an event nobody has, - * - `MarmotInnerEvent.payloadEventId` would stop matching the row it carries, - * so `deleteByPayloadEventId` would silently un-queue nothing and superseded - * translations would go out anyway, - * - and every receiver would create a *second* row rather than converging on - * the sender's, because entity ids are content hashes and the two sides would - * be hashing different things. - * - * All of that is silent. The ids are opaque hex either way. - */ -class RumorIdAgreementTest { - private val author = "a".repeat(64) - private val chatRoomId = "room" - private val other = "b".repeat(64) - - /** Exactly what `MantraDao.rumorOf` does, and it must stay exactly that. */ - private fun rumorIdOf(template: EventTemplate<*>): String = EventHasher.hashId( - pubKey = author, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ) - - @Test - fun `a dialect's row and its rumor agree`() { - val template = DialectEvent.build(name = "Sesotho", country = "Lesotho", language = "st") - - val entity = MantraDialect.fromDialectEventTemplate( - dialectEventTemplate = template, - chatRoomId = chatRoomId, - userPublicKey = author - ) - - assertEquals(rumorIdOf(template), entity?.id) - } - - @Test - fun `an artifact's row and its rumor agree`() { - val template = ArtifactEvent.build( - name = "In Detention", - url = "example.com", - visibility = "private", - license = "cc", - dialectId = other, - versionLabel = "1.0" - ) - - val entity = MantraArtifact.fromArtifactEventTemplate( - artifactEventTemplate = template, - chatRoomId = chatRoomId, - userPublicKey = author - ) - - assertEquals(rumorIdOf(template), entity?.id) - } - - @Test - fun `an artifact version's row and its rumor agree`() { - val template = ArtifactVersionEvent.build(content = "1.0") { - addUnique(ArtifactIdTag.assemble(other)) - } - - val entity = MantraArtifactVersion.fromArtifactVersionEventTemplate( - artifactVersionEventTemplate = template, - chatRoomId = chatRoomId, - userPublicKey = author - ) - - assertEquals(rumorIdOf(template), entity?.id) - } - - @Test - fun `a chapter's and a chunk's rows agree with their rumors`() { - val chapter = ChapterEvent.build( - artifactVersionId = other, - name = "Chapter 1", - originalText = "some text", - index = 0, - wordCount = 2, - characterCount = 9 - ) - val chunk = ChunkEvent.build( - chapterId = other, - text = "some text", - index = 0, - wordCount = 2, - characterCount = 9 - ) - - assertEquals( - rumorIdOf(chapter), - MantraChapter.fromChapterEventTemplate(chapter, chatRoomId, author)?.id - ) - assertEquals( - rumorIdOf(chunk), - MantraChunk.fromChunkEventTemplate(chunk, chatRoomId, author)?.id - ) - } - - @Test - fun `a translation version's row and its rumor agree`() { - val template = TranslationArtifactVersionEvent.build( - artifactVersionId = other, - dialectId = other, - name = "Sesotho", - visibility = "private", - license = "cc" - ) - - val entity = MantraTranslationArtifactVersion.fromTranslationArtifactVersionEventTemplate( - translationArtifactVersionEventTemplate = template, - chatRoomId = chatRoomId, - userPublicKey = author - ) - - assertEquals(rumorIdOf(template), entity?.id) - } - - @Test - fun `the submission names the id the row was written under`() { - // The end of the chain the rest of this file checks a link of: what a - // receiver reads out of the envelope has to be the id the sender stored. - val template = DialectEvent.build(name = "Sesotho", country = "Lesotho", language = "st") - val entity = MantraDialect.fromDialectEventTemplate(template, chatRoomId, author) - - val payload = Event( - id = rumorIdOf(template), - pubKey = author, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - val submission = SubmissionEvent.build(payload = payload) - - val readBack = SubmissionEvent( - id = "f".repeat(64), - pubKey = author, - createdAt = submission.createdAt, - tags = submission.tags, - content = submission.content, - sig = "" - ) - - assertEquals(entity?.id, readBack.payloadId()) - assertEquals(entity?.id, readBack.payload()?.id) - assertEquals(DialectEvent.KIND, readBack.payloadKind()) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateTest.kt index 4a922454..e7f82d15 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyStateTest.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher @@ -26,9 +31,6 @@ import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupParentage -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent /** * What a room's key state is allowed to convince a member of. @@ -555,7 +557,7 @@ class GroupKeyStateTest { /** An event of [kind] authored and signed by [author]'s room at [path]. */ private fun signedByRoom( - kind: Int = DialectEvent.KIND, + kind: Int = TextNoteEvent.KIND, content: String = "isiZulu", tags: Array> = arrayOf(arrayOf("name", "isiZulu")), createdAt: Long = 1_700_000_500, @@ -605,17 +607,18 @@ class GroupKeyStateTest { @Test fun `the verifier does not care what kind it is looking at`() { - // The point of splitting it out: a chronicle carries documents rather than - // key states, and none of the three checks knows the difference. + // The point of splitting it out: a chronicle carries the group's work + // rather than key states, and none of the three checks knows the + // difference. // // Note the last one. A GroupKeyStateEvent signed by the room passes here - // exactly as a dialect does, which is why the chronicle needs an allowlist + // exactly as a post does, which is why the chronicle needs an allowlist // of kinds on top of this and cannot treat "the group signed it" as // permission to apply it. listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ChapterEvent.KIND, + TextNoteEvent.KIND, + MetadataEvent.KIND, + AdvertisedRelayListEvent.KIND, GroupKeyStateEvent.KIND ).forEach { kind -> assertTrue( @@ -627,9 +630,9 @@ class GroupKeyStateTest { @Test fun `a rumor nobody signed is not a group signature`() { - // Every nip30303 event on the wire today is a rumor: the signature is - // empty and the author is the member who sent it, because what vouches - // for it is the MLS frame. Neither half survives this check, which is + // A member's message in a room is a rumor: the signature is empty and + // the author is the member who sent it, because what vouches for it is + // the MLS frame. Neither half survives this check, which is // what makes "the group signed it" mean something narrower than "it // arrived from the group". val member = PrivateKey( @@ -642,13 +645,13 @@ class GroupKeyStateTest { id = EventHasher.hashId( pubKey = memberPubKey, createdAt = 1_700_000_500, - kind = DialectEvent.KIND, + kind = TextNoteEvent.KIND, tags = tags, content = "isiZulu" ), pubKey = memberPubKey, createdAt = 1_700_000_500, - kind = DialectEvent.KIND, + kind = TextNoteEvent.KIND, tags = tags, content = "isiZulu", sig = "" @@ -668,13 +671,13 @@ class GroupKeyStateTest { id = EventHasher.hashId( pubKey = chatRoomId, createdAt = 1_700_000_500, - kind = DialectEvent.KIND, + kind = TextNoteEvent.KIND, tags = tags, content = "isiZulu" ), pubKey = chatRoomId, createdAt = 1_700_000_500, - kind = DialectEvent.KIND, + kind = TextNoteEvent.KIND, tags = tags, content = "isiZulu", sig = "9".repeat(128) @@ -763,7 +766,8 @@ class GroupKeyStateTest { parent: String = parentChatRoomId, subgroupKey: String = thresholdPublicKey, certificatePath: List = path, - author: KeyMaterial = otherKeyMaterial + author: KeyMaterial = otherKeyMaterial, + extraTags: Array> = emptyArray() ): Event = signedByRoom( kind = SubgroupBirthCertificateEvent.KIND, content = subgroupChatRoomId, @@ -774,7 +778,7 @@ class GroupKeyStateTest { adminPublicKeys = listOf("a".repeat(64), "b".repeat(64), "c".repeat(64)), name = "Translation team", path = certificatePath - ), + ) + extraTags, author = author ) @@ -885,6 +889,31 @@ class GroupKeyStateTest { assertNull(GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = wrongKey))) } + @Test + fun `a state whose certificate's wallet policy does not read is dropped`() { + // Present and unreadable must not read as absent: an undecided child is + // offered both wallets, so a corrupt policy would hand it the one its + // parent took away. docs/subgroup-wallet-policy.md, Phase 5. + listOf( + arrayOf(arrayOf("wallet", "maybe")), + arrayOf(WalletPolicyTag.assemble(SubgroupWalletPolicy.GUARDED)), + arrayOf(WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED), WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED)), + ).forEach { extraTags -> + assertNull( + GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = birthCertificate(extraTags = extraTags))), + "a certificate with ${extraTags.joinToString { it.joinToString() }} was believed", + ) + } + } + + @Test + fun `a state whose certificate decides a wallet policy keeps it`() { + val unguarded = birthCertificate(extraTags = arrayOf(WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED))) + val state = GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = unguarded)) + + assertEquals(unguarded.toJson(), state?.birthCertificateJson) + } + @Test fun `a parentage survives the trip through the tags`() { val certificate = birthCertificate() diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletLineageTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletLineageTest.kt new file mode 100644 index 00000000..e53ac882 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletLineageTest.kt @@ -0,0 +1,59 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.managers.LineageExample.heldBy +import com.machankura.bennu.compose.managers.LineageExample.m +import com.machankura.bennu.compose.managers.LineageExample.n +import com.machankura.bennu.compose.managers.LineageExample.p +import com.machankura.bennu.compose.managers.LineageExample.r +import com.machankura.bennu.compose.managers.LineageExample.rent +import com.machankura.bennu.compose.managers.LineageExample.rentGuardians +import com.machankura.bennu.compose.managers.LineageExample.savings +import com.machankura.bennu.compose.managers.LineageExample.savingsGuardians +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Which group directly guards a member's wallet, and which branch of an + * ancestor's tree it sits under -- read off the guardians and the line of + * descent a verified certificate already gives. `docs/member-wallet-guarding-group.md`, Phase 1. + */ +class GuardedWalletLineageTest { + @Test + fun `the root sees Savings guarded by M, two generations down through P`() { + val wallet = heldBy(r, savings, savingsGuardians) + + assertEquals(m, wallet.directGuardianChatRoomId) + assertEquals(p, wallet.branchChatRoomId) + assertEquals(2, wallet.position) + assertFalse(wallet.isGuardedHere) + } + + @Test + fun `the root sees Rent guarded by its own child N, which is also the branch`() { + val wallet = heldBy(r, rent, rentGuardians) + + assertEquals(n, wallet.directGuardianChatRoomId) + assertEquals(n, wallet.branchChatRoomId) + assertEquals(1, wallet.position) + } + + @Test + fun `the middle group sees the same guardian, with M as its branch`() { + val wallet = heldBy(p, savings, savingsGuardians) + + assertEquals(m, wallet.directGuardianChatRoomId) + assertEquals(m, wallet.branchChatRoomId) + } + + @Test + fun `the group that signed the certificate guards it here, and has no branch`() { + val wallet = heldBy(m, savings, savingsGuardians) + + assertEquals(m, wallet.directGuardianChatRoomId) + assertTrue(wallet.isGuardedHere) + assertNull(wallet.branchChatRoomId) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt new file mode 100644 index 00000000..21a10d60 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt @@ -0,0 +1,267 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Descriptor +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The guardian keys, pinned and walked. + * + * The pinned vector freezes the two tags and the order of every input, so a + * change to either fails here rather than moving every leaf a certificate has + * already granted. The rest is the one property everything else rests on: the + * key a descendant derives from its grant and the key an ancestor's cache signs + * as are the same point, at every depth and both parities. + */ +class GuardianDerivationTest { + /** A threshold key nobody needs the secret of: the test is about public derivation. */ + private fun thresholdKey(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val rootKey = thresholdKey(0x600d) + private val middleKey = thresholdKey(0xbeef) + private val childKey = thresholdKey(0xcafe) + + private val rootRoom = SharedKeyDerivation.marmotGroupId(rootKey) + private val middleRoom = SharedKeyDerivation.marmotGroupId(middleKey) + private val childRoom = SharedKeyDerivation.marmotGroupId(childKey) + + /** root → middle → child, as the certificates would carry them. */ + private val middleGrant = GuardianDerivation.grant(rootKey, rootRoom, inherited = emptyList(), childChatRoomId = middleRoom) + private val childGrant = GuardianDerivation.grant(middleKey, middleRoom, inherited = middleGrant, childChatRoomId = childRoom) + + @Test + fun `the guardian root and the child index are pinned`() { + // Frozen. A failure here is not a test to update: every certificate + // already signed grants keys under these, and changing them moves every + // leaf in every guarded address. + val root = GuardianDerivation.root(rootKey) + assertEquals(PINNED_ROOT_KEY, root.publicKey.toString()) + assertEquals(PINNED_ROOT_CHAIN_CODE, root.chainCode.toHex()) + assertEquals(PINNED_CHILD_INDEX, GuardianDerivation.childIndex(middleRoom)) + assertEquals( + PINNED_LEAF, + GuardianDerivation.leafKey(childGrant[1], Chain.Mainnet, account = 0, change = 0, index = 7).value.toHex() + ) + } + + @Test + fun `a child index is unhardened and case-blind`() { + val index = GuardianDerivation.childIndex(childRoom) + assertTrue(index in 0L..0x7FFFFFFFL) + assertEquals(index, GuardianDerivation.childIndex(childRoom.uppercase())) + assertFailsWith { GuardianDerivation.childIndex("abcd") } + } + + @Test + fun `a grant is the parent's root and its own grant, each one step further`() { + assertEquals(listOf(rootRoom), middleGrant.map { it.chatRoomId }) + assertEquals(listOf(middleRoom, rootRoom), childGrant.map { it.chatRoomId }) + + val rootOfRoot = GuardianDerivation.root(rootKey).extendedPublicKey + val rootOfMiddle = GuardianDerivation.root(middleKey).extendedPublicKey + val middleIndex = GuardianDerivation.childIndex(middleRoom) + val childIndex = GuardianDerivation.childIndex(childRoom) + + assertEquals(rootOfMiddle.derivePublicKey(childIndex).publicKey, childGrant[0].publicKey) + assertEquals( + rootOfRoot.derivePublicKey(middleIndex).derivePublicKey(childIndex).publicKey, + childGrant[1].publicKey, + "the root's key in the grandchild is R_root / i(M) / i(C)" + ) + assertEquals(GuardianDerivation.DEFAULT_DELAY, childGrant[1].delay) + } + + @Test + fun `an ancestor's cache signs as the leaf its descendant derives, at every depth`() { + val parities = mutableSetOf() + + (1..8).forEach { seed -> + val parent = thresholdKey(seed) + val parentRoom = SharedKeyDerivation.marmotGroupId(parent) + val grandparent = thresholdKey(seed + 100) + val grandparentRoom = SharedKeyDerivation.marmotGroupId(grandparent) + + val parentGrant = GuardianDerivation.grant(grandparent, grandparentRoom, emptyList(), parentRoom) + val grant = GuardianDerivation.grant(parent, parentRoom, parentGrant, childRoom) + + listOf(Chain.Mainnet, Chain.Regtest).forEach { chain -> + (0L..2L).forEach { index -> + listOf(parent to parentRoom, grandparent to grandparentRoom).forEachIndexed { position, (key, room) -> + val lineage = GuardianDerivation.lineage(grant, childRoom, room)!! + val signing = GuardianDerivation.signingCache(key, lineage, chain, account = 0, change = 1, index = index) + val derived = GuardianDerivation.leafKey(grant[position], chain, account = 0, change = 1, index = index) + assertEquals(derived, signing.leafKey) + assertEquals(derived, signing.cache.tweakedPublicKey) + parities += grant[position].extendedPublicKey + .derivePublicKey(listOf(GuardianDerivation.networkIndex(chain), 0L, 1L, index)) + .publicKey.isEven() + } + } + } + } + + assertEquals(setOf(true, false), parities, "the sweep has to cover both parities of a leaf key") + } + + @Test + fun `the lineage runs from the ancestor's child down to the descendant`() { + val a1 = "11".repeat(32) + val a2 = "22".repeat(32) + val a3 = "33".repeat(32) + val c = "cc".repeat(32) + val grant = listOf(a1, a2, a3).map { GuardianDerivation.Guardian(it, middleGrant[0].publicKey, middleGrant[0].chainCode) } + + assertEquals(listOf(c), GuardianDerivation.lineage(grant, c, a1)) + assertEquals(listOf(a2, a1, c), GuardianDerivation.lineage(grant, c, a3)) + assertNull(GuardianDerivation.lineage(grant, c, "44".repeat(32))) + } + + @Test + fun `no two places share a leaf`() { + val siblingRoom = SharedKeyDerivation.marmotGroupId(thresholdKey(0xd00d)) + val sibling = GuardianDerivation.grant(middleKey, middleRoom, middleGrant, siblingRoom) + + fun leaf(guardian: GuardianDerivation.Guardian, chain: Chain = Chain.Mainnet, account: Long = 0) = + GuardianDerivation.leafKey(guardian, chain, account, change = 0, index = 0) + + val leaves = listOf( + leaf(childGrant[0]), + leaf(childGrant[1]), + leaf(sibling[0]), + leaf(sibling[1]), + leaf(middleGrant[0]), + leaf(childGrant[1], Chain.Regtest), + leaf(childGrant[1], account = 1), + ) + assertEquals(leaves.size, leaves.toSet().size, "siblings, a parent and its child, networks and accounts all differ") + + val room = SharedKeyDerivation.derive(rootKey).publicKey + assertTrue(leaves.none { it == room }, "no leaf is a room key") + } + + @Test + fun `a leaf is and_v(v_pk, older 12) and 36 bytes`() { + val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) + val script = Script.write(GuardianDerivation.leafScript(key, GuardianDerivation.DEFAULT_DELAY)) + + assertEquals(36, script.size) + assertEquals("20" + key.value.toHex() + "ad5cb2", Hex.encode(script)) + // Past sixteen the lock is a number push rather than an opcode. + assertEquals("02e803", Hex.encode(Script.write(GuardianDerivation.leafScript(key, 1000).subList(2, 3)))) + assertFailsWith { GuardianDerivation.leafScript(key, 0) } + } + + /** + * Where a script number changes length, byte for byte. A lock pushed any + * other way is not minimal, and a leaf with a non-minimal push is a coin + * nobody can spend through it. docs/guardian-delay.md. + */ + @Test + fun `a delay is pushed minimally at every edge of its encoding`() { + val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) + val encodings = mapOf( + 6L to ("56" to 36), + 16L to ("60" to 36), + 17L to ("0111" to 37), + 127L to ("017f" to 37), + 128L to ("028000" to 38), + 32_767L to ("02ff7f" to 38), + 32_768L to ("03008000" to 39), + 65_535L to ("03ffff00" to 39), + ) + encodings.forEach { (delay, expected) -> + val (lock, size) = expected + val script = Script.write(GuardianDerivation.leafScript(key, delay)) + assertEquals("20" + key.value.toHex() + "ad" + lock + "b2", Hex.encode(script), "a delay of $delay") + assertEquals(size, script.size, "a delay of $delay") + } + } + + @Test + fun `a delay outside 6 to 65535 is refused everywhere it could enter`() { + val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) + listOf(5L, 65_536L).forEach { delay -> + assertFailsWith("leafScript at $delay") { GuardianDerivation.leafScript(key, delay) } + assertFailsWith("grant at $delay") { + GuardianDerivation.grant(middleKey, middleRoom, middleGrant, childRoom, delay = delay) + } + val tag = GuardianTag.assemble(childGrant[0].copy(delay = delay)) + assertNull(GuardianTag.parse(tag), "a tag at $delay reads") + } + assertEquals(childGrant[0].copy(delay = 6), GuardianTag.parse(GuardianTag.assemble(childGrant[0].copy(delay = 6)))) + assertEquals(childGrant[0].copy(delay = 65_535), GuardianTag.parse(GuardianTag.assemble(childGrant[0].copy(delay = 65_535)))) + } + + @Test + fun `a parent chooses its own leaf's delay, and an inherited key keeps the one its ancestor chose`() { + val rootChose = GuardianDerivation.grant(rootKey, rootRoom, emptyList(), middleRoom, delay = 26_280) + val middleChose = GuardianDerivation.grant(middleKey, middleRoom, rootChose, childRoom, delay = 144) + + assertEquals(listOf(144L, 26_280L), middleChose.map { it.delay }) + // Only the delay moved: the keys are the default grant's. + assertEquals(childGrant.map { it.publicKey }, middleChose.map { it.publicKey }) + assertEquals(GuardianDerivation.DEFAULT_DELAY, GuardianDerivation.grant(rootKey, rootRoom, emptyList(), middleRoom).single().delay) + } + + @Test + fun `the longest delay is a descriptor bitcoin-kmp can checksum`() { + val longest = GuardianDerivation.grant(middleKey, middleRoom, middleGrant, childRoom, delay = GuardianDerivation.MAX_DELAY) + val tree = GuardianDerivation.descriptorTree(longest, Chain.Mainnet, account = 0, change = 0) + + assertTrue("older(65535)" in tree, tree) + assertTrue("older(12)" in tree, "the root's inherited leaf keeps its own") + assertEquals(8, Descriptor.checksum("tr(${longest[0].encoded(Chain.Mainnet)}/0/*,$tree)").length) + } + + @Test + fun `the tree is a caterpillar, nearest first`() { + val leaves = (0..2).map { ScriptTree.Leaf(ByteVector(byteArrayOf(it.toByte())), Script.TAPROOT_LEAF_TAPSCRIPT) } + + assertEquals(leaves[0], GuardianDerivation.tree(leaves.take(1))) + assertEquals(ScriptTree.Branch(leaves[0], ScriptTree.Branch(leaves[1], leaves[2])), GuardianDerivation.tree(leaves)) + + // The control block grows by one hash per level: the parent's is the shortest. + val internalKey = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) + val tree = GuardianDerivation.tree(leaves) + assertEquals(65, Script.ControlBlock.build(internalKey, tree, leaves[0]).size()) + assertEquals(97, Script.ControlBlock.build(internalKey, tree, leaves[2]).size()) + } + + @Test + fun `the descriptor tree is the same caterpillar, ranged`() { + val tree = GuardianDerivation.descriptorTree(childGrant, Chain.Mainnet, account = 0, change = 0) + val parent = childGrant[0].encoded(Chain.Mainnet) + val root = childGrant[1].encoded(Chain.Mainnet) + + assertEquals("{and_v(v:pk($parent/0/0/0/*),older(12)),and_v(v:pk($root/0/0/0/*),older(12))}", tree) + assertTrue(childGrant[0].encoded(Chain.Signet).startsWith("tpub")) + // A descriptor with this tree in it is one bitcoin-kmp can checksum. + assertEquals(8, Descriptor.checksum("tr(${parent}/0/*,$tree)").length) + assertNotEquals(tree, GuardianDerivation.descriptorTree(childGrant, Chain.Mainnet, account = 0, change = 1)) + } + + /** + * Checked against an independent implementation -- HMAC-SHA512, SHA-256 and + * point arithmetic written out in plain Python -- before they were pinned, so + * they are BIP32 and the doc's formulas rather than this code's own output. + */ + private companion object { + const val PINNED_ROOT_KEY = "02437ef22d50eb95d81d3344b49d4872b23881fbd46f4c658fabfe5f7753db84e9" + const val PINNED_ROOT_CHAIN_CODE = "089593979b6055ff3b34dd2bc378160405108766f34c4804a37cf909a1246530" + const val PINNED_CHILD_INDEX = 977297025L + const val PINNED_LEAF = "ae5078c25c84b630c7ac199cdf86fb3f32b36c677f63415d3405222623359927" + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt new file mode 100644 index 00000000..0cd2fac7 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt @@ -0,0 +1,264 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.ScriptWitness +import fr.acinq.bitcoin.SigHash +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import fr.acinq.bitcoin.crypto.dkg.chill.ParticipantFinalizeResult +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.test.assertTrue + +/** + * An ancestor group spending a descendant's coin through its guardian leaf, + * against real ChillDKG and real FROST, with no database and no manager. + * + * The counterpart of `GroupWalletSpendRoundTest` for the script path, and judged + * the same way: by `correctlySpends`, the script interpreter, which is the only + * check that asks what the network will -- including whether the coin has sat + * long enough for the leaf's relative lock. + * + * The ceremony is the ancestor's. The descendants' keys are anybody's, since + * nothing here signs as them: what is under test is that the key a descendant + * derives from its certificate's grant is the key the ancestor's shares sign as. + */ +class GuardianSpendRoundTest { + private val participants = 3 + private val threshold = 2 + + /** The ancestor's ceremony, as in `GroupWalletSpendRoundTest`. */ + private val dkg: List = run { + val hostSecretKeys = (1..participants).map { PrivateKey(ByteVector32(ByteArray(32) { i -> (it * 5 + i).toByte() })) } + val hostPublicKeys = hostSecretKeys.map { ChillDKG.hostPublicKey(it) } + val step1 = hostSecretKeys.mapIndexed { i, key -> + ChillDKG.participantStep1(key, hostPublicKeys, threshold, ByteVector32(ByteArray(32) { (i + 3).toByte() })) + } + val coordinator1 = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) + val step2 = hostSecretKeys.mapIndexed { i, key -> + ChillDKG.participantStep2(key, step1[i].state, coordinator1.message, ByteVector32(ByteArray(32) { (i + 17).toByte() })) + } + val certificate = ChillDKG.coordinatorFinalize(coordinator1.state, step2.map { it.certEqSignature }, threshold).certificate + (0 until participants).map { i -> ChillDKG.participantFinalize(step2[i].state, certificate, participants, threshold) } + .onEach { assertTrue(it.fault.isOk, "the ceremony has to succeed for the rest to mean anything") } + } + + private val ancestorKey: PublicKey = dkg[0].thresholdPublicKey!! + private val publicShares: List = dkg[0].publicShares + private val ancestorRoom = SharedKeyDerivation.marmotGroupId(ancestorKey.toString()) + + private fun someKey(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val chain = Chain.Regtest + + /** A guarded address of [childKey]'s wallet, under [grant]: its internal key, its tree, and its script. */ + private class Address(val internalKey: fr.acinq.bitcoin.XonlyPublicKey, val leaves: List, val tree: ScriptTree) { + val pubkeyScript: ByteVector get() = ByteVector(Script.write(Script.pay2tr(internalKey, tree))) + } + + private fun address(childKey: String, grant: List, change: Long = 0, index: Long = 0): Address { + val account = GroupWalletDerivation.account(childKey, chain) + val internalKey = account.extendedPublicKey.derivePublicKey(change).derivePublicKey(index).publicKey.xOnly() + val leaves = GuardianDerivation.leaves(grant, chain, 0, change, index) + return Address(internalKey, leaves, GuardianDerivation.tree(leaves)) + } + + private fun funding(address: Address) = Transaction( + version = 2, + txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x24 })), 0), ByteVector.empty, 0xffffffffL)), + txOut = listOf(TxOut(Satoshi(50_000), address.pubkeyScript)), + lockTime = 0, + ) + + private fun spend(funding: Transaction, sequence: Long = GuardianDerivation.DEFAULT_DELAY) = Transaction( + version = 2, + txIn = listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, sequence)), + txOut = listOf(TxOut(Satoshi(49_000), Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))), + lockTime = 0, + ) + + /** One FROST instance over [message] with [cache], by signers 0 and 2. */ + private fun sign(message: ByteVector32, cache: TweakCache): ByteVector64 { + val signerIds = listOf(0, 2) + val nonces = signerIds.map { id -> + SecretNonce.generate( + sessionRandom = ByteVector32(ByteArray(32) { (id + 40).toByte() }), + secretShare = dkg[id].secretShare!!, + publicShare = publicShares[id], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null, + ) + } + val session = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { publicShares[it] }, + nParticipants = participants, + threshold = threshold, + tweakCache = cache, + message = message, + ) + val partials = signerIds.mapIndexed { position, id -> + session.sign(nonces[position].first, dkg[id].secretShare!!, id.toUInt()).right!!.also { + assertTrue(session.verify(it, nonces[position].second, publicShares[id], position), "signer $id's partial signature") + } + } + return session.aggregateSigs(partials).right!! + } + + /** The ancestor signs [leaf] of [address] in [tx] with [cache], and the witness goes on. */ + private fun guardianSpend(tx: Transaction, funding: Transaction, address: Address, leaf: ScriptTree.Leaf, cache: TweakCache): Transaction { + val sighash = tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, leaf.hash()) + val signature = sign(sighash, cache) + return tx.updateWitness(0, Script.witnessScriptPathPay2tr(address.internalKey, leaf, ScriptWitness(listOf(signature)), address.tree)) + } + + private fun assertSpends(tx: Transaction, funding: Transaction) = + tx.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + + @Test + fun `a parent's quorum spends its child's coin through its leaf`() { + val child = someKey(0xc1) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) + val address = address(child, grant) + val funding = funding(address) + + val signing = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0) + val signed = guardianSpend(spend(funding), funding, address, address.leaves[0], signing.cache) + + assertEquals(1, address.leaves.size) + assertEquals(33, signed.txIn[0].witness.stack.last().size(), "a tree of one leaf has a bare control block") + assertSpends(signed, funding) + } + + @Test + fun `a grandparent's quorum spends its grandchild's coin from the bottom of the tree`() { + val middle = someKey(0xb1) + val middleRoom = SharedKeyDerivation.marmotGroupId(middle) + val child = someKey(0xc2) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + + val middleGrant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), middleRoom) + val grant = GuardianDerivation.grant(middle, middleRoom, middleGrant, childRoom) + val address = address(child, grant, change = 1, index = 3) + val funding = funding(address) + + val lineage = GuardianDerivation.lineage(grant, childRoom, ancestorRoom)!! + assertEquals(listOf(middleRoom, childRoom), lineage) + val signing = GuardianDerivation.signingCache(ancestorKey.toString(), lineage, chain, 0, 1, 3) + val signed = guardianSpend(spend(funding), funding, address, address.leaves[1], signing.cache) + + assertEquals(65, signed.txIn[0].witness.stack.last().size(), "the root's leaf is one level down") + assertSpends(signed, funding) + } + + @Test + fun `the coin has to have sat for 12 blocks`() { + val child = someKey(0xc3) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) + val address = address(child, grant) + val funding = funding(address) + val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0).cache + + assertSpends(guardianSpend(spend(funding, sequence = 12), funding, address, address.leaves[0], cache), funding) + assertFails("eleven blocks") { + assertSpends(guardianSpend(spend(funding, sequence = 11), funding, address, address.leaves[0], cache), funding) + } + assertFails("no relative lock at all") { + assertSpends(guardianSpend(spend(funding, sequence = 0xfffffffdL), funding, address, address.leaves[0], cache), funding) + } + } + + /** + * A chosen delay, at every edge of its encoding: the script interpreter takes + * the spend at exactly that many blocks and not one fewer. Where an encoding + * mistake would be caught before a coin could be lost to it. + * docs/guardian-delay.md, Phase 2. + */ + @Test + fun `a chosen delay holds at exactly its own number of blocks`() { + val child = someKey(0xc6) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0).cache + + listOf(6L, 16L, 17L, 127L, 128L, 32_767L, 32_768L, 65_535L).forEach { delay -> + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom, delay = delay) + val address = address(child, grant) + val funding = funding(address) + + assertSpends(guardianSpend(spend(funding, sequence = delay), funding, address, address.leaves[0], cache), funding) + assertFails("one block short of $delay") { + assertSpends(guardianSpend(spend(funding, sequence = delay - 1), funding, address, address.leaves[0], cache), funding) + } + } + } + + @Test + fun `the wrong cache signs for a key the leaf does not name`() { + val child = someKey(0xc4) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val sibling = SharedKeyDerivation.marmotGroupId(someKey(0xc5)) + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) + val address = address(child, grant) + val funding = funding(address) + + val wrongCaches = mapOf( + "the room key's" to SharedKeyDerivation.derive(ancestorKey.toString()).cache, + "the guardian root's" to GuardianDerivation.root(ancestorKey.toString()).cache, + "a sibling's leaf" to GuardianDerivation.signingCache(ancestorKey.toString(), listOf(sibling), chain, 0, 0, 0).cache, + "the next address's leaf" to GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 1).cache, + "the wallet's own key" to GroupWalletDerivation.account(ancestorKey.toString(), chain).cache, + ) + + wrongCaches.forEach { (name, cache) -> + assertFails("$name cache") { + assertSpends(guardianSpend(spend(funding), funding, address, address.leaves[0], cache), funding) + } + } + } + + @Test + fun `a guardian signature is over the leaf it names`() { + // Sign the parent's leaf and present it as the grandparent's: the leaf hash + // is in the sighash, so a signature cannot be moved between leaves. + val middle = someKey(0xb2) + val middleRoom = SharedKeyDerivation.marmotGroupId(middle) + val child = someKey(0xc6) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val grant = GuardianDerivation.grant(middle, middleRoom, GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), middleRoom), childRoom) + val address = address(child, grant) + val funding = funding(address) + val tx = spend(funding) + val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(middleRoom, childRoom), chain, 0, 0, 0).cache + + val overParentLeaf = sign(tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, address.leaves[0].hash()), cache) + val moved = tx.updateWitness(0, Script.witnessScriptPathPay2tr(address.internalKey, address.leaves[1], ScriptWitness(listOf(overParentLeaf)), address.tree)) + + assertTrue(!Crypto.verifySignatureSchnorr(tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, address.leaves[1].hash()), overParentLeaf, GuardianDerivation.leafKey(grant[1], chain, 0, 0, 0))) + assertFails { assertSpends(moved, funding) } + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt new file mode 100644 index 00000000..c8853eeb --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt @@ -0,0 +1,87 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex + +/** + * The tree `docs/member-wallet-guarding-group.md` uses throughout, with Alice's + * two wallets in it: + * + * ``` + * R root + * ├── P R's guarded subgroup + * │ └── M P's guarded subgroup — guards Alice's "Savings" + * └── N R's guarded subgroup — guards Alice's "Rent" + * ``` + * + * The guardians are real grants, so `position` and `lineage` are what a + * verified certificate would give; the events are stand-ins, since nothing here + * checks a signature. + */ +object LineageExample { + private fun key(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + val rKey = key(0x600d) + val pKey = key(0xbeef) + val mKey = key(0xcafe) + val nKey = key(0xf00d) + + val r = SharedKeyDerivation.marmotGroupId(rKey) + val p = SharedKeyDerivation.marmotGroupId(pKey) + val m = SharedKeyDerivation.marmotGroupId(mKey) + val n = SharedKeyDerivation.marmotGroupId(nKey) + + val alice = key(0xa11ce) + val savings = "5".repeat(64) + val rent = "7".repeat(64) + + private val pGrant = GuardianDerivation.grant(rKey, r, emptyList(), p) + private val mGrant = GuardianDerivation.grant(pKey, p, pGrant, m) + private val nGrant = GuardianDerivation.grant(rKey, r, emptyList(), n) + + /** Savings' guardians, `[M, P, R]`. */ + val savingsGuardians = GuardianDerivation.grant(mKey, m, mGrant, savings) + + /** Rent's guardians, `[N, R]`. */ + val rentGuardians = GuardianDerivation.grant(nKey, n, nGrant, rent) + + /** + * Alice's wallet [walletId] under [guardians], as [ancestor] holds it. + * [label] and the names are what `GuardianManager.named` would fill. + */ + fun heldBy( + ancestor: String, + walletId: String, + guardians: List, + label: String? = null, + ownerPublicKey: String = alice, + ownerName: String? = "alice", + guardianName: String? = null, + branchName: String? = null, + walletKey: Int = 0xdecaf, + ): GuardianManager.GuardedWallet { + val account = GroupWalletDerivation.account(key(walletKey), Chain.Regtest, guardians = guardians) + val certificate = Event(walletId.take(63) + "c", guardians.first().chatRoomId, 1_700_000_000, MemberWalletCertificateEvent.KIND, emptyArray(), walletId, "") + return GuardianManager.GuardedWallet( + ancestorChatRoomId = ancestor, + descendantChatRoomId = walletId, + statement = certificate, + account = account, + certificate = certificate, + lineage = requireNotNull(GuardianDerivation.lineage(guardians, walletId, ancestor)) { "$ancestor does not guard $walletId" }, + subject = GuardianManager.GuardedSubject.Member( + id = walletId, + ownerPublicKey = ownerPublicKey, + label = label, + ownerName = ownerName, + guardianName = guardianName, + branchName = branchName, + ), + ) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt new file mode 100644 index 00000000..cef93ce4 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt @@ -0,0 +1,168 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Descriptor +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** + * A member's guarded wallet, from the member's side: the private key reaches + * every address the public derivation does, and a spend signed with it is one + * the script interpreter accepts. The guardians' side -- that an ancestor signs + * every leaf of a member's wallet -- is the last test. + */ +class MemberWalletDerivationTest { + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val walletPrivateKey = privateKey(0xa11ce) + private val walletKey = walletPrivateKey.publicKey() + private val walletId = MemberWalletDerivation.walletId(walletKey) + + private val groupKey = privateKey(0x6a0b).publicKey().toString() + private val groupRoom = SharedKeyDerivation.marmotGroupId(groupKey) + private val parentKey = privateKey(0x9a9e).publicKey().toString() + private val parentRoom = SharedKeyDerivation.marmotGroupId(parentKey) + + /** The group's own grant from its parent, then the group's grant to the member's wallet: two guardians. */ + private val grant: List = run { + val groupsOwn = GuardianDerivation.grant(parentKey, parentRoom, emptyList(), groupRoom) + GuardianDerivation.grant(groupKey, groupRoom, groupsOwn, walletId) + } + + private val account = MemberWalletDerivation.account(walletKey, chain, grant) + + @Test + fun `the wallet id is a hash of the key and not the key`() { + assertEquals(64, walletId.length) + assertNotEquals(walletKey.xOnly().value.toHex(), walletId) + assertEquals(walletId, MemberWalletDerivation.walletId(walletKey.toString())) + assertNotEquals(walletId, MemberWalletDerivation.walletId(privateKey(0xb0b).publicKey())) + // A wallet id is a valid child index, as a room id is. + GuardianDerivation.childIndex(walletId) + } + + @Test + fun `the private key reaches every address the public derivation does`() { + for (change in listOf(GroupWalletDerivation.RECEIVE, GroupWalletDerivation.CHANGE)) { + for (index in listOf(0L, 1L, 2L, 7L, 1_000L)) { + val derived = GroupWalletDerivation.derive(account, change, index) + val privateKey = MemberWalletDerivation.privateKeyAt(walletPrivateKey, chain, change, index) + assertEquals(derived.internalKey, privateKey.xOnlyPublicKey(), "at $change/$index") + } + } + } + + @Test + fun `the account private key extends to the account xpub`() { + val extended = MemberWalletDerivation.accountPrivateKey(walletPrivateKey, chain) + assertEquals(account.extendedPublicKey, extended.extendedPublicKey) + assertNotEquals(walletKey, extended.publicKey, "the wallet key itself is never the account key") + } + + @Test + fun `the descriptors carry the tree and check out`() { + assertTrue(account.isGuarded) + val descriptor = account.receiveDescriptor + val (body, checksum) = descriptor.split('#') + assertEquals(Descriptor.checksum(body), checksum) + assertTrue(body.contains("and_v(v:pk("), "a leaf per guardian") + assertEquals(2, Regex("older\\(12\\)").findAll(body).count()) + } + + private fun coin(index: Int, sats: Long): Pair { + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) + val tx = Transaction( + 2, + listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { (index + 1).toByte() })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), + 0, + ) + val meta = WalletState.AddressMeta.Derived(index) + return derived.address(chain) to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta))) + } + + private fun state(vararg coins: Pair): GroupWalletState { + val change = WalletState( + mapOf( + GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0).address(chain) to + WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()) + ) + ) + return GroupWalletState(account, WalletState(coins.toMap()), change, tipHeight = 110) + } + + private fun checked(result: GroupSpendBuilder.Result): GroupSpend.Checked { + val built = assertIs(result) + return assertIs(GroupSpend.check(built.psbt, account)).checked + } + + @Test + fun `a spend the member signs alone is one the network accepts`() { + val spend = checked( + GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(3, 40_000)), "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 5L, emptySet()) + ) + val signatures = spend.inputs.map { MemberWalletDerivation.sign(walletPrivateKey, chain, it) } + val signed = spend.witnessed(signatures) + + assertEquals(2, signed.txIn.size) + signed.txIn.forEach { assertEquals(1, it.witness.stack.size, "a key-path spend reveals no tree") } + signed.correctlySpends(spend.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + } + + @Test + fun `another key does not sign the member's coins`() { + val spend = checked( + GroupSpendBuilder.sendAll(state(coin(0, 60_000)), "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 5L, emptySet()) + ) + assertFails { MemberWalletDerivation.sign(privateKey(0xb0b), chain, spend.inputs.single()) } + } + + @Test + fun `every guardian reaches its leaf in the member's wallet`() { + // The group itself, then its parent two generations up: the walk each + // signs a leaf with ends at the wallet id, as it would end at a room. + val groupLineage = GuardianDerivation.lineage(grant, walletId, groupRoom)!! + assertEquals(listOf(walletId), groupLineage) + val parentLineage = GuardianDerivation.lineage(grant, walletId, parentRoom)!! + assertEquals(listOf(groupRoom, walletId), parentLineage) + + listOf(groupKey to groupLineage, parentKey to parentLineage).forEachIndexed { position, (key, lineage) -> + val signing = GuardianDerivation.signingCache(key, lineage, chain, MemberWalletDerivation.ACCOUNT, 0, 4) + assertEquals(GuardianDerivation.leafKey(grant[position], chain, MemberWalletDerivation.ACCOUNT, 0, 4), signing.leafKey) + } + } + + @Test + fun `the exported descriptors carry the private key and nothing else changes`() { + val (receive, change) = MemberWalletDerivation.privateDescriptors(walletPrivateKey, account) + for ((exported, public) in listOf(receive to account.receiveDescriptor, change to account.changeDescriptor)) { + val (body, checksum) = exported.split('#') + assertEquals(Descriptor.checksum(body), checksum) + assertTrue(body.contains("tprv"), "a test network's private key") + assertTrue(!body.contains(account.xpub), "the account xpub is gone") + assertEquals(public.substringBefore('#').replace(account.xpub, ""), body.replace(Regex("tprv[1-9A-HJ-NP-Za-km-z]+"), "")) + } + assertFails { MemberWalletDerivation.privateDescriptors(privateKey(0xb0b), account) } + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/SignedArtifactTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/SignedArtifactTest.kt deleted file mode 100644 index 8190e758..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/SignedArtifactTest.kt +++ /dev/null @@ -1,297 +0,0 @@ -package com.machankura.bennu.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotEquals -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import com.machankura.bennu.compose.database.model.FrostSigningItem -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent - -/** - * An artifact the group signed, from proposal to rows, against real FROST. - * - * Adding an artifact used to write a row and submit it; the row said the - * submitter wrote it, because they had. Now the group signs it, and the claim - * this test exists to hold is that the artifact every device ends up with is - * the group's: authored by the threshold key, carrying a signature that - * verifies, with an id every member arrives at independently. - * - * None of that is visible when it breaks. A row whose author is the proposer - * looks exactly like a row whose author is the group -- both are opaque hex -- - * and a group that disagrees about the id has two artifacts that look like one. - */ -class SignedArtifactTest { - private val participants = 3 - private val threshold = 2 - - /** The member who filled in the form. Nothing they own should end up on the row. */ - private val proposer = "9".repeat(64) - private val dialectId = "b".repeat(64) - - /** Stands in for a completed ceremony; the test is about what gets signed, not the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** - * The room the group signs in: derived from its key at the admin path, which - * is what makes the room's id and the key it signs as one value. - */ - private val room: SharedKeyDerivation.Derived = SharedKeyDerivation.derive( - thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex(), - path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - ) - - private val tweakCache: TweakCache = room.cache - - /** The group's nostr identity here, which is also [chatRoomId]. */ - private val groupPubKey = room.hex - - private val chatRoomId = room.hex - - private fun proposalTemplate(versionLabel: String = "1.0") = ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = versionLabel, - createdAt = 1_700_000_000L, - ) - - /** - * Exactly what `FrostSigningManager.unsignedEventOf` does, and it must stay - * exactly that: the proposer's fields re-authored under the group's key. - */ - private fun unsignedEventOf(template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate<*>) = Event( - id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = groupPubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - - private fun itemOver(unsignedEvent: Event) = FrostSigningItem( - sessionId = "s".repeat(64), - itemIndex = 0, - unsignedEventJson = unsignedEvent.toJson(), - eventId = unsignedEvent.id, - nonceRandom = "f".repeat(64) - ) - - /** A quorum signing the item's event, in the manager's order. */ - private fun groupSignature(item: FrostSigningItem): String { - val message = ByteVector(item.eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = keyMaterial.secretShares[signerId], - publicShare = keyMaterial.publicShares[signerId], - tweakedThresholdPublicKey = tweakCache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { keyMaterial.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = tweakCache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - keyMaterial.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } - - /** Everything from the form to the row a device holds afterwards. */ - private fun signedArtifactEvent(versionLabel: String = "1.0"): ArtifactEvent { - val item = itemOver(unsignedEventOf(proposalTemplate(versionLabel))) - val signed = FrostSigningManager.signedEvent(item, groupSignature(item)) - - return ArtifactEvent( - signed.id, signed.pubKey, signed.createdAt, signed.tags, signed.content, signed.sig - ) - } - - @Test - fun `the artifact the group signs is authored by the group not the proposer`() { - val artifact = MantraArtifact.fromArtifactEvent(signedArtifactEvent(), chatRoomId) - - assertNotNull(artifact) - assertEquals(groupPubKey, artifact.publicKey) - assertNotEquals(proposer, artifact.publicKey) - } - - @Test - fun `the group it is authored by is the room it was signed in`() { - // Signing runs at the room's derivation path, so the author is the room's - // own id rather than the bare threshold key. That is what lets anybody - // holding the row check it without being told which key to expect -- and - // it is why the path a session signs at cannot come from the proposer. - val artifact = MantraArtifact.fromArtifactEvent(signedArtifactEvent(), chatRoomId) - - assertEquals(chatRoomId, artifact?.publicKey) - assertNotEquals( - keyMaterial.thresholdPublicKey.xOnly().value.toHex(), - artifact?.publicKey, - "an artifact must be signed by the room's key, not by the group's root key" - ) - } - - @Test - fun `the row's id is the id the group put its signature to`() { - // Every device builds this row from the same signed event, so the id has - // to be the one that was signed rather than anything recomputed from the - // proposer. Otherwise members converge on nothing and each holds its own - // copy of what is meant to be one artifact. - val item = itemOver(unsignedEventOf(proposalTemplate())) - val signed = FrostSigningManager.signedEvent(item, groupSignature(item)) - - val artifact = MantraArtifact.fromArtifactEvent( - ArtifactEvent(signed.id, signed.pubKey, signed.createdAt, signed.tags, signed.content, signed.sig), - chatRoomId - ) - - assertEquals(item.eventId, artifact?.id) - } - - @Test - fun `the signature on the row verifies against the row's own id and author`() { - // The payoff of signing rather than submitting: the row carries proof the - // group made it, checkable by anybody holding it. - val artifact = MantraArtifact.fromArtifactEvent(signedArtifactEvent(), chatRoomId) - - assertNotNull(artifact) - assertTrue( - Nip01Crypto.verify( - signature = artifact.signature.hexToByteArray(), - hash = artifact.id.hexToByteArray(), - pubKey = artifact.publicKey.hexToByteArray() - ), - "an artifact row should carry a signature the group's key made over its own id" - ) - } - - @Test - fun `what the form asked for is what the group signed`() { - // The fields travel as tags through a session that knows nothing about - // artifacts. Anything dropped in there is signed away silently. - val artifact = MantraArtifact.fromArtifactEvent(signedArtifactEvent(), chatRoomId) - - assertEquals("In Detention", artifact?.name) - assertEquals("https://example.com/in-detention", artifact?.url) - assertEquals("private", artifact?.visibility) - assertEquals("cc", artifact?.license) - assertEquals(dialectId, artifact?.dialectId) - } - - /** The second item of the batch, through the same quorum as the first. */ - private fun signedInitialVersionEvent(versionLabel: String = "1.0"): ArtifactVersionEvent { - // Built from the unsigned lead, which is what `proposeSigningBatch` hands - // to `dependents` -- the artifact's id is settled at proposal, not at - // signature, which is the only reason a version can name it at all. - val lead = unsignedEventOf(proposalTemplate(versionLabel)) - val item = itemOver(unsignedEventOf(ArtifactVersionEvent.initialVersionOf(lead).single())) - val signed = FrostSigningManager.signedEvent(item, groupSignature(item)) - - return ArtifactVersionEvent( - signed.id, signed.pubKey, signed.createdAt, signed.tags, signed.content, signed.sig - ) - } - - @Test - fun `the artifact arrives with the first version hanging off it`() { - // A chapter attaches to a version rather than to an artifact, so an - // artifact that arrives without one is inert. Both come out of one - // batch, so neither can arrive without the other. - val artifact = MantraArtifact.fromArtifactEvent( - signedArtifactEvent(versionLabel = "First Edition"), chatRoomId - ) - val version = MantraArtifactVersion.fromArtifactVersionEvent( - signedInitialVersionEvent(versionLabel = "First Edition"), chatRoomId - ) - - assertNotNull(version) - assertEquals(artifact?.id, version.artifactId) - assertEquals("First Edition", version.versionLabel) - assertEquals(groupPubKey, version.publicKey) - } - - @Test - fun `the first version carries the group's signature over its own id`() { - // The point of signing it rather than deriving it. A derived version was - // authored by the group and signed by nobody -- indistinguishable, on the - // row, from one somebody made up, and the parent of every chapter in it. - val version = MantraArtifactVersion.fromArtifactVersionEvent( - signedInitialVersionEvent(), chatRoomId - ) - - assertNotNull(version) - assertNotEquals("", version.signature) - assertTrue( - Nip01Crypto.verify( - signature = version.signature.hexToByteArray(), - hash = version.id.hexToByteArray(), - pubKey = version.publicKey.hexToByteArray() - ), - "a first version should carry a signature the group's key made over its own id" - ) - } - - @Test - fun `the version is a second message signed under its own nonce`() { - // Two items of a batch are two independent FROST instances: k signatures - // over k ids, never one signature stretched over both. A version whose - // signature verified against the artifact's id would mean a nonce had - // been reused, which is how a share is extracted rather than a cosmetic - // mix-up. - val artifact = signedArtifactEvent() - val version = signedInitialVersionEvent() - - assertNotEquals(artifact.id, version.id) - assertNotEquals(artifact.sig, version.sig) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/SignedChapterTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/SignedChapterTest.kt deleted file mode 100644 index dcfbe7c8..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/SignedChapterTest.kt +++ /dev/null @@ -1,354 +0,0 @@ -package com.machankura.bennu.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotEquals -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import com.machankura.bennu.compose.database.model.FrostSigningItem -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent - -/** - * A chapter and its chunks the group signed, from proposal to rows, against - * real FROST. - * - * Adding a chapter used to write the rows and submit them, one submission for - * the chapter and one per paragraph; the rows said the submitter wrote them, - * because they had. Now the group signs the lot in one session, and the claim - * this test exists to hold is that every row a device ends up with is the - * group's: authored by the threshold key, carrying a signature that verifies - * over its own id, with the chunks naming the chapter that was signed beside - * them. - * - * None of that is visible when it breaks. A row whose author is the proposer - * looks exactly like a row whose author is the group -- both are opaque hex -- - * and a chunk that names the wrong chapter is a foreign key away from vanishing - * with no sign of why. - * - * A batch is k independent FROST instances, so the signatures here are made one - * per item, each over its own message with its own nonces, which is the only - * way they can be made. - */ -class SignedChapterTest { - private val participants = 3 - private val threshold = 2 - - /** The member who pasted the text. Nothing they own should end up on the rows. */ - private val proposer = "9".repeat(64) - private val artifactVersionId = "b".repeat(64) - - private val originalText = "The first paragraph.\n\nThe second paragraph." - - /** Stands in for a completed ceremony; the test is about what gets signed, not the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** - * The room the group signs in: derived from its key at the admin path, which - * is what makes the room's id and the key it signs as one value. - */ - private val room: SharedKeyDerivation.Derived = SharedKeyDerivation.derive( - thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex(), - path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - ) - - private val tweakCache: TweakCache = room.cache - - /** The group's nostr identity here, which is also [chatRoomId]. */ - private val groupPubKey = room.hex - - private val chatRoomId = room.hex - - private fun proposalTemplate( - name: String = "Chapter 1", - text: String = originalText, - index: Int = 0, - ) = ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = name, - originalText = text, - index = index, - wordCount = 6, - characterCount = text.length, - createdAt = 1_700_000_000L, - ) - - /** - * Exactly what `FrostSigningManager.unsignedEventOf` does, and it must stay - * exactly that: the proposer's fields re-authored under the group's key. - */ - private fun unsignedEventOf(template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate<*>) = Event( - id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = groupPubKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - - private fun itemsOver(unsignedEvents: List) = unsignedEvents.mapIndexed { index, event -> - FrostSigningItem( - sessionId = "s".repeat(64), - itemIndex = index, - unsignedEventJson = event.toJson(), - eventId = event.id, - // One seed per item, never shared: two messages under one nonce is - // how a share is extracted. - nonceRandom = "f".repeat(63) + "${index + 1}" - ) - } - - /** A quorum signing one item's event, in the manager's order. */ - private fun groupSignature(item: FrostSigningItem): String { - val message = ByteVector(item.eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32( - "a".repeat(62) + "${item.itemIndex + 1}${signerId + 1}" - ), - secretShare = keyMaterial.secretShares[signerId], - publicShare = keyMaterial.publicShares[signerId], - tweakedThresholdPublicKey = tweakCache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { keyMaterial.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = tweakCache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - keyMaterial.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } - - /** - * The batch a proposal makes: the chapter, then a chunk per paragraph, cut - * from the chapter after it is authored under the group's key -- exactly - * what `AddChapterViewModel` hands `proposeSigningBatch` as lead and - * dependents. - */ - private fun proposedBatch( - name: String = "Chapter 1", - text: String = originalText, - index: Int = 0, - ): List { - val chapter = unsignedEventOf(proposalTemplate(name, text, index)) - - return listOf(chapter) + ChunkEvent.splitOf(chapter).map(::unsignedEventOf) - } - - /** Everything from the form to the rows a device holds afterwards. */ - private fun signedBatch( - name: String = "Chapter 1", - text: String = originalText, - index: Int = 0, - ): List = itemsOver(proposedBatch(name, text, index)).map { item -> - FrostSigningManager.signedEvent(item, groupSignature(item)) - } - - private fun signedChapterEvent( - name: String = "Chapter 1", - text: String = originalText, - index: Int = 0, - ): ChapterEvent = signedBatch(name, text, index).first().let { signed -> - ChapterEvent( - signed.id, signed.pubKey, signed.createdAt, signed.tags, signed.content, signed.sig - ) - } - - private fun signedChunkEvents( - text: String = originalText, - ): List = signedBatch(text = text).drop(1).map { signed -> - ChunkEvent( - signed.id, signed.pubKey, signed.createdAt, signed.tags, signed.content, signed.sig - ) - } - - @Test - fun `the chapter the group signs is authored by the group not the proposer`() { - val chapter = MantraChapter.fromChapterEvent(signedChapterEvent(), chatRoomId) - - assertNotNull(chapter) - assertEquals(groupPubKey, chapter.publicKey) - assertNotEquals(proposer, chapter.publicKey) - } - - @Test - fun `the group it is authored by is the room it was signed in`() { - // Signing runs at the room's derivation path, so the author is the room's - // own id rather than the bare threshold key. That is what lets anybody - // holding the row check it without being told which key to expect -- and - // it is why the path a session signs at cannot come from the proposer. - val chapter = MantraChapter.fromChapterEvent(signedChapterEvent(), chatRoomId) - - assertEquals(chatRoomId, chapter?.publicKey) - assertNotEquals( - keyMaterial.thresholdPublicKey.xOnly().value.toHex(), - chapter?.publicKey, - "a chapter must be signed by the room's key, not by the group's root key" - ) - } - - @Test - fun `the row's id is the id the group put its signature to`() { - // Every device builds this row from the same signed event, so the id has - // to be the one that was signed rather than anything recomputed from the - // proposer. Otherwise members converge on nothing and each holds its own - // copy of what is meant to be one chapter. - val item = itemsOver(proposedBatch()).first() - val signed = FrostSigningManager.signedEvent(item, groupSignature(item)) - - val chapter = MantraChapter.fromChapterEvent( - ChapterEvent(signed.id, signed.pubKey, signed.createdAt, signed.tags, signed.content, signed.sig), - chatRoomId - ) - - assertEquals(item.eventId, chapter?.id) - } - - @Test - fun `the signature on the row verifies against the row's own id and author`() { - // The payoff of signing rather than submitting: the row carries proof the - // group made it, checkable by anybody holding it. - val chapter = MantraChapter.fromChapterEvent(signedChapterEvent(), chatRoomId) - - assertNotNull(chapter) - assertTrue( - Nip01Crypto.verify( - signature = chapter.signature.hexToByteArray(), - hash = chapter.id.hexToByteArray(), - pubKey = chapter.publicKey.hexToByteArray() - ), - "a chapter row should carry a signature the group's key made over its own id" - ) - } - - @Test - fun `what the form asked for is what the group signed`() { - // The fields travel as tags through a session that knows nothing about - // chapters. Anything dropped in there is signed away silently -- and the - // original text most of all, since the chunks are split out of it. - val chapter = MantraChapter.fromChapterEvent( - signedChapterEvent(name = "In Detention", index = 2), - chatRoomId - ) - - assertEquals("In Detention", chapter?.name) - assertEquals(originalText, chapter?.originalText) - assertEquals(artifactVersionId, chapter?.artifactVersionId) - assertEquals(2, chapter?.index) - } - - @Test - fun `the chapter is signed with a chunk for every paragraph`() { - // One session, one approval, and a row per paragraph at the end of it. - // A translation is of a chunk rather than of a chapter, so a chapter - // that arrived without them could not be worked on. - val batch = signedBatch() - - assertEquals(3, batch.size) - assertEquals(ChapterEvent.KIND, batch.first().kind) - assertTrue(batch.drop(1).all { it.kind == ChunkEvent.KIND }) - } - - @Test - fun `every chunk the group signed names the chapter it signed beside it`() { - // The batch is applied in item order, so the chapter row is written - // first and the chunks hang off it. A chunk naming anything else fails a - // foreign key and disappears with no sign of why. - val batch = signedBatch() - val chapter = MantraChapter.fromChapterEvent( - batch.first().let { - ChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - }, - chatRoomId - ) - - val chunks = signedChunkEvents().map { MantraChunk.fromChunkEvent(it, chatRoomId) } - - assertEquals(2, chunks.size) - assertTrue(chunks.all { it?.chapterId == chapter?.id }) - assertEquals(listOf("The first paragraph.", "The second paragraph."), chunks.map { it?.text }) - assertEquals(listOf(0, 1), chunks.map { it?.index }) - } - - @Test - fun `each chunk row carries a signature the group made over its own id`() { - // The point of signing the chunks rather than splitting them out of the - // chapter on arrival: a chunk can be checked on its own, by anybody - // holding it, without re-deriving it from anything. - signedChunkEvents().forEach { signed -> - val chunk = MantraChunk.fromChunkEvent(signed, chatRoomId) - - assertNotNull(chunk) - assertEquals(groupPubKey, chunk.publicKey) - assertNotEquals(proposer, chunk.publicKey) - assertTrue( - Nip01Crypto.verify( - signature = chunk.signature.hexToByteArray(), - hash = chunk.id.hexToByteArray(), - pubKey = chunk.publicKey.hexToByteArray() - ), - "a chunk row should carry a signature the group's key made over its own id" - ) - } - } - - @Test - fun `the chapter and its chunks are different messages to sign`() { - // A batch is k FROST instances precisely because it has to be: one nonce - // over two messages leaks the share. That the items are distinct - // messages is the premise -- `FrostSigningRoundTest` and - // `SignedGroupKeyStateTest` hold the manager to giving each its own - // nonce; what a chapter has to hold up is that its own items are not - // secretly one message repeated. - val batch = proposedBatch(text = "Again.\n\nAgain.") - - assertEquals(batch.size, batch.map { it.id }.toSet().size) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt deleted file mode 100644 index 2290545f..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/TranslationScaffoldTest.kt +++ /dev/null @@ -1,183 +0,0 @@ -package com.machankura.bennu.compose.managers - -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.tags.ChapterIdTag -import com.machankura.bennu.compose.nostr.nip30303.tags.IndexTag -import com.machankura.bennu.compose.nostr.nip30303.tags.TranslationArtifactVersionIdTag - -/** - * The join between a translation and the chapters it is of, as a pure function. - * - * Both ends arrive on their own schedule, so this is built from three - * directions -- a translation being proposed, a chapter being proposed, and a - * catch-up filling in what the two missed. What it must not do is disagree with - * itself about what a translation covers depending on which direction it was - * built from. - */ -class TranslationScaffoldTest { - - private val translationA = "a".repeat(64) - private val translationB = "b".repeat(64) - - private fun sourceChapter(index: Int, id: String = "c$index".padEnd(64, 'f')) = MantraChapter( - id = id, - artifactVersionId = "v".repeat(64), - publicKey = "p".repeat(64), - name = "Chapter ${index + 1}", - originalText = "Paragraph.", - index = index, - wordCount = 1, - characterCount = 10, - signature = "", - chatRoomId = "r".repeat(64), - ) - - private fun translationChapterFor(chapter: MantraChapter, translationId: String) = - MantraTranslationChapter( - id = "t${chapter.id}".take(64), - publicKey = "p".repeat(64), - chapterId = chapter.id, - translationArtifactVersionId = translationId, - index = chapter.index, - signature = "", - chatRoomId = "r".repeat(64), - ) - - private fun parse(templates: List>) = - templates.map { template -> - Triple( - template.tags.firstNotNullOfOrNull(TranslationArtifactVersionIdTag::parse)?.ref?.eventId, - template.tags.firstNotNullOfOrNull(ChapterIdTag::parse)?.ref?.eventId, - template.tags.firstNotNullOfOrNull(IndexTag::parse)?.index, - ) - } - - @Test - fun `a translation's chapters stay together and in reading order`() { - val chapters = (0..2).map(::sourceChapter) - - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA, translationB), - chapters = chapters.map(TranslationScaffold.SourceChapter::of), - createdAt = 1_000, - ) - - // Item order is the order a session signs and applies in, so it is - // fixed here rather than left to a caller. Translations outer, chapters - // inner: one translation's chapters are contiguous and in order. - assertEquals( - listOf( - Triple(translationA, chapters[0].id, 0), - Triple(translationA, chapters[1].id, 1), - Triple(translationA, chapters[2].id, 2), - Triple(translationB, chapters[0].id, 0), - Triple(translationB, chapters[1].id, 1), - Triple(translationB, chapters[2].id, 2), - ), - parse(templates) - ) - } - - @Test - fun `a chapter proposed on its own is scaffolded into every translation`() { - // The other direction: one chapter, every existing translation. This is - // what a chapter's own scaffolding session carries. - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA, translationB), - chapters = listOf(TranslationScaffold.SourceChapter(id = "z".repeat(64), index = 7)), - createdAt = 1_000, - ) - - assertEquals( - listOf( - Triple(translationA, "z".repeat(64), 7), - Triple(translationB, "z".repeat(64), 7), - ), - parse(templates) - ) - } - - @Test - fun `a catch-up keeps each chapter's own position not the position in the gap`() { - val chapters = (0..5).map(::sourceChapter) - - // A catch-up proposes a subset, and the subset is not contiguous. - // Counting the list would renumber chapters 3 and 5 as 1 and 2, which - // is a translation that reads in a different order than the work. - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA), - chapters = listOf(chapters[3], chapters[5]).map(TranslationScaffold.SourceChapter::of), - createdAt = 1_000, - ) - - assertEquals(listOf(3, 5), parse(templates).map { it.third }) - } - - @Test - fun `the whole scaffolding carries one timestamp`() { - val templates = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA, translationB), - chapters = (0..2).map(::sourceChapter).map(TranslationScaffold.SourceChapter::of), - createdAt = 4_242, - ) - - // Read once by the caller rather than per template, so a scaffolding - // proposed as one act reads as one. - assertEquals(listOf(4_242L), templates.map { it.createdAt }.distinct()) - } - - @Test - fun `nothing to scaffold when there is nothing on one side`() { - assertTrue( - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = emptyList(), - chapters = listOf(TranslationScaffold.SourceChapter("z".repeat(64), 0)), - createdAt = 1_000, - ).isEmpty() - ) - - assertTrue( - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translationA), - chapters = emptyList(), - createdAt = 1_000, - ).isEmpty() - ) - } - - @Test - fun `what is missing is matched on the chapter named not on how many there are`() { - val chapters = (0..3).map(::sourceChapter) - - // Chapter 1 never landed but chapter 2 did, which a count would read as - // "the last one is missing" and scaffold the wrong chapter. - val missing = TranslationScaffold.chaptersMissingFrom( - translationChapters = listOf(chapters[0], chapters[2]).map { - translationChapterFor(it, translationA) - }, - sourceChapters = chapters, - ) - - assertEquals(listOf(chapters[1].id, chapters[3].id), missing.map { it.id }) - } - - @Test - fun `a translation that is already complete is missing nothing`() { - val chapters = (0..2).map(::sourceChapter) - - // So that running a catch-up twice proposes nothing the second time, - // rather than a second copy of every chapter under fresh ids. - assertEquals( - emptyList(), - TranslationScaffold.chaptersMissingFrom( - translationChapters = chapters.map { translationChapterFor(it, translationA) }, - sourceChapters = chapters, - ) - ) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt deleted file mode 100644 index 2e9862fb..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt +++ /dev/null @@ -1,300 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -/** - * What a pasted event may become, and where it goes once the group has signed it. - * - * Two halves. The first is the reading: which pastes are refused and why, and - * that what is refused is exactly what a reader would refuse -- the point of - * checking before proposing is that a quorum is never asked to sign something - * that will be filed and shown nowhere. - * - * The second is the promise the feature makes: a pasted kind 0 becomes the - * profile, a kind 1 a post, a relay list a relay list. That - * is not this module's doing -- `FrostSigningManager.complete` files every signed - * event and the group's screen reads each section off those by kind -- so the - * test is the whole chain: the paste read here, signed by a real quorum through - * the same shape `FrostSigningManager.advance` runs, and read back by the reader - * that section uses. - */ -class GroupEventProposalTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - /** - * A post as another client would print it: a whole event, id, author, - * signature and time included. - */ - private val pastedPost = """ - { - "id": "b2f8c7a7b4d5e6f70123456789abcdef0123456789abcdef0123456789abcdef", - "pubkey": "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25", - "created_at": 1735689600, - "kind": 1, - "tags": [ - ["t", "translation"], - ["alt", "{\"chapter\":1,\"of\":12}"] - ], - "content": "We have finished the first chapter.", - "sig": "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" - } - """.trimIndent() - - @Test - fun `a pasted event is read as its kind tags and content and nothing else`() { - val ready = assertIs(GroupEventProposal.read(pastedPost)) - - assertEquals(1, ready.kind) - assertEquals("We have finished the first chapter.", ready.content) - assertEquals(2, ready.tags.size) - assertEquals(listOf("t", "translation"), ready.tags.first().toList()) - // A JSON value inside a tag comes through verbatim, escapes and all. - assertEquals("{\"chapter\":1,\"of\":12}", ready.tags[1][1]) - - // The id, author, signature and time are not the paste's to decide, and - // there is nowhere on a reading for them to go: the session hashes the id - // over the room's key and the time it opens at. - val preview = ready.preview() - assertEquals("", preview.pubKey) - assertEquals(0L, preview.createdAt) - } - - @Test - fun `a bare template with no tags or content still reads`() { - val ready = assertIs( - GroupEventProposal.read("""{"kind": 0, "content": "{}"}""") - ) - assertEquals(0, ready.kind) - assertEquals(0, ready.tags.size) - - // A numeric string for the kind is what a hand types; a relay writes a number. - assertIs( - GroupEventProposal.read("""{"kind": "1", "content": "Hello"}""") - ) - } - - @Test - fun `what is not an event is refused and named`() { - assertEquals(GroupEventProposal.Refused.NotJson, GroupEventProposal.read("not json at all")) - assertEquals(GroupEventProposal.Refused.NotJson, GroupEventProposal.read("{\"kind\": 1,")) - assertEquals(GroupEventProposal.Refused.NotAnObject, GroupEventProposal.read("[1, 2, 3]")) - assertEquals(GroupEventProposal.Refused.NotAnObject, GroupEventProposal.read("\"a string\"")) - assertEquals(GroupEventProposal.Refused.NoKind, GroupEventProposal.read("""{"content": "Hello"}""")) - assertEquals(GroupEventProposal.Refused.NoKind, GroupEventProposal.read("""{"kind": "one"}""")) - assertEquals( - GroupEventProposal.Refused.TagsMalformed, - GroupEventProposal.read("""{"kind": 1, "tags": "e", "content": "Hello"}""") - ) - assertEquals( - GroupEventProposal.Refused.TagsMalformed, - GroupEventProposal.read("""{"kind": 1, "tags": [["e", 1]], "content": "Hello"}""") - ) - assertEquals( - GroupEventProposal.Refused.ContentNotText, - GroupEventProposal.read("""{"kind": 1, "content": {"note": "Hello"}}""") - ) - } - - @Test - fun `a kind the group's screen has no place for is refused whatever else it says`() { - // A long-form article is a perfectly good nostr event and the group could - // sign it. It would then be filed and shown nowhere, with nothing to tell - // the member their quorum was spent on it. - assertEquals( - GroupEventProposal.Refused.KindNotAccepted(30023), - GroupEventProposal.read("""{"kind": 30023, "tags": [["d", "x"]], "content": "An article"}""") - ) - - // The kinds with a section: the profile, the posts and the four relay - // lists. A subgroup certificate is deliberately not among them. - assertEquals( - setOf(0, 1, 10002, 10050, 10007, 10006), - GroupEventProposal.ACCEPTED_KINDS - ) - } - - @Test - fun `a kind zero whose content is not a profile is refused and an empty one is not`() { - assertEquals( - GroupEventProposal.Refused.ProfileUnreadable, - GroupEventProposal.read("""{"kind": 0, "content": "not a profile"}""") - ) - - // Wiping a profile is a thing groups are entitled to do -- the same line - // `GroupNostrProfile.of` draws. - assertIs(GroupEventProposal.read("""{"kind": 0, "content": ""}""")) - assertIs( - GroupEventProposal.read("""{"kind": 0, "content": "{\"name\":\"Translation collective\"}"}""") - ) - } - - @Test - fun `a blank post is refused the way the composer refuses one`() { - listOf("", " ", "\\n\\n").forEach { blank -> - assertEquals( - GroupEventProposal.Refused.PostBlank, - GroupEventProposal.read("""{"kind": 1, "content": "$blank"}"""), - "a post saying \"$blank\" was accepted" - ) - } - } - - @Test - fun `a relay list reads whether or not it names a relay`() { - // An empty one is a list the group is withdrawing, which the relays card - // shows as "no relays" rather than as nothing. - assertIs(GroupEventProposal.read("""{"kind": 10002}""")) - assertIs( - GroupEventProposal.read("""{"kind": 10002, "tags": [["r", "wss://relay.example.com", "write"]]}""") - ) - } - - @Test - fun `a pasted kind zero once signed is the group's profile`() { - val ready = assertIs( - GroupEventProposal.read( - """{"kind": 0, "pubkey": "not the group", "content": "{\"name\":\"Translation collective\",\"about\":\"We translate hard books.\"}"}""" - ) - ) - - val profile = assertNotNull(GroupNostrProfile.of(signed(ready), chatRoomId)) - - assertEquals("Translation collective", profile.name()) - assertEquals("We translate hard books.", profile.about()) - assertEquals(chatRoomId, profile.publicKey) - } - - @Test - fun `a pasted kind one once signed is one of the group's posts`() { - val ready = assertIs( - GroupEventProposal.read("""{"kind": 1, "tags": [], "content": "We have finished the first chapter."}""") - ) - - val posts = GroupPost.newestFirstAmong(listOf(signed(ready)), chatRoomId) - - assertEquals(listOf("We have finished the first chapter."), posts.map { it.content }) - assertTrue(posts.single().isNewThread()) - } - - @Test - fun `a pasted relay list once signed is one of the group's relay lists`() { - val ready = assertIs( - GroupEventProposal.read("""{"kind": 10002, "tags": [["r", "wss://relay.example.com", "write"]]}""") - ) - - val list = GroupRelayList.newestAmong(listOf(signed(ready)), chatRoomId, GroupRelaySet.General) - - assertTrue(list.isAgreed) - assertEquals(listOf("relay.example.com"), list.relays.map { it.displayUrl() }) - assertEquals(listOf(false), list.relays.map { it.read }) - assertEquals(listOf(true), list.relays.map { it.write }) - } - - /** - * A reading as `FrostSigningManager.complete` would file it: authored by the - * room's key at its path, the id hashed over that, a real quorum's signature - * on it, and the time the session opened at rather than anything pasted. - */ - private fun signed(ready: GroupEventProposal.Ready, createdAt: Long = 1_700_000_000): GroupSignedEvent { - val groupPubKey = SharedKeyDerivation - .derive(groupMaterial.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = ready.kind, - tags = ready.tags, - content = ready.content - ) - - return GroupSignedEvent.fromEvent( - event = Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = ready.kind, - tags = ready.tags, - content = ready.content, - sig = groupSignature(groupMaterial, id) - ), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt deleted file mode 100644 index e80ae282..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt +++ /dev/null @@ -1,438 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull - -/** - * What a group's nostr profile is allowed to be read out of. - * - * A room's id is the pubkey it signs as, so a kind:0 authored by that key is the - * group describing itself and a kind:0 authored by anything else is not -- however - * it came to be filed against the room. The reading is what the group detail screen - * shows and what an edit is built on top of, so both halves are worth pinning: - * which events become a profile, and what an edit does to the one before it. - * - * The edit half is the one with a silent failure behind it. `updateFromPast` is - * used precisely so a field this app does not offer survives being edited, and - * `createNew` in its place would compile, pass any test that only looked at the - * fields the form knows about, and quietly wipe the rest of the group's profile - * every time somebody fixed a typo in its name. - */ -class GroupNostrProfileTest { - private val participants = 3 - private val threshold = 2 - - /** The group whose profile this is. */ - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the profiles signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - private val strangerChatRoomId = - SharedKeyDerivation.marmotGroupId(strangerMaterial.thresholdPublicKey.value.toHex(), path) - - @Test - fun `a kind zero the room signed is the group's profile`() { - val profile = GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"Translation collective","about":"We translate hard books.",""" + - """"picture":"https://example.com/group.png","nip05":"group@example.com"}""" - ), - chatRoomId = chatRoomId - ) - - assertNotNull(profile) - assertEquals("Translation collective", profile.name()) - assertEquals("We translate hard books.", profile.about()) - assertEquals("https://example.com/group.png", profile.picture()) - assertEquals("group@example.com", profile.nip05()) - assertEquals(chatRoomId, profile.publicKey) - } - - @Test - fun `display_name is what a name is read out of when both are set`() { - // Every other nostr client prefers it, and `template` writes both so they - // agree. A group whose two names disagree got them from somewhere else, - // and the answer has to be the one the rest of nostr will give. - val profile = GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"collective","display_name":"Translation collective"}""" - ), - chatRoomId = chatRoomId - ) - - assertEquals("Translation collective", profile?.name()) - } - - @Test - fun `a kind zero another group signed is not this group's profile`() { - // A real quorum and a real signature by a group with no standing to say - // anything about this room. The row names this room because that is where - // the event was filed; the author is what decides whose profile it is. - val stranger = GroupSignedEvent.fromEvent( - event = metadataEvent( - content = """{"name":"Somebody else"}""", - material = strangerMaterial - ), - chatRoomId = chatRoomId - ) - - assertEquals(strangerChatRoomId, stranger.publicKey, "the fixture signs as the stranger") - assertNull(GroupNostrProfile.of(signedEvent = stranger, chatRoomId = chatRoomId)) - } - - @Test - fun `a kind zero whose signature is not the room's is not a profile`() { - // Authored by the room, saying the right things, and signed by a key that - // is not the room's. This is the shape a member forging a rename produces. - assertNull( - GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"Renamed by one member"}""", - signer = strangerMaterial - ), - chatRoomId = chatRoomId - ) - ) - - // And everything off the wire is allowed to be nonsense, which means no - // rather than an exception. - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupNostrProfile.of( - signedEvent = signed(content = """{"name":"x"}""", signature = rubbish), - chatRoomId = chatRoomId - ), - "a profile signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `an event of another kind is not a profile`() { - assertNull( - GroupNostrProfile.of( - signedEvent = signed(content = """{"name":"x"}""").copy(kind = 1), - chatRoomId = chatRoomId - ) - ) - } - - @Test - fun `the newest profile the group signed is the one that counts`() { - // kind:0 is replaceable: editing a profile signs a second one, and the - // second is the answer whatever order the query hands them over in. - val older = signed(content = """{"name":"What it was called"}""", createdAt = 1_700_000_000) - val newer = signed(content = """{"name":"What it is called"}""", createdAt = 1_700_000_900) - - listOf(listOf(older, newer), listOf(newer, older)).forEach { events -> - assertEquals( - "What it is called", - GroupNostrProfile.newestAmong(events, chatRoomId)?.name(), - "the newest profile lost to query order" - ) - } - } - - @Test - fun `two profiles signed in the same second resolve the same way on every device`() { - // Two devices catching up read the same events in whatever order the - // relay or the query gives them, and they have to end up showing the same - // profile. A tie on the timestamp is broken by the id, which every device - // agrees on because it is a hash of the event. - val one = signed(content = """{"name":"One"}""", createdAt = 1_700_000_000) - val other = signed(content = """{"name":"Other"}""", createdAt = 1_700_000_000) - - val expected = GroupNostrProfile.newestAmong(listOf(one, other), chatRoomId)?.name() - - assertNotNull(expected) - assertEquals( - expected, - GroupNostrProfile.newestAmong(listOf(other, one), chatRoomId)?.name(), - "a tie on the timestamp was broken differently by the two orderings" - ) - assertEquals( - if (one.id > other.id) "One" else "Other", - expected, - "the tie should break on the id, which is the only thing both devices share" - ) - } - - @Test - fun `the first profile a group signs carries the fields it was given`() { - val template = GroupNostrProfile.template( - latest = null, - name = "Translation collective", - about = "We translate hard books.", - picture = "https://example.com/group.png", - website = "https://example.com", - nip05 = "group@example.com", - lud16 = "group@getalby.com" - ) - - val profile = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - ) - - assertNotNull(profile) - assertEquals(MetadataEvent.KIND, template.kind) - assertEquals("Translation collective", profile.name()) - assertEquals("We translate hard books.", profile.about()) - assertEquals("https://example.com/group.png", profile.picture()) - assertEquals("https://example.com", profile.website()) - assertEquals("group@example.com", profile.nip05()) - assertEquals("group@getalby.com", profile.lud16()) - } - - @Test - fun `an edit keeps a field the form does not offer`() { - // The reason `template` builds on the group's own event rather than from - // scratch. `bot` is not on the form and never will be reached by it; an - // edit that dropped it would be this app deciding a group is not a bot - // because somebody fixed its name. - val existing = GroupNostrProfile.of( - signedEvent = signed(content = """{"name":"Old name","bot":true}"""), - chatRoomId = chatRoomId - ) - assertNotNull(existing) - - val template = GroupNostrProfile.template( - latest = existing, - name = "New name", - about = "", - picture = "", - website = "", - nip05 = "", - lud16 = "" - ) - - val edited = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - ) - - assertNotNull(edited) - assertEquals("New name", edited.name()) - assertEquals(true, edited.metadata.bot, "an edit dropped a field the form does not offer") - } - - @Test - fun `an emptied field unsays what the group had said`() { - // The only way to withdraw something a group has signed. A form that sent - // nulls for its blanks could add to a profile and never subtract from one. - val existing = GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"Translation collective","about":"Something regretted"}""" - ), - chatRoomId = chatRoomId - ) - assertNotNull(existing) - - val template = GroupNostrProfile.template( - latest = existing, - name = "Translation collective", - about = "", - picture = "", - website = "", - nip05 = "", - lud16 = "" - ) - - val edited = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - ) - - assertNotNull(edited) - assertNull(edited.about()) - assertEquals("Translation collective", edited.name()) - } - - @Test - fun `a name is written to both of the keys a reader might look in`() { - val template = GroupNostrProfile.template( - latest = null, - name = "Translation collective", - about = "", - picture = "", - website = "", - nip05 = "", - lud16 = "" - ) - - val metadata = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - )?.metadata - - assertNotNull(metadata) - assertEquals("Translation collective", metadata.name) - assertEquals( - "Translation collective", - metadata.displayName, - "a client preferring display_name would show the old name after an edit" - ) - } - - @Test - fun `an empty profile is a profile rather than a parse failure`() { - // Wiping a profile is something a group is entitled to do, and an empty - // kind:0 is how nostr says it. Reading it as nothing would leave the - // screen claiming the group had never said anything. - val profile = GroupNostrProfile.of( - signedEvent = signed(content = ""), - chatRoomId = chatRoomId - ) - - assertNotNull(profile) - assertNull(profile.name()) - assertNull(profile.about()) - } - - @Test - fun `content that is not a profile at all is refused`() { - assertNull( - GroupNostrProfile.of( - signedEvent = signed(content = "not json"), - chatRoomId = chatRoomId - ) - ) - } - - /** - * A profile row as `FrostSigningManager.complete` files one: the content under - * the room's own key, with the id hashed over it and the group's signature on - * it. - * - * [signer] is pulled apart from the author so a signature by the wrong quorum - * can be tested, and [signature] replaces the real one outright for what is - * not a signature at all. - */ - private fun signed( - content: String, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = metadataEvent( - content = content, - createdAt = createdAt, - material = material, - signer = signer, - signature = signature - ), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun metadataEvent( - content: String, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = content - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = content, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - * - * Assembled any other way it would not be evidence about the signatures this - * app actually produces. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt deleted file mode 100644 index 92362772..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt +++ /dev/null @@ -1,307 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What may be shown as something the group said. - * - * The reading gate is `GroupNostrProfileTest`'s -- the room has to be the author and - * the signature has to be the room's -- and it matters more here than anywhere else - * in this feature. A profile read wrong shows the wrong name; a post read wrong puts - * words in a group's mouth under a byline saying a quorum agreed to them, on a page - * whose whole purpose is to be read by people who were not there. - * - * The ordering half is the other thing worth pinning. Posts are the one statement - * here that **accumulates**: kind:1 is not replaceable, so a second post stands - * beside the first rather than replacing it, and everything the profile and the - * relay lists do with "newest wins" is wrong for these. - */ -class GroupPostTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the posts signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - @Test - fun `a kind one the room signed is a post by the group`() { - val post = GroupPost.of( - signedEvent = signed("We have finished the first chapter."), - chatRoomId = chatRoomId - ) - - assertEquals("We have finished the first chapter.", post?.content) - assertEquals(chatRoomId, post?.publicKey) - assertTrue(post?.isNewThread() == true) - } - - @Test - fun `a kind one another group signed is not this group's post`() { - // A real quorum and a real signature by a group with no standing to speak - // for this one. The row names this room because that is where it was filed; - // the author is what decides whose words they are. - val stranger = GroupSignedEvent.fromEvent( - event = noteEvent("Said by somebody else entirely.", material = strangerMaterial), - chatRoomId = chatRoomId - ) - - assertNull(GroupPost.of(signedEvent = stranger, chatRoomId = chatRoomId)) - } - - @Test - fun `a kind one the room did not sign is not a post`() { - // Authored by the room and signed by somebody else: the shape a member - // putting words in the group's mouth would produce, and the reason the - // reading verifies rather than trusting the author field. - assertNull( - GroupPost.of( - signedEvent = signed("The group has decided to disband.", signer = strangerMaterial), - chatRoomId = chatRoomId - ) - ) - - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupPost.of( - signedEvent = signed("Anything at all", signature = rubbish), - chatRoomId = chatRoomId - ), - "a post signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `an event of another kind is not a post`() { - assertNull( - GroupPost.of( - signedEvent = signed("Hello").copy(kind = 30023), - chatRoomId = chatRoomId - ) - ) - } - - @Test - fun `posts accumulate rather than replace newest first`() { - // The property that separates these from the profile and the relay lists. - // A reading that kept only the newest would silently delete a group's whole - // history the first time it posted twice. - val first = signed("First", createdAt = 1_700_000_000) - val second = signed("Second", createdAt = 1_700_000_900) - val third = signed("Third", createdAt = 1_700_001_800) - - listOf( - listOf(first, second, third), - listOf(third, second, first), - listOf(second, third, first), - ).forEach { events -> - assertEquals( - listOf("Third", "Second", "First"), - GroupPost.newestFirstAmong(events, chatRoomId).map { it.content }, - "posts came back in the wrong order, or one of them went missing" - ) - } - } - - @Test - fun `two posts signed in the same second resolve the same way on every device`() { - // Two devices reading the same posts in whatever order the query hands them - // over have to show the same feed. A tie on the timestamp breaks on the id, - // which both agree on because it is a hash of the event. - val one = signed("One", createdAt = 1_700_000_000) - val other = signed("Other", createdAt = 1_700_000_000) - - val expected = GroupPost.newestFirstAmong(listOf(one, other), chatRoomId).map { it.content } - - assertEquals( - expected, - GroupPost.newestFirstAmong(listOf(other, one), chatRoomId).map { it.content }, - "a tie on the timestamp was broken differently by the two orderings" - ) - assertEquals( - if (one.id > other.id) listOf("One", "Other") else listOf("Other", "One"), - expected, - "the tie should break on the id, which is the only thing both devices share" - ) - } - - @Test - fun `a blank post is dropped rather than drawn as an empty card`() { - // The composer will not produce one, so anything reaching here empty came - // from somewhere this app does not control -- and an empty signed card - // cannot be told from a broken one. - listOf("", " ", "\n\n").forEach { blank -> - assertEquals( - emptyList(), - GroupPost.newestFirstAmong(listOf(signed(blank)), chatRoomId), - "a post saying \"$blank\" was shown" - ) - } - } - - @Test - fun `a reply is marked as one`() { - // Nothing here writes replies, so this is about an event that arrived some - // other way. Drawing one as an announcement would put half a conversation on - // a group's page with no sign that it was half. - val reply = GroupPost.of( - signedEvent = signed( - "Yes, agreed.", - tags = arrayOf(arrayOf("e", "b".repeat(64), "", "reply")) - ), - chatRoomId = chatRoomId - ) - - assertFalse(reply?.isNewThread() == true) - } - - @Test - fun `the composer builds a bare note and trims it`() { - // No reply tags, no mentions, no subject: every tag `TextNoteEvent.build` - // can add describes a relationship to something else, which a group's first - // way of posting does not have and should not guess at. - val template = GroupPost.template(" Something the group would say. ") - - assertEquals(TextNoteEvent.KIND, template.kind) - assertEquals("Something the group would say.", template.content) - assertEquals(emptyList(), template.tags.toList()) - } - - @Test - fun `a post the composer built reads back as the group said it`() { - val template = GroupPost.template("We have finished the first chapter.") - val post = GroupPost.of( - signedEvent = signed(template.content, tags = template.tags), - chatRoomId = chatRoomId - ) - - assertEquals("We have finished the first chapter.", post?.content) - assertTrue(post?.isNewThread() == true) - } - - /** A post as `FrostSigningManager.complete` files one. */ - private fun signed( - note: String, - tags: Array> = emptyArray(), - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = noteEvent(note, tags, createdAt, material, signer, signature), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun noteEvent( - note: String, - tags: Array> = emptyArray(), - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = TextNoteEvent.KIND, - tags = tags, - content = note - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = TextNoteEvent.KIND, - tags = tags, - content = note, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt deleted file mode 100644 index 22ed566e..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt +++ /dev/null @@ -1,398 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What a group's relay lists are allowed to be read out of, and what an edit - * produces. - * - * The reading half is `GroupNostrProfileTest`'s again -- the room has to be the - * author, the signature has to be the room's -- and it is repeated here because - * these are four different kinds through two different tag vocabularies, and a - * mistake in any one of them would be invisible in the other three. - * - * The writing half is the one that could not be settled by reading the code. - * NIP-65's markers are absent for both, `read` for read-only and `write` for - * write-only, so the tag for the ordinary case is the one with the least in it -- - * exactly the shape a round trip is most likely to lose. And "neither" is a state - * the format cannot express at all, which is why the editor refuses it and why - * building one drops it rather than writing a tag that means the opposite. - */ -class GroupRelayListTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the lists signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - @Test - fun `every set round trips through the tags it is written in`() { - // Four kinds and two tag vocabularies: NIP-65's "r" for General and the - // "relay" tag for the other three, through two RelayTag classes that are - // different classes in different packages. A set wired to the wrong one - // writes tags nothing reads back. - GroupRelaySet.entries.forEach { set -> - val relays = listOf(GroupRelay(one), GroupRelay(two)) - val list = GroupRelayList.of( - signedEvent = signed(set.template(relays)), - chatRoomId = chatRoomId, - set = set - ) - - assertEquals( - listOf(one, two), - list?.relays?.map { it.url }, - "${set.name} did not round trip through its own tags" - ) - } - } - - @Test - fun `a relay list only reads back as the set it was written as`() { - // The kinds are the only thing separating a general list from a blocked - // one, and reading a blocked list as a general one would have the group - // publishing to the relays it refuses to talk to. - val blocked = signed(GroupRelaySet.Blocked.template(listOf(GroupRelay(one)))) - - assertNull(GroupRelayList.of(blocked, chatRoomId, GroupRelaySet.General)) - assertNull(GroupRelayList.of(blocked, chatRoomId, GroupRelaySet.Search)) - assertEquals( - listOf(one), - GroupRelayList.of(blocked, chatRoomId, GroupRelaySet.Blocked)?.relays?.map { it.url } - ) - } - - @Test - fun `read and write markers survive being written and read`() { - // The ordinary case is the dangerous one: NIP-65 writes both by *omitting* - // the marker, so a round trip that lost the third element entirely would - // still look correct for a both-ways relay and would silently turn a - // read-only relay into a write one. - val relays = listOf( - GroupRelay(one, read = true, write = true), - GroupRelay(two, read = true, write = false), - GroupRelay(RelayUrlNormalizer.normalize("wss://relay.three.example"), - read = false, write = true), - ) - - val readBack = GroupRelayList.of( - signedEvent = signed(GroupRelaySet.General.template(relays)), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ) - - assertEquals(relays, readBack?.relays) - } - - @Test - fun `a relay that is neither read nor write is not written at all`() { - // NIP-65 has no marker for it. The editor will not produce the state, and - // this is the second line of that defence: writing a bare `r` tag would - // advertise it as both, which is the opposite of what was asked. - val list = GroupRelayList.of( - signedEvent = signed( - GroupRelaySet.General.template( - listOf( - GroupRelay(one, read = false, write = false), - GroupRelay(two), - ) - ) - ), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ) - - assertEquals(listOf(two), list?.relays?.map { it.url }) - } - - @Test - fun `a relay list another group signed is not this group's`() { - val stranger = GroupSignedEvent.fromEvent( - event = relayEvent( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - material = strangerMaterial - ), - chatRoomId = chatRoomId - ) - - assertNull(GroupRelayList.of(stranger, chatRoomId, GroupRelaySet.General)) - } - - @Test - fun `a relay list the room did not sign is not a relay list`() { - // Authored by the room and signed by somebody else -- the shape a member - // redirecting a group's traffic would produce. - assertNull( - GroupRelayList.of( - signedEvent = signed( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - signer = strangerMaterial - ), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ) - ) - - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupRelayList.of( - signedEvent = signed( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - signature = rubbish - ), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ), - "a list signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `a set the group never agreed reads back unsigned and empty`() { - // Not null. The screen has a row per set whatever the group has said, and - // `isAgreed` is what separates "never said" from "said nothing". - val list = GroupRelayList.newestAmong(emptyList(), chatRoomId, GroupRelaySet.Search) - - assertFalse(list.isAgreed) - assertEquals(emptyList(), list.relays) - assertEquals(GroupRelaySet.Search, list.set) - assertNull(list.signedAt) - } - - @Test - fun `an agreed empty list is not the same as one never agreed`() { - // A group withdrawing its relay list signs an empty one, and that decision - // has to survive being read back -- otherwise a deliberate withdrawal looks - // exactly like never having got round to it. - val list = GroupRelayList.of( - signedEvent = signed(GroupRelaySet.Messages.template(emptyList())), - chatRoomId = chatRoomId, - set = GroupRelaySet.Messages - ) - - assertTrue(list?.isAgreed == true) - assertEquals(emptyList(), list?.relays) - } - - @Test - fun `the newest list the group signed is the one that counts`() { - val older = signed( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - createdAt = 1_700_000_000 - ) - val newer = signed( - GroupRelaySet.General.template(listOf(GroupRelay(two))), - createdAt = 1_700_000_900 - ) - - listOf(listOf(older, newer), listOf(newer, older)).forEach { events -> - assertEquals( - listOf(two), - GroupRelayList.newestAmong(events, chatRoomId, GroupRelaySet.General) - .relays.map { it.url }, - "the newest relay list lost to query order" - ) - } - } - - @Test - fun `allAmong sorts every set into one entry each`() { - val events = listOf( - signed(GroupRelaySet.General.template(listOf(GroupRelay(one)))), - signed(GroupRelaySet.Blocked.template(listOf(GroupRelay(two)))), - ) - - val all = GroupRelayList.allAmong(events, chatRoomId) - - assertEquals(GroupRelaySet.entries.toList(), all.map { it.set }) - assertEquals(listOf(one), all.first { it.set == GroupRelaySet.General }.relays.map { it.url }) - assertEquals(listOf(two), all.first { it.set == GroupRelaySet.Blocked }.relays.map { it.url }) - assertFalse(all.first { it.set == GroupRelaySet.Search }.isAgreed) - assertFalse(all.first { it.set == GroupRelaySet.Messages }.isAgreed) - } - - @Test - fun `every set but blocked starts at the app's own relay`() { - // What a group setting up for the first time is shown. Seeding with nothing - // would make its first proposal an empty list, which says less than never - // having said anything. - GroupRelaySet.entries.filterNot { it == GroupRelaySet.Blocked }.forEach { set -> - assertEquals( - listOf(Relays.ephemeral), - set.defaults().map { it.url }, - "${set.name} did not default to the app's relay" - ) - } - - // And blocked starts empty: a default there is a refusal to talk to - // somebody that nobody in the group chose. - assertEquals(emptyList(), GroupRelaySet.Blocked.defaults()) - } - - @Test - fun `only a wss relay somewhere other than this device is accepted`() { - assertEquals(one, GroupRelaySet.relayUrlOrNull("wss://relay.one.example")) - assertEquals(one, GroupRelaySet.relayUrlOrNull(" wss://relay.one.example ")) - - // A group's list is read by strangers over the open network: ws:// asks - // them to fetch it in the clear, and loopback names a relay only one device - // can reach. - listOf( - "ws://relay.one.example", - "http://relay.one.example", - "relay.one.example", - "wss://localhost", - "wss://127.0.0.1", - "", - ).forEach { - assertNull(GroupRelaySet.relayUrlOrNull(it), "\"$it\" was accepted as a relay") - } - } - - @Test - fun `a duplicated relay is read once`() { - // Two tags for one relay is one relay said twice, and a list that shows it - // twice reads as two to a human -- the same reasoning a birth certificate's - // admin roster is deduplicated on. - val duplicated = Event( - id = "", - pubKey = chatRoomId, - createdAt = 1_700_000_000, - kind = AdvertisedRelayListEvent.KIND, - tags = arrayOf(arrayOf("r", one.url), arrayOf("r", one.url, "read")), - content = "", - sig = "" - ) - - assertEquals(listOf(one), GroupRelaySet.General.parse(duplicated.tags).map { it.url }) - } - - /** A relay list as `FrostSigningManager.complete` files one. */ - private fun signed( - template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate<*>, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = relayEvent(template, createdAt, material, signer, signature), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun relayEvent( - template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate<*>, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt index a53528c4..39f48fa2 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt @@ -11,8 +11,8 @@ import com.vitorpamplona.quartz.nip01Core.tags.people.PTag import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent +import com.machankura.bennu.compose.nostr.chronicle.TEST_KINDS +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -52,6 +52,10 @@ class MarmotPayloadBoundsTest { count = 1, recipient = recipient, createdAt = at, + // The app's own list carries nothing at the moment, so the page is + // built over the chronicle tests' list: what is under test is the + // envelope's size, not which kinds fill it. + kinds = TEST_KINDS, ) // From the template's fields, as the outbound queue assembles every rumor from // the row's: the typed template is not what goes through RumorAssembler. @@ -74,7 +78,7 @@ class MarmotPayloadBoundsTest { @Test fun `a chronicle page of the most smallest payloads is a conformant app event`() { val payloads = (0 until ChronicleEvent.MAX_PAGE_EVENTS).map { - signedPayload(DialectEvent.KIND, content = "d", id = it.toString().padStart(64, '0')) + signedPayload(TextNoteEvent.KIND, content = "d", id = it.toString().padStart(64, '0')) } assertConformant(chronicleAppEvent(payloads)) @@ -90,7 +94,7 @@ class MarmotPayloadBoundsTest { while (length < 4_096) append("{\"k\":\"v\",\"n\":[\"a\",\"b\"]}") } val payloads = (0 until ChronicleEvent.MAX_PAGE_EVENTS).map { - signedPayload(ChunkEvent.KIND, content = dense, id = it.toString().padStart(64, '0')) + signedPayload(TextNoteEvent.KIND, content = dense, id = it.toString().padStart(64, '0')) } // As many dense payloads as the byte cap admits, measured the way the packer // measures them: by the bytes the page occupies once escaped into the app diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt index 22542fb3..bb56ec7d 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt @@ -14,19 +14,10 @@ import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleRecipientTag import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent /** * The envelope a chronicle travels in: what it carries, what it refuses, and the @@ -35,6 +26,10 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent * Nothing here verifies a signature -- that is `GroupKeyStateTest`'s half, and * `ChronicleManager`'s at apply time. What these cover is the framing, and the two * bounds a page has to hold whoever sent it. + * + * The app's own list of kinds is empty, so what a chronicle may carry and the + * order it applies in are tested against [TEST_KINDS]; the framing and the caps + * do not care what kind a payload is. */ class ChronicleEventTest { private val recipient = "d".repeat(64) @@ -59,8 +54,8 @@ class ChronicleEventTest { @Test fun `what is encoded is what comes back whole`() { val events = listOf( - payload(DialectEvent.KIND, "isiZulu"), - payload(ArtifactEvent.KIND, "an artifact"), + payload(MetadataEvent.KIND, "{\"name\":\"Ekklesia\"}"), + payload(TextNoteEvent.KIND, "a post"), ) val decoded = ChronicleEvent.decodePage(ChronicleEvent.encodePage(events)) @@ -81,7 +76,7 @@ class ChronicleEventTest { // object for a batch of one so that builds predating batching can read // it. Both chronicle kinds are new, so there is no such build and no reason // to carry the second shape. - val encoded = ChronicleEvent.encodePage(listOf(payload(DialectEvent.KIND))) + val encoded = ChronicleEvent.encodePage(listOf(payload(TextNoteEvent.KIND))) assertTrue(encoded.startsWith("["), "a page is always an array") assertTrue(encoded.endsWith("]")) @@ -90,7 +85,7 @@ class ChronicleEventTest { @Test fun `a page that is not an array is not a page`() { - assertNull(ChronicleEvent.decodePage(payload(DialectEvent.KIND).toJson())) + assertNull(ChronicleEvent.decodePage(payload(TextNoteEvent.KIND).toJson())) assertNull(ChronicleEvent.decodePage("")) assertNull(ChronicleEvent.decodePage("not json")) assertNull(ChronicleEvent.decodePage("[unclosed")) @@ -110,7 +105,7 @@ class ChronicleEventTest { // whose signature does not verify is a well-framed page with one bad // event in it, and dropping its honest neighbours would let one forgery // deny an entire chronicle. - val good = payload(DialectEvent.KIND) + val good = payload(TextNoteEvent.KIND) assertNull(ChronicleEvent.decodePage("[${good.toJson()},\"not an event\"]")) assertNull(ChronicleEvent.decodePage("[\"not an event\",${good.toJson()}]")) @@ -121,7 +116,7 @@ class ChronicleEventTest { @Test fun `a page over the event cap is refused on the way in`() { val overCap = (0..ChronicleEvent.MAX_PAGE_EVENTS).map { - payload(DialectEvent.KIND, id = it.toString().padStart(64, '0')) + payload(TextNoteEvent.KIND, id = it.toString().padStart(64, '0')) } assertEquals(ChronicleEvent.MAX_PAGE_EVENTS + 1, overCap.size) @@ -139,7 +134,7 @@ class ChronicleEventTest { // runs, and the page-over-the-cap test above passes for the wrong reason. // Both caps have to be re-sized together; this is what says so. val atCap = (0 until ChronicleEvent.MAX_PAGE_EVENTS).map { - payload(DialectEvent.KIND, id = it.toString().padStart(64, '0')) + payload(TextNoteEvent.KIND, id = it.toString().padStart(64, '0')) } val page = ChronicleEvent.encodePage(atCap) @@ -157,7 +152,7 @@ class ChronicleEventTest { // work a remote party can ask this device to do. A chronicle is the second // place in this protocol where somebody else sets that size. val huge = ChronicleEvent.encodePage( - listOf(payload(DialectEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES))) + listOf(payload(TextNoteEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES))) ) assertTrue(huge.encodeToByteArray().size > ChronicleEvent.MAX_PAGE_BYTES) @@ -170,7 +165,7 @@ class ChronicleEventTest { // this were measured in characters the cap would let through up to four // times what it says. val wide = "世".repeat(ChronicleEvent.MAX_PAGE_BYTES / 2) - val page = ChronicleEvent.encodePage(listOf(payload(DialectEvent.KIND, content = wide))) + val page = ChronicleEvent.encodePage(listOf(payload(TextNoteEvent.KIND, content = wide))) assertTrue(page.length < ChronicleEvent.MAX_PAGE_BYTES) assertTrue(page.encodeToByteArray().size > ChronicleEvent.MAX_PAGE_BYTES) @@ -180,42 +175,24 @@ class ChronicleEventTest { // ---- What a chronicle may carry --------------------------------------- @Test - fun `the allowlist is every kind the group signs and only those`() { + fun `a kind set admits what it lists and nothing else`() { listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ArtifactVersionEvent.KIND, - ChapterEvent.KIND, - ChunkEvent.KIND, - TranslationArtifactVersionEvent.KIND, - TranslationChapterEvent.KIND, - TranslationChunkEvent.KIND, - ).forEach { assertTrue(ChronicleEvent.isChroniclable(it), "kind $it should be chroniclable") } + AdvertisedRelayListEvent.KIND, + MetadataEvent.KIND, + TextNoteEvent.KIND, + ).forEach { assertTrue(TEST_KINDS.isChroniclable(it), "kind $it should be chroniclable") } - assertEquals(8, ChronicleEvent.CHRONICLABLE_KINDS.size) - } + assertEquals(3, TEST_KINDS.all.size) + assertFalse(TEST_KINDS.isEmpty()) - @Test - fun `the translated text is chroniclable now that the group signs it`() { - // Worth its own case because it was the feature's headline limitation for - // as long as `saveTranslation` wrote the row and queued the member's own - // rumor. A chronicle can only carry what the receiver can check, so a - // translation nobody signed could not travel, and a new member got the - // whole structure and none of the prose. - assertTrue(ChronicleEvent.isChroniclable(TranslationChunkEvent.KIND)) + // Group-signed, with an arm in applyInnerEvent, and still refused: being + // signed is not what earns a kind its place, being on the list is. + assertFalse(TEST_KINDS.isChroniclable(GroupWalletStatementEvent.KIND)) + assertNull(TEST_KINDS.applyRank(GroupWalletStatementEvent.KIND)) - // Same shape, same fix: the version an artifact starts life with used to - // be derived on arrival, so it was authored by the group with no - // signature to show for it. It is the second item of the artifact's batch - // now. - assertTrue(ChronicleEvent.isChroniclable(ArtifactVersionEvent.KIND)) - } - - @Test - fun `the kinds nobody signs are still left out`() { - // Nothing builds one of these at all; the inbound arm exists and no - // producer does. - assertFalse(ChronicleEvent.isChroniclable(TranslationEvent.KIND)) + // And the empty list admits nothing at all. + assertTrue(ChronicleKinds.NONE.isEmpty()) + assertFalse(ChronicleKinds.NONE.isChroniclable(TextNoteEvent.KIND)) } @Test @@ -226,7 +203,8 @@ class ChronicleEventTest { // validly signed statement about what the room signs with, replayed by // whoever kept a copy. Nothing but this stops it. assertFalse(ChronicleEvent.isChroniclable(GroupKeyStateEvent.KIND)) - assertNull(ChronicleEvent.applyRank(GroupKeyStateEvent.KIND)) + assertFalse(TEST_KINDS.isChroniclable(GroupKeyStateEvent.KIND)) + assertNull(TEST_KINDS.applyRank(GroupKeyStateEvent.KIND)) } @Test @@ -244,12 +222,14 @@ class ChronicleEventTest { // chronicle may carry an event its own key did not sign, which no // chroniclable kind does. See docs/subgroups.md. assertFalse(ChronicleEvent.isChroniclable(SubgroupBirthCertificateEvent.KIND)) - assertNull(ChronicleEvent.applyRank(SubgroupBirthCertificateEvent.KIND)) + assertFalse(TEST_KINDS.isChroniclable(SubgroupBirthCertificateEvent.KIND)) + assertNull(TEST_KINDS.applyRank(SubgroupBirthCertificateEvent.KIND)) } @Test - fun `a chronicle carries documents not envelopes or protocol`() { - assertFalse(ChronicleEvent.isChroniclable(SubmissionEvent.KIND)) + fun `a chronicle carries the group's work not envelopes or protocol`() { + // Against the app's own list, which is the one that will grow: the day a + // kind is added back, none of these may come with it. assertFalse(ChronicleEvent.isChroniclable(ChronicleEvent.KIND)) assertFalse(ChronicleEvent.isChroniclable(ChronicleRequestEvent.KIND)) FrostSigningEvents.ALL.forEach { @@ -257,86 +237,57 @@ class ChronicleEventTest { } } - @Test - fun `the contributor lists are left out while nothing applies them`() { - // Not an oversight. ChatMessage.applyInnerEvent has no arm that writes a - // row for any of these, so chronicling them would cost bytes and restore - // nothing. They belong in the list on the day that changes. - assertFalse(ChronicleEvent.isChroniclable(TranslationArtifactVersionContributorListEvent.KIND)) - assertFalse(ChronicleEvent.isChroniclable(TranslationChapterContributorListEvent.KIND)) - assertFalse(ChronicleEvent.isChroniclable(TranslationContributorListEvent.KIND)) - } - // ---- Dependency order ------------------------------------------------ @Test - fun `the order is the foreign keys not the kind numbers`() { - fun rank(kind: Int) = assertNotNull(ChronicleEvent.applyRank(kind), "kind $kind has no rank") + fun `the order is the list's not the kind numbers'`() { + fun rank(kind: Int) = assertNotNull(TEST_KINDS.applyRank(kind), "kind $kind has no rank") - // Every one of these is a foreign key in Room, so a chronicle applied the - // other way round is a constraint violation rather than a wrong answer. - assertTrue(rank(DialectEvent.KIND) < rank(ArtifactEvent.KIND)) - assertTrue(rank(ArtifactEvent.KIND) < rank(ArtifactVersionEvent.KIND)) - assertTrue(rank(ArtifactVersionEvent.KIND) < rank(ChapterEvent.KIND)) - assertTrue(rank(ChapterEvent.KIND) < rank(ChunkEvent.KIND)) - assertTrue(rank(ArtifactVersionEvent.KIND) < rank(TranslationArtifactVersionEvent.KIND)) - assertTrue(rank(DialectEvent.KIND) < rank(TranslationArtifactVersionEvent.KIND)) - assertTrue(rank(TranslationArtifactVersionEvent.KIND) < rank(TranslationChapterEvent.KIND)) - assertTrue(rank(ChapterEvent.KIND) < rank(TranslationChapterEvent.KIND)) - - // A translated chunk hangs off both sides at once -- the source chunk it - // translates and the translation chapter it sits in -- so it is last. - assertTrue(rank(ChunkEvent.KIND) < rank(TranslationChunkEvent.KIND)) - assertTrue(rank(TranslationChapterEvent.KIND) < rank(TranslationChunkEvent.KIND)) + // In the app the list is the database's foreign keys, so a chronicle + // applied the other way round is a constraint violation rather than a + // wrong answer. Here it is only the test's own order, which is enough to + // show the machinery follows the list. + assertTrue(rank(AdvertisedRelayListEvent.KIND) < rank(MetadataEvent.KIND)) + assertTrue(rank(MetadataEvent.KIND) < rank(TextNoteEvent.KIND)) // And the numbers really do disagree with the order, which is why this is // a list rather than a sortedBy { kind }. - assertTrue(DialectEvent.KIND > ArtifactEvent.KIND) - assertTrue(rank(DialectEvent.KIND) < rank(ArtifactEvent.KIND)) + assertTrue(AdvertisedRelayListEvent.KIND > MetadataEvent.KIND) + assertTrue(rank(AdvertisedRelayListEvent.KIND) < rank(MetadataEvent.KIND)) } @Test - fun `sorting a page puts what is referenced before what refers to it`() { + fun `sorting a page puts it in the list's order`() { val jumbled = listOf( - payload(TranslationChunkEvent.KIND), - payload(TranslationChapterEvent.KIND), - payload(ChunkEvent.KIND), - payload(DialectEvent.KIND), - payload(TranslationArtifactVersionEvent.KIND), - payload(ChapterEvent.KIND), - payload(ArtifactVersionEvent.KIND), - payload(ArtifactEvent.KIND), + payload(TextNoteEvent.KIND), + payload(MetadataEvent.KIND), + payload(AdvertisedRelayListEvent.KIND), ) assertEquals( listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ArtifactVersionEvent.KIND, - ChapterEvent.KIND, - ChunkEvent.KIND, - TranslationArtifactVersionEvent.KIND, - TranslationChapterEvent.KIND, - TranslationChunkEvent.KIND, + AdvertisedRelayListEvent.KIND, + MetadataEvent.KIND, + TextNoteEvent.KIND, ), - ChronicleEvent.inApplyOrder(jumbled).map { it.kind } + TEST_KINDS.inApplyOrder(jumbled).map { it.kind } ) } @Test fun `two of a kind keep the order they were handed in`() { - // Nothing orders two chapters of one version, and keeping the caller's - // order is one less thing that differs between two members assembling the - // same chronicle. - val chapters = listOf( - payload(ChapterEvent.KIND, "one", id = "1".repeat(64)), - payload(ChapterEvent.KIND, "two", id = "2".repeat(64)), - payload(ChapterEvent.KIND, "three", id = "3".repeat(64)), + // Nothing orders two posts by the group, and keeping the caller's order + // is one less thing that differs between two members assembling the same + // chronicle. + val posts = listOf( + payload(TextNoteEvent.KIND, "one", id = "1".repeat(64)), + payload(TextNoteEvent.KIND, "two", id = "2".repeat(64)), + payload(TextNoteEvent.KIND, "three", id = "3".repeat(64)), ) assertEquals( listOf("one", "two", "three"), - ChronicleEvent.inApplyOrder(chapters).map { it.content } + TEST_KINDS.inApplyOrder(posts).map { it.content } ) } @@ -345,12 +296,13 @@ class ChronicleEventTest { @Test fun `a page says which chronicle it is where in it and who for`() { val template = ChronicleEvent.build( - payloads = listOf(payload(DialectEvent.KIND)), + payloads = listOf(payload(TextNoteEvent.KIND)), chronicleId = chronicleId, index = 2, count = 5, recipient = recipient, - createdAt = 1_700_000_100L + createdAt = 1_700_000_100L, + kinds = TEST_KINDS, ) val readBack = ChronicleEvent( @@ -406,17 +358,18 @@ class ChronicleEventTest { // security -- the inbound one is the boundary -- but a page nobody can // read back is better failed where it was made. assertFailsWith { - ChronicleEvent.build(emptyList(), chronicleId, 0, 1, recipient) + ChronicleEvent.build(emptyList(), chronicleId, 0, 1, recipient, kinds = TEST_KINDS) } assertFailsWith { ChronicleEvent.build( payloads = (0..ChronicleEvent.MAX_PAGE_EVENTS).map { - payload(DialectEvent.KIND, id = it.toString().padStart(64, '0')) + payload(TextNoteEvent.KIND, id = it.toString().padStart(64, '0')) }, chronicleId = chronicleId, index = 0, count = 1, - recipient = recipient + recipient = recipient, + kinds = TEST_KINDS, ) } assertFailsWith { @@ -425,18 +378,36 @@ class ChronicleEventTest { chronicleId = chronicleId, index = 0, count = 1, - recipient = recipient + recipient = recipient, + kinds = TEST_KINDS, ) } assertFailsWith { ChronicleEvent.build( payloads = listOf( - payload(DialectEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES)) + payload(TextNoteEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES)) ), chronicleId = chronicleId, index = 0, count = 1, - recipient = recipient + recipient = recipient, + kinds = TEST_KINDS, + ) + } + } + + @Test + fun `the app's own list builds no page at all`() { + // The outbound half of the app carrying nothing: a payload the test list + // admits is refused under the default, so nothing that assembles a page + // without naming its kinds can put one on the wire. + assertFailsWith { + ChronicleEvent.build( + payloads = listOf(payload(TextNoteEvent.KIND)), + chronicleId = chronicleId, + index = 0, + count = 1, + recipient = recipient, ) } } diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleRoundTripTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleRoundTripTest.kt deleted file mode 100644 index 78e88c4c..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleRoundTripTest.kt +++ /dev/null @@ -1,422 +0,0 @@ -package com.machankura.bennu.compose.nostr.chronicle - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChunk -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent - -/** - * The assumption the chronicle's *fallback* rests on: a row can be turned back - * into the event the group signed. - * - * Signed events used to be stored only as rows. `FrostSigningManager.complete` - * applied one and what survived was a `Mantra*` row, so a chronicle had to - * rebuild each payload with `toXEvent()` and hope it came out byte-identical -- - * and if it did not, the id changed, the signature no longer covered it, and - * every receiver dropped the payload as a forgery, silently, one kind at a time. - * - * That is what the round-trip note on each `toXEvent` claims and what nothing - * asserted until this ran. Every kind in `ChronicleEvent.CHRONICLABLE_KINDS` is - * checked here against a real FROST quorum, because a signature that verifies is - * the only evidence that the rebuild is faithful -- comparing fields would only - * prove the test and the code agree about which fields matter. - * - * ### Deprecated, along with what it guards - * - * `GroupSignedEvent` keeps the events now, and `ChronicleManager.assemble` reads - * them; the rebuild survives only for work signed before that table existed, and - * so does this. Nothing else covers the `toXEvent()` methods, so **this whole - * file goes when they do** -- see "Retiring the rebuild" in - * docs/member-chronicle.md. Until then a kind that fails here cannot be chronicled - * *from a row*, whatever the allowlist says, which for a pre-v13 room is the - * same thing as not at all. - */ -class ChronicleRoundTripTest { - private val participants = 3 - private val threshold = 2 - - /** Stands in for a completed ceremony; nothing here is about the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val room: SharedKeyDerivation.Derived = SharedKeyDerivation.derive( - thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex(), - path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - ) - - private val tweakCache: TweakCache = room.cache - - /** The group's identity, which is also the room's id. */ - private val chatRoomId = room.hex - - private val dialectId = "b".repeat(64) - private val artifactVersionId = "c".repeat(64) - private val chapterId = "d".repeat(64) - private val translationArtifactVersionId = "e".repeat(64) - private val translationChapterId = "f".repeat(64) - private val chunkId = "a".repeat(64) - - /** Exactly what `FrostSigningManager.unsignedEventOf` does. */ - private fun unsignedEventOf(template: EventTemplate<*>) = Event( - id = EventHasher.hashId( - pubKey = chatRoomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = chatRoomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - - /** A real quorum signing [eventId], in the manager's order. */ - private fun groupSignature(eventId: String): String { - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = keyMaterial.secretShares[signerId], - publicShare = keyMaterial.publicShares[signerId], - tweakedThresholdPublicKey = tweakCache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { keyMaterial.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = tweakCache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - keyMaterial.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } - - /** A template, signed by the group, the way a finished session leaves one. */ - private fun signed(template: EventTemplate<*>): Event { - val unsigned = unsignedEventOf(template) - - return Event( - id = unsigned.id, - pubKey = unsigned.pubKey, - createdAt = unsigned.createdAt, - kind = unsigned.kind, - tags = unsigned.tags, - content = unsigned.content, - sig = groupSignature(unsigned.id) - ) - } - - /** - * The claim, for one kind: sign it, file it as a row, rebuild it from the - * row, and the group's signature still covers what comes out. - */ - private fun assertRoundTrips(template: EventTemplate<*>, rebuild: (Event) -> Event?) { - val signedEvent = signed(template) - assertTrue( - GroupKeyStateEvent.isSignedByRoom(signedEvent, chatRoomId), - "the harness itself must produce a verifiable event" - ) - - val rebuilt = assertNotNull( - rebuild(signedEvent), - "kind ${template.kind} did not survive being turned into a row" - ) - - // Asserted before the signature so a failure says which half broke: an id - // that moved means the tag order or a field changed in the rebuild, where - // a signature that fails on a matching id would mean something stranger. - assertEquals( - signedEvent.id, - rebuilt.id, - "kind ${template.kind} came back with a different id" - ) - assertEquals( - signedEvent.sig, - rebuilt.sig, - "kind ${template.kind} lost the group's signature" - ) - assertTrue( - GroupKeyStateEvent.isSignedByRoom(rebuilt, chatRoomId), - "kind ${template.kind} rebuilt into something the group's signature does not cover" - ) - } - - @Test - fun `a dialect survives the trip through a row`() { - assertRoundTrips( - DialectEvent.build( - name = "isiZulu", - country = "ZA", - language = "zu", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraDialect.fromDialectEvent( - DialectEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toDialectEvent() - } - } - - @Test - fun `an artifact survives the trip through a row`() { - // The one that did not, when this test was written. Two faults, and the - // second is the interesting one: `toArtifactEvent` put the alt tag last - // where `build` puts it first, and it left out the version metadata - // entirely -- because that tag is not on the row at all. It is consumed - // into the artifact's first MantraArtifactVersion and dropped. So the - // label has to come back from there, which is why it is a parameter. - assertRoundTrips( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraArtifact.fromArtifactEvent( - ArtifactEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toArtifactEvent(versionLabel = "1.0") - } - } - - @Test - fun `an artifact rebuilt with the wrong version label is not the one that was signed`() { - // What the parameter costs if a caller guesses. The label was part of - // what the group put its signature to, so a rebuild carrying a different - // one is a different event -- and it fails as a forgery rather than as a - // mistake, which is why the assembler reads it off the initial version - // rather than defaulting it. - val signedEvent = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - createdAt = 1_700_000_000L - ) - ) - - val rebuilt = MantraArtifact.fromArtifactEvent( - ArtifactEvent( - signedEvent.id, signedEvent.pubKey, signedEvent.createdAt, - signedEvent.tags, signedEvent.content, signedEvent.sig - ), - chatRoomId - )?.toArtifactEvent(versionLabel = "2.0") - - assertNotNull(rebuilt) - assertFalse(GroupKeyStateEvent.isSignedByRoom(rebuilt, chatRoomId)) - } - - @Test - fun `an artifact version survives the trip through a row`() { - // The second fault of the same shape, found the moment this kind became - // chroniclable: `toArtifactVersionEvent` emitted [artifactId, alt] where - // `build` emits [alt, artifactId]. It had been that way for as long as - // nothing called it, which is what makes an unused rebuild dangerous - // rather than merely dead -- the claim in its comment was never checked. - // - // Built through `initialVersionOf` rather than by hand, because that is - // what the signing batch actually proposes. - val artifact = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - createdAt = 1_700_000_000L - ) - ) - - assertRoundTrips( - ArtifactVersionEvent.initialVersionOf(artifact).single() - ) { event -> - MantraArtifactVersion.fromArtifactVersionEvent( - ArtifactVersionEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toArtifactVersionEvent() - } - } - - @Test - fun `a translated chunk survives the trip through a row`() { - // The translated text. Chroniclable only because the app stopped saving it - // as its author's rumor and started asking the group to sign it -- until - // then a new member got the whole structure and none of the prose. - assertRoundTrips( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = "Wayeyindoda enezingxenye.", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraTranslationChunk.fromTranslationChunkEvent( - TranslationChunkEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toTranslationChunkEvent() - } - } - - @Test - fun `a chapter survives the trip through a row`() { - assertRoundTrips( - ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = "Chapter One", - originalText = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_000L - ) - ) { event -> - MantraChapter.fromChapterEvent( - ChapterEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toChapterEvent() - } - } - - @Test - fun `a chunk survives the trip through a row`() { - assertRoundTrips( - ChunkEvent.build( - chapterId = chapterId, - text = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_000L - ) - ) { event -> - MantraChunk.fromChunkEvent( - ChunkEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toChunkEvent() - } - } - - @Test - fun `a translation artifact version survives the trip through a row`() { - assertRoundTrips( - TranslationArtifactVersionEvent.build( - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = "isiZulu", - visibility = "private", - license = "cc", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraTranslationArtifactVersion.fromTranslationArtifactVersionEvent( - TranslationArtifactVersionEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toTranslationArtifactVersionEvent() - } - } - - @Test - fun `a translation chapter survives the trip through a row`() { - assertRoundTrips( - TranslationChapterEvent.build( - translationArtifactVersionId = translationArtifactVersionId, - chapterId = chapterId, - index = 0, - createdAt = 1_700_000_000L - ) - ) { event -> - MantraTranslationChapter.fromTranslationChapterEvent( - TranslationChapterEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toTranslationChapterEvent() - } - } - - @Test - fun `every chroniclable kind has a round-trip test above`() { - // The list and this file have to move together. A kind added to the - // allowlist without a case here is one nobody has checked can be rebuilt, - // and the failure is silent: the receiver drops it as a forgery. - assertEquals( - 8, - ChronicleEvent.CHRONICLABLE_KINDS.size, - "a chroniclable kind was added or removed; add or remove its round-trip case" - ) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt new file mode 100644 index 00000000..7af91bf4 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt @@ -0,0 +1,34 @@ +package com.machankura.bennu.compose.nostr.chronicle + +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent + +/** + * The kinds the chronicle tests chronicle, in the order they apply. + * + * The app's own list, [ChronicleEvent.KINDS], is empty, so the machinery is + * exercised with this one instead. It is not a proposal for what the app should + * carry -- see [ChronicleEvent.KINDS] for why each of these is left out there. + * + * Chosen for three properties: + * + * - **none is a kind the app gives a meaning of its own** -- a profile and a + * relay list apply to nothing, and a kind:1 to the "unsupported" line it + * has always been -- so applying one neither throws nor writes a + * `GroupSignedEvent` of its own, and the `GroupSignedEvent` rows a receiver + * holds afterwards are exactly the ones the chronicle recorded: comparing + * those is comparing the work; + * - **the order disagrees with the kind numbers** (10002 before 0 before 1), + * so a test that the order is the list's cannot pass by sorting on kind. + * + * A key state and a birth certificate are deliberately not here: they are what + * the allowlist has to refuse, so they are what the tests try to replay. + */ +internal val TEST_KINDS: ChronicleKinds = ChronicleKinds( + listOf( + AdvertisedRelayListEvent.KIND, + MetadataEvent.KIND, + TextNoteEvent.KIND, + ) +) diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEventsTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEventsTest.kt index 23ba89e7..34008f26 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEventsTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningEventsTest.kt @@ -7,7 +7,12 @@ import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -26,7 +31,14 @@ class GroupLightningEventsTest { SubgroupBirthCertificateEvent.KIND, MarmotDirectMessage.ENVELOPE_KIND, GroupWalletStatementEvent.KIND, - ) + (30300..30312).toSet() // the nip30303 document kinds + // The guarded-wallet family, which took 30333-30337 while this one was being built under + // those numbers: the reason it moved. + GuardedWalletNoticeEvent.KIND, + MemberWalletCertificateEvent.KIND, + MemberWalletRequestEvent.KIND, + GroupKeyNoticeEvent.KIND, + MemberWalletPolicyEvent.KIND, + ) + (30300..30312).toSet() // the nip30303 document kinds, gone but not to be reused @Test fun `no lightning kind is a kind the app already routes`() { @@ -34,8 +46,13 @@ class GroupLightningEventsTest { } @Test - fun `the family is one unbroken run from 30333 to 30349`() { - assertEquals((30333..30349).toSet(), GroupLightningEvents.ALL) + fun `the family starts past every kind the app uses, so the next family can follow it`() { + assertTrue(GroupLightningEvents.ALL.min() > taken.max(), "a Lightning kind sits inside another family's range") + } + + @Test + fun `the family is one unbroken run from 30350 to 30366`() { + assertEquals((30350..30366).toSet(), GroupLightningEvents.ALL) } @Test diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactEventTest.kt deleted file mode 100644 index c9db7fc0..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/ArtifactEventTest.kt +++ /dev/null @@ -1,118 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNull -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionMetadataTag - -/** - * What the form collects has to reach the members deciding whether to sign it. - * - * An artifact proposal leaves the proposer's device as a kind, a tag array and - * a string, and everything a member is shown before signing -- and every row - * built afterwards -- is read back out of those. A field that does not survive - * the trip is not a visible failure: the artifact still appears, just without - * a url, or a source dialect, or a first version, on every device but the one - * that typed it. - */ -class ArtifactEventTest { - private val groupKey = "a".repeat(64) - private val dialectId = "b".repeat(64) - - /** The event a member actually receives: bytes, with no template behind it. */ - private fun readBack(template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate) = - ArtifactEvent( - id = EventHasher.hashId( - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - ), - pubKey = groupKey, - createdAt = template.createdAt, - tags = template.tags, - content = template.content, - sig = "c".repeat(128), - ) - - private fun proposal(versionLabel: String = "1.0") = ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = versionLabel, - createdAt = 1_700_000_000L, - ) - - @Test - fun `every field the form collects survives the trip through the tags`() { - val artifact = readBack(proposal()) - - assertEquals("In Detention", artifact.content) - assertEquals("https://example.com/in-detention", artifact.url()) - assertEquals("private", artifact.visibility()) - assertEquals("cc", artifact.license()) - assertEquals(dialectId, artifact.dialectId()) - assertEquals("1.0", artifact.versionLabel()) - } - - @Test - fun `the proposal is the artifact's kind so the signing screen can describe it`() { - // The session carries a kind and nothing else to go on. Get this wrong - // and members are asked to sign "event of kind 30300" -- a question - // nobody can answer. - assertEquals(ArtifactEvent.KIND, proposal().kind) - } - - @Test - fun `an artifact declares one version whatever an initializer adds`() { - // addUnique, not add: two labels would leave receivers deriving two - // different first versions depending on which one they read first. - val template = ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - ) { - addUnique(ArtifactVersionMetadataTag.assemble("2.0")) - } - - assertEquals( - 1, - template.tags.count { it.firstOrNull() == ArtifactVersionMetadataTag.TAG_NAME } - ) - } - - @Test - fun `an artifact from before the label existed reads back as declaring none`() { - // Not an error: it is what every artifact submitted the old way looks - // like, and they have to keep parsing rather than failing to load. - val template = proposal() - val older = Event( - id = "d".repeat(64), - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags - .filterNot { it.firstOrNull() == ArtifactVersionMetadataTag.TAG_NAME } - .toTypedArray(), - content = template.content, - sig = "", - ) - - val artifact = ArtifactEvent( - older.id, older.pubKey, older.createdAt, older.tags, older.content, older.sig - ) - - assertNull(artifact.versionLabel()) - // Everything else still reads, so the artifact itself is unharmed. - assertEquals(dialectId, artifact.dialectId()) - assertEquals("https://example.com/in-detention", artifact.url()) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChapterChunkSplitTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChapterChunkSplitTest.kt deleted file mode 100644 index 40e8990c..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/ChapterChunkSplitTest.kt +++ /dev/null @@ -1,196 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue -import com.machankura.bennu.compose.nostr.nip30303.tags.OriginalTextTag -import com.machankura.bennu.compose.text.Markdown - -/** - * The chunks a chapter is proposed with are cut from the chapter itself. - * - * A chapter and a chunk per paragraph go to the group as one batch, and the - * chunks can only be built once the chapter has been authored under the group's - * key — a chunk carries the chapter's id, and that id does not exist before - * then. So the split takes the unsigned chapter the session is about to sign - * and cuts from what it holds. - * - * What breaks quietly here is a chunk that names the wrong chapter, or none: - * every id in sight is opaque hex, the batch signs whatever it is handed, and - * the first sign of trouble is a chapter that arrives with no chunks under it - * because every one of them failed a foreign key on the way in. - */ -class ChapterChunkSplitTest { - private val groupKey = "a".repeat(64) - private val artifactVersionId = "b".repeat(64) - - private val twoParagraphs = "The first paragraph.\n\nThe second paragraph." - - /** - * The chapter as the session will sign it: the proposer's fields re-authored - * under the group's key, with the id computed from them. - */ - private fun unsignedChapter( - name: String = "Chapter 1", - originalText: String = twoParagraphs, - index: Int = 0, - createdAt: Long = 1_700_000_000, - ): Event { - val template = ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = name, - originalText = originalText, - index = index, - wordCount = Markdown.wordCount(originalText), - characterCount = Markdown.characterCount(originalText), - createdAt = createdAt, - ) - - return Event( - id = EventHasher.hashId( - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - } - - /** What a chunk template says once it is tags and a string, which is all it travels as. */ - private fun readBack(template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate) = - ChunkEvent( - id = EventHasher.hashId( - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = groupKey, - createdAt = template.createdAt, - tags = template.tags, - content = template.content, - sig = "" - ) - - @Test - fun `every chunk names the chapter it was cut from`() { - // The whole reason the split happens against the built chapter rather - // than against the form. A chunk naming anything else is a row that - // cannot be written. - val chapter = unsignedChapter() - - val chunks = ChunkEvent.splitOf(chapter).map(::readBack) - - assertEquals(2, chunks.size) - assertTrue(chunks.all { it.chapterId() == chapter.id }) - } - - @Test - fun `the chunks carry the chapter's text in order`() { - val chunks = ChunkEvent.splitOf(unsignedChapter()).map(::readBack) - - assertEquals(listOf("The first paragraph.", "The second paragraph."), chunks.map { it.content }) - assertEquals(listOf(0, 1), chunks.map { it.index() }) - } - - @Test - fun `each chunk counts its own paragraph rather than the chapter's`() { - // The chapter's counts describe the whole text. A chunk that inherited - // them would report every paragraph as the length of the chapter, and - // any progress measured per chunk would be wrong by that factor. - val chunks = ChunkEvent - .splitOf(unsignedChapter(originalText = "One two three.\n\nFour.")) - .map(::readBack) - - assertEquals(listOf(3, 1), chunks.map { it.wordCount() }) - assertEquals(listOf("One two three.".length, "Four.".length), chunks.map { it.characterCount() }) - } - - @Test - fun `the chunks are signed as of the chapter's own moment`() { - // Reading the clock here would put the batch's items minutes apart on a - // slow device, and a chapter signed at one time with chunks stamped at - // another is a batch that reads as two events that happened to share a - // session. - val chapter = unsignedChapter(createdAt = 1_700_000_000) - - val chunks = ChunkEvent.splitOf(chapter) - - assertTrue(chunks.all { it.createdAt == 1_700_000_000L }) - } - - @Test - fun `two identical paragraphs stay two chunks`() { - // Ids are content hashes, so repeated text is where two chunks would - // collide and the batch would carry one where the chapter has two. The - // position is in the event, which is what keeps them apart. - val chunks = ChunkEvent - .splitOf(unsignedChapter(originalText = "Again.\n\nAgain.")) - .map(::readBack) - - assertEquals(2, chunks.size) - assertNotEquals(chunks[0].id, chunks[1].id) - } - - @Test - fun `chapters that differ split into chunks that differ`() { - // Two chapters with the same words are two chapters, and their chunks - // belong to their own. Chunks of chapter three must not be chunks of - // chapter one. - val first = unsignedChapter(index = 0) - val second = unsignedChapter(index = 3) - - val firstChunks = ChunkEvent.splitOf(first).map(::readBack) - val secondChunks = ChunkEvent.splitOf(second).map(::readBack) - - assertNotEquals(first.id, second.id) - assertEquals(firstChunks.map { it.content }, secondChunks.map { it.content }) - assertNotEquals(firstChunks.map { it.id }, secondChunks.map { it.id }) - } - - @Test - fun `the split counts what the form counted`() { - // The screen shows a chunk count as the text is typed and refuses to - // propose past the batch cap on the strength of it. If the split - // disagreed with that count, the form would allow a batch the session - // then rejects -- or refuse one it would have taken. - val text = "One.\n\nTwo.\n\n\nThree.\n\n \n\nFour." - - assertEquals( - Markdown.splitParagraphs(text).size, - ChunkEvent.splitOf(unsignedChapter(originalText = text)).size - ) - } - - @Test - fun `a chapter with no text to split proposes no chunks`() { - assertEquals(emptyList(), ChunkEvent.splitOf(unsignedChapter(originalText = " "))) - - // And a chapter that declares no text at all, which is malformed rather - // than empty: nothing to split, and nothing to throw over either. - val declared = unsignedChapter() - val silent = Event( - id = declared.id, - pubKey = declared.pubKey, - createdAt = declared.createdAt, - kind = declared.kind, - tags = declared.tags.filterNot { it.firstOrNull() == OriginalTextTag.TAG_NAME } - .toTypedArray(), - content = declared.content, - sig = declared.sig - ) - - assertEquals(emptyList(), ChunkEvent.splitOf(silent)) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/InitialArtifactVersionTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/InitialArtifactVersionTest.kt deleted file mode 100644 index 7d9e7f40..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/InitialArtifactVersionTest.kt +++ /dev/null @@ -1,160 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue -import com.machankura.bennu.compose.nostr.nip30303.tags.ArtifactVersionMetadataTag - -/** - * The version an artifact starts life with, built to be signed beside it. - * - * It used to be derived on arrival from the label the artifact carries, because - * proposing it on its own would have cost a second quorum for one form. A batch - * costs one quorum, so it is signed now -- and a chapter hangs off this row, - * which is the reason to care: a version nobody signed is a parent vouched for - * by its own signed children rather than the other way round. - * - * What has to hold is that every input comes off the artifact. The id is not - * settled here -- the signing session hashes it under the group's key -- so an - * input read from anywhere else would not show up as a wrong row. It would show - * up as two devices proposing two different batches, which reads as a batch that - * simply never aggregates. - */ -class InitialArtifactVersionTest { - private val groupKey = "a".repeat(64) - private val dialectId = "b".repeat(64) - - /** - * The artifact as the session will sign it: the proposer's fields re-authored - * under the group's key. This is what `proposeSigningBatch` hands to - * `dependents`, so it is what the version has to be built from. - */ - private fun leadArtifact( - versionLabel: String = "1.0", - createdAt: Long = 1_700_000_000, - ): Event { - val template = ArtifactEvent.build( - name = "In Detention", - url = "example.com", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = versionLabel, - createdAt = createdAt, - ) - - return Event( - id = EventHasher.hashId( - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - } - - /** The version item as the session would author it, so the accessors read. */ - private fun versionOf(artifact: Event): ArtifactVersionEvent? = - ArtifactVersionEvent.initialVersionOf(artifact).singleOrNull()?.let { template -> - ArtifactVersionEvent( - id = EventHasher.hashId( - pubKey = groupKey, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = groupKey, - createdAt = template.createdAt, - tags = template.tags, - content = template.content, - sig = "" - ) - } - - @Test - fun `the version names the artifact it was built from`() { - // The whole reason this takes the lead event rather than a form's fields: - // the id it carries is a hash over the group's key at the room's path, so - // there is no artifact to name until the proposal has been authored. - val artifact = leadArtifact() - - assertEquals(artifact.id, versionOf(artifact)?.artifactId()) - } - - @Test - fun `it carries the label the artifact declared`() { - val artifact = leadArtifact(versionLabel = "First Edition") - - assertEquals("First Edition", versionOf(artifact)?.content) - } - - @Test - fun `it takes the artifact's own timestamp rather than the clock`() { - // So the batch reads as one act. Reading the clock here would agree with - // itself on one device and disagree between two that proposed the same - // artifact a second apart -- which is a batch nobody can aggregate, and - // the case nobody can reproduce on demand. - val artifact = leadArtifact(createdAt = 1_700_000_042) - - assertEquals(1_700_000_042, versionOf(artifact)?.createdAt) - } - - @Test - fun `an artifact declares exactly one first version`() { - // Item 0 is the artifact and item 1 is this, and a chapter hangs off - // whichever version it finds. Two would make that a coin toss. - assertEquals(1, ArtifactVersionEvent.initialVersionOf(leadArtifact()).size) - } - - @Test - fun `two devices build the same version from the same artifact`() { - // Every signer authors the batch itself and signs the ids it arrives at. - // Devices that disagree here produce partial signatures over different - // messages, and the session stalls rather than saying why. - val artifact = leadArtifact() - - assertEquals(versionOf(artifact)?.id, versionOf(artifact)?.id) - } - - @Test - fun `artifacts alike but for the label do not share a version`() { - // The label is bound into the id rather than hung beside it, so renaming - // a version cannot leave the row it replaces standing. - val first = versionOf(leadArtifact(versionLabel = "1.0")) - val second = versionOf(leadArtifact(versionLabel = "2.0")) - - assertNotEquals(first?.id, second?.id) - } - - @Test - fun `an artifact that declares no version proposes none`() { - // Artifacts written before the artifact carried its first version. The - // batch is then one item, which is what an artifact proposal used to be. - val declared = leadArtifact() - val silent = Event( - id = declared.id, - pubKey = declared.pubKey, - createdAt = declared.createdAt, - kind = declared.kind, - tags = declared.tags.filterNot { it.firstOrNull() == ArtifactVersionMetadataTag.TAG_NAME } - .toTypedArray(), - content = declared.content, - sig = declared.sig - ) - - assertTrue(ArtifactVersionEvent.initialVersionOf(silent).isEmpty()) - assertNull(versionOf(silent)) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/SubmissionEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/SubmissionEventTest.kt deleted file mode 100644 index 21149222..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/nip30303/SubmissionEventTest.kt +++ /dev/null @@ -1,126 +0,0 @@ -package com.machankura.bennu.compose.nostr.nip30303 - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotEquals -import kotlin.test.assertNull - -/** - * What a submission has to survive: the trip through a group. - * - * The envelope is only worth having if the event inside it comes out the other - * side unchanged -- same id, same author, same signature. The moment any of - * those is rewritten in transit, a group can no longer hold work by anyone but - * its own members, which is the whole reason submissions exist. - */ -class SubmissionEventTest { - private val submitter = "a".repeat(64) - private val outsider = "b".repeat(64) - - /** A dialect written by somebody who is not in the group. */ - private fun outsiderDialect(): Event { - val template = DialectEvent.build( - name = "Sesotho", - country = "Lesotho", - language = "st", - createdAt = 1_700_000_000L, - ) - return Event( - id = EventHasher.hashId( - pubKey = outsider, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - ), - pubKey = outsider, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "c".repeat(128), - ) - } - - /** Send a submission template and read it back the way inbound does. */ - private fun roundTrip(payload: Event): SubmissionEvent { - val template = SubmissionEvent.build(payload = payload, createdAt = 1_700_000_100L) - val onTheWire = Event.fromJson( - Event( - id = EventHasher.hashId( - pubKey = submitter, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - ), - pubKey = submitter, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "", - ).toJson() - ) - - return SubmissionEvent( - id = onTheWire.id, - pubKey = onTheWire.pubKey, - createdAt = onTheWire.createdAt, - tags = onTheWire.tags, - content = onTheWire.content, - sig = onTheWire.sig, - ) - } - - @Test - fun `the payload comes back as the event that went in`() { - val dialect = outsiderDialect() - - val payload = roundTrip(dialect).payload() - - assertEquals(dialect.id, payload?.id) - assertEquals(dialect.pubKey, payload?.pubKey) - assertEquals(dialect.kind, payload?.kind) - assertEquals(dialect.content, payload?.content) - assertEquals(dialect.sig, payload?.sig) - } - - @Test - fun `submitting does not make the submitter the author`() { - val dialect = outsiderDialect() - - val submission = roundTrip(dialect) - - assertEquals(submitter, submission.pubKey) - assertEquals(outsider, submission.payload()?.pubKey) - assertNotEquals(submission.pubKey, submission.payload()?.pubKey) - } - - @Test - fun `the envelope names what it carries without being opened`() { - val dialect = outsiderDialect() - - val submission = roundTrip(dialect) - - assertEquals(DialectEvent.KIND, submission.payloadKind()) - assertEquals(dialect.id, submission.payloadId()) - assertEquals(outsider, submission.payloadAuthor()) - } - - @Test - fun `a payload the group cannot read is null rather than empty`() { - val submission = SubmissionEvent( - id = "d".repeat(64), - pubKey = submitter, - createdAt = 1_700_000_100L, - tags = arrayOf(), - content = "not an event", - sig = "", - ) - - assertNull(submission.payload()) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt index c9f643ff..f8380920 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt @@ -17,7 +17,10 @@ import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import com.machankura.bennu.compose.extensions.toHex +import com.machankura.bennu.compose.managers.GuardianDerivation import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag /** * What a birth certificate is allowed to convince a member of. @@ -350,6 +353,98 @@ class SubgroupBirthCertificateEventTest { * way to test that both are checked. [signature] replaces the real one * outright, for the cases where what arrives is not a signature at all. */ + @Test + fun `guardian keys ride on a certificate without touching what it certifies`() { + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + val guardians = GuardianDerivation.grant(parentKey, parentChatRoomId, emptyList(), subgroupChatRoomId) + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = subgroupChatRoomId, + parentChatRoomId = parentChatRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = admins, + name = name, + path = path, + guardians = guardians, + ) + + assertTrue(SubgroupBirthCertificateEvent.certifies(certificate(tags = tags), subgroupChatRoomId, parentChatRoomId)) + assertEquals(guardians, SubgroupBirthCertificateEvent.parseGuardians(tags)) + assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(certificate().tags)) + + // One unreadable entry makes the list unreadable, rather than shorter. + val broken = tags.map { if (it[0] == GuardianTag.TAG_NAME) it.copyOf().also { tag -> tag[2] = "04" + tag[2].drop(2) } else it } + assertNull(SubgroupBirthCertificateEvent.parseGuardians(broken.toTypedArray())) + } + + @Test + fun `a guarded certificate carries its keys and reads as guarded`() { + val tags = policyTags(SubgroupWalletPolicy.GUARDED, guardians = grant()) + + assertEquals(WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED), SubgroupBirthCertificateEvent.parseWalletPolicy(tags)) + assertEquals(grant(), SubgroupBirthCertificateEvent.parseGuardians(tags)) + } + + @Test + fun `an unguarded certificate carries no keys and reads as unguarded`() { + val tags = policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = emptyList()) + + assertEquals(WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED), SubgroupBirthCertificateEvent.parseWalletPolicy(tags)) + assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(tags)) + } + + @Test + fun `a certificate from before policies reads as undecided, with keys or without`() { + assertEquals(WalletPolicyReading.Undecided, SubgroupBirthCertificateEvent.parseWalletPolicy(certificate().tags)) + assertEquals(WalletPolicyReading.Undecided, SubgroupBirthCertificateEvent.parseWalletPolicy(policyTags(null, guardians = grant()))) + } + + @Test + fun `a policy that contradicts its keys, or does not read, reads as nothing`() { + // Each of these must not fall back to undecided: that would hand the + // child the choice its parent took away. + val contradictions = mapOf( + "guarded with no keys" to policyTags(SubgroupWalletPolicy.GUARDED, guardians = emptyList()), + "unguarded with keys" to policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = grant()), + "two policies" to policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = emptyList()) + WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED), + "an unknown policy" to policyTags(null, guardians = emptyList()) + arrayOf(WalletPolicyTag.TAG_NAME, "maybe"), + "an empty policy" to policyTags(null, guardians = emptyList()) + arrayOf(WalletPolicyTag.TAG_NAME), + ) + + contradictions.forEach { (what, tags) -> + assertNull(SubgroupBirthCertificateEvent.parseWalletPolicy(tags), "a certificate with $what was read") + } + } + + @Test + fun `a policy does not touch what a certificate certifies`() { + // Lineage stays six questions. A certificate whose policy reads as nothing + // is still the parent's word that the child is its child. + listOf( + policyTags(SubgroupWalletPolicy.GUARDED, guardians = grant()), + policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = emptyList()), + policyTags(SubgroupWalletPolicy.GUARDED, guardians = emptyList()), + ).forEach { tags -> + assertTrue(SubgroupBirthCertificateEvent.certifies(certificate(tags = tags), subgroupChatRoomId, parentChatRoomId)) + } + } + + private fun grant(): List = + GuardianDerivation.grant(parentMaterial.thresholdPublicKey.value.toHex(), parentChatRoomId, emptyList(), subgroupChatRoomId) + + private fun policyTags( + policy: SubgroupWalletPolicy?, + guardians: List, + ): Array> = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = subgroupChatRoomId, + parentChatRoomId = parentChatRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = admins, + name = name, + path = path, + guardians = guardians, + walletPolicy = policy, + ) + private fun certificate( content: String = subgroupChatRoomId, tags: Array> = SubgroupBirthCertificateEvent.assembleTags( diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt index f707eb15..539deb72 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt @@ -1,7 +1,13 @@ package com.machankura.bennu.compose.nostr.wallet +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import fr.acinq.bitcoin.ByteVector32 @@ -13,6 +19,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue /** * A wallet statement, read and believed. @@ -47,7 +54,7 @@ class GroupWalletStatementEventTest { } private fun statement(account: GroupWalletDerivation.Account, createdAt: Long = 1_700_000_000): GroupSignedEvent { - val template = GroupWalletStatementEvent.template(account, createdAt) + val template = GroupWalletStatementEvent.template(account, createdAt = createdAt) return signed(template.tags, template.content, createdAt) } @@ -120,6 +127,145 @@ class GroupWalletStatementEventTest { assertNull(GroupWallet.newestAmong(listOf(older, newer), thresholdKey, Chain.Signet)) } + // ---- A guarded statement --------------------------------------------- + + /** + * The parent, as a key whose secret the test holds: `certifies` asks only + * that the room the certificate names as parent signed it. + */ + private val parentKey = PrivateKey(ByteVector32(Hex.decode("0b".repeat(32)))) + private val parentRoomId = parentKey.publicKey().xOnly().value.toString() + private val childRoomId = SharedKeyDerivation.marmotGroupId(thresholdKey) + private val grant = GuardianDerivation.grant(key(0x9a4e47), parentRoomId, emptyList(), childRoomId) + + private fun certificate(guardians: List = grant, childKey: String = thresholdKey): Event { + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = SharedKeyDerivation.marmotGroupId(childKey), + parentChatRoomId = parentRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = listOf("a".repeat(64)), + name = "Translation team", + guardians = guardians, + ) + val content = SharedKeyDerivation.marmotGroupId(childKey) + val id = EventHasher.hashId(parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content) + val sig = Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString() + return Event(id, parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content, sig) + } + + private val guarded = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = grant) + + private fun guardedStatement( + account: GroupWalletDerivation.Account = guarded, + certificate: Event = certificate(), + createdAt: Long = 1_700_000_000, + ): GroupSignedEvent { + val template = GroupWalletStatementEvent.template(account, certificate, createdAt) + return signed(template.tags, template.content, createdAt) + } + + @Test + fun `a guarded statement reads back as the guarded account, tree and all`() { + val wallet = assertNotNull(GroupWallet.of(guardedStatement(), thresholdKey)) + + assertEquals(guarded, wallet.account) + assertEquals(grant, wallet.account.guardians) + assertTrue(wallet.account.receiveDescriptor.contains("and_v(v:pk("), wallet.account.receiveDescriptor) + // Same internal key as the plain account, different address: only the tree differs. + val plainAddress = GroupWalletDerivation.derive(mainnet, 0, 0) + val guardedAddress = GroupWalletDerivation.derive(guarded, 0, 0) + assertEquals(plainAddress.internalKey, guardedAddress.internalKey) + assertTrue(plainAddress.address(Chain.Mainnet) != guardedAddress.address(Chain.Mainnet)) + assertTrue(guardedAddress.address(Chain.Mainnet).startsWith("bc1p")) + assertEquals(guardedAddress.outputKey, guardedAddress.cache.tweakedPublicKey, "the cache signs the key path of the guarded address") + } + + @Test + fun `guardians the certificate does not grant open nothing`() { + val stranger = GuardianDerivation.grant(key(0x5), parentRoomId, emptyList(), childRoomId) + val wrongGuardians = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = stranger) + + assertNull(GroupWallet.of(guardedStatement(account = wrongGuardians), thresholdKey), "guardians the parent never granted") + assertNull(GroupWallet.of(guardedStatement(certificate = certificate(childKey = otherThresholdKey)), thresholdKey), "a certificate for another child") + } + + @Test + fun `a guarded statement with its guardians stripped is no wallet at all`() { + // What a client that predates guardians sees: descriptors with a tree it + // does not build. It refuses rather than hand out plain addresses under + // the guarded account's name. + val template = GroupWalletStatementEvent.template(guarded, certificate()) + val stripped = template.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + assertNull(GroupWallet.of(signed(stripped, template.content), thresholdKey)) + } + + @Test + fun `an account opened guarded stays guarded, under its first guardians`() { + val firstGuarded = guardedStatement(createdAt = 1_700_000_000) + val laterPlain = statement(mainnet, createdAt = 1_700_000_200) + val laterOtherGuardians = run { + // The parent re-certified with other keys; a later statement adopting + // them would move every address, so it is ignored. + val other = GuardianDerivation.grant(key(0x77), parentRoomId, emptyList(), childRoomId) + guardedStatement( + account = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = other), + certificate = certificate(other), + createdAt = 1_700_000_300, + ) + } + + val wallet = assertNotNull(GroupWallet.newestAmong(listOf(laterPlain, firstGuarded, laterOtherGuardians), thresholdKey, Chain.Mainnet)) + assertEquals(firstGuarded.id, wallet.signedEvent.id) + assertEquals(laterPlain.id, GroupWallet.newestAmong(listOf(laterPlain), thresholdKey, Chain.Mainnet)?.signedEvent?.id) + } + + // ---- the parent's decision: docs/subgroup-wallet-policy.md ------------- + + private val decidedGuarded = WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) + private val decidedUnguarded = WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) + + @Test + fun `under a guarded policy a plain statement is no wallet, even alone`() { + // Stronger than rule 1: an older client's plain wallet opens nothing, + // so no device derives its addresses or watches its coins. + val plain = statement(mainnet) + + assertNull(GroupWallet.newestAmong(listOf(plain), thresholdKey, Chain.Mainnet, policy = decidedGuarded)) + + val guarded = guardedStatement(createdAt = 1_700_000_100) + assertEquals( + guarded.id, + GroupWallet.newestAmong(listOf(plain, guarded), thresholdKey, Chain.Mainnet, policy = decidedGuarded)?.signedEvent?.id, + ) + } + + @Test + fun `under an unguarded policy a guarded statement is no wallet`() { + val plain = statement(mainnet, createdAt = 1_700_000_000) + val guarded = guardedStatement(createdAt = 1_700_000_100) + + assertEquals( + plain.id, + GroupWallet.newestAmong(listOf(plain, guarded), thresholdKey, Chain.Mainnet, policy = decidedUnguarded)?.signedEvent?.id, + "rule 1 would have picked the guarded one; the parent ruled it out", + ) + } + + @Test + fun `an undecided room reads exactly as before policies`() { + val plain = statement(mainnet, createdAt = 1_700_000_200) + val guarded = guardedStatement(createdAt = 1_700_000_000) + + listOf(WalletPolicyReading.Undecided, null).forEach { policy -> + assertEquals( + guarded.id, + GroupWallet.newestAmong(listOf(plain, guarded), thresholdKey, Chain.Mainnet, policy = policy)?.signedEvent?.id, + ) + assertEquals(plain.id, GroupWallet.newestAmong(listOf(plain), thresholdKey, Chain.Mainnet, policy = policy)?.signedEvent?.id) + } + } + @Test fun `every network name round trips`() { listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest).forEach { diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEventTest.kt new file mode 100644 index 00000000..95cf01de --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEventTest.kt @@ -0,0 +1,92 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNull + +/** + * A group's policy on its members' wallets -- `docs/member-wallet-delay.md`, + * Phase 1. The room is a key whose secret the test holds: `isSignedByRoom` asks + * only that the room's id signed it. + */ +class MemberWalletPolicyEventTest { + private val roomKey = PrivateKey(ByteVector32(Hex.decode("07".repeat(32)))) + private val roomId = roomKey.publicKey().xOnly().value.toString() + private val strangerKey = PrivateKey(ByteVector32(Hex.decode("09".repeat(32)))) + + private fun signed( + tags: Array>, + createdAt: Long = 1_700_000_000, + by: PrivateKey = roomKey, + kind: Int = MemberWalletPolicyEvent.KIND, + ): Event { + val pubKey = by.publicKey().xOnly().value.toString() + val id = EventHasher.hashId(pubKey, createdAt, kind, tags, "") + return Event(id, pubKey, createdAt, kind, tags, "", Crypto.signSchnorr(ByteVector32(id), by, null).toString()) + } + + private fun open(delay: Long, createdAt: Long = 1_700_000_000) = signed(MemberWalletPolicyEvent.open(delay, createdAt).tags, createdAt) + private fun closed(createdAt: Long = 1_700_000_000) = signed(MemberWalletPolicyEvent.closed(createdAt).tags, createdAt) + + @Test + fun `an open policy and a closed one each read back`() { + val opened = assertIs(MemberWalletPolicyEvent.verify(open(144), roomId)) + assertEquals(144L, opened.delay) + assertIs(MemberWalletPolicyEvent.verify(closed(), roomId)) + } + + @Test + fun `a policy that does not say one thing a device can act on does not read`() { + val d = arrayOf("d", MemberWalletPolicyEvent.IDENTIFIER) + val cases = mapOf( + "another kind" to signed(arrayOf(d, arrayOf("guardian_delay", "144")), kind = 30336), + "no d tag" to signed(arrayOf(arrayOf("guardian_delay", "144"))), + "another d tag" to signed(arrayOf(arrayOf("d", "subgroups"), arrayOf("guardian_delay", "144"))), + "two delays" to signed(arrayOf(d, arrayOf("guardian_delay", "144"), arrayOf("guardian_delay", "12"))), + "five blocks" to signed(arrayOf(d, arrayOf("guardian_delay", "5"))), + "65,536 blocks" to signed(arrayOf(d, arrayOf("guardian_delay", "65536"))), + "a word" to signed(arrayOf(d, arrayOf("guardian_delay", "twelve"))), + "both a delay and closed" to signed(arrayOf(d, arrayOf("guardian_delay", "144"), arrayOf("closed"))), + "neither" to signed(arrayOf(d)), + "another room's signature" to signed(MemberWalletPolicyEvent.open(144).tags, by = strangerKey), + ) + cases.forEach { (name, event) -> assertNull(MemberWalletPolicyEvent.verify(event, roomId), "a policy with $name read") } + } + + @Test + fun `the newest decides, open or closed, in any order`() { + val first = open(12, createdAt = 1_700_000_000) + val shut = closed(createdAt = 1_700_000_100) + val reopened = open(1_008, createdAt = 1_700_000_200) + + listOf(listOf(first, shut, reopened), listOf(reopened, first, shut), listOf(shut, reopened, first)).forEach { events -> + assertEquals(1_008L, assertIs(MemberWalletPolicyEvent.newestAmong(events, roomId)).delay) + } + assertIs(MemberWalletPolicyEvent.newestAmong(listOf(shut, first), roomId)) + assertNull(MemberWalletPolicyEvent.newestAmong(emptyList(), roomId)) + } + + @Test + fun `a tie on the timestamp goes to the larger id, on every device`() { + val a = open(144, createdAt = 1_700_000_000) + val b = open(1_008, createdAt = 1_700_000_000) + val larger = listOf(a, b).maxBy { it.id } + + assertEquals(larger.id, MemberWalletPolicyEvent.newestAmong(listOf(a, b), roomId)?.event?.id) + assertEquals(larger.id, MemberWalletPolicyEvent.newestAmong(listOf(b, a), roomId)?.event?.id) + } + + @Test + fun `an open policy outside the range cannot be built`() { + assertFailsWith { MemberWalletPolicyEvent.open(5) } + assertFailsWith { MemberWalletPolicyEvent.open(65_536) } + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEventTest.kt new file mode 100644 index 00000000..8977a5b0 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEventTest.kt @@ -0,0 +1,127 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.MemberWalletDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * A member's request, read and believed on everything that can be checked + * without the group's key -- one mutation per check, each of which has to be + * enough on its own to refuse it. + */ +class MemberWalletRequestEventTest { + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val member = privateKey(0x3e3be7) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletKey = walletPrivateKey.publicKey() + private val walletId = MemberWalletDerivation.walletId(walletKey) + + private val groupKey = privateKey(0x6a0b).publicKey().toString() + private val groupRoom = SharedKeyDerivation.marmotGroupId(groupKey) + private val parentKey = privateKey(0x9a9e).publicKey().toString() + private val parentRoom = SharedKeyDerivation.marmotGroupId(parentKey) + + private val grant = GuardianDerivation.grant( + groupKey, groupRoom, GuardianDerivation.grant(parentKey, parentRoom, emptyList(), groupRoom), walletId, + ) + private val account = MemberWalletDerivation.account(walletKey, chain, grant) + + private fun request(label: String? = "Savings", group: String = groupRoom) = + MemberWalletRequestEvent.build(member, group, walletPrivateKey, account, label, createdAt = 1_700_000_000) + + /** [event] with [tags], re-signed by the member, so only the tags are wrong. */ + private fun resigned(event: Event, tags: Array> = event.tags, content: String = event.content): Event { + val id = EventHasher.hashId(event.pubKey, event.createdAt, event.kind, tags, content) + val sig = Crypto.signSchnorr(ByteVector32(id), member, null).toHex() + return Event(id, event.pubKey, event.createdAt, event.kind, tags, content, sig) + } + + private fun Event.replacing(name: String, vararg value: String): Array> = + tags.map { if (it[0] == name) arrayOf(name, *value) else it }.toTypedArray() + + @Test + fun `a request reads and is believed`() { + val verified = assertNotNull(MemberWalletRequestEvent.verified(request())) + assertEquals(member.xOnlyPublicKey().value.toHex(), verified.reading.memberPublicKey) + assertEquals(groupRoom, verified.reading.groupChatRoomId) + assertEquals(walletId, verified.reading.walletId) + assertEquals(grant, verified.reading.guardians) + assertEquals("Savings", verified.reading.label) + assertEquals(account, verified.account) + } + + @Test + fun `a request with no label reads`() { + assertNull(assertNotNull(MemberWalletRequestEvent.verified(request(label = null))).reading.label) + assertNull(MemberWalletRequestEvent.verified(request(label = " ")).let { it?.reading?.label }) + } + + @Test + fun `a request somebody else signed is refused`() { + val signedByAnother = request().let { Event(it.id, it.pubKey, it.createdAt, it.kind, it.tags, it.content, "0".repeat(128)) } + assertNull(MemberWalletRequestEvent.verified(signedByAnother)) + } + + @Test + fun `a wallet id that is not the key's is refused`() { + val event = request() + assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("wallet", "f".repeat(64))))) + } + + @Test + fun `a possession signature by another key is refused`() { + val event = request() + val other = Crypto.signSchnorr(ByteVector32("ab".repeat(32)), privateKey(0xb0b), null).toHex() + assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("possession", other)))) + } + + @Test + fun `a request that leaves out the group it asks is refused`() { + // Signed for the group, but asking a stranger: the nearest guardian is not the group asked. + val event = request() + val stranger = SharedKeyDerivation.marmotGroupId(privateKey(0x57a9).publicKey().toString()) + assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("h", stranger)))) + } + + @Test + fun `a descriptor that does not rederive is refused`() { + val event = request() + val plain = MemberWalletDerivation.account(walletKey, chain, emptyList()) + val tags = event.tags.map { if (it[0] == "descriptor" && it[2] == "receive") arrayOf("descriptor", plain.receiveDescriptor, "receive") else it } + assertNull(MemberWalletRequestEvent.verified(resigned(event, tags.toTypedArray()))) + // The xpub does not depend on the guardians, so it is another key's that does not rederive. + val another = MemberWalletDerivation.account(privateKey(0xb0b).publicKey(), chain, grant) + assertNull(MemberWalletRequestEvent.verified(resigned(event, content = another.xpub))) + } + + @Test + fun `two wallet tags, or none, do not read`() { + val event = request() + assertNull(MemberWalletRequestEvent.read(resigned(event, event.tags + arrayOf(arrayOf("wallet", walletId))))) + assertNull(MemberWalletRequestEvent.read(resigned(event, event.tags.filterNot { it[0] == "wallet" }.toTypedArray()))) + } + + @Test + fun `a request travels whole, sent only by the member who signed it`() { + val signed = request() + fun inner(sender: String) = Event("1".repeat(64), sender, signed.createdAt, MemberWalletRequestEvent.KIND, emptyArray(), signed.toJson(), "") + + assertEquals(signed.id, MemberWalletRequestEvent.carried(inner(signed.pubKey))?.id) + assertNotNull(MemberWalletRequestEvent.verified(MemberWalletRequestEvent.carried(inner(signed.pubKey))!!), "the signature survives the trip") + assertNull(MemberWalletRequestEvent.carried(inner("2".repeat(64))), "nobody passes a request on") + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/BlockDurationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/BlockDurationTest.kt new file mode 100644 index 00000000..7982be8e --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/BlockDurationTest.kt @@ -0,0 +1,68 @@ +package com.machankura.bennu.compose.text + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.text.BlockDuration.Approximate +import com.machankura.bennu.compose.text.BlockDuration.Unit.DAYS +import com.machankura.bennu.compose.text.BlockDuration.Unit.HOURS +import com.machankura.bennu.compose.text.BlockDuration.Unit.MINUTES +import com.machankura.bennu.compose.text.BlockDuration.Unit.MONTHS +import com.machankura.bennu.compose.text.BlockDuration.Unit.YEARS +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * How a guardian's delay is said in time -- `docs/guardian-delay.md`, D5. The + * table is the plan's, row for row, so the words a member reads are the words + * the plan argued for. + */ +class BlockDurationTest { + @Test + fun `every row of the plan's table`() { + val table = mapOf( + 6L to Approximate(1, HOURS), + 12L to Approximate(2, HOURS), + 100L to Approximate(17, HOURS), + 144L to Approximate(1, DAYS), + 216L to Approximate(36, HOURS), + 1_008L to Approximate(7, DAYS), + 4_320L to Approximate(1, MONTHS), + 13_140L to Approximate(3, MONTHS), + 26_280L to Approximate(6, MONTHS), + 52_560L to Approximate(1, YEARS), + 65_535L to Approximate(15, MONTHS), + ) + table.forEach { (blocks, expected) -> assertEquals(expected, BlockDuration.approximate(blocks), "$blocks blocks") } + } + + @Test + fun `exactly one of a unit is a five percent window either side`() { + // A day is 144 blocks: 137 is 95.1% of it and 151 is 104.9%. + assertEquals(Approximate(1, DAYS), BlockDuration.approximate(137)) + assertEquals(Approximate(1, DAYS), BlockDuration.approximate(151)) + assertEquals(Approximate(23, HOURS), BlockDuration.approximate(136)) + assertEquals(Approximate(25, HOURS), BlockDuration.approximate(152)) + } + + @Test + fun `under an hour is minutes`() { + assertEquals(Approximate(10, MINUTES), BlockDuration.approximate(1)) + assertEquals(Approximate(50, MINUTES), BlockDuration.approximate(5)) + } + + @Test + fun `nothing a leaf can carry comes out as zero or past a year`() { + GuardianDerivation.DELAY_RANGE.forEach { blocks -> + val approximate = BlockDuration.approximate(blocks) + assertTrue(approximate.count >= 1, "$blocks blocks came out as $approximate") + assertTrue(approximate.unit != YEARS || approximate.count == 1, "$blocks blocks came out as $approximate") + } + } + + @Test + fun `a block count is grouped in thousands`() { + assertEquals("6", 6L.groupedBlocks()) + assertEquals("1,008", 1_008L.groupedBlocks()) + assertEquals("65,535", 65_535L.groupedBlocks()) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt index 62889d8b..bf9c45ba 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.text +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.ByteVector32 +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent @@ -8,55 +13,15 @@ import kotlin.test.Test import kotlin.test.assertEquals /** - * How the events a group signs about itself are said to the member signing them. + * How the events a group signs are said to the member signing them. * - * These are read on the signing screen, in the room's list of proposals and now - * on the paste screen before proposing, and the same words in all three is the - * point of there being one mapping. What is pinned is that each kind is said as - * the thing it is and by the part of it a signer is actually deciding about -- - * a profile by its name, a post by its words, a relay list by its hosts -- and - * never as "kind 0" over a wall of JSON. + * These are read on the signing screen and in the room's list of proposals, and + * the same words in both is the point of there being one mapping. What is + * pinned is that a kind the app has no words for is said by its number rather + * than described wrongly. */ class ProposedEventTest { - @Test - fun `a profile is said by its name and what it says about itself`() { - val summary = ProposedEvent.summarize( - event(MetadataEvent.KIND, content = """{"name":"Translation collective","about":"We translate hard books."}""") - ) - - assertEquals("Nostr profile", summary.label) - assertEquals("Translation collective · We translate hard books.", summary.detail) - - // Empty and unreadable are different things, and a signer should know which. - assertEquals("An empty profile", ProposedEvent.summarize(event(MetadataEvent.KIND, content = "{}")).detail) - assertEquals("Unreadable profile", ProposedEvent.summarize(event(MetadataEvent.KIND, content = "not json")).detail) - } - - @Test - fun `a post is said by its words`() { - val summary = ProposedEvent.summarize(event(TextNoteEvent.KIND, content = "We have finished the first chapter.")) - - assertEquals("Post", summary.label) - assertEquals("We have finished the first chapter.", summary.detail) - } - - @Test - fun `a relay list is said by which list it is and its hosts`() { - val summary = ProposedEvent.summarize( - event( - AdvertisedRelayListEvent.KIND, - tags = arrayOf(arrayOf("r", "wss://relay.one.example"), arrayOf("r", "wss://relay.two.example", "read")) - ) - ) - - assertEquals("General relay list", summary.label) - assertEquals("relay.one.example, relay.two.example", summary.detail) - - // An empty list is a withdrawal, which is worth saying in as many words. - assertEquals("No relays", ProposedEvent.summarize(event(AdvertisedRelayListEvent.KIND)).detail) - } - @Test fun `a kind with no words of its own keeps its number`() { // Refusing to describe an event is better than describing it wrongly. @@ -66,6 +31,51 @@ class ProposedEventTest { assertEquals("An article", summary.detail) } + @Test + fun `a birth certificate says what it decides about the child's wallet, either way`() { + val parent = "1".repeat(64) + val child = "2".repeat(64) + val key = PrivateKey(ByteVector32("01".repeat(32))).publicKey().toHex() + fun certificate(policy: SubgroupWalletPolicy?, guarded: Boolean) = event( + SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = child, + parentChatRoomId = parent, + thresholdPublicKey = key, + adminPublicKeys = listOf("a".repeat(64)), + name = "#Translation", + guardians = if (guarded) GuardianDerivation.grant(key, parent, emptyList(), child) else emptyList(), + walletPolicy = policy, + ), + ) + + assertEquals( + "#Translation · run by 1 members · this group can spend from its wallet · this group after 12 blocks, about 2 hours · its wallet must be guarded", + ProposedEvent.summarize(certificate(SubgroupWalletPolicy.GUARDED, guarded = true)).detail, + ) + // Not left to an absent line: a signer approving this is taking the + // subgroup's wallet out of every group's reach above it. + assertEquals( + "#Translation · run by 1 members · its wallet will not be guarded", + ProposedEvent.summarize(certificate(SubgroupWalletPolicy.UNGUARDED, guarded = false)).detail, + ) + assertEquals( + "#Translation · run by 1 members · this group can spend from its wallet · this group after 12 blocks, about 2 hours", + ProposedEvent.summarize(certificate(null, guarded = true)).detail, + "an older certificate decides nothing, and says nothing about it", + ) + } + + @Test + fun `a profile, a post and a relay list are no longer described`() { + // The group's nostr profile, posts and relay lists were removed, and with + // them the words for what they were; a proposal for one from an older + // build is said like any other kind the app does not know. + listOf(MetadataEvent.KIND, TextNoteEvent.KIND, AdvertisedRelayListEvent.KIND).forEach { kind -> + assertEquals("Event of kind $kind", ProposedEvent.summarize(event(kind)).label) + } + } + private fun event( kind: Int, tags: Array> = emptyArray(), diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt new file mode 100644 index 00000000..5be93861 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt @@ -0,0 +1,123 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.managers.LineageExample +import com.machankura.bennu.compose.managers.LineageExample.heldBy +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * What an ancestor's wallet screen says about a descendant's guarded wallet: a + * funding is *arriving* until the leaf's lock lets it go, and then *within + * reach* -- never neither, which would make the money look gone. + */ +class GuardedWalletRowTest { + private val descendantRoomId = "c".repeat(64) + /** Guarded by the ancestor below, at the default delay, as a verified statement would be. */ + private val account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), Chain.Regtest, + guardians = GuardianDerivation.grant(PrivateKey(ByteVector32(Hex.decode("a11ce".padStart(64, '0')))).publicKey().toString(), "d".repeat(64), emptyList(), descendantRoomId), + ) + private val wallet = GuardianManager.GuardedWallet( + ancestorChatRoomId = "d".repeat(64), + descendantChatRoomId = descendantRoomId, + statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), + account = account, + certificate = Event("2".repeat(64), "d".repeat(64), 1_700_000_000, 0, emptyArray(), "", ""), + lineage = listOf(descendantRoomId), + ) + + /** One coin of 50,000 sats at the first receive address, confirmed at [height] (0 in the mempool), with the tip at [tip]. */ + private fun holding(height: Long, tip: Int): GroupWalletState { + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(50_000), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(0) + return GroupWalletState( + account, + WalletState(mapOf(derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta))))), + WalletState.empty, + tipHeight = tip, + ) + } + + @Test + fun `a coin is arriving until the lock lets it go, then within reach`() { + val lock = GuardianDerivation.DEFAULT_DELAY.toInt() + + val mempool = GuardedWalletRow(wallet, holding(height = 0, tip = 100)) + assertEquals(Satoshi(50_000), mempool.arriving) + assertEquals(Satoshi(0), mempool.withinReach) + + val young = GuardedWalletRow(wallet, holding(height = 100, tip = 100 + lock - 2)) + assertEquals(Satoshi(50_000), young.arriving, "${lock - 1} confirmations") + assertEquals(Satoshi(0), young.withinReach) + + val old = GuardedWalletRow(wallet, holding(height = 100, tip = 100 + lock - 1)) + assertEquals(Satoshi(0), old.arriving, "$lock confirmations") + assertEquals(Satoshi(50_000), old.withinReach) + } + + @Test + fun `nothing is said before the chain is known`() { + val row = GuardedWalletRow(wallet, walletState = null) + assertNull(row.arriving) + assertNull(row.withinReach) + } + + // ---- By person: docs/member-wallet-guarding-group.md, Phase 4 --------- + + private val r = LineageExample.r + private val savingsAtR = GuardedWalletRow(heldBy(r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M"), walletState = null) + private val rentAtR = GuardedWalletRow(heldBy(r, LineageExample.rent, LineageExample.rentGuardians, label = "Rent", guardianName = "#N"), walletState = null) + + @Test + fun `a member's two wallets under two groups are one person, the nearer first`() { + val people = listOf(savingsAtR, rentAtR).byPerson() + + val alice = people.single() + assertEquals(LineageExample.alice, alice.ownerPublicKey) + assertEquals("alice", alice.ownerName) + assertEquals(2, alice.guardianCount) + assertEquals(listOf("Rent", "Savings"), alice.rows.map { (it.wallet.subject as GuardianManager.GuardedSubject.Member).label }) + } + + @Test + fun `two wallets under one group count one guardian`() { + // A second wallet N guards for her: the guardians name the same rooms. + val holiday = GuardedWalletRow(heldBy(r, "9".repeat(64), LineageExample.rentGuardians, label = "Holiday"), walletState = null) + val alice = listOf(rentAtR, holiday).byPerson().single() + assertEquals(1, alice.guardianCount) + } + + @Test + fun `a subgroup's wallet is not a person`() { + assertEquals(emptyList(), listOf(GuardedWalletRow(wallet, walletState = null)).byPerson()) + } + + @Test + fun `people sort by name, and by key where there is none`() { + val bob = GuardedWalletRow(heldBy(r, "8".repeat(64), LineageExample.rentGuardians, ownerPublicKey = "b".repeat(64), ownerName = "bob"), walletState = null) + val nameless = GuardedWalletRow(heldBy(r, "6".repeat(64), LineageExample.rentGuardians, ownerPublicKey = "0".repeat(64), ownerName = null), walletState = null) + + val people = listOf(bob, nameless, savingsAtR).byPerson() + assertEquals(listOf("0".repeat(64), LineageExample.alice, "b".repeat(64)), people.map { it.ownerPublicKey }) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt new file mode 100644 index 00000000..9ad95515 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt @@ -0,0 +1,61 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * A spend checked the way every member but the proposer checks it: after the + * PSBT has been through the wire. + * + * Half of all accounts have a fingerprint with its top bit set, and bitcoin-kmp + * reads a taproot derivation's fingerprint back from a serialised PSBT as a + * signed int. Compared as written, every such wallet's spends were refused by + * every member who did not build them. + */ +class GroupSpendFingerprintTest { + /** The first account, counting up from a fixed seed, whose fingerprint has its top bit set. */ + private val account: GroupWalletDerivation.Account = generateSequence(1) { it + 1 } + .map { seed -> + val key = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + GroupWalletDerivation.account(key, Chain.Regtest) + } + .first { it.fingerprint >= 0x80000000L } + + @Test + fun `a spend from a wallet with a high fingerprint checks out after the wire`() { + val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) + val funding = Transaction( + 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x51 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(50_000), coin.pubkeyScript)), 0, + ) + val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) + val tx = Transaction( + 2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GroupSpend.MAX_SEQUENCE)), + listOf(TxOut(Satoshi(30_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0, + ) + val proposed = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to coin), mapOf(1 to change), account) + + assertTrue(account.fingerprint >= 0x80000000L) + val received = GroupSpend.decode(GroupSpend.encode(proposed))!! + + val checked = assertIs(GroupSpend.check(received, account)).checked + assertEquals(listOf(false, true), checked.outputs.map { it.isChange }) + assertEquals(setOf(0L), GroupSpend.claimedChangeIndices(received, account)) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFundingTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFundingTest.kt new file mode 100644 index 00000000..1fc0c296 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFundingTest.kt @@ -0,0 +1,127 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * A spend that funds a descendant's wallet: the payment carries its place under + * the descendant's account, and that claim has to survive the wire and never + * be taken for change. See `docs/guarded-wallet-funding.md`, Phase 2. + */ +class GroupSpendFundingTest { + private fun accountFrom(seed: Int): GroupWalletDerivation.Account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString(), + Chain.Regtest, + ) + + private val account = accountFrom(0x1c0ffee) + + /** The first descendant account, counting up, whose fingerprint has its top bit set: the one the wire reads back signed. */ + private val descendant: GroupWalletDerivation.Account = generateSequence(1) { it + 1 } + .map { accountFrom(it) } + .first { it.fingerprint >= 0x80000000L } + + private val funding = GroupSpendBuilder.Destination.Funding( + descendant, GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, 7), + ) + private val typed = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + private val feerate = 5L + + private fun coin(index: Int, sats: Long): Pair { + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) + val tx = Transaction( + 2, + listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { index.toByte() })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), + 0, + ) + val meta = WalletState.AddressMeta.Derived(index) + return derived.address(Chain.Regtest) to WalletState.AddressState( + meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta)), + ) + } + + private fun state(vararg coins: Pair): GroupWalletState { + val change = WalletState(mapOf( + GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0).address(Chain.Regtest) to + WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()) + )) + return GroupWalletState(account, WalletState(coins.toMap()), change, tipHeight = 110) + } + + @Test + fun `a funding's claim survives the wire for a high fingerprint`() { + val built = assertIs( + GroupSpendBuilder.send(state(coin(0, 60_000)), funding, Satoshi(30_000), feerate, emptySet()) + ) + assertEquals(funding, built.funded) + assertEquals(funding.derived.pubkeyScript, built.psbt.global.tx.txOut[0].publicKeyScript) + + assertTrue(descendant.fingerprint >= 0x80000000L) + val received = GroupSpend.decode(GroupSpend.encode(built.psbt))!! + assertEquals(setOf(7L), GroupSpend.claimedFundingIndices(received, descendant)) + assertEquals(setOf(0L), GroupSpend.claimedChangeIndices(received, account), "the change is still the room's own") + assertEquals(emptySet(), GroupSpend.claimedFundingIndices(received, account), "the room's own account funds nothing") + } + + @Test + fun `a funding is a payment, not change`() { + val built = assertIs( + GroupSpendBuilder.send(state(coin(0, 60_000)), funding, Satoshi(30_000), feerate, emptySet()) + ) + val received = GroupSpend.decode(GroupSpend.encode(built.psbt))!! + + val checked = assertIs(GroupSpend.check(received, account)).checked + assertEquals(listOf(false, true), checked.outputs.map { it.isChange }) + assertEquals(Satoshi(30_000), checked.amountSent) + } + + @Test + fun `sending everything can fund too`() { + val built = assertIs( + GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(1, 40_000)), funding, feerate, emptySet()) + ) + assertEquals(funding, built.funded) + assertEquals(setOf(7L), GroupSpend.claimedFundingIndices(built.psbt, descendant)) + assertIs(GroupSpend.check(built.psbt, account)) + } + + @Test + fun `a send to a typed address claims nothing about its payment`() { + val built = assertIs( + GroupSpendBuilder.send(state(coin(0, 60_000)), typed, Satoshi(30_000), feerate, emptySet()) + ) + assertNull(built.funded) + assertTrue(built.psbt.outputs[0].taprootDerivationPaths.isEmpty()) + assertEquals(1, built.psbt.outputs[1].taprootDerivationPaths.size, "change is described as it always was") + } + + @Test + fun `a wallet on another network is not one to fund`() { + val elsewhere = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), + Chain.Signet, + ) + val across = GroupSpendBuilder.Destination.Funding(elsewhere, GroupWalletDerivation.derive(elsewhere, GroupWalletDerivation.RECEIVE, 0)) + assertEquals( + GroupSpendBuilder.Result.NotAnAddress, + GroupSpendBuilder.send(state(coin(0, 60_000)), across, Satoshi(30_000), feerate, emptySet()), + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt index d29712a3..f60b13d2 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt @@ -32,8 +32,8 @@ import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent /** * The table that keeps what a quorum signed, checked against a real quorum. @@ -132,8 +132,8 @@ class GroupSignedEventDaoJvmTest { ) } - private val dialect = signed( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) + private val post = signed( + TextNoteEvent.build(note = "isiZulu", createdAt = 1_700_000_000L) ) /** @@ -169,7 +169,7 @@ class GroupSignedEventDaoJvmTest { } private fun rowFor( - event: Event = dialect, + event: Event = post, path: String? = derivationPath, sessionId: String? = "session-1", ) = GroupSignedEvent.fromEvent( @@ -184,20 +184,20 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor()) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored, "the event just recorded could not be read back") - assertEquals(dialect.pubKey, stored.publicKey) - assertEquals(dialect.kind, stored.kind) - assertEquals(dialect.content, stored.content) - assertEquals(dialect.sig, stored.signature) - assertEquals(dialect.createdAt, stored.createdAt.epochSeconds) - assertContentEquals(dialect.tags.map { it.toList() }, stored.tags.map { it.toList() }) + assertEquals(post.pubKey, stored.publicKey) + assertEquals(post.kind, stored.kind) + assertEquals(post.content, stored.content) + assertEquals(post.sig, stored.signature) + assertEquals(post.createdAt, stored.createdAt.epochSeconds) + assertContentEquals(post.tags.map { it.toList() }, stored.tags.map { it.toList() }) // The claim the columns exist to support: the group's signature is still // checkable from the row, with nothing else on hand. assertTrue(stored.verifies(), "the stored row no longer verifies as the room's") - assertEquals(dialect.id, stored.toEvent().id) + assertEquals(post.id, stored.toEvent().id) } @Test @@ -205,7 +205,7 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor()) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertEquals(derivationPath, stored.derivationPath) @@ -227,7 +227,7 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor(path = null)) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertNull(stored.derivationPath) @@ -245,7 +245,7 @@ class GroupSignedEventDaoJvmTest { // state and never ran the session. db.groupSignedEventDao().record(rowFor(path = null, sessionId = null)) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertEquals(derivationPath, stored.derivationPath) @@ -259,7 +259,7 @@ class GroupSignedEventDaoJvmTest { db.groupSignedEventDao().record(rowFor(path = null, sessionId = null)) db.groupSignedEventDao().record(rowFor()) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertEquals(derivationPath, stored.derivationPath) @@ -270,31 +270,23 @@ class GroupSignedEventDaoJvmTest { fun `a batch is filed together and reads back oldest first`() = runBlocking { seedRoom() - val artifact = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) + val profile = signed( + MetadataEvent.createNew(name = "In Detention", createdAt = 1_700_000_010L) ) db.groupSignedEventDao().recordAll( - listOf(rowFor(event = artifact), rowFor(event = dialect)) + listOf(rowFor(event = profile), rowFor(event = post)) ) val dao = db.groupSignedEventDao() assertEquals( - listOf(dialect.id, artifact.id), + listOf(post.id, profile.id), dao.getByChatRoomId(chatRoomId).map { it.id }, "a room's signed work has to come back in the order it can be applied in" ) assertEquals( - listOf(dialect.id), - dao.getByChatRoomIdAndKind(chatRoomId, DialectEvent.KIND).map { it.id } + listOf(post.id), + dao.getByChatRoomIdAndKind(chatRoomId, TextNoteEvent.KIND).map { it.id } ) assertEquals(2, dao.getByFrostSigningSessionId("session-1").size) } @@ -304,38 +296,11 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor().copy(content = "isiXhosa")) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) // The id is the hash of the fields, so an edited row is an event the // group never signed. Nothing else has to be consulted to know that. assertFalse(stored.verifies(), "an event with edited content must not verify") } - - @Test - fun `the row a signed event becomes points back at it`() = runBlocking { - seedRoom() - db.groupSignedEventDao().record(rowFor()) - - ChatMessage.applyInnerEvent( - database = db, - groupId = chatRoomId, - event = dialect, - marmotGroupEventId = null, - marmotInnerEventId = null, - senderPublicKey = chatRoomId, - isUserMessage = false, - createdAt = Instant.fromEpochSeconds(dialect.createdAt), - groupSignedEventId = dialect.id, - ) - - val row = db.mantraDialectDao().getDialectById(dialect.id) - assertNotNull(row, "the dialect the group signed was not applied") - - // Both Marmot ids are null on a group-signed event -- no group event and - // no inner event carried it -- so this column is the only provenance the - // row has. - assertNull(row.marmotGroupEventId) - assertEquals(dialect.id, row.groupSignedEventId) - } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/MantraDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/MantraDaoJvmTest.kt deleted file mode 100644 index 2ce2705e..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/MantraDaoJvmTest.kt +++ /dev/null @@ -1,206 +0,0 @@ -package com.machankura.bennu.compose.database.dao - -import androidx.room3.Room -import kotlinx.coroutines.runBlocking -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.builder.getRoomDatabase -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.repository.MantraRepository -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * The nip30303 create-entity flow: every `add*` on [MantraDao] writes the entity and queues a - * [SubmissionEvent] carrying the same event for the group, in one transaction. - * - * The invariant worth a test is the one `rumorOf` exists for. The entity's id is computed by - * the `Mantra*.from*EventTemplate` factory and the payload's id is computed here, from the same - * template -- so the row on disk and the payload on the wire are meant to be *the same event*, - * not two copies of one. Nothing enforces that: both sides compile independently, both produce - * a plausible 64-character id, and a divergence would only show up as a group that can never - * match an arriving submission to the entity it was supposed to create. - */ -class MantraDaoJvmTest { - - private val db: BennuDatabase = getRoomDatabase( - Room.inMemoryDatabaseBuilder() - ) - - @AfterTest - fun closeDb() = db.close() - - private val author = "a".repeat(64) - private val roomId = "b".repeat(64) - - /** ChatRoom -> Profile -> NostrEvent, the foreign key chain a room hangs off. */ - private suspend fun seedRoom(): LocalChatRoom { - val nostrEventId = "c".repeat(64) - db.nostrEventDao().upsert( - NostrEvent( - id = nostrEventId, - pubKey = author, - kind = 0, - tags = emptyArray(), - content = "{}", - sig = "0".repeat(128), - ) - ) - db.profileDao().upsert(Profile(publicKey = author, userName = "author", nostrEventId = nostrEventId)) - val chatRoom = ChatRoom( - id = roomId, - userPublicKey = author, - subject = "a translation room", - description = null, - mlsGroupState = null, - ) - db.chatRoomDao().upsert(chatRoom) - return LocalChatRoom(chatRoom = chatRoom) - } - - private suspend fun submissions() = db.marmotInnerEventDao() - .getByChatRoomAndKinds(roomId, listOf(SubmissionEvent.KIND)) - - private suspend fun addDialect(name: String = "Sesotho") = db.mantraDao().addDialect( - localChatRoom = seedRoom(), - name = name, - country = "ZA", - language = "st", - userPublicKey = author, - ) - - @Test - fun `a dialect is stored and queued for the group in one call`() = runBlocking { - val dialect = assertNotNull(addDialect(), "addDialect returned null") - - assertEquals("Sesotho", dialect.name) - assertEquals(roomId, dialect.chatRoomId) - assertEquals(author, dialect.publicKey) - assertEquals(1, submissions().size, "the dialect was stored without being submitted") - } - - /** - * The `rumorOf` invariant, asserted across the seam: the submission records the payload's - * id, and that id has to be the entity's own. If the two factories ever compute it - * differently the group receives a submission whose payload matches nothing on disk. - */ - @Test - fun `the stored dialect and the submitted payload are the same event`() = runBlocking { - val dialect = assertNotNull(addDialect()) - - val submission = submissions().single() - - assertEquals( - dialect.id, - submission.payloadEventId, - "the entity id and the submitted payload id have diverged", - ) - } - - /** - * The envelope is not the payload. A submission's own id is the SubmissionEvent's, which is - * why `deleteByPayloadEventId` exists -- a superseded nip30303 event cannot be un-queued by - * its own id. - */ - @Test - fun `the submission is an envelope with its own id`() = runBlocking { - val dialect = assertNotNull(addDialect()) - - val submission = submissions().single() - - assertEquals(SubmissionEvent.KIND, submission.kind) - assertTrue( - submission.id != dialect.id, - "the envelope must not share the payload's id, or it could not be told apart", - ) - assertEquals(author, submission.publicKey) - assertEquals(roomId, submission.chatRoomId) - } - - /** - * `marmotGroupEventId == null` is what makes the row unprocessed, which is the state the - * outbound pipeline selects on to encrypt it into a kind:445. Filed as processed, it would - * be stored and never sent, and the group would never learn about the dialect. - */ - @Test - fun `the submission is queued unprocessed for the outbound pipeline`() = runBlocking { - addDialect() - - val submission = submissions().single() - - assertNull(submission.marmotGroupEventId, "a queued submission must not look processed") - } - - /** The room's feed reads ChatMessage, so an added entity has to leave a line behind. */ - @Test - fun `a chat message line is written so the room shows the change`() = runBlocking { - addDialect(name = "isiZulu") - - val submission = submissions().single() - val chatMessage = db.chatMessageDao().getChatMessagesByMarmotInnerEventId(submission.id) - - assertNotNull(chatMessage, "no chat line was written for the submission") - assertEquals("Added isiZulu as a dialect", chatMessage.content) - assertEquals(roomId, chatMessage.chatRoomId) - assertTrue(chatMessage.isUserMessage) - } - - /** - * A second entity type through the same path, because the store-and-submit shape is the - * convention every `add*` follows rather than something `addDialect` does on its own. - */ - @Test - fun `an artifact version follows the same store-and-submit shape`() = runBlocking { - val localChatRoom = seedRoom() - val dialect = assertNotNull( - db.mantraDao().addDialect( - localChatRoom = localChatRoom, - name = "Setswana", - country = "ZA", - language = "tn", - userPublicKey = author, - ) - ) - val artifactId = "d".repeat(64) - db.mantraArtifactDao().upsert( - MantraArtifact( - id = artifactId, - publicKey = author, - name = "a text", - url = "https://example.invalid/text", - visibility = MantraRepository.DEFAULT_VISIBILITY, - dialectId = dialect.id, - license = MantraRepository.DEFAULT_LICENSE, - chatRoomId = roomId, - signature = "", - ) - ) - - val version = assertNotNull( - db.mantraDao().addArtifactVersion( - localChatRoom = localChatRoom, - artifactId = artifactId, - versionLabel = "first draft", - userPublicKey = author, - ), - "addArtifactVersion returned null", - ) - - val versionSubmission = assertNotNull( - submissions().singleOrNull { it.payloadEventId == version.id }, - "the artifact version was stored without a matching submission", - ) - assertEquals(SubmissionEvent.KIND, versionSubmission.kind) - assertNull(versionSubmission.marmotGroupEventId) - assertEquals(2, submissions().size, "the dialect and the version should each be queued") - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/MemberWalletDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/MemberWalletDaoJvmTest.kt new file mode 100644 index 00000000..8b35f792 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/MemberWalletDaoJvmTest.kt @@ -0,0 +1,76 @@ +package com.machankura.bennu.compose.database.dao + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.database.model.MemberWalletSpend +import com.machankura.bennu.compose.managers.GroupFixtures +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * Schema 30's two tables round-trip, are scoped by profile, and -- the property + * that matters most -- outlive the room of the group that guards them. + */ +class MemberWalletDaoJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val group = "6a".repeat(32) + private val alice = "a1".repeat(32) + private val bob = "b0".repeat(32) + + private fun wallet(id: String, owner: String = alice) = MemberWallet( + walletId = id, + ownerPublicKey = owner, + guardingChatRoomId = group, + chain = "regtest", + walletPrivateKey = "11".repeat(32), + label = "Savings", + requestJson = "{}", + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ) + + @Test + fun `a wallet round-trips and is listed for its owner only`(): Unit = runBlocking { + val dao = db.memberWalletDao() + dao.upsert(wallet("01".repeat(32))) + dao.upsert(wallet("02".repeat(32), owner = bob)) + + assertEquals(wallet("01".repeat(32)), dao.getById("01".repeat(32))) + assertEquals(listOf("01".repeat(32)), dao.getByOwner(alice).map { it.walletId }) + assertEquals(2, dao.getByGuardingChatRoomId(group).size) + assertFalse(wallet("01".repeat(32)).toString().contains("11".repeat(32)), "the key is never in a log line") + } + + @Test + fun `deleting the group's room leaves the key`(): Unit = runBlocking { + GroupFixtures.seedRoom(db, group) + db.memberWalletDao().upsert(wallet("01".repeat(32))) + + db.chatRoomDao().delete(assertNotNull(db.chatRoomDao().findChatRoomById(group)).chatRoom) + + assertNull(db.chatRoomDao().findChatRoomById(group)) + assertNotNull(db.memberWalletDao().getById("01".repeat(32))) + } + + @Test + fun `a spend round-trips and is filled in`(): Unit = runBlocking { + val dao = db.memberWalletDao() + val spend = MemberWalletSpend(txid = "aa".repeat(32), walletId = "01".repeat(32), psbt = "cHNidP8=", signedTransaction = "00") + dao.upsertSpend(spend) + dao.upsertSpend(spend.copy(seenAt = Instant.fromEpochSeconds(1_700_000_100))) + + assertEquals(Instant.fromEpochSeconds(1_700_000_100), dao.getSpend("aa".repeat(32))?.seenAt) + assertEquals(1, dao.getSpends("01".repeat(32)).size) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/migrations/RemoveDocumentsMigrationJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/migrations/RemoveDocumentsMigrationJvmTest.kt new file mode 100644 index 00000000..6316ed77 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/migrations/RemoveDocumentsMigrationJvmTest.kt @@ -0,0 +1,145 @@ +package com.machankura.bennu.compose.database.migrations + +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.driver.bundled.BundledSQLiteDriver +import androidx.sqlite.execSQL +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import java.io.File +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The v26 -> v27 migration, against a real database holding what it removes and + * what it must leave alone. + * + * Two deletes and a drop. The drop is the easy half: twelve tables nothing reads + * and a column only a submission ever set. The deletes are the half worth + * asserting, because a transcript has no undo -- one is aimed at the lines the + * removed document arms wrote, and the other at the raw-hex bubbles a + * subgroup's ceremony left in its parent's chat, found by the kind of the inner + * event behind them. An `unsupported` line over any other kind is still the only + * trace an unrecognised payload leaves, and has to survive. + * + * Built from the exported schemas rather than copied SQL, so the tables are + * exactly the ones a v26 install has, and the result is compared with what Room + * expects of v27. Run on a bare connection, the way the other migration tests + * are: Room's version wiring belongs to `PlatformDatabaseBuilder`. + */ +class RemoveDocumentsMigrationJvmTest { + + private val connection: SQLiteConnection = BundledSQLiteDriver().open(":memory:") + + @AfterTest + fun close() = connection.close() + + private val schemas: File = + (File("schemas").takeIf { it.isDirectory } ?: File("composeApp/schemas")) + .resolve("com.machankura.bennu.compose.database.BennuDatabase") + + private fun entities(version: Int): List = + Json.parseToJsonElement(schemas.resolve("$version.json").readText()) + .jsonObject["database"]!!.jsonObject["entities"]!!.jsonArray + .map { it.jsonObject } + + private fun JsonObject.tableName() = this["tableName"]!!.jsonPrimitive.content + + private fun JsonObject.columns() = + this["fields"]!!.jsonArray.map { it.jsonObject["columnName"]!!.jsonPrimitive.content }.toSet() + + /** Every v26 table, as Room created it. */ + private fun createV26() { + entities(26).forEach { entity -> + val sql = entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", entity.tableName()) + connection.execSQL(sql) + } + } + + private fun tables(): Set = connection.prepare( + "SELECT name FROM sqlite_master WHERE type = 'table'" + ).use { statement -> + buildSet { while (statement.step()) add(statement.getText(0)) } + } + + private fun columnsOf(table: String): Set = connection.prepare("PRAGMA table_info(`$table`)").use { statement -> + buildSet { while (statement.step()) add(statement.getText(1)) } + } + + private fun lines(): List> = connection.prepare( + "SELECT id, messageType FROM ChatMessage ORDER BY id" + ).use { statement -> + buildList { while (statement.step()) add(statement.getLong(0) to statement.getText(1)) } + } + + private fun innerEvent(id: String, kind: Int) = connection.execSQL( + "INSERT INTO MarmotInnerEvent (id, publicKey, chatRoomId, kind, tags, content, " + + "payloadEventId, createdAt, updatedAt, savedAt) VALUES " + + "('$id', 'author', 'room', $kind, '[]', 'content', NULL, 1, 1, 1)" + ) + + private fun line(id: Long, type: String, innerEventId: String? = null) = connection.execSQL( + "INSERT INTO ChatMessage (id, senderPublicKey, isUserMessage, marmotInnerEventId, chatRoomId, " + + "content, messageType, createdAt, updatedAt, savedAt) VALUES " + + "($id, 'author', 0, ${innerEventId?.let { "'$it'" } ?: "NULL"}, 'room', 'x', '$type', 1, 1, 1)" + ) + + @Test + fun `the document tables and the submission column are gone, as Room expects of v27`(): Unit = runBlocking { + createV26() + connection.execSQL( + "INSERT INTO MantraDialect (id, publicKey, name, country, language, signature, chatRoomId, " + + "createdAt, updatedAt) VALUES ('d', 'p', 'isiZulu', 'ZA', 'zu', 's', 'room', 1, 1)" + ) + + MIGRATION_26_27.migrate(connection) + + val expected = entities(27).associate { it.tableName() to it.columns() } + + assertTrue(tables().none { it.startsWith("Mantra") }, "every document table is dropped") + assertEquals( + expected.keys, + tables().filterNot { it.startsWith("sqlite_") || it == "room_master_table" }.toSet(), + "and every other table is still there", + ) + assertFalse("payloadEventId" in columnsOf("MarmotInnerEvent")) + assertEquals(expected["MarmotInnerEvent"], columnsOf("MarmotInnerEvent")) + assertTrue( + "chronicleRequestedAt" in columnsOf("ChatRoom"), + "the chronicle is kept, and so is its column", + ) + } + + @Test + fun `only the lines nothing can show any more are deleted`(): Unit = runBlocking { + createV26() + + innerEvent("round1", kind = 30312) // a subgroup's round 1, read as a submission + innerEvent("proposal", kind = 30310) + innerEvent("mystery", kind = 4242) // a payload this app does not know + + line(1, "translation") + line(2, "dialect") + line(3, "unsupported", innerEventId = "round1") + line(4, "unsupported", innerEventId = "proposal") + line(5, "unsupported", innerEventId = "mystery") + line(6, "unsupported") + line(7, "message") + line(8, "chronicleReceived") + + MIGRATION_26_27.migrate(connection) + + assertEquals( + listOf(5L to "unsupported", 6L to "unsupported", 7L to "message", 8L to "chronicleReceived"), + lines(), + "a ceremony's raw-hex bubbles and the document lines go; an unknown payload's " + + "bubble, a message and the chronicle's line stay", + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt new file mode 100644 index 00000000..339a2ba6 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt @@ -0,0 +1,180 @@ +package com.machankura.bennu.compose.database.model + +import androidx.room3.Room +import com.vitorpamplona.quartz.marmot.GroupEventResult +import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlinx.coroutines.runBlocking +import kotlin.test.assertNotNull +import com.machankura.bennu.compose.nostr.MarmotDirectMessage +import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent +import com.vitorpamplona.quartz.nip01Core.tags.people.PTag +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents + +/** + * A key ceremony's or a signing session's message, arriving in a Marmot room, + * is recognised as one before anything that shares its kind number. + * + * 30310-30312 are both ceremony kinds and nip30303 document kinds. Round 1 of a + * subgroup's ceremony (30312, hex content) was read as a document submission, + * failed to parse, and reached the parent's chat as a bubble of raw hex on every + * other admin's device -- docs/ceremony-creation.md, finding F11. + */ +class ProtocolKindDispatchJvmTest { + + private val database: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = database.close() + + private val self = KeyPair() + private val senderSigner = NostrSignerSync(KeyPair()) + private val sender = senderSigner.pubKey + private val chatRoomId = "639f".repeat(16) + + private var next = 0 + + /** A kind:445 this device has stored, carrying one inner event of [kind]. */ + private suspend fun arrive(kind: Kind, content: String): Pair = arrive( + Event( + id = "%064x".format(2000 + next), + pubKey = sender, + createdAt = 1, + kind = kind, + tags = DkgRitualEvents.assembleTags(sessionId = "5e55".repeat(16)), + content = content, + sig = "", + ) + ) + + /** A kind:445 this device has stored, carrying [inner]. */ + private suspend fun arrive(inner: Event): Pair { + val n = next++ + val groupEventId = "%064x".format(1000 + n) + + database.nostrEventDao().upsert( + NostrEvent( + id = groupEventId, + pubKey = sender, + kind = GroupEvent.KIND, + tags = arrayOf(arrayOf("h", chatRoomId)), + content = "ciphertext", + sig = "0".repeat(128), + ) + ) + database.marmotGroupEventDao().upsert( + MarmotGroupEvent( + id = groupEventId, + userPublicKey = self.pubKey.toHexKey(), + publicKey = sender, + chatRoomId = chatRoomId, + signature = "0".repeat(128), + encryptedContent = "ciphertext", + expiresAt = null, + createdAt = Instant.fromEpochSeconds(1), + ) + ) + + val groupEvent = GroupEvent( + id = groupEventId, + pubKey = sender, + createdAt = 1, + tags = arrayOf(arrayOf("h", chatRoomId)), + content = "ciphertext", + sig = "0".repeat(128), + ) + val line = ChatMessage.fromGroupEventResult( + database = database, + activeKeyPair = self, + groupEvent = groupEvent, + groupEventResult = GroupEventResult.ApplicationMessage( + groupId = chatRoomId, + innerEventJson = inner.toJson(), + senderLeafIndex = 1, + epoch = 1, + ), + senderIdentity = sender, + ) + + return groupEvent to line + } + + // What a round-1 message actually carries: a ChillDKG pmsg1, hex encoded. + // Its leading zero is what made it unparseable as an event. + private val round1Content = "024f99efa68cafafd766eec95ad940cd096a5f1a7b42d14132121ad7d2dc310d03" + + @Test + fun `a ceremony message writes no chat line, whatever shares its number`(): Unit = runBlocking { + DkgRitualEvents.ALL.forEach { kind -> + val (groupEvent, line) = arrive(kind, content = round1Content) + + assertNull(line, "kind $kind is the ceremony's, and writes no line of its own") + assertNull( + database.chatMessageDao().getChatMessagesByMarmotGroupEventId(groupEvent.id), + "and nothing is filed in its place", + ) + } + + assertEquals( + DkgRitualEvents.ALL, + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, DkgRitualEvents.ALL.toList()) + .map { it.kind } + .toSet(), + "every one is still stored, so a ceremony can replay what arrived before its proposal", + ) + } + + /** + * A direct message's envelope shares 30330 with a signing session's decline. + * + * Treating every 30330 as a decline -- which is what recognising protocol + * kinds first did at first -- dropped every direct message in a + * current-profile room before it was opened. What tells the two apart is + * what the event carries. + */ + @Test + fun `a direct message envelope is opened, not taken for a decline`(): Unit = runBlocking { + val wrap = MarmotDirectMessage.wrap( + signer = senderSigner, + recipientPublicKey = self.pubKey.toHexKey(), + kind = ChatMessageEvent.KIND, + createdAt = 1, + tags = arrayOf(PTag.assemble(self.pubKey.toHexKey(), null)), + content = "the vote is at six", + ) + val envelope = MarmotDirectMessage.envelope(sender, self.pubKey.toHexKey(), wrap, createdAt = 1) + assertEquals(FrostSigningEvents.DECLINE, envelope.kind, "the collision this test exists for") + + val (_, line) = arrive(Event.fromJson(envelope.toJson())) + + val opened = assertNotNull(line, "the envelope must reach the direct-message path") + assertTrue(opened.content.contains("the vote is at six"), "and be opened: ${opened.content}") + } + + @Test + fun `a signing message writes no chat line`(): Unit = runBlocking { + FrostSigningEvents.ALL.forEach { kind -> + val (_, line) = arrive(kind, content = "{}") + assertNull(line, "kind $kind is a signing session's") + } + + assertTrue( + database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).isEmpty(), + "and the room's transcript is untouched", + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/TranslationChunkApplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/TranslationChunkApplyJvmTest.kt deleted file mode 100644 index ba4d1ef4..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/TranslationChunkApplyJvmTest.kt +++ /dev/null @@ -1,301 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Room -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlinx.coroutines.runBlocking -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.builder.getRoomDatabase -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * What happens when a chunk is translated twice. - * - * A translation chunk is not edited. Retranslating a passage means proposing a - * new event carrying new words, and an event's id is a hash over its content -- - * so the second translation arrives as a row of its own rather than as an - * overwrite of the first. Left alone, the chapter would hold two answers to - * what one passage says, and the table pairing chunks with their translations - * would show whichever the query reached first. - * - * The rule this asserts is that the newest one wins, decided by the timestamp - * the group signed at rather than by arrival: two devices catching up read the - * same events in whatever order the relay hands them over, and they have to end - * up holding the same translation either way. - */ -class TranslationChunkApplyJvmTest { - - private val db: BennuDatabase = getRoomDatabase( - Room.inMemoryDatabaseBuilder() - ) - - @AfterTest - fun closeDb() = db.close() - - private val author = "a".repeat(64) - private val roomId = "b".repeat(64) - private val chunkId = "c".repeat(64) - private val translationChapterId = "d".repeat(64) - private val signature = "0".repeat(128) - - /** - * Everything a translation chunk hangs off, seeded as already signed: the - * room, the artifact it belongs to, the chapter and chunk it translates, and - * the translation chapter it goes into. None of it is what this test is - * about; they are the foreign keys in the way. - */ - private suspend fun seed() { - val nostrEventId = "e".repeat(64) - db.nostrEventDao().upsert( - NostrEvent( - id = nostrEventId, - pubKey = author, - kind = 0, - tags = emptyArray(), - content = "{}", - sig = signature, - ) - ) - db.profileDao().upsert(Profile(publicKey = author, nostrEventId = nostrEventId)) - db.chatRoomDao().upsert( - ChatRoom( - id = roomId, - userPublicKey = author, - subject = "a translation room", - description = null, - mlsGroupState = null, - ) - ) - - val dialectId = "1".repeat(64) - db.mantraDialectDao().upsert( - MantraDialect( - id = dialectId, - publicKey = roomId, - name = "Sesotho", - country = "ZA", - language = "st", - signature = signature, - chatRoomId = roomId, - ) - ) - - val artifactId = "2".repeat(64) - db.mantraArtifactDao().upsert( - MantraArtifact( - id = artifactId, - publicKey = roomId, - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = dialectId, - license = "cc", - chatRoomId = roomId, - signature = signature, - ) - ) - - val artifactVersionId = "3".repeat(64) - db.mantraArtifactVersionDao().upsert( - MantraArtifactVersion( - id = artifactVersionId, - artifactId = artifactId, - publicKey = roomId, - versionLabel = "1.0", - signature = signature, - chatRoomId = roomId, - ) - ) - - val chapterId = "4".repeat(64) - db.mantraChapterDao().upsert( - MantraChapter( - id = chapterId, - artifactVersionId = artifactVersionId, - publicKey = roomId, - name = "Chapter 1", - originalText = "When he was nearly thirteen.", - index = 0, - wordCount = 5, - characterCount = 28, - signature = signature, - chatRoomId = roomId, - ) - ) - - db.mantraChunkDao().upsert( - MantraChunk( - id = chunkId, - chapterId = chapterId, - publicKey = roomId, - text = "When he was nearly thirteen.", - index = 0, - wordCount = 5, - characterCount = 28, - signature = signature, - chatRoomId = roomId, - ) - ) - - val translationId = "5".repeat(64) - db.mantraTranslationArtifactVersionDao().upsert( - MantraTranslationArtifactVersion( - id = translationId, - publicKey = roomId, - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = "Sesotho", - visibility = "private", - license = "cc", - signature = signature, - chatRoomId = roomId, - ) - ) - - db.mantraTranslationChapterDao().upsert( - MantraTranslationChapter( - id = translationChapterId, - publicKey = roomId, - chapterId = chapterId, - translationArtifactVersionId = translationId, - index = 0, - signature = signature, - chatRoomId = roomId, - ) - ) - } - - /** A translation of the seeded chunk, signed by the room as the group would. */ - private fun translation(text: String, createdAt: Long): Event { - val template = TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = text, - createdAt = createdAt, - ) - - return Event( - id = EventHasher.hashId( - pubKey = roomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - ), - pubKey = roomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = signature, - ) - } - - private suspend fun apply(event: Event) = ChatMessage.applyInnerEvent( - database = db, - groupId = roomId, - event = event, - marmotGroupEventId = null, - marmotInnerEventId = null, - senderPublicKey = roomId, - isUserMessage = false, - createdAt = Instant.fromEpochSeconds(event.createdAt), - ) - - private suspend fun translations() = db.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapterId) - - @Test - fun `a retranslation replaces the translation it supersedes`() = runBlocking { - seed() - - val signedAt = Clock.System.now().epochSeconds - apply(translation("Ha a le hantle lilemo li leshome le metso e meraro.", signedAt)) - apply(translation("Ha a batla ho ba lilemo li leshome le metso e meraro.", signedAt + 60)) - - // Both are valid signatures of the group's over the same passage, and - // the chapter has room for one of them. - val kept = translations().single() - assertEquals("Ha a batla ho ba lilemo li leshome le metso e meraro.", kept.text) - } - - @Test - fun `a translation arriving after the one that superseded it is dropped`() = runBlocking { - seed() - - val signedAt = Clock.System.now().epochSeconds - val first = translation("Ha a le hantle lilemo li leshome le metso e meraro.", signedAt) - val second = translation("Ha a batla ho ba lilemo li leshome le metso e meraro.", signedAt + 60) - - // The order the relay happened to hand them over in, which is not the - // order the group signed them in. A device catching up has to reach the - // same chapter as one that saw them the other way round. - apply(second) - apply(first) - - val kept = translations().single() - assertEquals(second.id, kept.id) - } - - @Test - fun `two chunks of the same chapter each keep their translation`() = runBlocking { - seed() - - // The rule is one translation per source chunk, not one per chapter. - // Matching on the chapter alone would leave a chapter that can only ever - // hold its most recently translated passage. - val otherChunkId = "f".repeat(64) - db.mantraChunkDao().upsert( - MantraChunk( - id = otherChunkId, - chapterId = "4".repeat(64), - publicKey = roomId, - text = "My brother Jem got his arm badly broken.", - index = 1, - wordCount = 8, - characterCount = 40, - signature = signature, - chatRoomId = roomId, - ) - ) - - val signedAt = Clock.System.now().epochSeconds - apply(translation("Ha a le hantle lilemo li leshome le metso e meraro.", signedAt)) - - val otherTemplate = TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = otherChunkId, - index = 1, - text = "Moholoane oa ka Jem o ile a robeha letsoho.", - createdAt = signedAt + 60, - ) - apply( - Event( - id = EventHasher.hashId( - pubKey = roomId, - createdAt = otherTemplate.createdAt, - kind = otherTemplate.kind, - tags = otherTemplate.tags, - content = otherTemplate.content, - ), - pubKey = roomId, - createdAt = otherTemplate.createdAt, - kind = otherTemplate.kind, - tags = otherTemplate.tags, - content = otherTemplate.content, - sig = signature, - ) - ) - - assertEquals( - listOf(chunkId, otherChunkId), - translations().map { it.chunkId }, - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/CeremonyEntryPointsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/CeremonyEntryPointsJvmTest.kt new file mode 100644 index 00000000..7a1ce634 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/CeremonyEntryPointsJvmTest.kt @@ -0,0 +1,47 @@ +package com.machankura.bennu.compose.managers + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A key ceremony is started in exactly three places, each of which knows what + * the ceremony is for. + * + * - group creation (`SelectChatRoomTypeViewModel`), a new group's own key; + * - the subgroup picker (`SelectSubgroupAdminsViewModel`), a subgroup's key, + * held in its parent's room; + * - `CreateSharedKeyViewModel`, an existing NIP-17 group that has no key yet. + * + * A fourth used to exist: the ceremony screen offered "Start key ceremony" from + * the same button slot its approvals used, and a member coming back from + * approving a subgroup's ceremony opened a second, whole-room one in the + * parent's room. See docs/ceremony-creation.md. + * + * This counts calls rather than proving anything about them, which is the + * point: it fails the day a fourth appears, so that adding one is a decision + * somebody makes here rather than a button somebody adds to a screen. + */ +class CeremonyEntryPointsJvmTest { + + private val source: File = + File("src").takeIf { it.resolve("commonMain").isDirectory } ?: File("composeApp/src") + + @Test + fun `a ceremony is opened from three screens and no others`() { + val callers = source.resolve("commonMain/kotlin").walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .filter { "dkgRepository.proposeRitual(" in it.readText() } + .map { it.nameWithoutExtension } + .toSet() + + assertEquals( + setOf( + "SelectChatRoomTypeViewModel", + "SelectSubgroupAdminsViewModel", + "CreateSharedKeyViewModel", + ), + callers, + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChapterBatchProposalJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChapterBatchProposalJvmTest.kt deleted file mode 100644 index bd62c329..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChapterBatchProposalJvmTest.kt +++ /dev/null @@ -1,238 +0,0 @@ -package com.machankura.bennu.compose.managers - -import androidx.room3.Room -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertTrue -import kotlinx.coroutines.runBlocking -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.builder.getRoomDatabase -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.DkgParticipantMessage -import com.machankura.bennu.compose.database.model.DkgSession -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.types.DkgRitualStage -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.text.Markdown - -/** - * What a chapter proposal actually puts in front of the group. - * - * `SignedChapterTest` builds the batch by hand and signs it, which proves the - * crypto and the rows but assumes the shape. This runs the real proposal - * against a real database, because the shape is the part with the sharp edge: - * a chunk carries its chapter's id, and that id does not exist until the - * proposal authors the chapter under the group's key at the room's derivation - * path. Both are resolved inside `proposeSigningBatch` and neither is knowable - * to the caller, which is why the chunks are built from what it hands back. - * - * If that came apart, the chapter would still be signed and every chunk would - * still verify -- against a chapter id nobody has. They would fail a foreign - * key on the way in and the chapter would simply arrive empty. - */ -class ChapterBatchProposalJvmTest { - private val participants = 3 - private val threshold = 2 - - /** Stands in for a completed ceremony; the test is about the proposal, not the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() - - /** The admin room: the group's key walked to the admin path, which is its id. */ - private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - - private val ceremonyId = "ceremony".padEnd(64, '0') - private val members = listOf("a", "b", "c").map { it.repeat(64) } - private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } - - private val proposer = members.first() - private val artifactVersionId = "b".repeat(64) - - private lateinit var db: BennuDatabase - private lateinit var room: LocalChatRoom - - @AfterTest - fun closeDatabase() { - if (::db.isInitialized) db.close() - } - - /** The proposer's device: a room it can sign in, and the share to sign with. */ - private suspend fun openDevice() { - db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - // Profile hangs off a nostr event, and a room off a profile. Neither is - // anything this test is about; they are the foreign keys in the way. - val nostrEventId = "e$proposer".take(64) - db.nostrEventDao().upsert( - NostrEvent( - id = nostrEventId, - pubKey = proposer, - kind = 0, - tags = emptyArray(), - content = "{}", - sig = "0".repeat(128) - ) - ) - db.profileDao().upsert(Profile(publicKey = proposer, nostrEventId = nostrEventId)) - - val chatRoom = ChatRoom( - id = roomId, - userPublicKey = proposer, - subject = "#Ekklesia", - description = SharedKeyDerivation.describe("Admins of the group."), - mlsGroupState = null - ) - db.chatRoomDao().upsert(chatRoom) - - db.dkgSessionDao().upsert( - DkgSession( - id = ceremonyId, - chatRoomId = roomId, - coordinatorPublicKey = proposer, - userPublicKey = proposer, - threshold = threshold, - participantCount = participants, - stage = DkgRitualStage.COMPLETE, - hostPublicKey = hostKeys[0], - round1Random = "1".repeat(64), - round2AuxRandom = "2".repeat(64), - thresholdPublicKey = thresholdPublicKey, - secretShare = keyMaterial.secretShares[0].value.toHex(), - publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() } - ) - ) - - members.forEachIndexed { index, member -> - db.dkgSessionDao().upsert( - DkgParticipantMessage( - sessionId = ceremonyId, - participantPublicKey = member, - kind = DkgRitualEvents.HOST_KEY, - payload = hostKeys[index] - ) - ) - } - - room = LocalChatRoom(chatRoom = chatRoom) - } - - private fun chapterTemplate(originalText: String, name: String = "Chapter 1") = - ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = name, - originalText = originalText, - index = 0, - wordCount = Markdown.wordCount(originalText), - characterCount = Markdown.characterCount(originalText), - ) - - /** Exactly what `AddChapterViewModel.addChapter` proposes. */ - private suspend fun proposeChapter(originalText: String) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - lead = chapterTemplate(originalText), - dependents = ChunkEvent::splitOf - ) - - private suspend fun itemEvents(sessionId: String): List = - db.frostSigningSessionDao().getItems(sessionId).map { Event.fromJson(it.unsignedEventJson) } - - private fun paragraphs(count: Int) = (1..count).joinToString("\n\n") { "Paragraph $it." } - - @Test - fun `the chapter leads the batch and its chunks follow`() = runBlocking { - openDevice() - - val session = proposeChapter("The first paragraph.\n\nThe second paragraph.") - val events = itemEvents(session.id) - - // Item order is apply order, and a chunk row whose chapter does not - // exist yet is a foreign key violation. The chapter has to be first. - assertEquals(3, events.size) - assertEquals(ChapterEvent.KIND, events.first().kind) - assertTrue(events.drop(1).all { it.kind == ChunkEvent.KIND }) - } - - @Test - fun `every chunk names the chapter as the group will author it`() = runBlocking { - openDevice() - - val session = proposeChapter("The first paragraph.\n\nThe second paragraph.") - val events = itemEvents(session.id) - val chapter = events.first() - - // The claim the whole `lead`/`dependents` form exists for. The id here is - // a hash over the group's key at the room's path; a caller that built the - // chunks before proposing could not have known it. - val chunks = events.drop(1).map { - ChunkEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - - assertTrue(chunks.all { it.chapterId() == chapter.id }) - assertEquals(listOf("The first paragraph.", "The second paragraph."), chunks.map { it.content }) - } - - @Test - fun `the whole batch is authored by the room, not by the proposer`() = runBlocking { - openDevice() - - val events = itemEvents(proposeChapter("One.\n\nTwo.").id) - - // Signing runs at the path the room was derived at, so the author of - // every item is the room's own id -- chunks included, which is what lets - // one be checked without being told which key to expect. - assertTrue(events.all { it.pubKey == roomId }) - assertTrue(events.none { it.pubKey == proposer }) - } - - @Test - fun `a chapter of the longest allowed length still proposes`() = runBlocking { - openDevice() - - val events = itemEvents( - proposeChapter(paragraphs(FrostSigningManager.MAX_BATCH_SIZE - 1)).id - ) - - // The arithmetic the form is built on: the chapter takes one of the - // batch's places and the paragraphs get the rest. If this stopped being - // true, `AddChapterScreen` would offer a chapter the session then refuses. - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, events.size) - } - - @Test - fun `a chapter of one paragraph too many is refused`() = runBlocking { - openDevice() - - // Refused here rather than truncated: a batch that quietly dropped its - // last paragraphs would sign a chapter whose text nobody holds the - // chunks for. The screen checks first so this is never what a member - // sees, but the screen is not what enforces it. - assertFailsWith { - proposeChapter(paragraphs(FrostSigningManager.MAX_BATCH_SIZE)) - } - - assertEquals(emptyList(), db.frostSigningSessionDao().getSessionsForChatRoom(roomId)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt index 6c1e88a2..322a4743 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt @@ -4,7 +4,10 @@ import androidx.room3.Room import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey @@ -27,26 +30,21 @@ import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.builder.getRoomDatabase import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.MarmotInnerEvent import com.machankura.bennu.compose.database.model.MarmotKeyPackage import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent +import com.machankura.bennu.compose.nostr.chronicle.ChronicleKinds import com.machankura.bennu.compose.nostr.chronicle.ChronicleRequestEvent +import com.machankura.bennu.compose.nostr.chronicle.TEST_KINDS import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleIdTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChroniclePageTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleRecipientTag import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent /** * Two devices, two databases: one that did the work and one that arrived after @@ -54,14 +52,18 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent * * This is the claim the whole feature is: a member who holds no share, took part * in no signing session and cannot decrypt a word of the room's history ends up - * with the same rows as everybody else, and gets there without trusting the - * member who sent them. + * holding what the group signed, and gets there without trusting the member who + * sent it. * * The negative cases matter more than the positive one. Verification is what * makes a chronicle safe to accept from anybody, so what has to be proved is that * it refuses -- a forged payload beside honest ones, and a genuine key state * replayed out of its epoch, which passes every signature check there is and is * stopped by nothing but the allowlist. + * + * The app's own list of kinds is empty, so everything here runs on [TEST_KINDS] + * except the last section, which is about the app's list and holds it to + * carrying nothing in either direction. */ class ChronicleApplyJvmTest { /** The member who did the work. */ @@ -174,6 +176,9 @@ class ChronicleApplyJvmTest { private fun signed(template: EventTemplate<*>) = signedBy(keyMaterial, template) + private fun template(kind: Int, createdAt: Long, content: String, tags: Array> = emptyArray()) = + EventTemplate(createdAt = createdAt, kind = kind, tags = tags, content = content) + private suspend fun seedRoom(db: BennuDatabase, user: String) { val nostrEventId = "c".repeat(63) + if (user == newMember) "1" else "2" db.nostrEventDao().upsert( @@ -198,7 +203,19 @@ class ChronicleApplyJvmTest { ) } - private suspend fun apply(db: BennuDatabase, event: Event) { + /** + * What `FrostSigningManager.complete` does with a finished batch: file the + * events as the group signed them, then apply them. + */ + private suspend fun recordAndApply(db: BennuDatabase, event: Event) { + db.groupSignedEventDao().record( + GroupSignedEvent.fromEvent( + event = event, + chatRoomId = chatRoomId, + derivationPath = SharedKeyDerivation.formatPath(), + frostSigningSessionId = "session-1", + ) + ) ChatMessage.applyInnerEvent( database = db, groupId = chatRoomId, @@ -207,106 +224,24 @@ class ChronicleApplyJvmTest { marmotInnerEventId = null, senderPublicKey = chatRoomId, isUserMessage = false, - createdAt = Instant.fromEpochSeconds(event.createdAt) + createdAt = Instant.fromEpochSeconds(event.createdAt), + groupSignedEventId = event.id, ) } - /** The sender's room, with a full artifact and one translation scaffolded. */ + /** The sender's room, holding one signed event of every test kind and two of one. */ private suspend fun seedSenderWork() { seedRoom(sender, oldMember) - val dialect = signed( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ).also { apply(sender, it) } - - val artifact = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) - ).also { apply(sender, it) } - - // The second item of the artifact's own signing batch, not a row derived - // on arrival -- which is what makes it chroniclable at all. - val version = signed(ArtifactVersionEvent.initialVersionOf(artifact).single()) - .also { apply(sender, it) } - - val chapter = signed( - ChapterEvent.build( - artifactVersionId = version.id, - name = "Chapter One", - originalText = "He was a man of parts. He had many.", - index = 0, - wordCount = 8, - characterCount = 35, - createdAt = 1_700_000_020L - ) - ).also { apply(sender, it) } - - val chunk = signed( - ChunkEvent.build( - chapterId = chapter.id, - text = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_030L - ) - ).also { apply(sender, it) } - apply( - sender, - signed( - ChunkEvent.build( - chapterId = chapter.id, - text = "He had many.", - index = 1, - wordCount = 3, - characterCount = 12, - createdAt = 1_700_000_031L - ) - ) - ) - - val translationVersion = signed( - TranslationArtifactVersionEvent.build( - artifactVersionId = version.id, - dialectId = dialect.id, - name = "isiZulu", - visibility = "private", - license = "cc", - createdAt = 1_700_000_040L - ) - ).also { apply(sender, it) } - - val translationChapter = signed( - TranslationChapterEvent.build( - translationArtifactVersionId = translationVersion.id, - chapterId = chapter.id, - index = 0, - createdAt = 1_700_000_050L - ) - ).also { apply(sender, it) } - - // The translated text. Group-signed now, so it can travel and be checked - // -- until it was, a chronicle handed a new member the whole structure and - // none of the prose. - apply( - sender, - signed( - TranslationChunkEvent.build( - translationChapterId = translationChapter.id, - chunkId = chunk.id, - index = 0, - text = "Wayeyindoda enezingxenye.", - createdAt = 1_700_000_060L - ) - ) - ) + listOf( + template( + AdvertisedRelayListEvent.KIND, 1_700_000_000L, "", + tags = arrayOf(arrayOf("r", "wss://relay.example.com")), + ), + template(MetadataEvent.KIND, 1_700_000_010L, "{\"name\":\"Ekklesia\"}"), + template(TextNoteEvent.KIND, 1_700_000_020L, "The group says hello."), + template(TextNoteEvent.KIND, 1_700_000_021L, "And says it again."), + ).forEach { recordAndApply(sender, signed(it)) } } /** @@ -318,6 +253,7 @@ class ChronicleApplyJvmTest { template: EventTemplate, to: String = newMember, from: String = oldMember, + kinds: ChronicleKinds = TEST_KINDS, ): ChronicleManager.Outcome { val page = Event( id = EventHasher.hashId( @@ -349,79 +285,46 @@ class ChronicleApplyJvmTest { ) ) - return ChronicleManager.receive(receiver, chatRoomId, to, page) + return ChronicleManager.receive(receiver, chatRoomId, to, page, kinds) } - private suspend fun senderChronicle() = ChronicleManager.assemble(sender, chatRoomId, newMember) + private suspend fun senderChronicle() = + ChronicleManager.assemble(sender, chatRoomId, newMember, kinds = TEST_KINDS) - private suspend fun rowCounts(db: BennuDatabase): Map { - val dialects = db.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - val artifacts = db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId) - val versions = artifacts.flatMap { - db.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(it.id) - } - val chapters = versions.flatMap { db.mantraChapterDao().getChaptersByArtifactVersionId(it.id) } - val chunks = chapters.flatMap { db.mantraChunkDao().getChunksByChapterId(it.id) } - val translationVersions = versions.flatMap { - db.mantraTranslationArtifactVersionDao().getTranslationsByArtifactVersionId(it.id) - } - val translationChapters = translationVersions.flatMap { - db.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId(it.id) - } - val translationChunks = translationChapters.flatMap { - db.mantraTranslationChunkDao().getTranslationChunksByTranslationChapterId(it.id) - } + /** Every payload of the sender's chronicle, one page each, numbered as [chronicleId]. */ + private suspend fun onePagePerPayload(chronicleId: String = "e".repeat(64)): List> { + val payloads = senderChronicle() + .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - return mapOf( - "dialects" to dialects.size, - "artifacts" to artifacts.size, - "versions" to versions.size, - "chapters" to chapters.size, - "chunks" to chunks.size, - "translationVersions" to translationVersions.size, - "translationChapters" to translationChapters.size, - "translationChunks" to translationChunks.size, - ) + return payloads.mapIndexed { index, payload -> + ChronicleEvent.build( + payloads = listOf(payload), + chronicleId = chronicleId, + index = index, + count = payloads.size, + recipient = newMember, + createdAt = 1_700_000_100L + index, + kinds = TEST_KINDS, + ) + } } /** - * Every chronicled row as (id, author, signature), sorted. + * Every group-signed event on file as (id, author, signature), sorted. * - * Counting is not the claim. Two databases can hold the same number of - * artifacts and disagree about every one of them, and a rebuild that lost the - * group's signature -- or re-authored a row as whoever sent it -- would pass a - * count and fail the only thing the chronicle is for. + * None of the test kinds' arms writes a row of its own, so this table is the + * whole of what a chronicle restores. Compared rather than counted: two + * databases can hold the same number of events and disagree about every one, + * and a chronicle that re-authored each as whoever sent it would pass a count + * and fail the only thing it is for. */ - private suspend fun rowFingerprints(db: BennuDatabase): List> { - val artifacts = db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId) - val versions = artifacts.flatMap { - db.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(it.id) - } - val chapters = versions.flatMap { db.mantraChapterDao().getChaptersByArtifactVersionId(it.id) } - val translationVersions = versions.flatMap { - db.mantraTranslationArtifactVersionDao().getTranslationsByArtifactVersionId(it.id) - } + private suspend fun fingerprints(db: BennuDatabase): List> = + db.groupSignedEventDao().getByChatRoomId(chatRoomId) + .map { Triple(it.id, it.publicKey, it.signature) } + .sortedBy { it.first } - return buildList { - db.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - .forEach { add(Triple(it.id, it.publicKey, it.signature)) } - artifacts.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - versions.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - chapters.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - chapters.flatMap { db.mantraChunkDao().getChunksByChapterId(it.id) } - .forEach { add(Triple(it.id, it.publicKey, it.signature)) } - translationVersions.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - val translationChapters = translationVersions.flatMap { - db.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId(it.id) - } - translationChapters.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - translationChapters - .flatMap { db.mantraTranslationChunkDao().getTranslationChunksByTranslationChapterId(it.id) } - .forEach { add(Triple(it.id, it.publicKey, it.signature)) } - }.sortedBy { it.first } - } + private suspend fun lines(db: BennuDatabase) = + db.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).map { it.chatMessage.messageType } @Test fun `a member who was never there ends up holding what the group signed`() = runBlocking { @@ -429,78 +332,62 @@ class ChronicleApplyJvmTest { seedRoom(receiver, newMember) assertEquals( - mapOf( - "dialects" to 0, "artifacts" to 0, "versions" to 0, "chapters" to 0, - "chunks" to 0, "translationVersions" to 0, "translationChapters" to 0, - "translationChunks" to 0, - ), - rowCounts(receiver), + emptyList(), + fingerprints(receiver), "the new member starts with nothing, which is the whole problem" ) senderChronicle().forEach { deliver(it) } - assertEquals(rowCounts(sender), rowCounts(receiver)) + val fingerprints = fingerprints(receiver) + assertTrue(fingerprints.isNotEmpty()) - // Not merely the same shape: the same rows, each with the group's own - // signature on it. A chronicle that produced look-alike rows authored by - // the member who sent them would pass a count and fail the only thing - // this is for. - val fingerprints = rowFingerprints(receiver) - assertEquals(rowFingerprints(sender), fingerprints) + // Not merely the same number: the same events, each with the group's own + // signature on it. + assertEquals(fingerprints(sender), fingerprints) - // And every one of them is the room's own work, with no exception left. - // The artifact version used to be one -- derived on arrival, so authored - // by the group and carrying no signature to show for it -- and is signed - // in the artifact's own batch now, which is what let it into the chronicle. fingerprints.forEach { (id, author, signature) -> - assertEquals(chatRoomId, author, "row $id is not authored by the room") - assertTrue(signature.isNotBlank(), "row $id came across without a signature") + assertEquals(chatRoomId, author, "event $id is not authored by the room") + assertTrue(signature.isNotBlank(), "event $id came across without a signature") } } /** * The member who was handed history can hand it on. * - * Rows are a reading of what the group signed; the events are the thing - * itself, and until they are kept the recipient of a chronicle is a dead end - * -- holding the work, unable to prove any of it, and unable to build a page - * for the next member to arrive. The path is the room's, read from the key - * state when the recipient has one. + * The events are the thing itself, and until they are kept the recipient of + * a chronicle is a dead end -- holding the work, unable to prove any of it, + * and unable to build a page for the next member to arrive. */ @Test - fun `the chronicle leaves the receiver holding the events, not only the rows`() = runBlocking { + fun `the chronicle leaves the receiver holding the events as the group signed them`() = runBlocking { seedSenderWork() seedRoom(receiver, newMember) senderChronicle().forEach { deliver(it) } - val signed = receiver.groupSignedEventDao().getByChatRoomId(chatRoomId) + val held = receiver.groupSignedEventDao().getByChatRoomId(chatRoomId) + val original = sender.groupSignedEventDao().getByChatRoomId(chatRoomId).associateBy { it.id } - assertEquals( - senderChronicle() - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - .map { it.id } - .toSet(), - signed.map { it.id }.toSet(), - "every payload that applied should be on file as the group signed it" - ) - assertTrue(signed.isNotEmpty()) + assertEquals(original.keys, held.map { it.id }.toSet()) - signed.forEach { event -> - assertEquals(chatRoomId, event.publicKey, "${event.id} is not authored by the room") + held.forEach { event -> assertTrue(event.verifies(), "${event.id} does not read back as the room's") + assertEquals( + assertNotNull(original[event.id]).toEvent().toJson(), + event.toEvent().toJson(), + "${event.id} did not arrive as the group signed it" + ) // Nothing on this device ran a session for any of it. assertNull(event.frostSigningSessionId) } - - // The rows the payloads became point back at them, which is the only - // provenance a group-signed row has: no group event, no inner event. - val dialects = receiver.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - assertTrue(dialects.isNotEmpty()) - dialects.forEach { assertEquals(it.id, it.groupSignedEventId) } } + /** + * Every test kind's arm in `applyInnerEvent` hands back a line -- "the group + * posted in its own name" and the like -- so this is a real refusal and not + * an absence. + */ @Test fun `a chronicle files no chat lines`() = runBlocking { seedSenderWork() @@ -510,9 +397,7 @@ class ChronicleApplyJvmTest { assertEquals( emptyList(), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - .filterNot { it in ChatMessage.CHRONICLE_TYPES }, + lines(receiver).filterNot { it in ChatMessage.CHRONICLE_TYPES }, "the chronicle restores the work; the conversation is forward secret and stays gone" ) } @@ -522,87 +407,90 @@ class ChronicleApplyJvmTest { seedSenderWork() seedRoom(receiver, newMember) - // One page per payload, delivered backwards -- a translation chapter - // before the chapter it names, chunks before their chapter, the artifact - // last. Relays give no ordering guarantee, so this is the ordinary case - // rather than the adversarial one. - val payloads = senderChronicle() - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - val chronicleId = "e".repeat(64) + // One page per payload, delivered backwards. Relays give no ordering + // guarantee, so this is the ordinary case rather than the adversarial + // one. Nothing in the test list hangs off anything else, so no payload + // has to wait here; the retry that waiting needs is the next test's. + val outcomes = onePagePerPayload().reversed().map { deliver(it) } - val outcomes = payloads.reversed().mapIndexed { index, payload -> - deliver( - ChronicleEvent.build( - payloads = listOf(payload), - chronicleId = chronicleId, - index = index, - count = payloads.size, - recipient = newMember, - createdAt = 1_700_000_100L + index, - ) - ) - } + assertEquals(0, outcomes.sumOf { it.failed }) + assertEquals(fingerprints(sender), fingerprints(receiver)) + } - // Without this the test could pass for the wrong reason -- if nothing - // ever failed to apply, the pages were not really out of order and the - // sweep was never the thing that saved them. - assertTrue( - outcomes.any { it.failed > 0 }, - "delivering backwards should have left payloads waiting on rows they depend on" - ) - assertEquals( - 0, - outcomes.last().failed, - "the last page completes the chronicle, so the pass it triggers should leave nothing" - ) + /** + * The sweep's reason to exist: a payload that threw is run again when the + * next page arrives, because the pages are on disk and the sweep takes all of + * them. + * + * In the app the missing dependency is another payload's row; nothing in the + * test list depends on another, so here it is the room row itself, the one + * foreign key every recorded event has. What is under test is the retry, not + * the reason for it. + */ + @Test + fun `a payload that could not apply yet is retried when the next page arrives`() = runBlocking { + seedSenderWork() - assertEquals(rowCounts(sender), rowCounts(receiver)) + val pages = onePagePerPayload() + assertTrue(pages.size >= 2, "this needs a second page to arrive after the first fails") + + // No room on file yet: the first page's payload has nowhere to go. + val first = deliver(pages.first()) + assertEquals(1, first.failed, "the first payload should have been left waiting") + assertEquals(0, first.applied) + assertEquals(emptyList(), fingerprints(receiver)) + + // The room appears, and the next page's sweep takes the first one with it. + seedRoom(receiver, newMember) + val second = deliver(pages[1]) + + assertEquals(0, second.failed) + assertEquals(2, second.applied, "the waiting payload and the new one") + + pages.drop(2).forEach { deliver(it) } + assertEquals(fingerprints(sender), fingerprints(receiver)) } @Test fun `one forged payload costs itself and nothing else`() = runBlocking { - seedSenderWork() seedRoom(receiver, newMember) - val honest = signed( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ) + val honest = signed(template(MetadataEvent.KIND, 1_700_000_000L, "{\"name\":\"Ekklesia\"}")) // Four ways to be a dishonest member, in one page beside one honest - // dialect. Every one of them is well-formed and would file a row without - // the check. + // profile. Every one of them is well-formed and of a kind the list admits. val forgeries = listOf( // The room's id as author -- everybody knows it -- and a made-up // signature. Event( id = EventHasher.hashId( - pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = DialectEvent.KIND, - tags = honest.tags, content = "forged" + pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"forged\"}" ), - pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = DialectEvent.KIND, - tags = honest.tags, content = "forged", sig = "9".repeat(128) + pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"forged\"}", sig = "9".repeat(128) ), // A real quorum, of another group. signedBy( otherKeyMaterial, - DialectEvent.build(name = "seSotho", country = "ZA", language = "st", createdAt = 1_700_000_002L) + template(MetadataEvent.KIND, 1_700_000_002L, "{\"name\":\"Elsewhere\"}") ), // Edited after the group signed it. Event( id = honest.id, pubKey = honest.pubKey, createdAt = honest.createdAt, kind = honest.kind, - tags = arrayOf(arrayOf("alt", "Dialect"), arrayOf("name", "tampered")), + tags = arrayOf(arrayOf("name", "tampered")), content = honest.content, sig = honest.sig ), // A member's own rumor, which is what everything on the wire looks // like today. Event( id = EventHasher.hashId( - pubKey = oldMember, createdAt = 1_700_000_003L, kind = DialectEvent.KIND, - tags = honest.tags, content = "unsigned" + pubKey = oldMember, createdAt = 1_700_000_003L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"unsigned\"}" ), - pubKey = oldMember, createdAt = 1_700_000_003L, kind = DialectEvent.KIND, - tags = honest.tags, content = "unsigned", sig = "" + pubKey = oldMember, createdAt = 1_700_000_003L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"unsigned\"}", sig = "" ), ) @@ -614,28 +502,25 @@ class ChronicleApplyJvmTest { count = 1, recipient = newMember, createdAt = 1_700_000_100L, + kinds = TEST_KINDS, ) ) assertEquals(4, outcome.skipped) assertEquals(1, outcome.applied) - val dialects = receiver.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - assertEquals(1, dialects.size, "exactly the honest one") - assertEquals(honest.id, dialects.single().id) - - // And nothing forged was kept as an event either. The record is what a - // later chronicle is built from, so a forgery filed here would be one this - // member goes on to hand to everybody else. + // Nothing forged was kept. The record is what a later chronicle is built + // from, so a forgery filed here would be one this member goes on to hand + // to everybody else. assertEquals( listOf(honest.id), - receiver.groupSignedEventDao().getByChatRoomId(chatRoomId).map { it.id } + receiver.groupSignedEventDao().getByChatRoomId(chatRoomId).map { it.id }, + "exactly the honest one" ) } @Test fun `a key state the room really signed cannot be replayed through a chronicle`() = runBlocking { - seedSenderWork() seedRoom(receiver, newMember) // Signed by the room, verifying perfectly, and refused: the allowlist is @@ -676,6 +561,7 @@ class ChronicleApplyJvmTest { assertEquals(1, outcome.skipped) assertEquals(0, outcome.applied) assertNull(receiver.groupKeyStateDao().getByChatRoomId(chatRoomId)) + assertEquals(emptyList(), fingerprints(receiver)) } @Test @@ -687,12 +573,8 @@ class ChronicleApplyJvmTest { assertEquals(0, outcome.sumOf { it.applied }) assertEquals( - mapOf( - "dialects" to 0, "artifacts" to 0, "versions" to 0, "chapters" to 0, - "chunks" to 0, "translationVersions" to 0, "translationChapters" to 0, - "translationChunks" to 0, - ), - rowCounts(receiver), + emptyList(), + fingerprints(receiver), "a bystander already holds the work; re-applying would only rewrite its provenance" ) } @@ -704,17 +586,12 @@ class ChronicleApplyJvmTest { val chronicle = senderChronicle() chronicle.forEach { deliver(it) } - val afterFirst = rowCounts(receiver) + val afterFirst = fingerprints(receiver) chronicle.forEach { deliver(it) } - assertEquals(afterFirst, rowCounts(receiver)) - assertEquals( - emptyList(), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - .filterNot { it in ChatMessage.CHRONICLE_TYPES }, - ) + assertEquals(afterFirst, fingerprints(receiver)) + assertEquals(emptyList(), lines(receiver).filterNot { it in ChatMessage.CHRONICLE_TYPES }) } // ---- Asking for one -------------------------------------------------- @@ -727,7 +604,7 @@ class ChronicleApplyJvmTest { fun `a device holding none of the room's work asks for it`() = runBlocking { seedRoom(receiver, newMember) - assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) // Queued with no chat line, the way a signing message travels. Broadcast // does not depend on one, and a row of envelopes in the transcript is not @@ -736,19 +613,15 @@ class ChronicleApplyJvmTest { // One line saying so, and nothing else. Asking is a thing this device did // and the room would otherwise sit empty with no explanation. - assertEquals( - listOf(ChatMessage.TYPE_CHRONICLE_REQUESTED), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - ) + assertEquals(listOf(ChatMessage.TYPE_CHRONICLE_REQUESTED), lines(receiver)) } @Test fun `a device does not ask twice while an answer is in flight`() = runBlocking { seedRoom(receiver, newMember) - assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) - assertFalse(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) + assertFalse(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) assertEquals(1, queued(receiver, ChronicleRequestEvent.KIND).size) } @@ -757,16 +630,45 @@ class ChronicleApplyJvmTest { fun `a device holding the work does not ask for it`() = runBlocking { seedSenderWork() - assertFalse(ChronicleManager.requestIfEmpty(sender, chatRoomId, oldMember)) + assertFalse(ChronicleManager.requestIfEmpty(sender, chatRoomId, oldMember, kinds = TEST_KINDS)) assertEquals(0, queued(sender, ChronicleRequestEvent.KIND).size) } + /** + * "Holds the work" means holds something a chronicle would carry. A device + * whose only signed event is one the list refuses is as far behind as one + * holding nothing, and has to ask like one. + */ + @Test + fun `a device holding only signed kinds off the list still asks`() = runBlocking { + seedRoom(receiver, newMember) + + receiver.groupSignedEventDao().record( + GroupSignedEvent.fromEvent( + event = signed( + EventTemplate( + createdAt = 1_700_000_060L, + kind = GroupKeyStateEvent.KIND, + tags = GroupKeyStateEvent.assembleTags( + chatRoomId = chatRoomId, + dkgSessionId = "the-ceremony", + ), + content = keyMaterial.thresholdPublicKey.value.toHex(), + ) + ), + chatRoomId = chatRoomId, + ) + ) + + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) + } + @Test fun `an answered request lets the room ask again`() = runBlocking { seedSenderWork() seedRoom(receiver, newMember) - ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember) + ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS) assertNotNull(receiver.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.chronicleRequestedAt) senderChronicle().forEach { deliver(it) } @@ -782,7 +684,7 @@ class ChronicleApplyJvmTest { fun `answering a request queues the chronicle for whoever asked`() = runBlocking { seedSenderWork() - val pages = ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember) + val pages = ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember, kinds = TEST_KINDS) assertEquals(1, pages) @@ -798,21 +700,20 @@ class ChronicleApplyJvmTest { sig = "", ) assertEquals(newMember, page.recipient()) - assertEquals(ChronicleEvent.CHRONICLABLE_KINDS, page.payloads()?.map { it.kind }?.toSet()) + assertEquals(TEST_KINDS.all, page.payloads()?.map { it.kind }?.toSet()) // One line about the chronicle, and no line per page. - assertEquals( - listOf(ChatMessage.TYPE_CHRONICLE_SENT), - sender.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - ) + assertEquals(listOf(ChatMessage.TYPE_CHRONICLE_SENT), lines(sender)) } @Test fun `a member with nothing signed answers nothing rather than an empty chronicle`() = runBlocking { seedRoom(receiver, newMember) - assertEquals(0, ChronicleManager.sendTo(receiver, chatRoomId, newMember, recipient = oldMember)) + assertEquals( + 0, + ChronicleManager.sendTo(receiver, chatRoomId, newMember, recipient = oldMember, kinds = TEST_KINDS) + ) assertEquals(0, queued(receiver, ChronicleEvent.KIND).size) } @@ -820,7 +721,10 @@ class ChronicleApplyJvmTest { fun `a member does not answer their own request`() = runBlocking { seedSenderWork() - assertEquals(0, ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = oldMember)) + assertEquals( + 0, + ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = oldMember, kinds = TEST_KINDS) + ) assertEquals(0, queued(sender, ChronicleEvent.KIND).size) } @@ -830,10 +734,10 @@ class ChronicleApplyJvmTest { seedRoom(receiver, newMember) // The joiner asks. - assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) // A member holding the work answers it, addressed to whoever asked. - ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember) + ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember, kinds = TEST_KINDS) // The pages reach the joiner, who applies them. queued(sender, ChronicleEvent.KIND).forEach { queuedPage -> @@ -847,7 +751,7 @@ class ChronicleApplyJvmTest { ) } - assertEquals(rowCounts(sender), rowCounts(receiver)) + assertEquals(fingerprints(sender), fingerprints(receiver)) assertNull(receiver.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.chronicleRequestedAt) } @@ -885,57 +789,30 @@ class ChronicleApplyJvmTest { return keyPackageId } - @Test - fun `inviting a member offers them the group's work alongside the welcome`() = runBlocking { - seedSenderWork() + private suspend fun invite() = sender.marmotOutboundDao().deliveryWelcome( + chatRoomId = chatRoomId, + userPublicKey = oldMember, + welcomeBytes = ByteArray(8), + peerKeyPackageEventId = seedInviteeKeyPackage(), + relays = listOf("wss://relay.example.com"), + createdAt = Clock.System.now(), + ) - sender.marmotOutboundDao().deliveryWelcome( - chatRoomId = chatRoomId, - userPublicKey = oldMember, - welcomeBytes = ByteArray(8), - peerKeyPackageEventId = seedInviteeKeyPackage(), - relays = listOf("wss://relay.example.com"), - createdAt = Clock.System.now(), - ) - - val page = queued(sender, ChronicleEvent.KIND).single() - - assertEquals( - newMember, - ChronicleEvent( - id = page.id, - pubKey = page.publicKey, - createdAt = page.createdAt.epochSeconds, - tags = page.tags, - content = page.content, - sig = "", - ).recipient() - ) - } + private suspend fun welcomesSent() = sender.giftWrapPayloadDao() + .getByChatRoomAndKinds(chatRoomId, listOf(WelcomeEvent.KIND)) + .size @Test fun `inviting into a room with nothing signed offers nothing, and still invites`() = runBlocking { seedRoom(sender, oldMember) - sender.marmotOutboundDao().deliveryWelcome( - chatRoomId = chatRoomId, - userPublicKey = oldMember, - welcomeBytes = ByteArray(8), - peerKeyPackageEventId = seedInviteeKeyPackage(), - relays = listOf("wss://relay.example.com"), - createdAt = Clock.System.now(), - ) + invite() assertEquals(0, queued(sender, ChronicleEvent.KIND).size) // The Welcome itself still went out. A push that has nothing to say is // not a failed invite, and nothing about the chronicle may report one: // the invitee asks for themselves on their first open regardless. - assertEquals( - 1, - sender.giftWrapPayloadDao() - .getByChatRoomAndKinds(chatRoomId, listOf(WelcomeEvent.KIND)) - .size - ) + assertEquals(1, welcomesSent()) } @Test @@ -943,25 +820,11 @@ class ChronicleApplyJvmTest { seedSenderWork() seedRoom(receiver, newMember) - ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember) + ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS) // Delivered a page at a time and out of order, so the sweep runs several // times over several pages. The transcript is not a log of that. - val payloads = senderChronicle() - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - - payloads.reversed().forEachIndexed { index, payload -> - deliver( - ChronicleEvent.build( - payloads = listOf(payload), - chronicleId = "e".repeat(64), - index = index, - count = payloads.size, - recipient = newMember, - createdAt = 1_700_000_100L + index, - ) - ) - } + onePagePerPayload().reversed().forEach { deliver(it) } // Newest first, which is the transcript's order: the answer is the line above // the composer and the ask sits over it. Both land in the same second, so what @@ -969,8 +832,7 @@ class ChronicleApplyJvmTest { // without it this read whichever way SQLite happened to hand the tie back. assertEquals( listOf(ChatMessage.TYPE_CHRONICLE_RECEIVED, ChatMessage.TYPE_CHRONICLE_REQUESTED), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } + lines(receiver) ) } @@ -983,10 +845,93 @@ class ChronicleApplyJvmTest { // "caught up on work you have not seen yet" is a line about nothing. senderChronicle().forEach { deliver(it) } - assertEquals( - emptyList(), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } + assertEquals(emptyList(), lines(receiver)) + } + + // ---- The app's own list ---------------------------------------------- + // + // Everything above names its kinds. The app's call sites do not, so these hold + // the default -- ChronicleEvent.KINDS -- to what its comment promises: with + // nothing on the list, a device asks for nothing, sends nothing, and applies + // nothing an older build sends it. + + /** + * The decision itself, pinned. Adding a kind back is meant to be made on + * purpose, with the reason it is safe to replay, and this is the line that + * has to change when it is. + */ + @Test + fun `the app's own list carries nothing`() { + assertTrue(ChronicleEvent.KINDS.isEmpty()) + assertTrue(ChronicleEvent.CHRONICLABLE_KINDS.isEmpty()) + } + + /** + * Asking while nothing could answer would put a request on the wire and a + * line in the transcript on every room a member opens, for a reply that can + * only ever be silence. + */ + @Test + fun `under the app's own list a device asks for nothing`() = runBlocking { + seedRoom(receiver, newMember) + + assertFalse(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + + assertEquals(0, queued(receiver, ChronicleRequestEvent.KIND).size) + assertNull( + receiver.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.chronicleRequestedAt, + "a stamp would hold back a real request on the day the list grows" ) + assertEquals(emptyList(), lines(receiver)) + } + + /** + * Both ways a chronicle goes out -- the reply to a request and the push + * behind a Welcome -- from a room that holds plenty the group signed. The + * table holds every kind the group ever signed, so this is the filter on the + * way out doing its job, not an empty room. + */ + @Test + fun `under the app's own list a device sends nothing, even holding signed work`() = runBlocking { + seedSenderWork() + assertTrue(sender.groupSignedEventDao().getByChatRoomId(chatRoomId).isNotEmpty()) + + // Answering a request. + assertEquals(0, ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember)) + + // The push behind a Welcome, which calls the same thing with no kinds. + invite() + + assertEquals(0, queued(sender, ChronicleEvent.KIND).size) + assertEquals(emptyList(), lines(sender).filter { it in ChatMessage.CHRONICLE_TYPES }) + // And the invite itself still went out. + assertEquals(1, welcomesSent()) + } + + /** + * A member on an older build still chronicles, and its pages are genuine: + * events the room really signed, of kinds that build still lists. Arriving + * here they are refused by the list, not by the signature -- every payload + * counts as skipped, none as failed, so nothing waits to be retried. + */ + @Test + fun `under the app's own list a page from an older build applies nothing`() = runBlocking { + seedSenderWork() + seedRoom(receiver, newMember) + + val pages = senderChronicle() + val payloadCount = pages.sumOf { assertNotNull(ChronicleEvent.decodePage(it.content)).size } + + pages.forEach { deliver(it, kinds = ChronicleEvent.KINDS) } + + // And a sweep of everything stored, the way the next arrival would run it. + val outcome = ChronicleManager.sweep(receiver, chatRoomId, newMember) + + assertEquals(0, outcome.applied) + assertEquals(0, outcome.failed) + assertEquals(payloadCount, outcome.skipped) + + assertEquals(emptyList(), fingerprints(receiver)) + assertEquals(emptyList(), lines(receiver)) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt index ed613d76..4771e20c 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt @@ -4,7 +4,10 @@ import androidx.room3.Room import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey @@ -25,30 +28,26 @@ import com.machankura.bennu.compose.database.builder.getRoomDatabase import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.MantraDialect +import com.machankura.bennu.compose.database.model.MarmotInnerEvent import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent +import com.machankura.bennu.compose.nostr.chronicle.TEST_KINDS import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent /** - * Assembling a room's chronicle out of the rows a device actually holds. + * Assembling a room's chronicle out of what a device actually holds. * - * The seed is the real inbound path -- `ChatMessage.applyInnerEvent`, the same - * call a finished signing session makes -- so what is chronicled here is what a - * member's database really contains rather than rows built to suit the test. - * That matters because the whole risk in this direction is a rebuild that - * differs from what was signed, and rows assembled by hand would hide it. + * The seed is the real path a finished signing session takes -- the events filed + * in `GroupSignedEvent`, then handed to `ChatMessage.applyInnerEvent` -- so what is + * chronicled here is what a member's database really contains rather than rows + * built to suit the test. The record is the only source: nothing is rebuilt from + * rows, so what a chronicle carries is byte for byte what the group signed. + * + * The app's own list of kinds is empty, so these assemble with [TEST_KINDS]; the + * last case holds the default to assembling nothing. */ class ChronicleAssemblyJvmTest { private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) @@ -134,20 +133,17 @@ class ChronicleAssemblyJvmTest { ) } - /** - * Every event `apply` has been given, in the order it was given them. - * - * A test that wants the room's work on file as events too replays this - * through [record], which is the pair `FrostSigningManager.complete` writes - * in one pass. Kept here rather than returned by `seedSignedWork` so the - * seeding reads the same in both worlds. - */ - private val applied = mutableListOf() + /** Every event [seed] has been given, in the order it was given them. */ + private val seeded = mutableListOf() - /** What `FrostSigningManager.applySignedEvent` does, through the same call. */ - private suspend fun apply(template: EventTemplate<*>): Event { + /** + * What `FrostSigningManager.complete` does with a finished batch: file the + * event as the group signed it, then apply it through the same call. + */ + private suspend fun seed(template: EventTemplate<*>): Event { val event = signed(template) + record(event) ChatMessage.applyInnerEvent( database = db, groupId = chatRoomId, @@ -156,10 +152,11 @@ class ChronicleAssemblyJvmTest { marmotInnerEventId = null, senderPublicKey = chatRoomId, isUserMessage = false, - createdAt = Instant.fromEpochSeconds(event.createdAt) + createdAt = Instant.fromEpochSeconds(event.createdAt), + groupSignedEventId = event.id, ) - applied += event + seeded += event return event } @@ -178,9 +175,6 @@ class ChronicleAssemblyJvmTest { ) } - /** The whole seeded batch on file as events, as a device that signed it holds it. */ - private suspend fun recordEverythingApplied() = record(*applied.toTypedArray()) - /** ChatRoom -> Profile -> NostrEvent, the foreign key chain a room hangs off. */ private suspend fun seedRoom() { val nostrEventId = "c".repeat(64) @@ -208,105 +202,48 @@ class ChronicleAssemblyJvmTest { ) } - /** A room with one artifact, one chapter, two chunks and one translation. */ + private fun template(kind: Int, createdAt: Long, content: String, tags: Array> = emptyArray()) = + EventTemplate(createdAt = createdAt, kind = kind, tags = tags, content = content) + + /** + * A room that has signed a relay list, a profile and two posts, seeded posts + * first -- the reverse of the order they apply in, so that the chronicle being + * in order is something assembly did. + */ private suspend fun seedSignedWork() { seedRoom() - val dialect = apply( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ) - - val artifact = apply( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) - ) - - // The second item of the artifact's own batch, built the way the batch - // builds it. It used to be derived on arrival, which is why the chronicle - // once could not carry it: a derived row has no signature to check. - val version = apply(ArtifactVersionEvent.initialVersionOf(artifact).single()) - - val chapter = apply( - ChapterEvent.build( - artifactVersionId = version.id, - name = "Chapter One", - originalText = "He was a man of parts. He had many.", - index = 0, - wordCount = 8, - characterCount = 35, - createdAt = 1_700_000_020L - ) - ) - - val chunk = apply( - ChunkEvent.build( - chapterId = chapter.id, - text = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_030L - ) - ) - apply( - ChunkEvent.build( - chapterId = chapter.id, - text = "He had many.", - index = 1, - wordCount = 3, - characterCount = 12, - createdAt = 1_700_000_031L - ) - ) - - val translationVersion = apply( - TranslationArtifactVersionEvent.build( - artifactVersionId = version.id, - dialectId = dialect.id, - name = "isiZulu", - visibility = "private", - license = "cc", - createdAt = 1_700_000_040L - ) - ) - - val translationChapter = apply( - TranslationChapterEvent.build( - translationArtifactVersionId = translationVersion.id, - chapterId = chapter.id, - index = 0, - createdAt = 1_700_000_050L - ) - ) - - // The translated text, which the group signs now rather than each member - // saving their own. - apply( - TranslationChunkEvent.build( - translationChapterId = translationChapter.id, - chunkId = chunk.id, - index = 0, - text = "Wayeyindoda enezingxenye.", - createdAt = 1_700_000_060L + seed(template(TextNoteEvent.KIND, 1_700_000_000L, "The group says hello.")) + seed(template(TextNoteEvent.KIND, 1_700_000_001L, "And says it again.")) + seed(template(MetadataEvent.KIND, 1_700_000_010L, "{\"name\":\"Ekklesia\"}")) + seed( + template( + AdvertisedRelayListEvent.KIND, 1_700_000_020L, "", + tags = arrayOf(arrayOf("r", "wss://relay.example.com")), ) ) } private suspend fun chronicledPayloads(): List = - ChronicleManager.assemble(db, chatRoomId, newMember) + ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS) .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } + /** + * Nothing leaves that the recipient could not check for themselves -- which + * includes a row on file whose fields have drifted from the event it + * recorded. Its id and signature are the group's; what they no longer cover + * is what it says. + */ @Test fun `every payload in a chronicle is one the room signed`() = runBlocking { seedSignedWork() + val drifted = signed(template(TextNoteEvent.KIND, 1_700_000_030L, "What the group said.")) + db.groupSignedEventDao().record( + GroupSignedEvent.fromEvent(event = drifted, chatRoomId = chatRoomId) + .copy(content = "What somebody wishes it had said.") + ) + val payloads = chronicledPayloads() assertTrue(payloads.isNotEmpty(), "a room with signed work chronicles something") @@ -316,6 +253,8 @@ class ChronicleAssemblyJvmTest { "kind ${it.kind} (${it.id.take(8)}) was chronicled without a signature the room can be checked for" ) } + assertTrue(payloads.none { it.id == drifted.id }, "the drifted row should have been left out") + assertEquals(seeded.map { it.id }.toSet(), payloads.map { it.id }.toSet()) } @Test @@ -324,71 +263,88 @@ class ChronicleAssemblyJvmTest { val byKind = chronicledPayloads().groupBy { it.kind } - assertEquals(1, byKind[DialectEvent.KIND]?.size) - assertEquals(1, byKind[ArtifactEvent.KIND]?.size) - assertEquals(1, byKind[ArtifactVersionEvent.KIND]?.size) - assertEquals(1, byKind[ChapterEvent.KIND]?.size) - assertEquals(2, byKind[ChunkEvent.KIND]?.size) - assertEquals(1, byKind[TranslationArtifactVersionEvent.KIND]?.size) - assertEquals(1, byKind[TranslationChapterEvent.KIND]?.size) - assertEquals(1, byKind[TranslationChunkEvent.KIND]?.size) + assertEquals(1, byKind[AdvertisedRelayListEvent.KIND]?.size) + assertEquals(1, byKind[MetadataEvent.KIND]?.size) + assertEquals(2, byKind[TextNoteEvent.KIND]?.size) - assertEquals(ChronicleEvent.CHRONICLABLE_KINDS, byKind.keys) + assertEquals(TEST_KINDS.all, byKind.keys) } @Test - fun `a chronicle is in dependency order across its whole length`() = runBlocking { + fun `a chronicle is in the list's order across its whole length`() = runBlocking { seedSignedWork() - val ranks = chronicledPayloads().map { assertNotNull(ChronicleEvent.applyRank(it.kind)) } + val ranks = chronicledPayloads().map { assertNotNull(TEST_KINDS.applyRank(it.kind)) } - assertEquals(ranks.sorted(), ranks, "a chronicle out of order is a foreign key violation") + // Seeded in the reverse order, so a chronicle that kept the table's order + // would fail here. In the app this is a foreign key violation on the + // receiver rather than a wrong answer. + assertEquals(ranks.sorted(), ranks, "a chronicle out of order is applied out of order") } @Test fun `a member's own rumor is not part of the group's record`() = runBlocking { seedSignedWork() - // What `MantraDao.addDialect` writes: the member's key, no signature. It - // is real work in the room and the group never signed it, so it cannot be + // A member's own kind:1, travelling through the room the way everything + // on the wire does: stored as an inner event and applied. It is real + // content in the room and the group never signed it, so it cannot be // handed to somebody who has no way to check it. - db.mantraDialectDao().upsert( - MantraDialect( - id = "f".repeat(64), - publicKey = newMember, - name = "seSotho", - country = "ZA", - language = "st", - signature = "", + val rumor = Event( + id = EventHasher.hashId( + pubKey = newMember, createdAt = 1_700_000_060L, kind = TextNoteEvent.KIND, + tags = emptyArray(), content = "My own note." + ), + pubKey = newMember, createdAt = 1_700_000_060L, kind = TextNoteEvent.KIND, + tags = emptyArray(), content = "My own note.", sig = "" + ) + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = rumor.id, + publicKey = rumor.pubKey, + kind = rumor.kind, + createdAt = Instant.fromEpochSeconds(rumor.createdAt), + tags = rumor.tags, + content = rumor.content, chatRoomId = chatRoomId, - createdAt = Instant.fromEpochSeconds(1_700_000_060L), ) ) + ChatMessage.applyInnerEvent( + database = db, + groupId = chatRoomId, + event = rumor, + marmotGroupEventId = null, + marmotInnerEventId = rumor.id, + senderPublicKey = newMember, + isUserMessage = true, + createdAt = Instant.fromEpochSeconds(rumor.createdAt), + ) assertEquals( - 2, - db.mantraDialectDao().getDialectsByChatRoomId(chatRoomId).size, + 1, + db.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(TextNoteEvent.KIND)).size, "the rumor should be on disk" ) assertEquals( - 1, - chronicledPayloads().count { it.kind == DialectEvent.KIND }, - "the unsigned dialect should not have been chronicled" + 2, + chronicledPayloads().count { it.kind == TextNoteEvent.KIND }, + "only the group's two posts should have been chronicled" ) + assertTrue(chronicledPayloads().none { it.id == rumor.id }) } @Test fun `a room with nothing signed chronicles nothing, and says so rather than failing`() = runBlocking { seedRoom() - assertEquals(emptyList(), ChronicleManager.assemble(db, chatRoomId, newMember)) + assertEquals(emptyList(), ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS)) } @Test fun `a chronicle of one page still says it is one of one`() = runBlocking { seedSignedWork() - val pages = ChronicleManager.assemble(db, chatRoomId, newMember) + val pages = ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS) assertEquals(1, pages.size, "this much work fits one page") @@ -407,29 +363,25 @@ class ChronicleAssemblyJvmTest { assertNotNull(page.chronicleId()) } - // ---- Reading from the record rather than rebuilding ------------------- - /** * The events, not a reconstruction of them. * - * Byte-for-byte against what was signed, which is the assertion the whole - * rebuild machinery exists to approximate. Here it is exact by construction: - * nothing is rebuilt, so there is no tag order to get wrong and no field a - * row could have failed to keep. + * Byte-for-byte against what was signed. Exact by construction: nothing is + * rebuilt, so there is no tag order to get wrong and no field a row could + * have failed to keep. */ @Test fun `a chronicle carries the group's events as the group signed them`() = runBlocking { seedSignedWork() - recordEverythingApplied() val payloads = chronicledPayloads().associateBy { it.id } assertEquals( - applied.map { it.id }.toSet(), + seeded.map { it.id }.toSet(), payloads.keys, "everything the group signed here should be in the chronicle" ) - applied.forEach { event -> + seeded.forEach { event -> assertEquals( event.toJson(), assertNotNull(payloads[event.id]).toJson(), @@ -439,41 +391,11 @@ class ChronicleAssemblyJvmTest { } /** - * Both sources, one chronicle, and nothing counted twice. + * The failure the record makes possible, and the allowlist that stops it. * - * The state a device upgrading mid-life is in: older work only the rows - * remember, newer work on file as events. Neither half is the chronicle on its - * own, and an event held both ways is still one event. - */ - @Test - fun `work held both ways travels exactly once`() = runBlocking { - seedSignedWork() - - // Half the batch on file, the other half only as rows -- which is what - // a room that was upgraded partway through its life looks like. - record(*applied.take(applied.size / 2).toTypedArray()) - - val payloads = chronicledPayloads() - - assertEquals( - applied.map { it.id }.toSet(), - payloads.map { it.id }.toSet(), - "the two sources together should still be the whole record" - ) - assertEquals( - payloads.size, - payloads.map { it.id }.toSet().size, - "an event on file and rebuildable is one event, not two" - ) - } - - /** - * The failure this source made possible, and the allowlist that stops it. - * - * A key state is group-signed and verifies perfectly. The rebuild could not - * reach one because no `Mantra*` row holds it; the record holds every kind. - * Without the filter on the way out `ChronicleEvent.build` refuses the page - * and the room's whole chronicle fails on one event. + * A key state is group-signed and verifies perfectly, and the record holds + * every kind. Without the filter on the way out `ChronicleEvent.build` + * refuses the page and the room's whole chronicle fails on one event. * * A room no longer signs its own key state -- a group agrees that before the * room exists, in the NIP-17 room its ceremony ran in, and files it under @@ -485,7 +407,6 @@ class ChronicleAssemblyJvmTest { @Test fun `a key state the room really signed is never chronicled`() = runBlocking { seedSignedWork() - recordEverythingApplied() val keyState = signed( EventTemplate( @@ -508,88 +429,21 @@ class ChronicleAssemblyJvmTest { assertTrue(payloads.isNotEmpty(), "the rest of the room's work still chronicles") assertEquals( - ChronicleEvent.CHRONICLABLE_KINDS, + TEST_KINDS.all, payloads.map { it.kind }.toSet(), - "a chronicle carries the document kinds and nothing else" + "a chronicle carries the listed kinds and nothing else" ) assertTrue(payloads.none { it.id == keyState.id }) } /** The same rule, for a kind that is merely not on the list rather than dangerous. */ @Test - fun `a signed kind the chronicle has no arm for is left behind`() = runBlocking { + fun `a signed kind off the list is left behind`() = runBlocking { seedSignedWork() - recordEverythingApplied() - record( - signed( - EventTemplate( - createdAt = 1_700_000_080L, - kind = SubmissionEvent.KIND, - tags = emptyArray(), - content = "{}", - ) - ) - ) + record(signed(template(GroupWalletStatementEvent.KIND, 1_700_000_080L, "{}"))) - assertEquals( - ChronicleEvent.CHRONICLABLE_KINDS, - chronicledPayloads().map { it.kind }.toSet() - ) - } - - /** - * The case the rebuild cannot reach at all, which is why the record is the - * source and not merely a faster one. - * - * `MantraArtifact` does not hold the version label it was signed with -- - * `fromArtifactEvent` drops it -- so `toArtifactEvent` has to go and find it - * on the initial version, and an artifact whose version row is missing is one - * the rebuild logs and leaves out. On file as an event there is nothing to - * find: the label never left. - */ - @Test - fun `an artifact the rebuild has to leave out still chronicles from the record`() = runBlocking { - seedRoom() - - val dialect = apply( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ) - - // Applied without the second item of its batch, so no version row carries - // the label back. A device that was offline for half a batch, or one that - // failed to apply the version, is in exactly this state. - val artifact = apply( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) - ) - - assertEquals( - emptyList(), - db.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(artifact.id), - "this test is only about an artifact whose initial version is missing" - ) - - // Rows only: the rebuild reaches the dialect and gives up on the artifact. - assertEquals( - listOf(dialect.id), - chronicledPayloads().map { it.id }, - ) - - record(dialect, artifact) - - assertEquals( - setOf(dialect.id, artifact.id), - chronicledPayloads().map { it.id }.toSet(), - "the record holds the whole event, version label and all" - ) + assertEquals(TEST_KINDS.all, chronicledPayloads().map { it.kind }.toSet()) } @Test @@ -609,144 +463,21 @@ class ChronicleAssemblyJvmTest { // counts differ whenever their databases do. Sharing an id would let one // chronicle's pages be counted towards the other's total. assertTrue( - idOf(ChronicleManager.assemble(db, chatRoomId, newMember).single()) != - idOf(ChronicleManager.assemble(db, chatRoomId, newMember).single()) + idOf(ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS).single()) != + idOf(ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS).single()) ) } - // ---- Supersession ---------------------------------------------------- - // - // The record keeps every event the group signed; the rows keep one - // translation per passage. Reading the chronicle from the record is what makes - // the difference visible, and these are what keep the two sides agreeing - // about which translation stands. - - /** The passage the seed already translated, resolved back out of the rows. */ - private suspend fun seededPassage(): Pair { - val artifactId = db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).single().id - val versionId = db.mantraArtifactVersionDao() - .getArtifactVersionsByArtifactId(artifactId).single().id - val chapterId = db.mantraChapterDao().getChaptersByArtifactVersionId(versionId).single().id - val chunkId = db.mantraChunkDao().getChunksByChapterId(chapterId).first().id - val translationChapterId = db.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId( - db.mantraTranslationArtifactVersionDao() - .getTranslationsByArtifactVersionId(versionId).single().id - ).single().id - - return translationChapterId to chunkId - } - - private suspend fun chronicledTranslations(): List = - ChronicleManager.assemble(db, chatRoomId, newMember) - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - .filter { it.kind == TranslationChunkEvent.KIND } - + /** + * The default the app's call sites use. A room full of signed work assembles + * to nothing, because the filter on the way out is the list and the list is + * empty -- see `ChronicleApplyJvmTest` for the same from the sending side. + */ @Test - fun `a retranslated passage chronicles once, not once per draft`() = runBlocking { + fun `under the app's own list a room with signed work assembles nothing`() = runBlocking { seedSignedWork() - val (translationChapterId, chunkId) = seededPassage() + assertTrue(db.groupSignedEventDao().getByChatRoomId(chatRoomId).isNotEmpty()) - val current = apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = "A better rendering.", - createdAt = 1_700_000_070L - ) - ) - recordEverythingApplied() - - // One row, because the applying arm superseded the first. Two events, - // because the record keeps what the group signed and does not pretend a - // signature was never made. - assertEquals( - 1, - db.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapterId).size - ) - assertEquals( - 2, - db.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, TranslationChunkEvent.KIND).size - ) - - // And one payload. Otherwise every draft a group ever signed travels in - // every chronicle it ever sends, for as long as the room exists. - assertEquals(listOf(current.id), chronicledTranslations().map { it.id }) - } - - @Test - fun `the chronicle picks the translation the recipient would keep`() = runBlocking { - seedSignedWork() - val (translationChapterId, chunkId) = seededPassage() - - // Two translations signed in the same second, which the applying arm - // settles by id. The chronicle has to settle it the same way or it ships - // one as current while the recipient keeps the other -- and both being - // validly signed, nothing downstream would notice they disagree. - val sameSecond = 1_700_000_070L - val rivals = listOf("Rendering one.", "Rendering two.", "Rendering three.") - .map { text -> - apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = text, - createdAt = sameSecond - ) - ) - } - recordEverythingApplied() - - val kept = db.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapterId).single() - - assertEquals(rivals.maxOf { it.id }, kept.id, "the row keeps the highest id of the second") - assertEquals(listOf(kept.id), chronicledTranslations().map { it.id }) - } - - @Test - fun `two passages each keep their own current translation`() = runBlocking { - seedSignedWork() - val (translationChapterId, firstChunkId) = seededPassage() - - val chapterId = db.mantraChapterDao() - .getChaptersByArtifactVersionId( - db.mantraArtifactVersionDao() - .getArtifactVersionsByArtifactId( - db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).single().id - ).single().id - ).single().id - val secondChunkId = db.mantraChunkDao().getChunksByChapterId(chapterId) - .first { it.id != firstChunkId }.id - - // Grouping is per passage, so retranslating one must not take the other - // with it -- the bug a naive "newest translation wins" would have. - val retranslated = apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = firstChunkId, - index = 0, - text = "A better rendering.", - createdAt = 1_700_000_070L - ) - ) - val other = apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = secondChunkId, - index = 1, - text = "Wayenezinye eziningi.", - createdAt = 1_700_000_065L - ) - ) - recordEverythingApplied() - - assertEquals( - setOf(retranslated.id, other.id), - chronicledTranslations().map { it.id }.toSet() - ) + assertEquals(emptyList(), ChronicleManager.assemble(db, chatRoomId, newMember)) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt new file mode 100644 index 00000000..21a54efd --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt @@ -0,0 +1,250 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgParticipantMessage +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.Participant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.nostr.Relays +import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData +import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519 +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.machankura.bennu.compose.database.model.GroupKeyState +import com.machankura.bennu.compose.database.model.NostrEvent +import com.machankura.bennu.compose.database.model.Profile +import com.machankura.bennu.compose.extensions.toHex +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.bitcoin.ByteVector64 +import kotlin.time.Instant + +/** + * Groups with real keys, for the tests that need a group's signature on + * something: a trusted-dealer key per group, its room id, and a 2-of-3 FROST + * signature as the room. The shape `SubgroupManagerJvmTest` builds inline, kept + * in one place for the member-wallet tests, which need a parent, a group and a + * certificate between them in nearly every case. + */ +internal object GroupFixtures { + private const val PARTICIPANTS = 3 + private const val THRESHOLD = 2 + + val path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH + + fun keyMaterial(secret: String): KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32(secret.padStart(64, '0'))), + nParticipants = PARTICIPANTS, + threshold = THRESHOLD, + ) + + fun thresholdKeyOf(material: KeyMaterial): HexKey = material.thresholdPublicKey.value.toHex() + + fun roomOf(material: KeyMaterial): String = SharedKeyDerivation.marmotGroupId(thresholdKeyOf(material), path) + + /** [kind] over [tags] and [content], signed by [material]'s quorum as its room. */ + fun signedAsRoom(material: KeyMaterial, kind: Int, tags: Array>, content: String, createdAt: Long = 1_700_000_000): Event { + val pubKey = roomOf(material) + val id = EventHasher.hashId(pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content) + return Event(id = id, pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content, sig = signature(material, id)) + } + + /** + * [group]'s policy on its members' wallets, signed by its room: open at + * [delay], or closed when [delay] is null. `docs/member-wallet-delay.md`. + */ + fun memberWalletPolicy(group: KeyMaterial, delay: Long?, createdAt: Long = 1_700_000_000): Event { + val template = delay?.let { MemberWalletPolicyEvent.open(it, createdAt) } ?: MemberWalletPolicyEvent.closed(createdAt) + return signedAsRoom(group, template.kind, template.tags, template.content, createdAt) + } + + /** + * [group] opened to its members' wallets at [delay]: the policy every member + * wallet test needs before a member can ask, since a group with none does + * not guard members' wallets. `docs/member-wallet-delay.md`, D8. + */ + suspend fun openToMembers(db: BennuDatabase, group: KeyMaterial, delay: Long = GuardianDerivation.DEFAULT_DELAY, createdAt: Long = 1_600_000_000) { + if (db.chatRoomDao().findChatRoomById(roomOf(group)) == null) seedRoom(db, roomOf(group)) + filePolicy(db, group, memberWalletPolicy(group, delay, createdAt)) + } + + /** [policy] filed as [group]'s room files a signed event: a `GroupSignedEvent` row. */ + suspend fun filePolicy(db: BennuDatabase, group: KeyMaterial, policy: Event) { + db.groupSignedEventDao().upsert( + GroupSignedEvent.fromEvent(policy, chatRoomId = roomOf(group), derivationPath = SharedKeyDerivation.formatPath(path), frostSigningSessionId = null) + ) + } + + /** + * [parent]'s certificate for [child], granting [guardians] under [policy] -- + * the grant is the caller's, so a test can hand over a wrong one. + */ + fun birthCertificate( + parent: KeyMaterial, + child: KeyMaterial, + guardians: List, + policy: SubgroupWalletPolicy? = if (guardians.isEmpty()) SubgroupWalletPolicy.UNGUARDED else SubgroupWalletPolicy.GUARDED, + admins: List = listOf("a".repeat(64)), + name: String = "#Child", + ): Event = signedAsRoom( + material = parent, + kind = SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = roomOf(child), + parentChatRoomId = roomOf(parent), + thresholdPublicKey = thresholdKeyOf(child), + adminPublicKeys = admins, + name = name, + path = path, + guardians = guardians, + walletPolicy = policy, + ), + content = roomOf(child), + ) + + /** [parent]'s guarded certificate for [child], with exactly the grant a parent with no parent makes. */ + fun guardedCertificate(parent: KeyMaterial, child: KeyMaterial): Event = + birthCertificate(parent, child, GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), roomOf(child))) + + /** [material]'s verified key state on this device, carrying [certificate] when it is somebody's subgroup. */ + suspend fun fileKeyState(db: BennuDatabase, material: KeyMaterial, certificate: Event? = null) { + seedRoom(db, roomOf(material)) + db.groupKeyStateDao().upsert( + GroupKeyState( + chatRoomId = roomOf(material), + dkgSessionId = "ceremony-" + roomOf(material).take(8), + thresholdPublicKey = thresholdKeyOf(material), + derivationPath = SharedKeyDerivation.formatPath(path), + announcedBy = roomOf(material), + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = certificate?.let { SubgroupBirthCertificateEvent.parseParentChatRoomId(it.tags) }, + birthCertificateJson = certificate?.toJson(), + ) + ) + } + + /** The device's own profile, which every room row names. */ + val owner: HexKey = "0e".repeat(32) + + suspend fun seedProfile(db: BennuDatabase, publicKey: HexKey, name: String = "member") { + if (db.profileDao().getProfileByPublicKey(publicKey) != null) return + val nostrEventId = publicKey.take(63) + "f" + db.nostrEventDao().upsert( + NostrEvent(id = nostrEventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)) + ) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = nostrEventId)) + } + + /** A room row for [chatRoomId], if there is none: what a key state, a signed event or a session hangs off. */ + suspend fun seedRoom(db: BennuDatabase, chatRoomId: String, subject: String? = null) { + seedProfile(db, owner) + if (db.chatRoomDao().findChatRoomById(chatRoomId) != null) return + db.chatRoomDao().upsert(ChatRoom(id = chatRoomId, userPublicKey = owner, subject = subject, description = null, mlsGroupState = null)) + } + + /** + * [material]'s Marmot room on this device, with [owner] holding a share of its + * key and every one of [members] a participant: a room this device can open + * a signing session in. Built as a real room is -- the id derived from the + * group's own key -- for the reason `SubgroupManagerJvmTest.parentWith` gives. + */ + suspend fun signingRoom( + db: BennuDatabase, + material: KeyMaterial, + members: List, + subject: String = "#Ekklesia", + holdsShare: Boolean = true, + ): LocalChatRoom { + val roomId = roomOf(material) + (members + owner).forEach { seedProfile(db, it) } + + val metadata = MarmotGroupData( + nostrGroupId = roomId, + name = subject, + description = SharedKeyDerivation.describe("Admins of $subject."), + adminPubkeys = members + owner, + relays = Relays.DefaultDMRelayList.map { it.url }, + ) + val mlsGroup = MlsGroup.create(KeyPair().pubKey, Ed25519.generateKeyPair().privateKey, listOf(metadata.toExtension())) + db.chatRoomDao().upsert( + ChatRoom(id = roomId, userPublicKey = owner, subject = subject, description = metadata.description, mlsGroupState = mlsGroup.saveState().encodeTls().toHex()) + ) + db.participantDao().upsert((members + owner).map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) }) + + if (!holdsShare) return requireNotNull(db.chatRoomDao().findChatRoomById(roomId)) + + val ceremonyId = "signing-" + roomId.take(8) + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = roomId, + coordinatorPublicKey = owner, + userPublicKey = owner, + threshold = THRESHOLD, + participantCount = members.size + 1, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = thresholdKeyOf(material), + secretShare = "cc".repeat(32), + ) + ) + (members + owner).forEachIndexed { index, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = "0${index + 1}".repeat(33)) + ) + } + return requireNotNull(db.chatRoomDao().findChatRoomById(roomId)) + } + + private fun signature(material: KeyMaterial, eventId: String): String = + signWith(material, SharedKeyDerivation.derive(thresholdKeyOf(material), path).cache, ByteVector(eventId.hexToByteArray())).toHex() + + /** A 2-of-3 FROST signature by [material]'s quorum over [message] under [cache] -- a leaf's, an address's, the room's. */ + fun signWith(material: KeyMaterial, cache: TweakCache, message: ByteVector): ByteVector64 { + val signerIds = listOf(0, 1) + + val nonces = signerIds.map { signerId -> + SecretNonce.generate( + sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), + secretShare = material.secretShares[signerId], + publicShare = material.publicShares[signerId], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null, + ) + } + val session = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { material.publicShares[it] }, + nParticipants = PARTICIPANTS, + threshold = THRESHOLD, + tweakCache = cache, + message = message, + ) + val partials = signerIds.mapIndexed { position, signerId -> + session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!! + } + return session.aggregateSigs(partials).right!! + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt new file mode 100644 index 00000000..a137e13f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt @@ -0,0 +1,176 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.MemberWalletManager.asEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * A member who holds no key state asking what the group signs with, and a member + * who holds one answering -- two devices, two databases, the inner-event rows + * carried from one to the other as the MLS room would carry them. + * + * The negative cases carry the weight: an answer is believed only for what it + * can prove about itself, and never filed as the room's key state. + */ +class GroupKeyNoticeJvmTest { + private val asking: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val answering: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDbs() { + asking.close() + answering.close() + } + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + private val certificate = guardedCertificate(parent, group) + + private val member = KeyPair().pubKey.toHexKey() + private val signer = KeyPair().pubKey.toHexKey() + + /** Carries every row of [kind] in the group's room from [from] to [to], as the room would. */ + private suspend fun deliver(from: BennuDatabase, to: BennuDatabase) = + from.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).forEach { to.marmotInnerEventDao().upsert(it) } + + @Test + fun `a member with no key state asks, is answered, and learns the key and the certificate`(): Unit = runBlocking { + fileKeyState(answering, group, certificate) + + assertNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) + assertTrue(MemberWalletManager.askForGroupKey(asking, groupRoom, member)) + assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "asked and not yet answered") + + deliver(asking, answering) + val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() + assertTrue(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) + assertFalse(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer), "answered once") + + deliver(answering, asking) + val groupKey = assertNotNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) + assertEquals(thresholdKeyOf(group), groupKey.thresholdPublicKey) + assertEquals(certificate.id, groupKey.certificate?.id) + assertEquals(SubgroupBirthCertificateEvent.parseGuardians(certificate.tags), groupKey.guardians) + assertNull(groupKey.policy, "the answering device held no member-wallet policy, and says nothing about one") + + assertNull(asking.groupKeyStateDao().getByChatRoomId(groupRoom), "an answer is never filed as key state") + assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "nothing left to ask") + } + + /** docs/member-wallet-delay.md, Phase 3: the late member's only way to the group's policy. */ + private suspend fun askedAndAnswered(policy: Event) { + fileKeyState(answering, group, certificate) + GroupFixtures.filePolicy(answering, group, policy) + MemberWalletManager.askForGroupKey(asking, groupRoom, member) + deliver(asking, answering) + val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() + assertTrue(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) + deliver(answering, asking) + } + + @Test + fun `an answer carries the group's open policy to a member who joined after it`(): Unit = runBlocking { + askedAndAnswered(GroupFixtures.memberWalletPolicy(group, 144)) + + val policy = MemberWalletManager.policyFor(asking, groupRoom) + assertEquals(144L, (policy as MemberWalletPolicyEvent.Policy.Open).delay) + } + + @Test + fun `an answer carries a closed policy as well`(): Unit = runBlocking { + askedAndAnswered(GroupFixtures.memberWalletPolicy(group, null)) + + assertTrue(MemberWalletManager.policyFor(asking, groupRoom) is MemberWalletPolicyEvent.Policy.Closed) + } + + @Test + fun `an answer carrying a policy another room signed does not read at all`() { + val forged = GroupFixtures.memberWalletPolicy(stranger, 6) + val tags = GroupKeyNoticeEvent.answeringTags("e".repeat(64), GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), certificate), GroupFixtures.path) + + arrayOf(arrayOf("member_wallet_policy", forged.toJson())) + + assertNull(GroupKeyNoticeEvent.read(answer(thresholdKeyOf(group), tags), groupRoom), "present and unreadable is not \"no policy\"") + } + + @Test + fun `a device that holds no key state answers nothing`(): Unit = runBlocking { + MemberWalletManager.askForGroupKey(asking, groupRoom, member) + deliver(asking, answering) + val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() + + assertFalse(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) + } + + private fun answer(content: String, tags: Array>): Event { + val pubKey = signer + val id = EventHasher.hashId(pubKey, 1_700_000_000, GroupKeyNoticeEvent.KIND, tags, content) + return Event(id, pubKey, 1_700_000_000, GroupKeyNoticeEvent.KIND, tags, content, "") + } + + private fun answerFor(groupKey: GroupKeyNoticeEvent.GroupKey): Event = + answer(groupKey.thresholdPublicKey, GroupKeyNoticeEvent.answeringTags("e".repeat(64), groupKey, GroupFixtures.path)) + + @Test + fun `an answer is believed only for what it proves`() { + val honest = GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), certificate) + assertNotNull(GroupKeyNoticeEvent.read(answerFor(honest), groupRoom)) + + // Another group's key does not derive this room. + assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(thresholdPublicKey = thresholdKeyOf(stranger))), groupRoom)) + // An answer about another room is not one about this room. + assertNull(GroupKeyNoticeEvent.read(answerFor(honest), roomOf(stranger))) + // A certificate for another child does not certify this one. + val elsewhere = guardedCertificate(parent, stranger) + assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(certificate = elsewhere)), groupRoom)) + // A certificate whose signature is not the parent's. + val forged = Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)) + assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(certificate = forged)), groupRoom)) + // The asking shape is not an answer. + assertNull(GroupKeyNoticeEvent.read(answer("", GroupKeyNoticeEvent.askingTags(groupRoom)), groupRoom)) + // A root group's answer, with no certificate, reads with no guardians. + val root = GroupKeyNoticeEvent.read(answerFor(GroupKeyNoticeEvent.GroupKey(roomOf(parent), thresholdKeyOf(parent), null)), roomOf(parent)) + assertEquals(emptyList(), assertNotNull(root).guardians) + } + + @Test + fun `an answer that does not check out leaves the member asking`(): Unit = runBlocking { + val forged = answerFor(GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(stranger), null)) + asking.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = forged.id, + publicKey = forged.pubKey, + kind = forged.kind, + createdAt = Instant.fromEpochSeconds(forged.createdAt), + tags = forged.tags, + content = forged.content, + chatRoomId = groupRoom, + ) + ) + assertNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt index e09d440f..c9cb4528 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt @@ -5,7 +5,6 @@ import com.machankura.bennu.compose.network.serialization.CommonJson import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatementEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent -import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.core.toHexKey import fr.acinq.bitcoin.ByteVector @@ -95,14 +94,13 @@ class GroupLightningWalletJvmTest { } @Test - fun `there is no Lightning wallet on mainnet, and no wallet statement leaves the group`() = runBlocking { + // That no statement leaves the group needs no test of its own: nothing in the app sends a + // group-signed event to a relay any more. + fun `there is no Lightning wallet on mainnet`() = runBlocking { val all = fixture.group() fixture.runCeremony(all) val refused = runCatching { GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, Chain.Mainnet, lsp) } assertTrue(refused.isFailure) - assertTrue(GroupLightningEvents.WALLET_STATEMENT in GroupWalletStatementEvent.NEVER_BROADCAST) - assertTrue(GroupLightningEvents.OPERATOR_STATEMENT in GroupWalletStatementEvent.NEVER_BROADCAST) - assertTrue(GroupLightningEvents.AUTHORISATION in GroupWalletStatementEvent.NEVER_BROADCAST) } @Test diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt index 0edb4897..805632b8 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt @@ -452,4 +452,78 @@ class GroupSpendSigningJvmTest { val confirmedLine = lines.single { it.messageType == ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED } assertEquals("The group's transaction confirmed: 30000 sats sent.", confirmedLine.content) } + + // ---- A guarded wallet ----------------------------------------------- + + /** + * Files the room's key state as a subgroup's, under a certificate granting + * one guardian -- signed by a parent whose key the test holds, since + * `certifies` asks only that the room it names as parent signed it. + */ + private suspend fun fileGuardedParentage(device: Device): GroupWalletManager.GuardedOpening { + val parentKey = PrivateKey(ByteVector32(ByteArray(32) { 0x0b })) + val parentRoomId = parentKey.publicKey().xOnly().value.toString() + val guardians = GuardianDerivation.grant( + PrivateKey(ByteVector32(ByteArray(32) { 0x0c })).publicKey().toString(), parentRoomId, emptyList(), roomId, + ) + val tags = com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = roomId, parentChatRoomId = parentRoomId, thresholdPublicKey = thresholdPublicKey, + adminPublicKeys = members, name = "Treasury", guardians = guardians, + ) + val id = EventHasher.hashId(parentRoomId, 1_700_000_000, 30329, tags, roomId) + val certificate = Event(id, parentRoomId, 1_700_000_000, 30329, tags, roomId, + fr.acinq.bitcoin.Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString()) + + device.db.groupKeyStateDao().upsert( + com.machankura.bennu.compose.database.model.GroupKeyState( + chatRoomId = roomId, dkgSessionId = ceremonyId, thresholdPublicKey = thresholdPublicKey, + derivationPath = SharedKeyDerivation.formatPath(), announcedBy = roomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = parentRoomId, birthCertificateJson = certificate.toJson(), + ) + ) + return assertNotNull(GroupWalletManager.guardedAccountFor(device.db, roomId, chain)) + } + + @Test + fun `a guarded wallet is opened by its quorum, and its own spends stay on the key path`() = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val opening = fileGuardedParentage(proposer) + fileGuardedParentage(other) + + val template = GroupWalletStatementEvent.template(opening.account, opening.certificate) + val statement = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, statement.id) + pump(proposer, other) + + val guarded = assertNotNull(GroupWalletManager.walletFor(other.db, roomId, chain)).account + assertTrue(guarded.isGuarded) + assertEquals(opening.account, guarded) + + val first = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0) + val change = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, 0) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x47 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(60_000), first.pubkeyScript)), 0) + val tx = Transaction(2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, 0xfffffffdL)), + listOf(TxOut(Satoshi(40_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0) + val psbt = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to first), mapOf(1 to change), guarded) + + // The plain account's check refuses the guarded coin: same internal key, another output. + assertIs(GroupSpend.check(psbt, account)) + + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt, chain) + pump(proposer, other) + assertEquals(listOf(false, true), assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)).outputs.map { it.isChange }) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val signed = Transaction.read(assertNotNull(device.transaction(session.id)?.signedTransaction)) + signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(1, signed.txIn[0].witness.stack.size, "a key-path spend: one signature, no script, no control block") + } + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardJvmTest.kt new file mode 100644 index 00000000..6b3f96f6 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardJvmTest.kt @@ -0,0 +1,328 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.managers.GroupFixtures.birthCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Telling the groups above about a guarded wallet, as a function: upward only, + * never a group that already holds it, never as another profile, and -- when + * a wallet has only just arrived -- only by the device elected to send at once. + * `docs/guarded-wallet-forwarding.md`, Phase 2. + * + * A root `R`, its guarded subgroup `M`, and `M`'s guarded subgroup `G`, which + * guards a member's wallet: the wallet's guardians are `G`, `M` and `R`. + */ +class GuardedWalletForwardJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val root = keyMaterial("7007") + private val middle = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val rootRoom = roomOf(root) + private val middleRoom = roomOf(middle) + private val groupRoom = roomOf(group) + + /** `M`'s certificate from `R`, and `G`'s from `M` with `R`'s key passed one step further. */ + private val middleCertificate = birthCertificate(root, middle, GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom)) + private val groupCertificate = birthCertificate( + middle, group, + GuardianDerivation.grant(thresholdKeyOf(middle), middleRoom, SubgroupBirthCertificateEvent.parseGuardians(middleCertificate.tags)!!, groupRoom), + ) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + private val walletPrivateKey = privateKey(0xa11ce) + private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + + private val certificate: Event = run { + val grant = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, SubgroupBirthCertificateEvent.parseGuardians(groupCertificate.tags)!!, walletId) + val request = MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = groupRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, grant), + label = null, + createdAt = 1_700_000_000, + ) + val template = MemberWalletCertificateEvent.template(request) + signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + } + + /** A member whose key sorts above this device's own, so this device stays the elected sender. */ + private val laterMember = "f".repeat(64) + + /** This device in [material]'s room, with its key state, and [members] beside it. */ + private suspend fun inRoom(material: KeyMaterial, certificate: Event?, members: List = listOf(memberPublicKey, laterMember)) { + signingRoom(db, material, members = members, subject = "#" + roomOf(material).take(4), holdsShare = false) + fileKeyState(db, material, certificate) + } + + private suspend fun inAllThree() { + inRoom(group, groupCertificate) + inRoom(middle, middleCertificate) + inRoom(root, null) + } + + private suspend fun signedInGroup() = + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + private suspend fun noticesIn(chatRoomId: String): List = + db.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)).mapNotNull { Event.fromJsonOrNull(it.content) } + + @Test + fun `from the group that signed it, every group above is told, and the group is not`(): Unit = runBlocking { + inAllThree() + signedInGroup() + + val told = GuardianManager.forward(db, certificate, groupRoom, whenElected = false).map { it.chatRoom.id } + assertEquals(listOf(middleRoom, rootRoom), told) + assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }) + assertTrue(noticesIn(groupRoom).isEmpty(), "the group holds what it signed") + assertTrue(GuardianManager.told(db, groupRoom, certificate.id), "a signed event counts as told") + + assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = false).isEmpty(), "told once") + } + + @Test + fun `from a group above, only the groups above it`(): Unit = runBlocking { + inAllThree() + signedInGroup() + // As though the middle group had been told by somebody else, and the + // root not yet. + GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom)), memberPublicKey) + + assertEquals(listOf(rootRoom), GuardianManager.forward(db, certificate, middleRoom, whenElected = false).map { it.chatRoom.id }) + assertTrue(GuardianManager.forward(db, certificate, rootRoom, whenElected = false).isEmpty(), "nothing goes back down") + } + + @Test + fun `the button offers only what goes up`(): Unit = runBlocking { + inAllThree() + signedInGroup() + // Carrying the group's birth certificate, as every share from this build + // does: a notice without it would be offered once more, so the name + // reaches the groups above. docs/member-wallet-guarding-group.md, D5. + GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom), db.chatRoomDao().findChatRoomById(rootRoom)), memberPublicKey, certificate = groupCertificate) + + // The root holds it as a notice, the middle group too, and the group signed it. + assertTrue(GuardianManager.shareableFrom(db, rootRoom, chain).isEmpty(), "the root has nobody above it to tell") + assertTrue(GuardianManager.shareableFrom(db, middleRoom, chain).isEmpty()) + assertTrue(GuardianManager.shareableFrom(db, groupRoom, chain).isEmpty()) + } + + @Test + fun `a group above that belongs to another profile on the device is never told`(): Unit = runBlocking { + inRoom(group, groupCertificate) + inRoom(middle, middleCertificate) + signedInGroup() + val other = "0f".repeat(32) + GroupFixtures.seedProfile(db, other) + val middleRow = db.chatRoomDao().findChatRoomById(middleRoom)!!.chatRoom + db.chatRoomDao().upsert(middleRow.copy(userPublicKey = other)) + + assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = false).isEmpty()) + assertTrue(noticesIn(middleRoom).isEmpty()) + } + + @Test + fun `when a wallet has only just arrived, only the elected device sends`(): Unit = runBlocking { + // A member whose key sorts below this device's sits in both rooms. + val earlier = "00".repeat(31) + "01" + inRoom(group, groupCertificate, members = listOf(memberPublicKey, earlier)) + inRoom(middle, middleCertificate, members = listOf(earlier)) + signedInGroup() + + assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = true).isEmpty(), "the earlier member sends") + assertEquals(listOf(middleRoom), GuardianManager.forward(db, certificate, groupRoom, whenElected = false).map { it.chatRoom.id }, "and the catch-up sends what is left") + } + + @Test + fun `the elected device sends at once`(): Unit = runBlocking { + inRoom(group, groupCertificate) + inRoom(middle, middleCertificate) + signedInGroup() + + assertEquals(listOf(middleRoom), GuardianManager.forward(db, certificate, groupRoom, whenElected = true).map { it.chatRoom.id }) + } + + @Test + fun `nothing it does not believe is forwarded anywhere`(): Unit = runBlocking { + inAllThree() + val forged = Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)) + assertTrue(GuardianManager.forward(db, forged, groupRoom, whenElected = false).isEmpty()) + assertFalse(noticesIn(middleRoom).isNotEmpty()) + } + + // ---- Phase 3: on arrival, with nobody calling share ------------------- + + /** [event] arriving in [chatRoomId] as the inbound path and a completed signing session both deliver it. */ + private suspend fun arrives(event: Event, chatRoomId: String) { + com.machankura.bennu.compose.database.model.ChatMessage.applyInnerEvent( + database = db, + groupId = chatRoomId, + event = event, + marmotGroupEventId = null, + marmotInnerEventId = null, + senderPublicKey = chatRoomId, + isUserMessage = false, + createdAt = kotlin.time.Instant.fromEpochSeconds(event.createdAt), + ) + } + + @Test + fun `a member's certificate signed in the group reaches the root two generations up`(): Unit = runBlocking { + inAllThree() + signedInGroup() + + arrives(certificate, groupRoom) + assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }, "the group's devices told the middle group") + assertEquals(listOf(certificate.id), noticesIn(rootRoom).map { it.id }, "and, being in the root too, the root") + + // The notice arriving in the middle group goes on, and not back down. + GuardianManager.forwardOnArrival(db, noticesIn(middleRoom).single(), middleRoom) + assertEquals(1, noticesIn(rootRoom).size, "the root was told once") + assertTrue(noticesIn(groupRoom).isEmpty()) + } + + @Test + fun `a notice arriving in the middle group is carried to the root`(): Unit = runBlocking { + // This device sits in the middle group and the root, not in the group below. + inRoom(middle, middleCertificate) + inRoom(root, null) + GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom)), memberPublicKey) + + GuardianManager.forwardOnArrival(db, certificate, middleRoom) + assertEquals(listOf(certificate.id), noticesIn(rootRoom).map { it.id }) + assertEquals(1, GuardianManager.guardedWalletsOf(db, rootRoom).size, "and the root lists it") + } + + @Test + fun `a subgroup's own guarded wallet reaches every group above it`(): Unit = runBlocking { + inAllThree() + val guardians = SubgroupBirthCertificateEvent.parseGuardians(groupCertificate.tags)!! + val account = GroupWalletDerivation.account(thresholdKeyOf(group), chain, 0, guardians) + val template = com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent.template(account, groupCertificate) + val statement = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + + arrives(statement, groupRoom) + assertEquals(listOf(statement.id), noticesIn(middleRoom).map { it.id }) + assertEquals(listOf(statement.id), noticesIn(rootRoom).map { it.id }) + } + + @Test + fun `a plain wallet statement is told to nobody`(): Unit = runBlocking { + inAllThree() + val template = com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdKeyOf(middle), chain)) + arrives(signedAsRoom(middle, template.kind, template.tags, template.content, template.createdAt), middleRoom) + assertTrue(noticesIn(rootRoom).isEmpty()) + } + + // ---- Phase 4: the catch-up --------------------------------------------- + + @Test + fun `a certificate filed before forwarding existed is told the first time its group is opened`(): Unit = runBlocking { + // A lower-keyed member in both rooms: on arrival this device would have + // waited for them, and nobody sent anything. + val earlier = "00".repeat(31) + "01" + inRoom(group, groupCertificate, members = listOf(memberPublicKey, earlier)) + inRoom(middle, middleCertificate, members = listOf(earlier)) + signedInGroup() + assertTrue(noticesIn(middleRoom).isEmpty()) + + assertEquals(1, GuardianManager.forwardAll(db, groupRoom)) + assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }) + assertEquals(0, GuardianManager.forwardAll(db, groupRoom), "and not again") + } + + @Test + fun `the catch-up through the repository, as opening the room runs it`(): Unit = runBlocking { + inAllThree() + signedInGroup() + val repository = com.machankura.bennu.compose.database.repository.DatabaseChatRepository(db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO)) + + assertEquals(2, repository.forwardGuardedWallets(groupRoom), "the middle group and the root") + assertEquals(0, repository.forwardGuardedWallets(middleRoom), "the root has heard, and the group signed it") + } + + // ---- Phase 5: the transcript ------------------------------------------ + + private suspend fun sharedLinesIn(chatRoomId: String) = + db.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).map { it.chatMessage } + .filter { it.messageType == com.machankura.bennu.compose.database.model.ChatMessage.TYPE_GUARDED_WALLET_SHARED } + + /** A notice of [statement] from [forwarder], filed in [chatRoomId] as the inbound path files one. */ + private suspend fun noticeFrom(forwarder: String, chatRoomId: String, statement: Event, at: Long): Event { + val tags = arrayOf(arrayOf("h", chatRoomId)) + val id = com.vitorpamplona.quartz.nip01Core.crypto.EventHasher.hashId(forwarder, at, GuardedWalletNoticeEvent.KIND, tags, statement.toJson()) + db.marmotInnerEventDao().upsert( + com.machankura.bennu.compose.database.model.MarmotInnerEvent( + id = id, publicKey = forwarder, kind = GuardedWalletNoticeEvent.KIND, + createdAt = kotlin.time.Instant.fromEpochSeconds(at), tags = tags, content = statement.toJson(), chatRoomId = chatRoomId, + ) + ) + return Event(id, forwarder, at, GuardedWalletNoticeEvent.KIND, tags, statement.toJson(), "") + } + + @Test + fun `two forwarders' notices of one wallet give the group one line`(): Unit = runBlocking { + GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") + inRoom(middle, middleCertificate) + + val first = noticeFrom("a1".repeat(32), middleRoom, certificate, 1_700_000_100) + assertEquals("Shared @alice's guarded wallet with this group.", GuardianManager.describeNotice(db, middleRoom, first)) + + val second = noticeFrom("b2".repeat(32), middleRoom, certificate, 1_700_000_200) + assertEquals(null, GuardianManager.describeNotice(db, middleRoom, second), "the second is filed and silent") + assertEquals(1, GuardianManager.guardedWalletsOf(db, middleRoom).size, "and the wallet listed once") + } + + @Test + fun `the forwarder sees its own line in the group it told`(): Unit = runBlocking { + GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") + inRoom(group, groupCertificate) + inRoom(middle, middleCertificate) + signedInGroup() + + GuardianManager.forward(db, certificate, groupRoom, whenElected = false) + val lines = sharedLinesIn(middleRoom) + assertEquals(1, lines.size) + assertTrue(lines.single().isUserMessage) + assertEquals("Shared @alice's guarded wallet with this group.", lines.single().content) + assertTrue(sharedLinesIn(groupRoom).isEmpty(), "nothing in the group that signed it") + + // Another member's notice of the same wallet, arriving afterwards, writes nothing more. + assertEquals(null, GuardianManager.describeNotice(db, middleRoom, noticeFrom("b2".repeat(32), middleRoom, certificate, 1_800_000_000))) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardingRulesJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardingRulesJvmTest.kt new file mode 100644 index 00000000..952b3e40 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardingRulesJvmTest.kt @@ -0,0 +1,116 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.GuardianManager.GuardedSubject +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * The rules forwarding is built on, with no database: which groups a statement + * is told to from a room -- upward only -- who sends at once, and what a + * forwarder believes before it passes anything on. + * `docs/guarded-wallet-forwarding.md`, Phase 1. + */ +class GuardedWalletForwardingRulesJvmTest { + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val root = keyMaterial("7007") + private val middle = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val rootRoom = roomOf(root) + private val middleRoom = roomOf(middle) + private val groupRoom = roomOf(group) + + /** A grandchild's guardians as its certificate lists them: its parent, then the root one step further. */ + private val grandchildRoom = roomOf(keyMaterial("c1d0")) + private val grandchildGuardians = GuardianDerivation.grant( + thresholdKeyOf(middle), middleRoom, + GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom), + grandchildRoom, + ) + + @Test + fun `a grandchild's statement goes up from where it is, and never back down`() { + assertEquals(listOf(middleRoom, rootRoom), GuardianManager.upwardOf(grandchildGuardians, grandchildRoom), "from its own room, every guardian") + assertEquals(listOf(rootRoom), GuardianManager.upwardOf(grandchildGuardians, middleRoom), "from the middle group, the root alone") + assertEquals(emptyList(), GuardianManager.upwardOf(grandchildGuardians, rootRoom), "from the root, nothing: the middle group told it") + } + + private val member = privateKey(0x3e3be7) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + + /** A member's wallet under `group`, two levels below the root. */ + private val memberGuardians = GuardianDerivation.grant( + thresholdKeyOf(group), groupRoom, + GuardianDerivation.grant( + thresholdKeyOf(middle), middleRoom, + GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom), + groupRoom, + ), + walletId, + ) + + private fun certificate(signer: fr.acinq.bitcoin.crypto.frost.KeyMaterial = group): Event { + val request = MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = groupRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, memberGuardians), + label = null, + createdAt = 1_700_000_000, + ) + val template = MemberWalletCertificateEvent.template(request) + return signedAsRoom(signer, template.kind, template.tags, template.content, template.createdAt) + } + + @Test + fun `a member's wallet goes up from the group that signed it`() { + assertEquals(listOf(middleRoom, rootRoom), GuardianManager.upwardOf(memberGuardians, groupRoom)) + assertEquals(listOf(rootRoom), GuardianManager.upwardOf(memberGuardians, middleRoom)) + } + + @Test + fun `the lowest key sends at once`() { + assertEquals("0a".repeat(32), GuardianManager.electedSender(setOf("ff".repeat(32), "0A".repeat(32), "7c".repeat(32)))) + assertNull(GuardianManager.electedSender(emptySet())) + } + + @Test + fun `a forwarder believes a member's certificate the group signed`() { + val believed = assertNotNull(GuardianManager.believable(certificate())) + assertEquals(walletId, believed.descendantId) + assertEquals(memberGuardians, believed.guardians) + assertIs(believed.subject) + } + + @Test + fun `a forwarder believes nothing it could not check`() { + // Signed by a group that was not the one asked. + assertNull(GuardianManager.believable(certificate(signer = middle))) + // A signature that is not one. + val certificate = certificate() + assertNull(GuardianManager.believable(Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)))) + // A plain wallet statement names no guardians. + val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdKeyOf(group), chain)) + assertNull(GuardianManager.believable(signedAsRoom(group, plain.kind, plain.tags, plain.content, plain.createdAt))) + // Something else altogether. + assertNull(GuardianManager.believable(signedAsRoom(group, 1, emptyArray(), "hello"))) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt new file mode 100644 index 00000000..fa7d9811 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt @@ -0,0 +1,814 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow +import com.machankura.bennu.compose.database.model.GroupKeyState +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgParticipantMessage +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.database.model.NostrEvent +import com.machankura.bennu.compose.database.model.Profile +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.extensions.toHex +import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import kotlinx.coroutines.runBlocking +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 com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import kotlin.test.assertTrue +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.machankura.bennu.compose.database.model.types.FrostSigningSubject +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import kotlin.test.assertIs + +/** + * A group's guardian keys through the real signing manager, between two of its + * devices, with the wire held by hand -- the harness `GroupSpendSigningJvmTest` + * uses. + * + * The group here is the *ancestor*. What is under test is what its members' + * devices agree to: a certificate is only signed when the guardian keys in it + * are the ones the group grants, whoever proposed it. + */ +class GuardianSigningJvmTest { + private val participants = 3 + private val threshold = 2 + + private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32("6a2d1a".padEnd(62, '0') + "a1")), + nParticipants = participants, + threshold = threshold, + ) + private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() + private val ceremonyId = "ceremony".padEnd(64, '0') + private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val members = listOf("a", "b", "c").map { it.repeat(64) } + private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } + + private val childKey = PrivateKey(ByteVector32(ByteArray(32) { 0x3c })).publicKey().toString() + private val childRoomId = SharedKeyDerivation.marmotGroupId(childKey) + + private val devices = mutableListOf() + + @AfterTest + fun closeDatabases() = devices.forEach { it.db.close() } + + private inner class Device(val publicKey: HexKey, val db: BennuDatabase, val room: LocalChatRoom) { + val received = mutableSetOf() + + suspend fun store(queued: Queued) = db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = queued.id, publicKey = queued.publicKey, kind = queued.kind, createdAt = queued.createdAt, + tags = queued.tags, content = queued.content, chatRoomId = roomId, + ) + ) + + suspend fun session(id: String) = db.frostSigningSessionDao().getSessionById(id) + } + + private suspend fun device(publicKey: HexKey, signerIndex: 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 = publicKey, subject = "Council", + description = SharedKeyDerivation.describe("Council."), mlsGroupState = "00", + ) + db.chatRoomDao().upsert(chatRoom) + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = publicKey, + threshold = threshold, participantCount = participants, stage = DkgRitualStage.COMPLETE, + hostPublicKey = hostKeys[signerIndex], round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), + thresholdPublicKey = thresholdPublicKey, + secretShare = keyMaterial.secretShares[signerIndex].value.toHex(), + publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, + ) + ) + members.forEachIndexed { index, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[index]) + ) + } + val localChatRoom = db.chatRoomDao().findChatRoomById(roomId) ?: LocalChatRoom(chatRoom = chatRoom) + return Device(publicKey, db, localChatRoom).also { devices += it } + } + + private data class Queued( + val id: HexKey, val publicKey: HexKey, val kind: Int, + val tags: Array>, val content: String, val createdAt: Instant, + ) { + fun toEvent() = Event(id, publicKey, createdAt.epochSeconds, kind, tags, content, "") + } + + private suspend fun outbox(device: Device): List = + device.db.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = roomId, kinds = FrostSigningEvents.ALL.toList()) + .map { Queued(it.id, it.publicKey, it.kind, it.tags, it.content, it.createdAt) } + .filter { it.publicKey == device.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + + private suspend fun deliver(to: Device, queued: Queued) { + if (!to.received.add(queued.id)) return + to.store(queued) + FrostSigningManager.processSigningPayload(to.db, to.room, queued.toEvent(), to.publicKey) + } + + private suspend fun pump(vararg between: Device) { + 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) moved = true + deliver(to, queued) + } + } + } + } + + private fun certificateTags(guardians: List) = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = childRoomId, + parentChatRoomId = roomId, + thresholdPublicKey = childKey, + adminPublicKeys = members, + name = "Translation team", + guardians = guardians, + ) + + private suspend fun proposeCertificate(proposer: Device, guardians: List) = + FrostSigningManager.proposeSigning( + proposer.db, proposer.room, proposer.publicKey, SubgroupBirthCertificateEvent.KIND, certificateTags(guardians), childRoomId, + ) + + // ---- The certificate's guardian keys -------------------------------- + + @Test + fun `a certificate granting the group's own key is signed, and carries it`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val granted = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), childRoomId) + + val session = proposeCertificate(proposer, granted) + pump(proposer, other) + assertNotNull(other.session(session.id), "the other member is asked") + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val certificate = assertNotNull(SubgroupManager.certificateFor(device.db, childRoomId, roomId)).toEvent() + assertEquals(granted, SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)) + } + } + + @Test + fun `a certificate granting any other key is never put to the member`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val coordinators = PrivateKey(ByteVector32(ByteArray(32) { 0x66 })).publicKey().toString() + + // The coordinator's own key dressed as the group's guardian key. + val session = proposeCertificate(proposer, GuardianDerivation.grant(coordinators, roomId, emptyList(), childRoomId)) + pump(proposer, other) + + assertNull(other.session(session.id), "refused at acceptance, so nothing of the member's is ever published for it") + } + + // ---- The parent's decision: docs/subgroup-wallet-policy.md ------------ + + /** A parent of this room, as a key whose certificate this test files without signing. */ + private val decidingParentKey = PrivateKey(ByteVector32(ByteArray(32) { 0x4d })).publicKey().toString() + private val decidingParentRoomId = SharedKeyDerivation.marmotGroupId(decidingParentKey) + private val grantedToRoom = GuardianDerivation.grant(decidingParentKey, decidingParentRoomId, emptyList(), roomId) + + /** + * This room as a subgroup its parent made under [policy], filed on [device] + * the way a verified key state leaves it. The policy is read off the + * certificate's tags; whether the parent signed it was `stateFrom`'s + * question, asked before the row was written. + */ + private suspend fun madeUnder(device: Device, policy: SubgroupWalletPolicy?): Event { + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = roomId, + parentChatRoomId = decidingParentRoomId, + thresholdPublicKey = thresholdPublicKey, + adminPublicKeys = members, + name = "Council", + guardians = if (policy == SubgroupWalletPolicy.UNGUARDED) emptyList() else grantedToRoom, + walletPolicy = policy, + ) + val certificate = Event("d".repeat(64), decidingParentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, roomId, "f".repeat(128)) + device.db.groupKeyStateDao().upsert( + GroupKeyState( + chatRoomId = roomId, + dkgSessionId = ceremonyId, + thresholdPublicKey = thresholdPublicKey, + derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH), + announcedBy = roomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = decidingParentRoomId, + birthCertificateJson = certificate.toJson(), + ) + ) + return certificate + } + + private suspend fun proposeStatement(proposer: Device, guarded: Boolean, certificate: Event) = run { + val template = if (guarded) { + GroupWalletStatementEvent.template( + GroupWalletDerivation.account(thresholdPublicKey, Chain.Regtest, guardians = grantedToRoom), + certificate, + ) + } else { + GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdPublicKey, Chain.Regtest)) + } + FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) + } + + @Test + fun `a plain wallet is never put to a member whose parent decided guarded`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + madeUnder(proposer, SubgroupWalletPolicy.GUARDED) + val certificate = madeUnder(other, SubgroupWalletPolicy.GUARDED) + + // What an older build, or a skipped screen, would propose. + val plain = proposeStatement(proposer, guarded = false, certificate) + val guarded = proposeStatement(proposer, guarded = true, certificate) + pump(proposer, other) + + assertNull(other.session(plain.id), "refused before it is shown") + assertNotNull(other.session(guarded.id), "the guarded one is asked") + } + + @Test + fun `a guarded wallet is never put to a member whose parent decided unguarded`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + madeUnder(proposer, SubgroupWalletPolicy.UNGUARDED) + madeUnder(other, SubgroupWalletPolicy.UNGUARDED) + + // A certificate granting keys, as a modified client might carry; the + // room's own decided none. + val guarded = proposeStatement(proposer, guarded = true, madeUnder(device(members[2], signerIndex = 2), SubgroupWalletPolicy.GUARDED)) + val plain = proposeStatement(proposer, guarded = false, madeUnder(proposer, SubgroupWalletPolicy.UNGUARDED)) + pump(proposer, other) + + assertNull(other.session(guarded.id)) + assertNotNull(other.session(plain.id)) + } + + @Test + fun `an undecided room is asked about either, as before`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + madeUnder(proposer, null) + val certificate = madeUnder(other, null) + + val plain = proposeStatement(proposer, guarded = false, certificate) + val guarded = proposeStatement(proposer, guarded = true, certificate) + pump(proposer, other) + + assertNotNull(other.session(plain.id)) + assertNotNull(other.session(guarded.id)) + } + + // ---- Telling an ancestor about a guarded wallet ----------------------- + + /** The child as a group of its own, so its room can sign its statement. */ + private val childMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32("c41d".padEnd(62, '0') + "b2")), + nParticipants = participants, + threshold = threshold, + ) + private val guardedChildKey = childMaterial.thresholdPublicKey.value.toHex() + private val guardedChildRoomId = SharedKeyDerivation.marmotGroupId(guardedChildKey) + + /** [material]'s room signing [id], as a quorum of its trusted-dealer shares. */ + private fun roomSignature(material: KeyMaterial, id: String): String { + val cache = SharedKeyDerivation.derive(material.thresholdPublicKey.value.toHex()).cache + val message = ByteVector(id.hexToByteArray()) + val signerIds = listOf(0, 1) + val nonces = signerIds.map { signerId -> + SecretNonce.generate( + sessionRandom = ByteVector32("b".repeat(63) + "${signerId + 1}"), + secretShare = material.secretShares[signerId], + publicShare = material.publicShares[signerId], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null, + ) + } + val session = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { material.publicShares[it] }, + nParticipants = participants, + threshold = threshold, + tweakCache = cache, + message = message, + ) + val partials = signerIds.mapIndexed { position, signerId -> + session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!! + } + return session.aggregateSigs(partials).right!!.toByteArray().toHex() + } + + private fun signedBy(material: KeyMaterial, kind: Int, tags: Array>, content: String, createdAt: Long = 1_700_000_000): Event { + val author = SharedKeyDerivation.marmotGroupId(material.thresholdPublicKey.value.toHex()) + val id = EventHasher.hashId(author, createdAt, kind, tags, content) + return Event(id, author, createdAt, kind, tags, content, roomSignature(material, id)) + } + + /** The ancestor certifies the child with [guardians], and the child signs a guarded statement under them. */ + private fun guardedStatement( + guardians: List = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId), + createdAt: Long = 1_700_000_000, + ): Event { + val certificate = signedBy( + keyMaterial, SubgroupBirthCertificateEvent.KIND, + SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = guardedChildRoomId, parentChatRoomId = roomId, thresholdPublicKey = guardedChildKey, + adminPublicKeys = members, name = "Translation team", guardians = guardians, + ), + guardedChildRoomId, + ) + val account = GroupWalletDerivation.account(guardedChildKey, Chain.Regtest, guardians = guardians) + val template = GroupWalletStatementEvent.template(account, certificate, createdAt) + return signedBy(childMaterial, template.kind, template.tags, template.content, createdAt) + } + + private suspend fun tell(device: Device, statement: Event, from: HexKey = members[2], createdAt: Long = 1_700_000_100) { + val content = statement.toJson() + device.db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = EventHasher.hashId(from, createdAt, GuardedWalletNoticeEvent.KIND, emptyArray(), content), + publicKey = from, kind = GuardedWalletNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(createdAt), + tags = emptyArray(), content = content, chatRoomId = roomId, + ) + ) + } + + @Test + fun `an ancestor believes a statement naming a key its own walk reaches, and nothing else`() { + val statement = guardedStatement() + + val wallet = assertNotNull(GuardianManager.verify(statement, roomId, thresholdPublicKey)) + assertEquals(guardedChildRoomId, wallet.descendantChatRoomId) + assertEquals(listOf(guardedChildRoomId), wallet.lineage) + assertEquals("Translation team", wallet.name) + assertTrue(wallet.account.isGuarded) + + val strangerKey = PrivateKey(ByteVector32(ByteArray(32) { 0x55 })).publicKey().toString() + val refusals = mapOf( + "a group that is not among its guardians" to GuardianManager.verify(statement, guardedChildRoomId, guardedChildKey), + "a key the ancestor's walk does not reach" to GuardianManager.verify( + guardedStatement(GuardianDerivation.grant(strangerKey, roomId, emptyList(), guardedChildRoomId)), roomId, thresholdPublicKey, + ), + "a statement the child's room did not sign" to GuardianManager.verify(Event(statement.id, statement.pubKey, statement.createdAt, statement.kind, statement.tags, statement.content, "0".repeat(128)), roomId, thresholdPublicKey), + "a plain statement" to run { + val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(guardedChildKey, Chain.Regtest)) + GuardianManager.verify(signedBy(childMaterial, plain.kind, plain.tags, plain.content), roomId, thresholdPublicKey) + }, + ) + refusals.forEach { (name, verified) -> assertNull(verified, name) } + } + + @Test + fun `a notice in the ancestor's room is a guarded wallet it holds, under its first guardians`(): Unit = runBlocking { + val ancestor = device(members[0], signerIndex = 0) + val first = guardedStatement(createdAt = 1_700_000_000) + tell(ancestor, first) + // A later statement for the same account, naming other guardians, cannot + // move what the ancestor watches -- the earliest decides. + val second = guardedStatement( + GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId).map { it.copy(delay = 13) }, + createdAt = 1_700_000_500, + ) + tell(ancestor, second, createdAt = 1_700_000_600) + // And nonsense is read past, not believed. + ancestor.db.marmotInnerEventDao().upsert( + MarmotInnerEvent(id = "f".repeat(64), publicKey = members[2], kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1), tags = emptyArray(), content = "not an event", chatRoomId = roomId) + ) + + val held = GuardianManager.guardedWalletsOf(ancestor.db, roomId) + assertEquals(listOf(first.id), held.map { it.statement.id }) + assertEquals( + "Shared the guarded wallet of Translation team with this group.", + // The notice as it was filed: a second notice of the same statement + // would be filed and silent (docs/guarded-wallet-forwarding.md, D6). + ancestor.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND)) + .first { Event.fromJsonOrNull(it.content)?.id == first.id } + .let { GuardianManager.describeNotice(ancestor.db, roomId, Event(it.id, it.publicKey, it.createdAt.epochSeconds, it.kind, it.tags, it.content, "")) } + ) + } + + @Test + fun `a member in both rooms carries the child's statement up, once`(): Unit = runBlocking { + val member = device(members[0], signerIndex = 0) + // This device is also in the child's room, and holds its signed statement there. + member.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = member.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) + member.db.groupKeyStateDao().upsert( + com.machankura.bennu.compose.database.model.GroupKeyState( + chatRoomId = guardedChildRoomId, dkgSessionId = "child-ceremony", thresholdPublicKey = guardedChildKey, + derivationPath = SharedKeyDerivation.formatPath(), announcedBy = guardedChildRoomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + ) + ) + val statement = guardedStatement() + member.db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(statement, chatRoomId = guardedChildRoomId)) + + val shareable = GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest).single() + assertEquals(statement.id, shareable.statement.id) + assertEquals(listOf(roomId), shareable.rooms.map { it.chatRoom.id }) + + assertEquals(1, GuardianManager.share(member.db, shareable.statement, shareable.rooms, member.publicKey)) + val queued = member.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND)).single() + assertEquals(member.publicKey, queued.publicKey) + assertNull(queued.marmotGroupEventId, "queued for the outbound pipeline, not yet sent") + + // Told is told: nothing left to share, and the ancestor's own device reads it back. + assertEquals(emptyList(), GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest)) + assertEquals(listOf(statement.id), GuardianManager.guardedWalletsOf(member.db, roomId).map { it.statement.id }) + } + + @Test + fun `a grandchild's statement told to its parent and grandparent at once reaches both`(): Unit = runBlocking { + val member = device(members[0], signerIndex = 0) + val grandparentRoomId = "9".repeat(64) + member.db.chatRoomDao().upsert(ChatRoom(id = grandparentRoomId, userPublicKey = member.publicKey, subject = "Assembly", description = null, mlsGroupState = "00")) + val rooms = listOf(roomId, grandparentRoomId).map { assertNotNull(member.db.chatRoomDao().findChatRoomById(it)) } + + // One statement, one sharer, one second: only the room tells the two notices apart. + assertEquals(2, GuardianManager.share(member.db, guardedStatement(), rooms, member.publicKey, createdAt = 1_700_000_100)) + + val told = listOf(roomId, grandparentRoomId).associateWith { room -> + member.db.marmotInnerEventDao().getByChatRoomAndKinds(room, listOf(GuardedWalletNoticeEvent.KIND)).single() + } + told.forEach { (room, notice) -> assertEquals(listOf(listOf("h", room)), notice.tags.map { it.toList() }) } + assertEquals(2, told.values.map { it.id }.toSet().size) + } + + // ---- Spending from a guarded wallet ------------------------------------ + + private val chain = Chain.Regtest + private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) + + /** Somebody else's money paying the child's first guarded receive address. */ + private fun fundingOf(guarded: GroupWalletDerivation.Account) = Transaction( + 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x61 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(50_000), GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0).pubkeyScript)), 0, + ) + + /** The child's wallet as Electrum would report it holding [funding], confirmed at [height], with the tip at [tip]. */ + private fun fundedState(guarded: GroupWalletDerivation.Account, funding: Transaction, height: Int, tip: Int): GroupWalletState { + val meta = WalletState.AddressMeta.Derived(0) + val address = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0).address(chain) + val receive = WalletState(mapOf(address to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(funding.txid, 0, height.toLong(), funding, meta))))) + val change = WalletState((0 until 3).associate { index -> + GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) + }) + return GroupWalletState(guarded, receive, change, tipHeight = tip) + } + + @Test + fun `the builder waits out the leaf's lock, and puts it on every input`() { + val guarded = assertNotNull(GuardianManager.verify(guardedStatement(), roomId, thresholdPublicKey)) + val funding = fundingOf(guarded.account) + val address = fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!! + + // Eleven confirmations: the owner could spend it, the guardian cannot yet. + val young = fundedState(guarded.account, funding, height = 100, tip = 110) + assertIs(GroupSpendBuilder.sendAll(young, address, 2, emptySet())) + assertEquals(GroupSpendBuilder.Result.NothingToSpend, GroupSpendBuilder.sendAll(young, address, 2, emptySet(), guarded.spender())) + + val old = fundedState(guarded.account, funding, height = 100, tip = 111) + val built = assertIs(GroupSpendBuilder.sendAll(old, address, 2, emptySet(), guarded.spender())) + assertEquals(listOf(12L), built.psbt.global.tx.txIn.map { it.sequence }) + + // What the builder charged for is what a signer weighs it at. + val checked = assertIs(GroupSpend.check(built.psbt, guarded.account, guarded.spender(thresholdPublicKey))).checked + assertEquals(built.fee.sat, 2 * ((checked.weight + 3) / 4).toLong()) + } + + /** + * The builder and the check read each leaf's own delay, at the edges of its + * encoding: a coin one block short of the lock is the owner's alone, at the + * lock it is the guardian's too, and every input carries exactly that lock. + * docs/guardian-delay.md, Phase 2. + */ + @Test + fun `the builder and the check follow a chosen delay, not the default`() { + val address = fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!! + listOf(6L, 17L, 128L, 32_768L, 65_535L).forEach { delay -> + val guardians = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId, delay = delay) + val guarded = assertNotNull(GuardianManager.verify(guardedStatement(guardians), roomId, thresholdPublicKey), "a delay of $delay") + val funding = fundingOf(guarded.account) + + // Confirmed at height 100, so `delay` confirmations at tip 99 + delay. + val young = fundedState(guarded.account, funding, height = 100, tip = 98 + delay.toInt()) + assertEquals(GroupSpendBuilder.Result.NothingToSpend, GroupSpendBuilder.sendAll(young, address, 2, emptySet(), guarded.spender()), "a delay of $delay") + + val old = fundedState(guarded.account, funding, height = 100, tip = 99 + delay.toInt()) + val built = assertIs(GroupSpendBuilder.sendAll(old, address, 2, emptySet(), guarded.spender())) + assertEquals(listOf(delay), built.psbt.global.tx.txIn.map { it.sequence }) + assertIs(GroupSpend.check(built.psbt, guarded.account, guarded.spender(thresholdPublicKey))) + + // The default's lock on a leaf that chose another is refused. + val atDefault = built.psbt.global.tx.copy(txIn = built.psbt.global.tx.txIn.map { it.copy(sequence = GuardianDerivation.DEFAULT_DELAY) }) + val refused = GroupSpend.check(built.psbt.copy(global = built.psbt.global.copy(tx = atDefault)), guarded.account, guarded.spender(thresholdPublicKey)) + if (delay != GuardianDerivation.DEFAULT_DELAY) assertIs(refused, "a delay of $delay") + } + } + + /** + * Two ancestors who gave the same wallet different delays: a coin 100 blocks + * deep is within the reach of the one at 12 and not the one at 4,320. + * docs/guardian-delay.md, Phase 7. + */ + @Test + fun `a guarded wallet's reach is each ancestor's own delay`() { + val farKey = PrivateKey(ByteVector32(ByteArray(32) { 0x5e })).publicKey().toString() + val farRoom = SharedKeyDerivation.marmotGroupId(farKey) + val inherited = GuardianDerivation.grant(farKey, farRoom, emptyList(), roomId, delay = 4_320) + val guardians = GuardianDerivation.grant(thresholdPublicKey, roomId, inherited, guardedChildRoomId, delay = 12) + val near = assertNotNull(GuardianManager.verify(guardedStatement(guardians), roomId, thresholdPublicKey)) + val far = near.copy(ancestorChatRoomId = farRoom) + assertEquals(12L, near.delay) + assertEquals(4_320L, far.delay) + + val state = fundedState(near.account, fundingOf(near.account), height = 100, tip = 199) + assertEquals(Satoshi(50_000), GuardedWalletRow(near, state).withinReach) + assertEquals(Satoshi(0), GuardedWalletRow(far, state).withinReach) + // And what is arriving is the rest of it, by the same leaf's lock. + assertEquals(Satoshi(0), GuardedWalletRow(near, state).arriving) + assertEquals(Satoshi(50_000), GuardedWalletRow(far, state).arriving) + } + + @Test + fun `an ancestor's quorum spends a descendant's coin through its leaf, on every device`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + tell(other, statement) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val funding = fundingOf(guarded.account) + val built = assertIs( + GroupSpendBuilder.send(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, + Satoshi(30_000), 2, emptySet(), emptySet(), guarded.spender()) + ) + + val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) + pump(proposer, other) + assertEquals(FrostSigningSubject.TRANSACTION, other.session(session.id)?.subject) + val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) + assertIs(seen.spender) + assertEquals(listOf(false, true), seen.outputs.map { it.isChange }, "the change goes back to the child") + + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val row = assertNotNull(device.db.groupTransactionDao().getBySessionId(session.id)) + assertEquals(guardedChildRoomId, row.guardedChatRoomId) + val signed = Transaction.read(assertNotNull(row.signedTransaction)) + signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(3, signed.txIn[0].witness.stack.size, "a signature, the leaf, and its control block") + } + } + + @Test + fun `the child reads off the chain which guardian took its coins, and says so once`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + tell(other, statement) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val funding = fundingOf(guarded.account) + val built = assertIs( + GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender()) + ) + val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + val signed = Transaction.read(assertNotNull(proposer.db.groupTransactionDao().getBySessionId(session.id)?.signedTransaction)) + + // What the child's device knows: its own coin, and the transaction that spent it. + val coins = mapOf(OutPoint(funding, 0) to (funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0))) + val taken = GuardianManager.takenIn(signed, guarded.account, coins) + assertEquals(listOf(GuardianManager.Taken(signed.txid, guarded.account.guardians[0], Satoshi(50_000))), taken) + + // The child's own key-path spend names nobody. + val ownSpend = signed.updateWitness(0, fr.acinq.bitcoin.ScriptWitness(listOf(ByteVector(ByteArray(64))))) + assertEquals(emptyList(), GuardianManager.takenIn(ownSpend, guarded.account, coins)) + + // The line, written once, in the child's room -- the ancestor's name from + // this device's own copy of its room. + proposer.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = proposer.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) + assertEquals(1, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken)) + assertEquals(0, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken), "a second reading of the chain writes nothing") + val line = proposer.db.chatMessageDao().getChatMessagesByChatRoomId(guardedChildRoomId).map { it.chatMessage } + .single { it.messageType == com.machankura.bennu.compose.database.model.ChatMessage.TYPE_GUARDIAN_SPEND } + assertTrue(line.content.startsWith("Council took 50000 sats from this wallet through its guardian leaf"), line.content) + } + + @Test + fun `a guardian's spend is refused for a wallet the room was not told about, or without the lock`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + // The other device was never told: it has no wallet to check the spend against. + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val funding = fundingOf(guarded.account) + val built = assertIs( + GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender()) + ) + val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) + pump(proposer, other) + assertNull(other.session(session.id), "a device not told about the wallet has nothing to sign it against") + + // And the proposer's own device will not propose one that skips the lock. + val unlocked = built.psbt.global.tx.let { tx -> tx.copy(txIn = tx.txIn.map { it.copy(sequence = GroupSpend.MAX_SEQUENCE) }) } + val psbt = GroupSpend.psbtOf(unlocked, listOf(funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0)), emptyMap(), guarded.account) + assertIs(GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) + } + + // ---- Funding a descendant's guarded wallet ------------------------------- + + /** The room opens its own plain wallet, signed by a quorum, so it has coins to fund with. */ + private suspend fun openOwnWallet(proposer: Device, other: Device): GroupWalletDerivation.Account { + val own = GroupWalletDerivation.account(thresholdPublicKey, chain) + val template = GroupWalletStatementEvent.template(own) + val session = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + listOf(proposer, other).forEach { assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "the room's own wallet is open") } + return own + } + + /** The room's own wallet holding one confirmed coin at its first receive address. */ + private fun ownState(own: GroupWalletDerivation.Account): GroupWalletState { + val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) + val paid = Transaction( + 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x71 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(80_000), coin.pubkeyScript)), 0, + ) + val meta = WalletState.AddressMeta.Derived(0) + val receive = WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(paid.txid, 0, 100, paid, meta))))) + val change = WalletState((0 until 3).associate { index -> + GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) + }) + return GroupWalletState(own, receive, change, tipHeight = 110) + } + + private fun fundingTo(guarded: GuardianManager.GuardedWallet, index: Long) = + GroupSpendBuilder.Destination.Funding(guarded.account, GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, index)) + + @Test + fun `a funding is read as one by every device holding the wallet, and its address is held`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + tell(other, statement) + val own = openOwnWallet(proposer, other) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val built = assertIs( + GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet()) + ) + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) + pump(proposer, other) + + val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) + val funding = seen.fundings.single() + assertEquals(guardedChildRoomId, funding.wallet.descendantChatRoomId) + assertEquals(2L, funding.derived.index) + assertEquals( + com.machankura.bennu.compose.text.ProposedEvent.Summary( + "Fund Translation team's guarded wallet", + "Send 30,000 sats to Translation team's guarded wallet, address 2", + ), + com.machankura.bennu.compose.text.ProposedSpend.summarize(seen, chain), + ) + assertEquals(setOf(2L), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account)) + + // A bump keeps the claim, or it would read as a payment to a bare address. + val bumped = assertIs(GroupSpendBuilder.bump(seen, 5)) + assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(bumped.psbt, guarded.account)) + assertEquals(2L, bumped.funded?.derived?.index) + + // Abandoned, it lets the address go. + other.db.frostSigningSessionDao().upsert(other.session(session.id)!!.copy(stage = FrostSigningStage.FAILED)) + assertEquals(emptySet(), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account)) + } + + @Test + fun `a funding claiming an address it does not pay is refused by every device that can tell`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + // Only the other device holds the wallet, so only it can check the claim. + tell(other, guardedStatement()) + val own = openOwnWallet(proposer, other) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(other.db, roomId, guardedChildRoomId, chain, 0)) + val honest = assertIs( + GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet()) + ) + // Pays address 2, says address 3. + val claimed = GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, 3) + val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) + val lying = GroupSpend.psbtOf( + honest.psbt.global.tx, + listOf(TxOut(Satoshi(80_000), coin.pubkeyScript) to coin), + mapOf(1 to GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0)), + own, + funding = mapOf(0 to (guarded.account to claimed)), + ) + assertIs( + GroupSpend.fundingsOf(assertIs(GroupSpend.check(lying, own)).checked, listOf(guarded)) + ) + + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, lying, chain) + pump(proposer, other) + assertNull(other.session(session.id), "the device that holds the wallet never puts it to the member") + } + + @Test + fun `a device never told about the wallet reads a funding as the bare address it pays`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + tell(proposer, guardedStatement()) + val own = openOwnWallet(proposer, other) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val destination = fundingTo(guarded, 2) + val built = assertIs( + GroupSpendBuilder.send(ownState(own), destination, Satoshi(30_000), 2, emptySet()) + ) + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) + pump(proposer, other) + + val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id), "accepted: the address is the truth") + assertEquals(emptyList(), seen.fundings) + assertEquals( + "Send 30,000 sats to ${destination.derived.address(chain)}", + com.machankura.bennu.compose.text.ProposedSpend.summarize(seen, chain).detail, + ) + assertEquals(1, assertNotNull(FrostSigningManager.checkedSpend(proposer.db, session.id)).fundings.size, "and the proposer's own device still names it") + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt new file mode 100644 index 00000000..78b100e1 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt @@ -0,0 +1,269 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.birthCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.GuardianManager.GuardedSubject +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * The names a member's wallet is shown under in a group above it: the group + * that directly guards it, and the branch of the holder's tree it sits under -- + * each from a birth certificate this device can check, whoever handed it over, + * and never from one it cannot. `docs/member-wallet-guarding-group.md`, Phase 2. + * + * The tree is R ⊃ P ⊃ M, and M guards Alice's Savings. + */ +class GuardingGroupNameJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val r = keyMaterial("7007") + private val p = keyMaterial("9a9e") + private val m = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val rRoom = roomOf(r) + private val pRoom = roomOf(p) + private val mRoom = roomOf(m) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + private val walletPrivateKey = privateKey(0xa11ce) + private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + + private val pGrant = GuardianDerivation.grant(thresholdKeyOf(r), rRoom, emptyList(), pRoom) + private val mGrant = GuardianDerivation.grant(thresholdKeyOf(p), pRoom, pGrant, mRoom) + private val savingsGrant = GuardianDerivation.grant(thresholdKeyOf(m), mRoom, mGrant, walletId) + + /** R's certificate for P, and P's for M, as their founding named them. */ + private val pCertificate = birthCertificate(r, p, pGrant, name = "#P") + private val mCertificate = birthCertificate(p, m, mGrant, name = "#M") + + /** M's certificate for Alice's Savings, guarded by `[M, P, R]`. */ + private val savings: Event = run { + val request = MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = mRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, savingsGrant), + label = "Savings", + createdAt = 1_700_000_000, + ) + val template = MemberWalletCertificateEvent.template(request) + signedAsRoom(m, template.kind, template.tags, template.content, template.createdAt) + } + + /** This device in [material]'s room, holding its key state. */ + private suspend fun inRoom(material: KeyMaterial, certificate: Event? = null, subject: String = "#" + roomOf(material).take(4)) { + signingRoom(db, material, members = listOf(memberPublicKey), subject = subject) + fileKeyState(db, material, certificate) + } + + /** [certificate] as one of [signer]'s own signed events here. */ + private suspend fun fileSigned(certificate: Event, signer: String) = + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = signer, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + /** A notice of [statement] told to [room], carrying [certificate] as today's build does, or not as an older one did. */ + private suspend fun noticeIn(room: String, statement: Event, certificate: Event? = null) = + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = statement.id.take(60) + if (certificate == null) "0000" else "0001", + publicKey = memberPublicKey, + kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1_700_000_100), + tags = listOfNotNull(arrayOf("h", room), certificate?.let(GuardedWalletNoticeEvent::certificateTag)).toTypedArray(), + content = statement.toJson(), + chatRoomId = room, + ) + ) + + private suspend fun heldByR(): GuardedSubject.Member { + val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() + assertEquals(mRoom, listed.directGuardianChatRoomId) + return assertIs(listed.subject) + } + + @Test + fun `a device in R and P names M from the certificate P signed`(): Unit = runBlocking { + inRoom(r) + inRoom(p, pCertificate) + fileSigned(pCertificate, signer = rRoom) + fileSigned(mCertificate, signer = pRoom) + noticeIn(rRoom, savings) + + val subject = heldByR() + assertEquals("#M", subject.guardianName) + assertEquals("#P", subject.branchName) + } + + @Test + fun `a device in R only knows its own branch, and not the group below it`(): Unit = runBlocking { + inRoom(r) + fileSigned(pCertificate, signer = rRoom) + noticeIn(rRoom, savings) + + val subject = heldByR() + assertNull(subject.guardianName) + assertEquals("#P", subject.branchName) + } + + @Test + fun `a certificate for M that P did not sign names nothing`(): Unit = runBlocking { + inRoom(r) + inRoom(p, pCertificate) + fileSigned(pCertificate, signer = rRoom) + // Filed under P, signed by a stranger: it does not certify M as P's child. + fileSigned(birthCertificate(stranger, m, mGrant, name = "#Impostor"), signer = pRoom) + noticeIn(rRoom, savings) + + assertNull(heldByR().guardianName) + } + + @Test + fun `a renamed M is still shown by its founding name`(): Unit = runBlocking { + inRoom(r) + inRoom(m, mCertificate, subject = "#Renamed") + fileSigned(pCertificate, signer = rRoom) + noticeIn(rRoom, savings) + + assertEquals("#M", heldByR().guardianName) + } + + @Test + fun `with no certificate to check, the room's name here is used`(): Unit = runBlocking { + inRoom(r) + inRoom(m, subject = "#Here") + noticeIn(rRoom, savings) + + assertEquals("#Here", heldByR().guardianName) + } + + // ---- Phase 3: the notice carries the guardian's certificate ---------- + + @Test + fun `a notice carrying M's certificate lets a device in R only name M`(): Unit = runBlocking { + inRoom(r) + noticeIn(rRoom, savings, certificate = mCertificate) + + val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() + assertEquals("#M", assertIs(listed.subject).guardianName) + assertEquals(mCertificate.id, listed.guardianCertificate?.id) + } + + @Test + fun `a carried certificate that does not certify M is ignored, and the wallet is still listed`(): Unit = runBlocking { + inRoom(r) + // P's own certificate, naming P rather than M; and one for M a stranger signed. + noticeIn(rRoom, savings, certificate = pCertificate) + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = "ab".repeat(32), + publicKey = memberPublicKey, + kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1_700_000_200), + tags = arrayOf(arrayOf("h", rRoom), GuardedWalletNoticeEvent.certificateTag(birthCertificate(stranger, m, mGrant, name = "#Impostor"))), + content = savings.toJson(), + chatRoomId = rRoom, + ) + ) + + val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() + assertNull(assertIs(listed.subject).guardianName) + assertNull(listed.guardianCertificate) + } + + @Test + fun `a room told before notices carried the certificate is offered again, once`(): Unit = runBlocking { + inRoom(m, mCertificate) + inRoom(p) + fileSigned(savings, signer = mRoom) + noticeIn(pRoom, savings) + + val again = GuardianManager.shareableFrom(db, mRoom, chain).single() + assertEquals(listOf(pRoom), again.rooms.map { it.chatRoom.id }) + assertEquals(mCertificate.id, again.certificate?.id) + + GuardianManager.share(db, again.statement, again.rooms, memberPublicKey, certificate = again.certificate) + assertEquals(emptyList(), GuardianManager.shareableFrom(db, mRoom, chain)) + } + + @Test + fun `with no certificate to add, a room already told is not offered again`(): Unit = runBlocking { + inRoom(m) + inRoom(p) + fileSigned(savings, signer = mRoom) + noticeIn(pRoom, savings) + + assertEquals(emptyList(), GuardianManager.shareableFrom(db, mRoom, chain)) + } + + @Test + fun `forwarding from M to P and on to R carries the certificate at both hops`(): Unit = runBlocking { + inRoom(m, mCertificate) + inRoom(p) + fileSigned(savings, signer = mRoom) + + val first = GuardianManager.shareableFrom(db, mRoom, chain).single() + GuardianManager.share(db, first.statement, first.rooms, memberPublicKey, certificate = first.certificate) + + // R joins this device later, so the second hop is P's to make. + inRoom(r) + val second = GuardianManager.shareableFrom(db, pRoom, chain).single() + assertEquals(listOf(rRoom), second.rooms.map { it.chatRoom.id }) + GuardianManager.share(db, second.statement, second.rooms, memberPublicKey, certificate = second.certificate) + + listOf(pRoom, rRoom).forEach { room -> + val notice = db.marmotInnerEventDao().getByChatRoomAndKinds(room, listOf(GuardedWalletNoticeEvent.KIND)).single() + assertEquals(mCertificate.id, GuardedWalletNoticeEvent.certificateIn(notice.tags)?.id, "the notice in $room") + } + } + + @Test + fun `forwarding on its own carries the certificate too, and tells a room told without it once more`(): Unit = runBlocking { + inRoom(m, mCertificate) + inRoom(p) + inRoom(r) + fileSigned(savings, signer = mRoom) + // R was told before notices carried the certificate. + noticeIn(rRoom, savings) + + val told = GuardianManager.forward(db, savings, mRoom, whenElected = false) + assertEquals(setOf(pRoom, rRoom), told.map { it.chatRoom.id }.toSet()) + listOf(pRoom, rRoom).forEach { room -> + val carried = db.marmotInnerEventDao().getByChatRoomAndKinds(room, listOf(GuardedWalletNoticeEvent.KIND)) + .mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } + assertEquals(listOf(mCertificate.id), carried.map { it.id }, "the notice in $room") + } + assertEquals(emptyList(), GuardianManager.forward(db, savings, mRoom, whenElected = false), "told once with it") + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt new file mode 100644 index 00000000..dc167c0e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt @@ -0,0 +1,242 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signWith +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.GuardianManager.GuardedSubject +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * The guardians' side of a member's wallet: the group that signed its + * certificate lists it, a group above learns of it from a notice and lists it + * too, each finds its own leaf in the wallet's addresses, and a spend through + * that leaf is one the script interpreter takes once the coin is 12 blocks old. + */ +class MemberWalletGuardianJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + private val parentRoom = roomOf(parent) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + private val walletPrivateKey = privateKey(0xa11ce) + private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + + private val grant = GuardianDerivation.grant( + thresholdKeyOf(group), groupRoom, + GuardianDerivation.grant(thresholdKeyOf(parent), parentRoom, emptyList(), groupRoom), + walletId, + ) + + private fun certificate(guardians: List = grant): Event { + val request = MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = groupRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians), + label = "Savings", + createdAt = 1_700_000_000, + ) + val template = MemberWalletCertificateEvent.template(request) + return signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + } + + /** This device in [material]'s room, holding its verified key state. */ + private suspend fun inRoom(material: fr.acinq.bitcoin.crypto.frost.KeyMaterial, certificate: Event? = null) { + signingRoom(db, material, members = listOf(memberPublicKey), subject = "#" + roomOf(material).take(4)) + fileKeyState(db, material, certificate) + GroupFixtures.openToMembers(db, material) + } + + private suspend fun fileSigned(certificate: Event) = + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + private suspend fun noticeIn(room: String, statement: Event) = + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = statement.id.take(60) + "0000", + publicKey = memberPublicKey, + kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1_700_000_100), + tags = arrayOf(arrayOf("h", room)), + content = statement.toJson(), + chatRoomId = room, + ) + ) + + @Test + fun `the group that signed it lists its member's wallet as theirs`(): Unit = runBlocking { + GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") + inRoom(group, guardedCertificate(parent, group)) + fileSigned(certificate()) + + val listed = GuardianManager.guardedWalletsOf(db, groupRoom).single() + val subject = assertIs(listed.subject) + assertEquals(walletId, subject.id) + assertEquals(memberPublicKey, subject.ownerPublicKey) + assertEquals("alice", subject.ownerName) + assertEquals("Savings", subject.label) + assertEquals(walletId, listed.descendantChatRoomId) + assertEquals(listOf(walletId), listed.lineage) + assertEquals(0, listed.position) + assertNull(listed.name, "a member's wallet has no founding name") + assertEquals("@alice", listed.spender().name) + } + + @Test + fun `a group above learns of it from a notice, and walks down to its own leaf`(): Unit = runBlocking { + inRoom(parent) + noticeIn(parentRoom, certificate()) + + val listed = GuardianManager.guardedWalletsOf(db, parentRoom).single() + assertEquals(listOf(groupRoom, walletId), listed.lineage) + assertEquals(1, listed.position) + // The notice as it was filed: a second of the same certificate would be silent. + val filed = db.marmotInnerEventDao().getByChatRoomAndKinds(parentRoom, listOf(GuardedWalletNoticeEvent.KIND)).single() + assertTrue(GuardianManager.describeNotice(db, parentRoom, Event(filed.id, filed.publicKey, filed.createdAt.epochSeconds, filed.kind, filed.tags, filed.content, ""))!!.startsWith("Shared @")) + } + + @Test + fun `a notice whose entry for this group is not the key it reaches is ignored`(): Unit = runBlocking { + inRoom(parent) + // The group signed a certificate naming the stranger's key under the parent's room. + val forged = listOf(grant[0], GuardianDerivation.grant(thresholdKeyOf(stranger), parentRoom, emptyList(), groupRoom).single().grantedTo(walletId)) + noticeIn(parentRoom, certificate(forged)) + assertTrue(GuardianManager.guardedWalletsOf(db, parentRoom).isEmpty()) + } + + @Test + fun `a member of both groups can carry it upward`(): Unit = runBlocking { + inRoom(group, guardedCertificate(parent, group)) + inRoom(parent) + fileSigned(certificate()) + + val shareable = GuardianManager.shareableFrom(db, groupRoom, chain).single() + assertEquals(memberPublicKey, shareable.ownerPublicKey) + assertEquals(listOf(parentRoom), shareable.rooms.map { it.chatRoom.id }) + + GuardianManager.share(db, shareable.statement, shareable.rooms, memberPublicKey, certificate = shareable.certificate) + assertEquals(walletId, GuardianManager.guardedWalletsOf(db, parentRoom).single().descendantChatRoomId) + assertTrue(GuardianManager.shareableFrom(db, groupRoom, chain).isEmpty(), "told once") + } + + @Test + fun `a guardian's spend through its leaf of a member's wallet`(): Unit = runBlocking { + inRoom(parent) + noticeIn(parentRoom, certificate()) + val wallet = GuardianManager.guardedWalletsOf(db, parentRoom).single() + + // One coin at receive address 2, confirmed long enough ago. + val derived = GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.RECEIVE, 2) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(60_000), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(2) + val receive = WalletState(mapOf(derived.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))) + val change = WalletState(mapOf(GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))) + val state = GroupWalletState(wallet.account, receive, change, tipHeight = 200) + + val spender = wallet.spender(thresholdKeyOf(parent)) + val built = assertIs(GroupSpendBuilder.sendAll(state, "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 3L, emptySet(), spender)) + val checked = assertIs(GroupSpend.check(built.psbt, wallet.account, spender)).checked + + val signatures = checked.inputs.map { signWith(parent, it.cache, it.sighash) } + val signed = checked.witnessed(signatures) + signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(3, signed.txIn.single().witness.stack.size, "signature, leaf, control block") + + // The member's own device names who took it. + val taken = GuardianManager.takenIn(signed, wallet.account, mapOf(funding.let { OutPoint(it, 0) } to (funding.txOut[0] to derived))) + assertEquals(parentRoom, taken.single().guardian.chatRoomId) + + // Eleven blocks is too soon: the same spend at sequence 11, signed properly + // for that sequence, so the only thing wrong with it is the lock. + val input = checked.inputs.single() + val unsigned = checked.tx.let { tx -> Transaction(tx.version, tx.txIn.map { it.copy(sequence = 11, witness = fr.acinq.bitcoin.ScriptWitness.empty) }, tx.txOut, tx.lockTime) } + val sighash = unsigned.hashForSigningTaprootScriptPath(0, checked.spentOutputs, fr.acinq.bitcoin.SigHash.SIGHASH_DEFAULT, input.leaf!!.hash()) + val early = unsigned.updateWitness(0, input.witness(signWith(parent, input.cache, sighash))) + assertFails { early.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) } + } + + @Test + fun `a group funds its member's wallet, and its signers read where the money goes`(): Unit = runBlocking { + GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") + inRoom(group, guardedCertificate(parent, group)) + fileSigned(certificate()) + val wallet = GuardianManager.guardedWalletsOf(db, groupRoom).single() + + // The group's own wallet, with one coin to fund from. + val own = GroupWalletDerivation.account(thresholdKeyOf(group), chain) + val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 5 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(90_000), coin.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(0) + val ownState = GroupWalletState( + own, + WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))), + WalletState(mapOf(GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))), + tipHeight = 110, + ) + + // The member's address two past their current one. + val target = GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.RECEIVE, 2) + val built = assertIs( + GroupSpendBuilder.send(ownState, GroupSpendBuilder.Destination.Funding(wallet.account, target), Satoshi(20_000), 3L, emptySet()) + ) + val checked = assertIs(GroupSpend.check(built.psbt, own)).checked + val reading = assertIs(GroupSpend.fundingsOf(checked, listOf(wallet))) + + val funded = reading.fundings.single() + assertEquals(walletId, funded.wallet.descendantChatRoomId) + assertEquals(target.pubkeyScript, checked.tx.txOut[funded.outputIndex].publicKeyScript) + val summary = com.machankura.bennu.compose.text.ProposedSpend.summarize(checked.copy(fundings = reading.fundings), chain) + assertEquals("Fund @alice's guarded wallet “Savings”", summary.label) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPagesJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPagesJvmTest.kt new file mode 100644 index 00000000..77b69f64 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPagesJvmTest.kt @@ -0,0 +1,155 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * What the group's page and the person's page say about member wallets: the + * group lists its members' wallets apart from its subgroups, with the requests + * still waiting for a signer, and the person's page lists every group here that + * guards them. + */ +class MemberWalletPagesJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val groupRoom = roomOf(group) + private val parentRoom = roomOf(parent) + + private val alice = privateKey(0xa11ce5) + private val alicePublicKey = alice.xOnlyPublicKey().value.toHex() + private val bob = privateKey(0xb0b5) + private val bobPublicKey = bob.xOnlyPublicKey().value.toHex() + + private suspend fun certify(requestJson: String): Event { + val template = MemberWalletCertificateEvent.template(Event.fromJson(requestJson)) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + return signed + } + + @Test + fun `the group lists its members' wallets, certified and waiting, and never as subgroups`(): Unit = runBlocking { + GroupFixtures.seedProfile(db, alicePublicKey, name = "alice") + signingRoom(db, group, members = listOf(alicePublicKey, bobPublicKey), holdsShare = false) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + + val certified = MemberWalletManager.request(db, groupRoom, alice, chain, label = "Savings") + certify(certified.requestJson) + val waiting = MemberWalletManager.request(db, groupRoom, bob, chain, label = null) + + val listed = MemberWalletManager.memberWalletsOf(db, groupRoom) + assertEquals(listOf(certified.walletId to true, waiting.walletId to false), listed.map { it.walletId to it.isCertified }) + assertEquals("alice", listed.first().ownerName) + assertEquals("Savings", listed.first().label) + assertEquals(bobPublicKey, listed.last().ownerPublicKey) + assertTrue(SubgroupManager.subgroupsOf(db, groupRoom).isEmpty()) + } + + @Test + fun `the person's page lists every group here that guards them`(): Unit = runBlocking { + signingRoom(db, group, members = listOf(alicePublicKey)) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + signingRoom(db, parent, members = listOf(alicePublicKey), holdsShare = false, subject = "#Root") + fileKeyState(db, parent) + GroupFixtures.openToMembers(db, parent) + + val wallet = MemberWalletManager.request(db, groupRoom, alice, chain, label = null) + val certificate = certify(wallet.requestJson) + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = "9".repeat(64), publicKey = alicePublicKey, kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1_700_000_100), tags = arrayOf(arrayOf("h", parentRoom)), + content = certificate.toJson(), chatRoomId = parentRoom, + ) + ) + + val here = MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, alicePublicKey) + assertEquals(setOf(groupRoom, parentRoom), here.map { it.wallet.ancestorChatRoomId }.toSet()) + assertEquals(true, here.single { it.wallet.ancestorChatRoomId == groupRoom }.canSpend, "a share of the group's key") + assertEquals(false, here.single { it.wallet.ancestorChatRoomId == parentRoom }.canSpend, "none of the root's") + assertEquals("#Root", here.single { it.wallet.ancestorChatRoomId == parentRoom }.holderName) + assertTrue(MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, bobPublicKey).isEmpty()) + } + + // ---- One entry per wallet: docs/member-wallet-guarding-group.md, Phase 6 + + @Test + fun `a wallet held by a group and its parent is one entry, guarded by the group, with both holders`(): Unit = runBlocking { + signingRoom(db, group, members = listOf(alicePublicKey)) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + signingRoom(db, parent, members = listOf(alicePublicKey), holdsShare = false, subject = "#Root") + fileKeyState(db, parent) + GroupFixtures.openToMembers(db, parent) + + val wallet = MemberWalletManager.request(db, groupRoom, alice, chain, label = "Savings") + val certificate = certify(wallet.requestJson) + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = "9".repeat(64), publicKey = alicePublicKey, kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1_700_000_100), tags = arrayOf(arrayOf("h", parentRoom)), + content = certificate.toJson(), chatRoomId = parentRoom, + ) + ) + + val entry = MemberWalletManager.byWallet(MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, alicePublicKey)).single() + assertEquals(wallet.walletId, entry.walletId) + assertEquals("Savings", entry.label) + assertEquals("#Child", entry.guardianName, "the founding name the parent certified") + assertEquals(listOf(groupRoom, parentRoom), entry.holders.map { it.wallet.ancestorChatRoomId }) + assertEquals(listOf(true, false), entry.holders.map { it.canSpend }, "a share of the group's key, none of the root's") + } + + @Test + fun `Savings held by P and R, and Rent held by R, are two entries`() { + val savingsAtP = MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.p, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M"), holderName = "#P", canSpend = true) + val savingsAtR = MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = null, branchName = "#P"), holderName = "#R", canSpend = true) + val rentAtR = MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.r, LineageExample.rent, LineageExample.rentGuardians), holderName = "#R", canSpend = false) + + val entries = MemberWalletManager.byWallet(listOf(savingsAtR, rentAtR, savingsAtP)) + assertEquals(listOf(LineageExample.savings, LineageExample.rent), entries.map { it.walletId }) + + val savings = entries.first() + assertEquals("#M", savings.guardianName, "named by whichever holder can") + assertEquals(listOf("#P", "#R"), savings.holders.map { it.holderName }, "nearest first") + + val rent = entries.last() + assertNull(rent.guardianName) + assertEquals("#R", rent.below, "N is unnamed here, but it is below R") + assertEquals(listOf(false), rent.holders.map { it.canSpend }) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt new file mode 100644 index 00000000..6afc7509 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt @@ -0,0 +1,251 @@ +package com.machankura.bennu.compose.managers + +import kotlin.test.assertFalse +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import kotlin.test.assertTrue +import kotlin.test.assertNotNull +import kotlin.test.assertFailsWith +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.secp256k1.Hex +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.managers.GroupFixtures.filePolicy +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.memberWalletPolicy +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.text.ProposedEvent +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull + +/** + * A group's policy on its members' wallets, as the group's own devices read it + * -- `docs/member-wallet-delay.md`. + */ +class MemberWalletPolicyJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("5e7a") + private val groupRoom = roomOf(group) + + // ---- Phase 2: the group files it --------------------------------------- + + @Test + fun `a group that never signed a policy has none`(): Unit = runBlocking { + assertNull(MemberWalletManager.policyFor(db, groupRoom)) + } + + @Test + fun `the newest stored policy decides, open or closed, either way round`(): Unit = runBlocking { + GroupFixtures.seedRoom(db, groupRoom) + filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = 1_700_000_000)) + filePolicy(db, group, memberWalletPolicy(group, null, createdAt = 1_700_000_100)) + assertIs(MemberWalletManager.policyFor(db, groupRoom)) + + filePolicy(db, group, memberWalletPolicy(group, 1_008, createdAt = 1_700_000_200)) + assertEquals(1_008L, assertIs(MemberWalletManager.policyFor(db, groupRoom)).delay) + } + + @Test + fun `a policy another room signed is not this group's`(): Unit = runBlocking { + GroupFixtures.seedRoom(db, groupRoom) + // Filed under this room, signed by another: nothing a device can act on. + val forged = memberWalletPolicy(stranger, 6) + db.groupSignedEventDao().upsert( + com.machankura.bennu.compose.database.model.GroupSignedEvent.fromEvent(forged, chatRoomId = groupRoom, derivationPath = null, frostSigningSessionId = null) + ) + assertNull(MemberWalletManager.policyFor(db, groupRoom)) + } + + @Test + fun `a signer reads what a policy decides, and what closing leaves alone`() { + val opened = memberWalletPolicy(group, 144) + assertEquals("Members' guarded wallets", ProposedEvent.summarize(opened).label) + assertEquals("this group after 144 blocks, about 1 day · for wallets asked for from now on", ProposedEvent.summarize(opened).detail) + + val closed = memberWalletPolicy(group, null) + assertEquals("no new ones · wallets already guarded stay guarded", ProposedEvent.summarize(closed).detail) + } + + // ---- Phase 4: the member builds under it ------------------------------- + + private val parent = keyMaterial("9a9e") + private val chain = Chain.Regtest + private val member = PrivateKey(ByteVector32(Hex.decode("3e3be7".padStart(64, '0')))) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + + private suspend fun asMember() { + GroupFixtures.signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) + GroupFixtures.fileKeyState(db, group, GroupFixtures.guardedCertificate(parent, group)) + } + + @Test + fun `a member asks only a group that has opened`(): Unit = runBlocking { + asMember() + assertEquals(MemberWalletManager.Refusal.NOT_OFFERED, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) + assertFailsWith { MemberWalletManager.request(db, groupRoom, member, chain, label = null) } + assertNull(MemberWalletManager.delaysOf(db, groupRoom)) + + filePolicy(db, group, memberWalletPolicy(group, null)) + assertEquals(MemberWalletManager.Refusal.CLOSED, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) + assertFailsWith { MemberWalletManager.request(db, groupRoom, member, chain, label = null) } + assertTrue(db.memberWalletDao().getByOwner(memberPublicKey).isEmpty(), "a refused request makes no key") + } + + @Test + fun `a request is built at the group's delay and carries the policy it was built under`(): Unit = runBlocking { + asMember() + val policy = memberWalletPolicy(group, 4_320) + filePolicy(db, group, policy) + + assertNull(MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) + assertEquals(listOf(4_320L, GuardianDerivation.DEFAULT_DELAY), MemberWalletManager.delaysOf(db, groupRoom), "the parent's keeps its own") + + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + val verified = assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(wallet.requestJson))) + assertEquals(4_320L, verified.reading.guardians.first().delay) + assertEquals(policy.id, verified.policy?.event?.id) + } + + @Test + fun `a request whose leaf disagrees with the policy it carries does not check out`(): Unit = runBlocking { + asMember() + val walletKey = MemberWalletDerivation.generate() + val walletId = MemberWalletDerivation.walletId(walletKey.publicKey()) + val atDefault = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, emptyList(), walletId) + val account = MemberWalletDerivation.account(walletKey.publicKey(), chain, atDefault) + fun build(policy: Event?) = MemberWalletRequestEvent.build(member, groupRoom, walletKey, account, label = null, policy = policy) + + assertNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(group, 4_320))), "built at 12 under a policy of 4,320") + assertNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(group, null))), "built under a closed policy") + assertNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(stranger, 12))), "under another group's policy") + assertNotNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(group, 12)))) + // A request from before policies still reads: old certificates embed one. + assertNotNull(MemberWalletRequestEvent.verified(build(null))) + } + + // ---- Phase 5: every signer checks it ----------------------------------- + + /** This device as a signer of the group, which the member is in. */ + private suspend fun asSigner() { + GroupFixtures.signingRoom(db, group, members = listOf(memberPublicKey)) + GroupFixtures.fileKeyState(db, group, GroupFixtures.guardedCertificate(parent, group)) + } + + /** What the signer is asked to sign: the certificate for a request built at [delay] under [carried]. */ + private fun proposedUnder(carried: Event?, delay: Long): Event { + val walletKey = MemberWalletDerivation.generate() + val walletId = MemberWalletDerivation.walletId(walletKey.publicKey()) + val parentsGrant = GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), groupRoom) + val guardians = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, parentsGrant, walletId, delay) + val account = MemberWalletDerivation.account(walletKey.publicKey(), chain, guardians) + val request = MemberWalletRequestEvent.build(member, groupRoom, walletKey, account, label = null, createdAt = 1_700_000_500, policy = carried) + val template = MemberWalletCertificateEvent.template(request) + return Event(MemberWalletManager.certificateIdFor(groupRoom, request), groupRoom, template.createdAt, template.kind, template.tags, template.content, "") + } + + private suspend fun refusal(certificate: Event) = + MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), certificate) + + @Test + fun `a signer judges a request by the policy it carries, unless it holds a newer one`(): Unit = runBlocking { + asSigner() + val older = 1_700_000_000L + val carried = memberWalletPolicy(group, 4_320, createdAt = older + 100) + + // Held none: a signer that missed the opening is told what it missed. + assertNull(refusal(proposedUnder(carried, 4_320))) + // The leaf has to have the carried delay, as every reader checks. + assertEquals("is not a certificate this group could have been asked for", refusal(proposedUnder(carried, 12))) + + // An older closing the group has since reversed is no reason to refuse. + filePolicy(db, group, memberWalletPolicy(group, null, createdAt = older)) + assertNull(refusal(proposedUnder(carried, 4_320))) + + // A newer delay held: the request is stale. + filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = older + 200)) + assertEquals("was asked under a delay the group has since changed", refusal(proposedUnder(carried, 4_320))) + + // A newer closing held: the group has stopped. + filePolicy(db, group, memberWalletPolicy(group, null, createdAt = older + 300)) + assertEquals("was asked of a group that has since stopped guarding members' wallets", refusal(proposedUnder(carried, 4_320))) + } + + @Test + fun `a request built under no policy, or under a closed one, is refused`(): Unit = runBlocking { + asSigner() + filePolicy(db, group, memberWalletPolicy(group, 12)) + + assertEquals("does not say the group guards members' wallets", refusal(proposedUnder(null, 12))) + assertNotNull(refusal(proposedUnder(memberWalletPolicy(group, null), 12)), "a closed policy opens nothing") + assertNotNull(refusal(proposedUnder(memberWalletPolicy(stranger, 12), 12)), "nor does another group's") + } + + @Test + fun `a stale request says why, and asking again makes a new one at the new delay`(): Unit = runBlocking { + asMember() + filePolicy(db, group, memberWalletPolicy(group, 12, createdAt = 1_700_000_000)) + val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") + assertNull(MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) + + filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = 1_700_000_100)) + assertEquals(MemberWalletManager.Why.DELAY_CHANGED, MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) + + val replacement = MemberWalletManager.askAgain(db, db.memberWalletDao().getById(asked.walletId)!!, member) + assertTrue(replacement.walletId != asked.walletId, "a new key") + assertNull(db.memberWalletDao().getById(asked.walletId), "the old key, never offered, is gone") + assertEquals("Savings", replacement.label) + val rebuilt = assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(replacement.requestJson))) + assertEquals(144L, rebuilt.reading.guardians.first().delay) + assertNull(MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) + } + + @Test + fun `a request to a group that has since closed can only be discarded`(): Unit = runBlocking { + asMember() + filePolicy(db, group, memberWalletPolicy(group, 12, createdAt = 1_700_000_000)) + val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + filePolicy(db, group, memberWalletPolicy(group, null, createdAt = 1_700_000_100)) + + assertEquals(MemberWalletManager.Why.CLOSED, MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) + assertFailsWith { MemberWalletManager.askAgain(db, db.memberWalletDao().getById(asked.walletId)!!, member) } + assertNotNull(db.memberWalletDao().getById(asked.walletId), "a refused ask leaves the old key for the member to discard") + } + + // ---- the picker leaves out direct chats ------------------------------- + + @Test + fun `a direct chat is not a group that can guard a wallet, a two-member group with a known key is`(): Unit = runBlocking { + val peer = "b".repeat(64) + val direct = keyMaterial("d1ec7") + val shrunk = keyMaterial("5412c") + val waiting = keyMaterial("3a17") + + // A direct chat: two people, and no key anywhere. + GroupFixtures.signingRoom(db, direct, members = listOf(peer), holdsShare = false) + // A group down to two members after its ceremony, whose key this device holds. + GroupFixtures.signingRoom(db, shrunk, members = listOf(peer), holdsShare = false) + GroupFixtures.fileKeyState(db, shrunk) + // A group of three whose key this device has not been told yet: it may be open. + GroupFixtures.signingRoom(db, waiting, members = listOf(peer, "c".repeat(64)), holdsShare = false) + + val listed = MemberWalletManager.groupsOf(db, GroupFixtures.owner).map { it.chatRoom.id }.toSet() + assertEquals(setOf(roomOf(shrunk), roomOf(waiting)), listed) + // And a direct chat's own page offers nothing about members' wallets. + assertFalse(MemberWalletManager.couldGuard(db, db.chatRoomDao().findChatRoomById(roomOf(direct))!!)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletRequestJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletRequestJvmTest.kt new file mode 100644 index 00000000..d4cb80c7 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletRequestJvmTest.kt @@ -0,0 +1,172 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.MemberWalletManager.Refusal +import com.machankura.bennu.compose.managers.MemberWalletManager.asEvent +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * A member asking a group to guard a wallet: the key stored before anything + * leaves the device, the request one every signer will accept, and each reason + * the screen gives for not asking. + */ +class MemberWalletRequestJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + + /** The group as a member who holds no share sees it: a Marmot room, and nothing to sign with. */ + private suspend fun asMember(knowsKey: Boolean = true) { + signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) + if (knowsKey) fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + } + + private suspend fun requestsSent(): List = + db.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(MemberWalletRequestEvent.KIND)) + .mapNotNull { MemberWalletRequestEvent.carried(it.asEvent()) } + + @Test + fun `the key is stored and the request one every signer will accept`(): Unit = runBlocking { + asMember() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") + + assertEquals(wallet, db.memberWalletDao().getById(wallet.walletId)) + assertEquals(memberPublicKey, wallet.ownerPublicKey) + assertEquals(groupRoom, wallet.guardingChatRoomId) + assertEquals("Savings", wallet.label) + assertEquals(wallet.walletId, MemberWalletDerivation.walletId(PrivateKey.fromHex(wallet.walletPrivateKey).publicKey())) + + val sent = requestsSent().single() + val verified = assertNotNull(MemberWalletRequestEvent.verified(sent)) + assertEquals(wallet.walletId, verified.reading.walletId) + assertEquals(SubgroupManager.grantFor(db, groupRoom, thresholdKeyOf(group), wallet.walletId), verified.reading.guardians) + assertEquals(2, verified.reading.guardians.size, "the group, and its parent one step further") + + // Exactly what a signer's device will be shown, and it is signable. + val template = MemberWalletCertificateEvent.template(sent) + val proposed = Event(MemberWalletManager.certificateIdFor(groupRoom, sent), groupRoom, template.createdAt, template.kind, template.tags, template.content, "") + assertNull(MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed)) + + assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(groupRoom).isEmpty(), "a member without a share waits for a signer") + assertEquals(listOf(wallet.walletId), MemberWalletManager.awaitingSponsor(db, groupRoom).map { it.reading.walletId }) + } + + @Test + fun `two requests are two keys`(): Unit = runBlocking { + asMember() + val first = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + val second = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + assertTrue(first.walletId != second.walletId) + assertTrue(first.walletPrivateKey != second.walletPrivateKey) + } + + @Test + fun `a member who holds a share puts it to the group at once`(): Unit = runBlocking { + // A share-holding member: one of the ceremony's participants on this device. + signingRoom(db, group, members = listOf(memberPublicKey)) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + + val session = assertNotNull(MemberWalletManager.openSessionFor(db, groupRoom, Event.fromJson(wallet.requestJson))) + assertNotNull(session.signApprovedAt, "proposing is approving") + assertTrue(MemberWalletManager.awaitingSponsor(db, groupRoom).isEmpty()) + } + + @Test + fun `each refusal holds`(): Unit = runBlocking { + assertEquals(Refusal.CANNOT_SIGN, MemberWalletManager.refusal(db, groupRoom, canSign = false, chain)) + assertEquals(Refusal.NOT_A_GROUP, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) + + GroupFixtures.seedRoom(db, groupRoom) + assertEquals(Refusal.NOT_A_GROUP, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain), "a room with no MLS state") + + db.chatRoomDao().delete(db.chatRoomDao().findChatRoomById(groupRoom)!!.chatRoom) + asMember(knowsKey = false) + assertEquals(Refusal.KEY_UNKNOWN, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) + assertFailsWith { MemberWalletManager.request(db, groupRoom, member, chain, label = null) } + assertTrue(db.memberWalletDao().getByOwner(memberPublicKey).isEmpty(), "a refused request makes no key") + + // Offered on mainnet since the gate lifted -- the refusal is the room's, not + // the network's -- and a member's own spend there still held to the cap. + assertTrue(com.machankura.bennu.compose.wallet.GroupWalletRollout.offersMemberWalletsOn(Chain.Mainnet)) + assertEquals(com.machankura.bennu.compose.wallet.GroupWalletRollout.MAINNET_CAP, com.machankura.bennu.compose.wallet.GroupWalletRollout.memberCapFor(Chain.Mainnet)) + assertNull(com.machankura.bennu.compose.wallet.GroupWalletRollout.memberCapFor(Chain.Signet)) + assertEquals(Refusal.KEY_UNKNOWN, MemberWalletManager.refusal(db, groupRoom, canSign = true, Chain.Mainnet)) + } + + @Test + fun `a member with no key state can ask once an answer is in the room`(): Unit = runBlocking { + asMember(knowsKey = false) + val answer = GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), guardedCertificate(parent, group)) + val tags = GroupKeyNoticeEvent.answeringTags("e".repeat(64), answer, GroupFixtures.path) + db.marmotInnerEventDao().upsert( + MarmotInnerEvent(id = "f".repeat(64), publicKey = "5".repeat(64), kind = GroupKeyNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(1_700_000_000), tags = tags, content = answer.thresholdPublicKey, chatRoomId = groupRoom) + ) + + assertNull(MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) + assertEquals(2, MemberWalletManager.reachOf(db, groupRoom)) + // The group's own leaf at the default, and the parent's at the delay it + // chose for the group -- the default too, here. docs/guardian-delay.md. + assertEquals(listOf(GuardianDerivation.DEFAULT_DELAY, GuardianDerivation.DEFAULT_DELAY), MemberWalletManager.delaysOf(db, groupRoom)) + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(wallet.requestJson))) + } + + @Test + fun `a key is discarded only before a group guards its wallet`(): Unit = runBlocking { + asMember() + val unasked = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + MemberWalletManager.discard(db, unasked.walletId) + assertNull(db.memberWalletDao().getById(unasked.walletId)) + + val guarded = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + val template = MemberWalletCertificateEvent.template(Event.fromJson(guarded.requestJson)) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + assertFailsWith { MemberWalletManager.discard(db, guarded.walletId) } + assertNotNull(db.memberWalletDao().getById(guarded.walletId)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt new file mode 100644 index 00000000..b0bbcb47 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt @@ -0,0 +1,206 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.machankura.bennu.compose.text.ProposedEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * A group's signers checking a member wallet certificate before they are asked + * to approve it, and a signer putting a member's request to the group. + * + * The group is itself a guarded subgroup, so a member's wallet under it carries + * two leaves -- the group's and its parent's, one step further -- and every + * refusal below is one way of getting that list wrong. + */ +class MemberWalletSigningJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + private val outsider = privateKey(0x07575) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + + /** What the group grants the member's wallet: its own key, then its parent's, one step further. */ + private val grant: List = GuardianDerivation.grant( + thresholdKeyOf(group), groupRoom, + GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), groupRoom), + walletId, + ) + + private suspend fun groupRoomHere() = signingRoom(db, group, members = listOf(memberPublicKey)).also { + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + } + + private fun request(guardians: List = grant, by: PrivateKey = member, asking: String = groupRoom) = + MemberWalletRequestEvent.build( + memberPrivateKey = by, + groupChatRoomId = asking, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians), + label = "Savings", + createdAt = 1_700_000_000, + // Built under the group's open policy, as a member's device builds + // it -- the one groupRoomHere() files. docs/member-wallet-delay.md. + policy = GroupFixtures.memberWalletPolicy(group, GuardianDerivation.DEFAULT_DELAY, createdAt = 1_600_000_000).takeIf { asking == groupRoom }, + ) + + /** The certificate [request] asks for, as a session would carry it -- unsigned, authored by the room. */ + private fun proposed(request: Event, room: String = groupRoom): Event { + val template = MemberWalletCertificateEvent.template(request) + return Event(MemberWalletManager.certificateIdFor(room, request), room, template.createdAt, template.kind, template.tags, template.content, "") + } + + private suspend fun refusal(request: Event): String? = + MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed(request)) + + @Test + fun `the honest certificate is signable`(): Unit = runBlocking { + groupRoomHere() + assertNull(refusal(request())) + } + + @Test + fun `a certificate that drops the group above is refused`(): Unit = runBlocking { + groupRoomHere() + assertEquals("grants guardian keys this group does not", refusal(request(guardians = grant.take(1)))) + } + + @Test + fun `a certificate whose leaves are reordered is refused`(): Unit = runBlocking { + groupRoomHere() + // Reordered, the group is no longer the nearest guardian, so the request itself is refused. + assertNotNull(refusal(request(guardians = grant.reversed()))) + } + + @Test + fun `a certificate naming another group's key is refused`(): Unit = runBlocking { + groupRoomHere() + val swapped = listOf(grant[0], GuardianDerivation.grant(thresholdKeyOf(stranger), roomOf(stranger), emptyList(), walletId).single()) + assertEquals("grants guardian keys this group does not", refusal(request(guardians = swapped))) + } + + @Test + fun `a certificate asked by somebody who is not a member is refused`(): Unit = runBlocking { + groupRoomHere() + assertEquals("was asked by somebody who is not a member", refusal(request(by = outsider))) + } + + @Test + fun `a request made of another group is refused here`(): Unit = runBlocking { + groupRoomHere() + val elsewhere = request(asking = roomOf(stranger), guardians = GuardianDerivation.grant(thresholdKeyOf(stranger), roomOf(stranger), emptyList(), walletId)) + assertNotNull(MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed(elsewhere))) + } + + @Test + fun `an unguarded group guards its members with its own key alone`(): Unit = runBlocking { + // A root group: no certificate, so nothing to pass down. + signingRoom(db, group, members = listOf(memberPublicKey)) + fileKeyState(db, group, certificate = null) + GroupFixtures.openToMembers(db, group) + assertNull(refusal(request(guardians = grant.take(1)))) + assertEquals("grants guardian keys this group does not", refusal(request())) + } + + private suspend fun deliverRequest(request: Event) { + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = "1".repeat(63) + "0", + publicKey = request.pubKey, + kind = MemberWalletRequestEvent.KIND, + createdAt = Instant.fromEpochSeconds(request.createdAt), + tags = arrayOf(arrayOf("h", groupRoom)), + content = request.toJson(), + chatRoomId = groupRoom, + ) + ) + } + + @Test + fun `a signer puts a request to the group, and a second sponsor finds the same session`(): Unit = runBlocking { + val room = groupRoomHere() + val request = request() + deliverRequest(request) + assertEquals(listOf(walletId), MemberWalletManager.awaitingSponsor(db, groupRoom).map { it.reading.walletId }) + + val session = MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request) + val items = db.frostSigningSessionDao().getItems(session.id) + assertEquals(listOf(MemberWalletManager.certificateIdFor(groupRoom, request)), items.map { it.eventId }) + assertTrue(MemberWalletManager.awaitingSponsor(db, groupRoom).isEmpty(), "no longer waiting for a sponsor") + + assertEquals(session.id, MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request).id) + } + + @Test + fun `a sponsor refuses to put what the group would refuse`(): Unit = runBlocking { + val room = groupRoomHere() + assertFailsWith { + MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request(guardians = grant.take(1))) + } + assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(groupRoom).isEmpty()) + } + + @Test + fun `a wallet the group already guards is not put to it again`(): Unit = runBlocking { + val room = groupRoomHere() + val request = request() + val template = MemberWalletCertificateEvent.template(request) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + assertEquals(listOf(walletId), MemberWalletManager.certificatesOf(db, groupRoom).map { it.walletId }) + assertFailsWith { MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request) } + } + + @Test + fun `the signers read who it is for and what the group can do`() { + val summary = ProposedEvent.summarize(proposed(request())) { if (it == memberPublicKey) "alice" else null } + assertEquals("Guard a member's wallet", summary.label) + assertTrue(summary.detail.startsWith("For @alice · Savings · on regtest"), summary.detail) + // Each guardian's own delay, nearest first: both are the default here. + assertTrue( + summary.detail.contains("this group can take its coins after 12 blocks, about 2 hours, and the one above it after 12 blocks, about 2 hours"), + summary.detail, + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSpendJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSpendJvmTest.kt new file mode 100644 index 00000000..6577863c --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSpendJvmTest.kt @@ -0,0 +1,140 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MemberWallet +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * A member spending their own guarded wallet alone: the spend checked against + * the account the wallet rederives to, signed with the member's key, accepted + * by the script interpreter, and filed -- and refused for every wallet this + * device cannot sign for. + */ +class MemberWalletSpendJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + + private val destination = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + + private suspend fun certifiedWallet(): MemberWallet { + signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + val template = MemberWalletCertificateEvent.template(Event.fromJson(wallet.requestJson)) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + return wallet + } + + /** [account]'s wallet with one coin of [sats] at receive address [index], and an unused change address. */ + private fun stateWith(account: GroupWalletDerivation.Account, index: Int = 0, sats: Long = 80_000): GroupWalletState { + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(index) + val receive = WalletState(mapOf(derived.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))) + val change = WalletState( + mapOf(GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList())) + ) + return GroupWalletState(account, receive, change, tipHeight = 110) + } + + @Test + fun `a member signs alone, and the network would take it`(): Unit = runBlocking { + val wallet = certifiedWallet() + val account = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)).account + val built = assertIs(GroupSpendBuilder.send(stateWith(account), destination, Satoshi(30_000), 3L, emptySet())) + + val signed = MemberWalletManager.signSpend(db, memberPublicKey, wallet.walletId, built.psbt, at = Instant.fromEpochSeconds(1_700_000_000)) + + val checked = assertIs(GroupSpend.check(built.psbt, account)).checked + signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + signed.txIn.forEach { assertEquals(1, it.witness.stack.size, "the key path: the tree stays hidden") } + + val spend = assertNotNull(db.memberWalletDao().getSpend(signed.txid.toString())) + assertEquals(wallet.walletId, spend.walletId) + assertNull(spend.seenAt) + + MemberWalletManager.recordChain(db, spend.txid, confirmations = 0, at = Instant.fromEpochSeconds(1_700_000_100)) + assertEquals(Instant.fromEpochSeconds(1_700_000_100), db.memberWalletDao().getSpend(spend.txid)?.seenAt) + assertNull(db.memberWalletDao().getSpend(spend.txid)?.confirmedAt) + MemberWalletManager.recordChain(db, spend.txid, confirmations = 2, at = Instant.fromEpochSeconds(1_700_000_700)) + assertEquals(Instant.fromEpochSeconds(1_700_000_700), db.memberWalletDao().getSpend(spend.txid)?.confirmedAt) + assertEquals(Instant.fromEpochSeconds(1_700_000_100), db.memberWalletDao().getSpend(spend.txid)?.seenAt, "first seen stays first seen") + } + + @Test + fun `a spend of another wallet's coins is refused`(): Unit = runBlocking { + val wallet = certifiedWallet() + val other = MemberWalletDerivation.account(privateKey(0xb0b).publicKey(), chain, emptyList()) + val built = assertIs(GroupSpendBuilder.sendAll(stateWith(other), destination, 3L, emptySet())) + assertFailsWith { MemberWalletManager.signSpend(db, memberPublicKey, wallet.walletId, built.psbt) } + assertEquals(emptyList(), db.memberWalletDao().getSpends(wallet.walletId)) + } + + @Test + fun `nothing is signed before a group certifies the wallet, or without its key`(): Unit = runBlocking { + signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + val account = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, asked.walletId)).account + val built = assertIs(GroupSpendBuilder.sendAll(stateWith(account), destination, 3L, emptySet())) + assertFailsWith { MemberWalletManager.signSpend(db, memberPublicKey, asked.walletId, built.psbt) } + + // Certified, and the key on another device. + val template = MemberWalletCertificateEvent.template(Event.fromJson(asked.requestJson)) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + db.memberWalletDao().delete(asked.walletId) + assertFailsWith { MemberWalletManager.signSpend(db, memberPublicKey, asked.walletId, built.psbt) } + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt new file mode 100644 index 00000000..27bd1eec --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt @@ -0,0 +1,128 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.MemberWalletManager.WalletState +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * A member's guarded wallets as their profile lists them: one state per wallet, + * read off the key here, the sessions in the group's room and the group's + * certificates -- and a wallet made on another device, which this one can + * only watch. + */ +class MemberWalletsJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + + private suspend fun setUp(signer: Boolean = false) { + signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = signer) + fileKeyState(db, group, guardedCertificate(parent, group)) + GroupFixtures.openToMembers(db, group) + } + + private suspend fun certify(request: Event) { + val template = MemberWalletCertificateEvent.template(request) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + } + + private suspend fun stateOf(walletId: String): WalletState? = + MemberWalletManager.walletsOf(db, memberPublicKey).firstOrNull { it.walletId == walletId }?.state + + @Test + fun `asked, then certified`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") + assertEquals(WalletState.ASKED, stateOf(wallet.walletId)) + + certify(Event.fromJson(wallet.requestJson)) + val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) + assertEquals(WalletState.OPEN, row.state) + assertTrue(row.isCertified) + assertTrue(row.isMember) + assertEquals("Savings", row.label) + assertEquals(groupRoom, row.groupRoom?.chatRoom?.id) + assertEquals(2, row.account.guardians.size) + assertNotNull(MemberWalletManager.exportKey(db, memberPublicKey, wallet.walletId)) + } + + @Test + fun `signing, then not signed`(): Unit = runBlocking { + setUp(signer = true) + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + assertEquals(WalletState.SIGNING, stateOf(wallet.walletId), "a signer puts it to the group at once") + + val session = assertNotNull(MemberWalletManager.openSessionFor(db, groupRoom, Event.fromJson(wallet.requestJson))) + db.frostSigningSessionDao().upsert(session.copy(stage = FrostSigningStage.FAILED)) + assertEquals(WalletState.NOT_SIGNED, stateOf(wallet.walletId)) + } + + @Test + fun `a wallet made on another device is listed to watch`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + certify(Event.fromJson(wallet.requestJson)) + // As the other device sees it: the certificate, and no key. + db.memberWalletDao().delete(wallet.walletId) + + val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) + assertEquals(WalletState.WATCH_ONLY, row.state) + assertNull(MemberWalletManager.exportKey(db, memberPublicKey, wallet.walletId), "no key to export here") + } + + @Test + fun `somebody else's wallets are not listed`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + certify(Event.fromJson(wallet.requestJson)) + assertTrue(MemberWalletManager.walletsOf(db, privateKey(0xb0b).xOnlyPublicKey().value.toHex()).isEmpty()) + } + + @Test + fun `a member who left keeps the wallet, and is told`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + certify(Event.fromJson(wallet.requestJson)) + db.participantDao().delete(db.participantDao().findParticipantsByChatRoomId(groupRoom).filter { it.participantPublicKey == memberPublicKey }) + + val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) + assertFalse(row.isMember) + assertEquals(WalletState.OPEN, row.state) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt index 8bcfa422..8b8d8815 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt @@ -26,6 +26,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Instant import kotlinx.coroutines.flow.first +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import kotlinx.coroutines.runBlocking import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.ChatMessage @@ -47,7 +48,6 @@ import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent /** * Two devices, two databases, one real signing session, and the wire between @@ -877,7 +877,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -924,7 +924,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -973,7 +973,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -1006,7 +1006,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -1042,9 +1042,9 @@ class SignedGroupKeyStateTest { ) } - /** Every event of a batch is applied, not just the first. */ + /** Every event of a batch is recorded as signed, not just the first. */ @Test - fun `every dialect in a batch lands on every device`() = runBlocking { + fun `every post in a batch lands on every device`() = runBlocking { val creator = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) @@ -1052,21 +1052,21 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) pump(creator, other) listOf(creator, other).forEach { device -> - val names = device.items(session.id).map { item -> + val notes = device.items(session.id).map { item -> assertNotNull( - device.db.mantraDialectDao().getDialectById(item.eventId), - "item ${item.itemIndex} should have been applied" - ).name + device.db.groupSignedEventDao().getById(item.eventId), + "item ${item.itemIndex} should have been recorded as signed" + ).content } - assertEquals(listOf("Sepedi", "isiZulu", "Setswana"), names) + assertEquals(listOf("Sepedi", "isiZulu", "Setswana"), notes) } } @@ -1080,7 +1080,7 @@ class SignedGroupKeyStateTest { val creator = device(members[0], signerIndex = 0) val tooMany = (0..FrostSigningManager.MAX_BATCH_SIZE).map { index -> - DialectEvent.build(name = "d$index", country = "ZA", language = "l$index") + TextNoteEvent.build(note = "post $index") } assertFailsWith { @@ -1113,7 +1113,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) @@ -1165,13 +1165,13 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) val before = other.items(session.id) - val substitute = DialectEvent.build(name = "Xitsonga", country = "ZA", language = "tso") + val substitute = TextNoteEvent.build(note = "Xitsonga") FrostSigningManager.processSigningPayload( database = other.db, localChatRoom = other.room, @@ -1207,23 +1207,19 @@ class SignedGroupKeyStateTest { assertEquals(before.map { it.nonceRandom }, other.items(session.id).map { it.nonceRandom }) } - /** Three dialects, distinct enough that an order bug shows up as a wrong name. */ - private fun dialects() = listOf( - Triple("Sepedi", "ZA", "nso"), - Triple("isiZulu", "ZA", "zul"), - Triple("Setswana", "ZA", "tsn"), - ).map { (name, country, language) -> - DialectEvent.build(name = name, country = country, language = language) + /** Three posts, distinct enough that an order bug shows up as the wrong words. */ + private fun posts() = listOf("Sepedi", "isiZulu", "Setswana").map { note -> + TextNoteEvent.build(note = note) } // ---- What a room signs as, once it has a key state --------------------- @Test - fun `a dialect the group signs is authored by the room it was signed in`() = runBlocking { + fun `a post the group signs is authored by the room it was signed in`() = runBlocking { val creator = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) - val template = DialectEvent.build(name = "Sepedi", country = "ZA", language = "nso") + val template = TextNoteEvent.build(note = "Sepedi") val session = FrostSigningManager.proposeSigning( database = creator.db, localChatRoom = creator.room, @@ -1237,19 +1233,19 @@ class SignedGroupKeyStateTest { pump(creator, other) listOf(creator, other).forEach { device -> - val dialect = device.db.mantraDialectDao().getDialectById(device.item(session.id).eventId) - assertNotNull(dialect, "a signed dialect should exist on every signer's device") - assertEquals("Sepedi", dialect.name) + val post = device.db.groupSignedEventDao().getById(device.item(session.id).eventId) + assertNotNull(post, "a signed post should exist on every signer's device") + assertEquals("Sepedi", post.content) // The ask this whole change serves: the group's work is authored by // the group's room, not by the member who typed it and not by the // bare threshold key. - assertEquals(adminRoomId, dialect.publicKey) - assertTrue(dialect.publicKey != creator.publicKey) - assertTrue(dialect.publicKey != rootPublicKey) + assertEquals(adminRoomId, post.publicKey) + assertTrue(post.publicKey != creator.publicKey) + assertTrue(post.publicKey != rootPublicKey) assertTrue( Nip01Crypto.verify( - signature = dialect.signature.hexToByteArray(), - hash = dialect.id.hexToByteArray(), + signature = post.signature.hexToByteArray(), + hash = post.id.hexToByteArray(), pubKey = adminRoomId.hexToByteArray() ) ) @@ -1402,7 +1398,7 @@ class SignedGroupKeyStateTest { description = null ) - val template = DialectEvent.build(name = "Sepedi", country = "ZA", language = "nso") + val template = TextNoteEvent.build(note = "Sepedi") val session = FrostSigningManager.proposeSigning( database = creator.db, localChatRoom = creator.room, @@ -1435,7 +1431,7 @@ class SignedGroupKeyStateTest { ) member.db.chatRoomDao().upsert(bystanderRoom) - val template = DialectEvent.build(name = "Sepedi", country = "ZA", language = "nso") + val template = TextNoteEvent.build(note = "Sepedi") assertFailsWith { FrostSigningManager.proposeSigning( diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupCeremonyInParentRoomTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupCeremonyInParentRoomTest.kt index ed890bc3..793c1203 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupCeremonyInParentRoomTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupCeremonyInParentRoomTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianDelayTag import androidx.room3.Room import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519 @@ -35,6 +36,9 @@ import com.machankura.bennu.compose.database.model.types.DkgRitualStage import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.Relays import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag +import com.machankura.bennu.compose.database.model.subgroupWalletPolicy /** * A subgroup's key ceremony, held in the room of the group making it. @@ -111,7 +115,11 @@ class SubgroupCeremonyInParentRoomTest { private val quorum = 2 - private suspend fun openCeremony(room: LocalChatRoom) = ChillDkgRitualManager.proposeRitual( + private suspend fun openCeremony( + room: LocalChatRoom, + walletPolicy: SubgroupWalletPolicy? = null, + guardianDelay: Long? = null, + ) = ChillDkgRitualManager.proposeRitual( database = parent, localChatRoom = room, userPublicKey = user, @@ -119,7 +127,9 @@ class SubgroupCeremonyInParentRoomTest { threshold = quorum, parentChatRoomId = parentRoomId, participantPublicKeys = admins, - subject = "Translation" + subject = "Translation", + walletPolicy = walletPolicy, + guardianDelay = guardianDelay ) private suspend fun innerEvents(database: BennuDatabase) = database.marmotInnerEventDao() @@ -222,6 +232,196 @@ class SubgroupCeremonyInParentRoomTest { } } + /** + * The coordinator's choice of wallet policy reaches every admin before they + * join -- docs/subgroup-wallet-policy.md, Phase 2. It is what the join screen + * shows and what the certificate is later proposed under, so it has to be on + * every admin's session, not only the coordinator's. + */ + @Test + fun `the wallet policy travels on the proposal and lands on every admin's session`(): Unit = runBlocking { + val room = parentRoom() + val session = openCeremony(room, SubgroupWalletPolicy.GUARDED) + assertEquals(SubgroupWalletPolicy.GUARDED, session.subgroupWalletPolicy) + + val proposal = assertNotNull( + innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL } + ) + assertEquals( + WalletPolicyTag.Result.Present(SubgroupWalletPolicy.GUARDED), + DkgRitualEvents.parseWalletPolicy(proposal.tags), + ) + innerEvents(parent).filterNot { it.kind == DkgRitualEvents.PROPOSAL }.forEach { + assertEquals(WalletPolicyTag.Result.Absent, DkgRitualEvents.parseWalletPolicy(it.tags), "kind ${it.kind} repeats the policy") + } + + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = receiverRoom(), + innerEvent = proposal.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + assertEquals( + SubgroupWalletPolicy.GUARDED, + receiver.dkgSessionDao().getSessionById(session.id)?.subgroupWalletPolicy, + ) + } + + /** docs/guardian-delay.md, Phase 4: the delay travels as the policy does, one field further. */ + @Test + fun `the guardian delay travels on the proposal and lands on every admin's session`(): Unit = runBlocking { + val session = openCeremony(parentRoom(), SubgroupWalletPolicy.GUARDED, guardianDelay = 4_320) + assertEquals(4_320L, session.guardianDelay) + + val proposal = assertNotNull(innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL }) + assertEquals(GuardianDelayTag.Result.Present(4_320), DkgRitualEvents.parseGuardianDelay(proposal.tags)) + innerEvents(parent).filterNot { it.kind == DkgRitualEvents.PROPOSAL }.forEach { + assertEquals(GuardianDelayTag.Result.Absent, DkgRitualEvents.parseGuardianDelay(it.tags), "kind ${it.kind} repeats the delay") + } + + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = receiverRoom(), + innerEvent = proposal.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + assertEquals(4_320L, receiver.dkgSessionDao().getSessionById(session.id)?.guardianDelay) + } + + @Test + fun `a guarded proposal with no delay files none`(): Unit = runBlocking { + val session = openCeremony(parentRoom(), SubgroupWalletPolicy.GUARDED) + val proposal = assertNotNull(innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL }) + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = receiverRoom(), + innerEvent = proposal.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + val joined = assertNotNull(receiver.dkgSessionDao().getSessionById(session.id)) + assertNull(joined.guardianDelay, "certified later at the default") + } + + @Test + fun `a proposal whose delay is out of range, unreadable, or unguarded is dropped`(): Unit = runBlocking { + val receiving = receiverRoom() + val cases = mapOf( + "five blocks" to (SubgroupWalletPolicy.GUARDED to arrayOf(GuardianDelayTag.TAG_NAME, "5")), + "a word" to (SubgroupWalletPolicy.GUARDED to arrayOf(GuardianDelayTag.TAG_NAME, "twelve")), + "an unguarded subgroup" to (SubgroupWalletPolicy.UNGUARDED to arrayOf(GuardianDelayTag.TAG_NAME, "144")), + ) + cases.entries.forEachIndexed { index, (name, case) -> + val (policy, delayTag) = case + val sessionId = "a${index}".padEnd(64, '0') + val proposal = Event( + id = "b${index}".padEnd(64, '0'), + pubKey = user, + createdAt = 1, + kind = DkgRitualEvents.PROPOSAL, + tags = admins.map { arrayOf("p", it) }.toTypedArray() + + DkgRitualEvents.assembleTags( + sessionId = sessionId, + threshold = quorum, + parentChatRoomId = parentRoomId, + subject = "Translation", + walletPolicy = policy, + ) + arrayOf(delayTag), + content = "", + sig = "" + ) + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = receiving, + innerEvent = proposal, + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + assertNull(receiver.dkgSessionDao().getSessionById(sessionId), "a proposal with $name was joined") + } + } + + @Test + fun `only a guarded subgroup's ceremony can carry a delay, and only one in range`(): Unit = runBlocking { + val room = parentRoom() + listOf(SubgroupWalletPolicy.UNGUARDED to 144L, SubgroupWalletPolicy.GUARDED to 5L, SubgroupWalletPolicy.GUARDED to 65_536L) + .forEach { (policy, delay) -> + assertTrue(runCatching { openCeremony(room, policy, guardianDelay = delay) }.isFailure, "$policy at $delay") + } + assertTrue(innerEvents(parent).isEmpty(), "and nothing goes out") + } + + @Test + fun `a subgroup proposal from a build before policies carries none`(): Unit = runBlocking { + val session = openCeremony(parentRoom()) + assertNull(session.walletPolicy) + + val proposal = assertNotNull( + innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL } + ) + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = receiverRoom(), + innerEvent = proposal.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + val joined = assertNotNull(receiver.dkgSessionDao().getSessionById(session.id)) + assertNull(joined.walletPolicy, "joined, with nothing to show at the gate") + } + + @Test + fun `a proposal whose wallet policy does not read is dropped`(): Unit = runBlocking { + val proposal = Event( + id = "cc".repeat(32), + pubKey = user, + createdAt = 1, + kind = DkgRitualEvents.PROPOSAL, + tags = admins.map { arrayOf("p", it) }.toTypedArray() + + DkgRitualEvents.assembleTags( + sessionId = "ab".repeat(32), + threshold = quorum, + parentChatRoomId = parentRoomId, + subject = "Translation", + ) + arrayOf(arrayOf(WalletPolicyTag.TAG_NAME, "maybe")), + content = "", + sig = "" + ) + + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = receiverRoom(), + innerEvent = proposal, + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + + assertNull( + receiver.dkgSessionDao().getSessionById("ab".repeat(32)), + "an admin is not enrolled in a ceremony whose policy they could not be shown", + ) + } + + @Test + fun `only a subgroup's ceremony can carry a wallet policy`(): Unit = runBlocking { + val refused = runCatching { + ChillDkgRitualManager.proposeRitual( + database = parent, + localChatRoom = parentRoom(), + userPublicKey = user, + nostrPrivateKey = coordinator.privKey!!, + threshold = quorum, + participantPublicKeys = admins, + walletPolicy = SubgroupWalletPolicy.UNGUARDED, + ) + } + + assertTrue(refused.isFailure) + assertTrue(innerEvents(parent).isEmpty(), "and nothing goes out") + } + /** * Everybody in the parent's room can read the proposal. Only the admins are in * it. @@ -369,6 +569,171 @@ class SubgroupCeremonyInParentRoomTest { ) } + /** + * A Marmot room hosts its subgroups' ceremonies and never one of its own. + * + * Its id is derived from the key it already has, so a key of its own is one + * the room could never answer to. This is what opened a whole-room ceremony + * beside a subgroup's when the shared-key screen offered "Start key ceremony" + * in the parent's room -- see docs/ceremony-creation.md. + */ + @Test + fun `a Marmot room refuses a ceremony of its own`(): Unit = runBlocking { + val room = parentRoom(withOwnKey = false) + + val refused = runCatching { + ChillDkgRitualManager.proposeRitual( + database = parent, + localChatRoom = room, + userPublicKey = user, + nostrPrivateKey = coordinator.privKey!!, + threshold = quorum, + ) + } + + assertTrue(refused.isFailure, "a ceremony with no parent is refused in a Marmot room") + assertNull( + parent.dkgSessionDao().getLatestSessionForChatRoom(parentRoomId), + "and no session is recorded", + ) + assertTrue(innerEvents(parent).isEmpty(), "and nothing goes out") + + // A subgroup's, in the same room, is still what the room is for. + openCeremony(room) + assertNotNull(parent.dkgSessionDao().getLatestSessionForChatRoom(parentRoomId)) + } + + /** + * The receiving half: a build from before the refusal can still send one. + */ + @Test + fun `a proposal naming no parent in a Marmot room is dropped`(): Unit = runBlocking { + val theirRoom = receiverRoom() + + val proposal = Event( + id = "dd".repeat(32), + pubKey = user, + createdAt = 1, + kind = DkgRitualEvents.PROPOSAL, + // The shape `broadcast` gives a group's own proposal: the roster as + // p-tags, a threshold, a name, and no parent. + tags = admins.map { arrayOf("p", it) }.toTypedArray() + + DkgRitualEvents.assembleTags( + sessionId = "ff".repeat(32), + threshold = quorum, + subject = "Ekklesia", + ), + content = "", + sig = "" + ) + + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = theirRoom, + innerEvent = proposal, + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + + assertNull( + receiver.dkgSessionDao().getSessionById("ff".repeat(32)), + "a whole-room ceremony is not recorded in a Marmot room", + ) + assertTrue(innerEvents(receiver).isEmpty(), "and nothing is published") + } + + /** + * A participant can end a ceremony for everyone in it. + * + * There is no "no" in ChillDKG short of this, and without it a ceremony + * opened by mistake could only be left running -- see + * docs/ceremony-creation.md, finding F8. + */ + @Test + fun `a participant who abandons ends the ceremony on every device`(): Unit = runBlocking { + val room = parentRoom() + val session = openCeremony(room) + + val theirRoom = receiverRoom() + val proposal = assertNotNull( + innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL } + ) + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = theirRoom, + innerEvent = proposal.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + + assertTrue(ChillDkgRitualManager.abandon(parent, room, session.id)) + assertEquals(DkgRitualStage.FAILED, parent.dkgSessionDao().getSessionById(session.id)?.stage) + + val failure = assertNotNull( + innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.FAILURE }, + "the other participants are told", + ) + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = theirRoom, + innerEvent = failure.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + + assertEquals( + DkgRitualStage.FAILED, + receiver.dkgSessionDao().getSessionById(session.id)?.stage, + "and it ends for them too", + ) + + assertTrue( + !ChillDkgRitualManager.abandon(parent, room, session.id), + "a ceremony that is over cannot be abandoned again", + ) + } + + /** + * Every member of the parent can read a subgroup's proposal, and so can name + * its session. Only the people in it can end it (finding F9). + */ + @Test + fun `a parent member outside the subgroup cannot end its ceremony`(): Unit = runBlocking { + val room = parentRoom() + val session = openCeremony(room) + + val theirRoom = receiverRoom() + val proposal = assertNotNull( + innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL } + ) + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = theirRoom, + innerEvent = proposal.asEvent(), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + + ChillDkgRitualManager.processRitualPayload( + database = receiver, + localChatRoom = theirRoom, + innerEvent = Event( + id = "ab".repeat(32), + pubKey = malloryPublicKey, + createdAt = 2, + kind = DkgRitualEvents.FAILURE, + tags = DkgRitualEvents.assembleTags(sessionId = session.id), + content = "not mine to end", + sig = "" + ), + userPublicKey = alice, + nostrPrivateKey = aliceKeys.privKey!! + ) + + val stillRunning = assertNotNull(receiver.dkgSessionDao().getSessionById(session.id)) + assertTrue(stillRunning.stage != DkgRitualStage.FAILED, "a non-participant's FAILURE is ignored") + } + /** * The parent does not start signing as its own child. * diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt index 2caaa42f..f4b5f04c 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.subgroup.SubgroupParentage +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.WalletPolicyTag +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import androidx.room3.Room import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519 @@ -34,7 +39,9 @@ import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.DkgParticipantMessage import com.machankura.bennu.compose.database.model.DkgSession import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.Profile @@ -130,6 +137,30 @@ class SubgroupManagerJvmTest { assertNull(subgroup.keyState) } + @Test + fun `a listed child carries what its parent decided about its wallet`(): Unit = runBlocking { + seedRoom(parentRoomId) + record( + certificate( + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = childRoomId, + parentChatRoomId = parentRoomId, + thresholdPublicKey = childMaterial.thresholdPublicKey.value.toHex(), + adminPublicKeys = listOf(user, alice, bob), + name = "Translation team", + path = path, + walletPolicy = SubgroupWalletPolicy.UNGUARDED, + ) + ) + ) + record(certificate(subgroupMaterial = siblingMaterial)) + + val subgroups = SubgroupManager.subgroupsOf(db, parentRoomId).associateBy { it.chatRoomId } + + assertEquals(WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED), subgroups.getValue(childRoomId).walletPolicy) + assertEquals(WalletPolicyReading.Undecided, subgroups.getValue(siblingRoomId).walletPolicy, "a certificate from before policies") + } + @Test fun `a child whose room this device holds reports it`(): Unit = runBlocking { seedRoom(parentRoomId) @@ -494,8 +525,359 @@ class SubgroupManagerJvmTest { } } + @Test + fun `a certificate grants the child the parent's guardian key`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + + val proposed = proposedCertificate(parentRoom) + + // A parent with no parent of its own grants one key: its own, one step on. + assertEquals( + GuardianDerivation.grant(parentMaterial.thresholdPublicKey.value.toHex(), parentRoomId, emptyList(), childRoomId), + SubgroupBirthCertificateEvent.parseGuardians(proposed.tags) + ) + assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentMaterial.thresholdPublicKey.value.toHex(), proposed)) + } + + @Test + fun `a subgroup passes on the keys its own parent granted it, one step further`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + // The parent is itself a subgroup of a grandparent, whose key reached it + // through the parent's own certificate. + val grandparentKey = strangerMaterial.thresholdPublicKey.value.toHex() + val grandparentRoomId = roomOf(strangerMaterial) + val inherited = GuardianDerivation.grant(grandparentKey, grandparentRoomId, emptyList(), parentRoomId) + fileParentage(inherited) + + val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposedCertificate(parentRoom).tags)) + + assertEquals(listOf(parentRoomId, grandparentRoomId), granted.map { it.chatRoomId }) + assertEquals(inherited[0].grantedTo(childRoomId), granted[1]) + assertEquals( + GuardianDerivation.root(grandparentKey).extendedPublicKey + .derivePublicKey(GuardianDerivation.childIndex(parentRoomId)) + .derivePublicKey(GuardianDerivation.childIndex(childRoomId)) + .publicKey, + granted[1].publicKey, + "the grandparent's key in the grandchild is R / i(parent) / i(child)" + ) + } + + @Test + fun `a signer refuses guardian keys the group does not grant`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + val proposed = proposedCertificate(parentRoom) + val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) + val coordinators = GuardianDerivation.grant(strangerMaterial.thresholdPublicKey.value.toHex(), parentRoomId, emptyList(), childRoomId) + + fun withGuardians(guardians: List) = certificate( + tags = proposed.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + guardians.map(GuardianTag::assemble) + ) + + val refusals = mapOf( + "a key of the coordinator's own" to withGuardians(coordinators), + "an extra ancestor" to withGuardians(granted + coordinators), + "the key not stepped for this child" to withGuardians(listOf(granted[0].copy(publicKey = GuardianDerivation.root(parentKey).publicKey))), + "a shorter delay" to withGuardians(listOf(granted[0].copy(delay = 1))), + ) + refusals.forEach { (name, certificate) -> + assertNotNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate), name) + } + + // An older proposer's certificate carries none, and grants nothing. + assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate())) + } + + // ---- the wallet policy: docs/subgroup-wallet-policy.md ----------------- + + /** The parent made a subgroup of a grandparent, under [policy]. */ + private suspend fun parentIs(policy: SubgroupWalletPolicy?) { + val grandparentRoomId = roomOf(strangerMaterial) + val inherited = if (policy == SubgroupWalletPolicy.UNGUARDED) { + emptyList() + } else { + GuardianDerivation.grant(strangerMaterial.thresholdPublicKey.value.toHex(), grandparentRoomId, emptyList(), parentRoomId) + } + fileParentage(inherited, policy) + } + + private fun ceremonyUnder(policy: SubgroupWalletPolicy?) = + completedChildCeremony().copy(walletPolicy = policy?.tagValue) + + private val guardedReading = WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) + private val unguardedReading = WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) + + @Test + fun `a guarded ceremony is certified guarded, with the grant`(): Unit = runBlocking { + val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + + assertEquals(guardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) + assertEquals(1, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.size) + } + + @Test + fun `an unguarded ceremony is certified unguarded, with no keys`(): Unit = runBlocking { + val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) + + assertEquals(unguardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) + assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) + } + + @Test + fun `an older build's ceremony is certified as it always was`(): Unit = runBlocking { + val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(null)) + + assertEquals(WalletPolicyReading.Undecided, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) + assertEquals(1, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.size) + } + + @Test + fun `under a guarded parent an older build's ceremony is certified guarded`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + parentIs(SubgroupWalletPolicy.GUARDED) + + val proposed = proposedCertificate(parentRoom, ceremonyUnder(null)) + + assertEquals(guardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) + assertEquals(2, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.size, "its own key and the grandparent's") + } + + @Test + fun `under a guarded parent an unguarded ceremony is refused, and nothing is proposed`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + parentIs(SubgroupWalletPolicy.GUARDED) + + val refused = runCatching { proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) } + + assertTrue(refused.exceptionOrNull() is IllegalStateException) + assertTrue("Start the subgroup again" in refused.exceptionOrNull()?.message.orEmpty(), "the remedy is in the reason") + assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(parentRoomId).isEmpty()) + } + + @Test + fun `under an unguarded parent an unguarded ceremony is certified`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + parentIs(SubgroupWalletPolicy.UNGUARDED) + + val proposed = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) + + assertEquals(unguardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) + } + + @Test + fun `a signer refuses a certificate whose policy does not read or contradicts its keys`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + val guarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + val withoutPolicy = guarded.tags.filterNot { it[0] == WalletPolicyTag.TAG_NAME }.toTypedArray() + + val refusals = mapOf( + "unguarded with keys" to certificate(tags = withoutPolicy + WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED)), + "guarded with no keys" to certificate( + tags = withoutPolicy.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + WalletPolicyTag.assemble(SubgroupWalletPolicy.GUARDED) + ), + "a policy that does not read" to certificate(tags = withoutPolicy + arrayOf(WalletPolicyTag.TAG_NAME, "maybe")), + ) + refusals.forEach { (name, certificate) -> + assertNotNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate), name) + } + + assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, guarded)) + assertNull( + SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED))), + "an unguarded certificate of a root group's child is signable", + ) + } + + @Test + fun `an older proposer's certificate is still signable under any parent but a guarded one`(): Unit = runBlocking { + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + parentWith(listOf(alice, bob)) + + // No keys and no policy: what a build before guardians proposed. + assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate()), "under a root group") + + listOf(SubgroupWalletPolicy.UNGUARDED, null).forEach { policy -> + parentIs(policy) + assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate()), "under a parent decided $policy") + } + } + + /** + * D4, at the signers. The picker stops a coordinator choosing this; the + * signers are what stop one who skipped the picker. The undecided case is the + * one a reviewer will want to loosen -- an older proposer's certificate, keys + * and all -- and is here to fail if anybody does: an undecided child is + * offered the plain wallet a guarded parent's subgroups may not have. + */ + @Test + fun `a guarded group's signers refuse anything but a guarded certificate`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + // Proposed while this device still read the parent as a root group -- the + // coordinator's device that saw no parent certificate. + val unguarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) + val undecided = proposedCertificate(parentRoom, ceremonyUnder(null)) + + // The signer's own device holds the parent's certificate. + parentIs(SubgroupWalletPolicy.GUARDED) + + assertEquals( + "would make an unguarded subgroup of a guarded group", + SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, unguarded), + ) + assertEquals( + "would make an unguarded subgroup of a guarded group", + SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, undecided), + ) + assertNull( + SubgroupManager.refuseCertificate( + db, parentRoomId, parentKey, + proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(id = "second-child-ceremony", thresholdPublicKey = siblingMaterial.thresholdPublicKey.value.toHex())), + ), + "a guarded one, with the parent's keys passed on, is signable", + ) + } + + /** A child key state carrying [certificate], unsigned -- the refusal reads its tags and nothing else. */ + private fun keyStateCarrying(certificate: Event) = Event( + id = "e".repeat(64), + pubKey = childRoomId, + createdAt = 1_700_000_000, + kind = GroupKeyStateEvent.KIND, + tags = GroupKeyStateEvent.assembleTags( + chatRoomId = childRoomId, + dkgSessionId = "child-ceremony", + path = path, + parent = SubgroupParentage(parentRoomId, certificate), + ), + content = "", + sig = "", + ) + + @Test + fun `a child signer refuses a certificate under a policy its ceremony did not announce`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val unguarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) + val guarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + val undecided = proposedCertificate(parentRoom, ceremonyUnder(null)) + + // The admins joined a guarded subgroup. + val ceremony = ceremonyUnder(SubgroupWalletPolicy.GUARDED) + assertNotNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(unguarded))) + assertNotNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(undecided)), "undecided is not what they agreed to either") + assertNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(guarded))) + + // An older build's ceremony announced nothing, and has nothing to hold a certificate to. + assertNull(SubgroupManager.refuseKeyState(ceremonyUnder(null), keyStateCarrying(unguarded))) + } + + // ---- the guardian delay: docs/guardian-delay.md, Phase 6 -------------- + + @Test + fun `a guarded ceremony's delay is the parent's own leaf's in the certificate`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + parentIs(SubgroupWalletPolicy.GUARDED) + + val proposed = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 4_320)) + + val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) + assertEquals(listOf(4_320L, GuardianDerivation.DEFAULT_DELAY), granted.map { it.delay }, "the grandparent's keeps its own") + assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentMaterial.thresholdPublicKey.value.toHex(), proposed)) + } + + @Test + fun `an older guarded ceremony is certified at the default delay`(): Unit = runBlocking { + val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + + assertEquals(GuardianDerivation.DEFAULT_DELAY, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.single()?.delay) + } + + @Test + fun `a signer refuses a certificate that changes an ancestor's delay`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + parentIs(SubgroupWalletPolicy.GUARDED) + val proposed = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 144)) + val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) + + // The grandparent's leaf brought closer, which was never this group's to do. + val shortened = certificate( + tags = proposed.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + listOf(granted[0], granted[1].copy(delay = 6)).map(GuardianTag::assemble) + ) + assertEquals("grants guardian keys this group does not", SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, shortened)) + } + + @Test + fun `a child signer refuses a certificate under a delay its ceremony did not announce`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val atDefault = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + val atMonth = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 4_320)) + + val ceremony = ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 4_320) + assertNotNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(atDefault))) + assertNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(atMonth))) + // A ceremony that announced none holds the certificate to no delay. + assertNull(SubgroupManager.refuseKeyState(ceremonyUnder(SubgroupWalletPolicy.GUARDED), keyStateCarrying(atMonth))) + } + // ---- fixtures ---------------------------------------------------------- + /** The certificate [parentRoom] is asked to sign for the child, as the session holds it. */ + private suspend fun proposedCertificate( + parentRoom: LocalChatRoom, + key: DkgSession = completedChildCeremony(), + ): Event { + val session = SubgroupManager.proposeBirthCertificate( + database = db, + parentRoom = parentRoom, + userPublicKey = user, + key = key, + adminPublicKeys = listOf(user, alice, bob), + name = "Translation team", + ) + return Event.fromJson(assertNotNull(db.frostSigningSessionDao().getItems(session.id).firstOrNull()).unsignedEventJson) + } + + /** + * The parent's own key state, naming a grandparent through a certificate + * that grants [guardians]. Filed as `stateFrom` would leave it; nothing here + * re-checks the certificate, which is what having passed `stateFrom` means. + */ + private suspend fun fileParentage( + guardians: List, + walletPolicy: SubgroupWalletPolicy? = null, + ) { + val grandparentRoomId = roomOf(strangerMaterial) + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = parentRoomId, + parentChatRoomId = grandparentRoomId, + thresholdPublicKey = parentMaterial.thresholdPublicKey.value.toHex(), + adminPublicKeys = listOf(user, alice, bob), + name = "Ekklesia", + path = path, + guardians = guardians, + walletPolicy = walletPolicy, + ) + val parentCertificate = certificate(subgroupMaterial = parentMaterial, tags = tags, author = strangerMaterial) + db.groupKeyStateDao().upsert( + GroupKeyState( + chatRoomId = parentRoomId, + dkgSessionId = "parent-ceremony", + thresholdPublicKey = parentMaterial.thresholdPublicKey.value.toHex(), + derivationPath = SharedKeyDerivation.formatPath(path), + announcedBy = parentRoomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = grandparentRoomId, + birthCertificateJson = parentCertificate.toJson(), + ) + ) + } + /** * The NIP-17 room a ceremony runs in, stood up the way the picker does it -- * room first, because `DkgSession.chatRoomId` is a foreign key onto it. diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt deleted file mode 100644 index c4b362d7..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/TranslationBatchProposalJvmTest.kt +++ /dev/null @@ -1,473 +0,0 @@ -package com.machankura.bennu.compose.managers - -import androidx.room3.Room -import com.vitorpamplona.quartz.nip01Core.core.Event -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue -import kotlinx.coroutines.runBlocking -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.builder.getRoomDatabase -import com.machankura.bennu.compose.database.model.ChatMessage -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.DkgParticipantMessage -import com.machankura.bennu.compose.database.model.DkgSession -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.Profile -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.types.DkgRitualStage -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.text.Markdown -import com.machankura.bennu.compose.ui.view.model.AddChapterViewModel -import com.machankura.bennu.compose.ui.view.model.AddTranslationArtifactVersionViewModel - -/** - * What a translation proposal actually puts in front of the group. - * - * The same sharp edge `ChapterBatchProposalJvmTest` covers for a chapter and - * its chunks, one level up: a translation chapter carries the id of the - * translation it belongs to, and that id does not exist until the proposal - * authors the translation under the group's key at the room's derivation path. - * Both are resolved inside `proposeSigningBatch` and neither is knowable to the - * caller, which is why the chapters are built from what it hands back. - * - * If that came apart, the translation would still be signed and every chapter - * would still verify -- against a translation id nobody has. They would fail a - * foreign key on the way in and the translation would simply arrive with no - * chapters, which is a translation nobody can start. - */ -class TranslationBatchProposalJvmTest { - private val participants = 3 - private val threshold = 2 - - /** Stands in for a completed ceremony; the test is about the proposal, not the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() - - /** The admin room: the group's key walked to the admin path, which is its id. */ - private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - - private val ceremonyId = "ceremony".padEnd(64, '0') - private val members = listOf("a", "b", "c").map { it.repeat(64) } - private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } - - private val proposer = members.first() - private val artifactVersionId = "b".repeat(64) - private val dialectId = "d".repeat(64) - - private lateinit var db: BennuDatabase - private lateinit var room: LocalChatRoom - - @AfterTest - fun closeDatabase() { - if (::db.isInitialized) db.close() - } - - /** The proposer's device: a room it can sign in, and the share to sign with. */ - private suspend fun openDevice() { - db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - // Profile hangs off a nostr event, and a room off a profile. Neither is - // anything this test is about; they are the foreign keys in the way. - val nostrEventId = "e$proposer".take(64) - db.nostrEventDao().upsert( - NostrEvent( - id = nostrEventId, - pubKey = proposer, - kind = 0, - tags = emptyArray(), - content = "{}", - sig = "0".repeat(128) - ) - ) - db.profileDao().upsert(Profile(publicKey = proposer, nostrEventId = nostrEventId)) - - val chatRoom = ChatRoom( - id = roomId, - userPublicKey = proposer, - subject = "#Ekklesia", - description = SharedKeyDerivation.describe("Admins of the group."), - mlsGroupState = null - ) - db.chatRoomDao().upsert(chatRoom) - - db.dkgSessionDao().upsert( - DkgSession( - id = ceremonyId, - chatRoomId = roomId, - coordinatorPublicKey = proposer, - userPublicKey = proposer, - threshold = threshold, - participantCount = participants, - stage = DkgRitualStage.COMPLETE, - hostPublicKey = hostKeys[0], - round1Random = "1".repeat(64), - round2AuxRandom = "2".repeat(64), - thresholdPublicKey = thresholdPublicKey, - secretShare = keyMaterial.secretShares[0].value.toHex(), - publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() } - ) - ) - - members.forEachIndexed { index, member -> - db.dkgSessionDao().upsert( - DkgParticipantMessage( - sessionId = ceremonyId, - participantPublicKey = member, - kind = DkgRitualEvents.HOST_KEY, - payload = hostKeys[index] - ) - ) - } - - room = LocalChatRoom(chatRoom = chatRoom) - } - - /** - * The source chapters, as the artifact already holds them. Only the id and - * the position travel into the translation, so nothing else is furnished. - */ - private fun sourceChapters(count: Int): List = (0 until count).map { index -> - MantraChapter( - id = "c$index".padEnd(64, 'f'), - artifactVersionId = artifactVersionId, - publicKey = roomId, - name = "Chapter ${index + 1}", - originalText = "Paragraph ${index + 1}.", - index = index, - wordCount = 2, - characterCount = 13, - signature = "0".repeat(128), - chatRoomId = roomId - ) - } - - private val translationTemplate = TranslationArtifactVersionEvent.build( - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = "Sesotho", - visibility = "private", - license = "cc", - ) - - /** Exactly what `AddTranslationArtifactVersionViewModel.addTranslation` proposes. */ - private suspend fun proposeTranslation(chapters: List) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - lead = translationTemplate, - dependents = { translation -> - TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = chapters.map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - } - ) - - private suspend fun itemEvents(sessionId: String): List = - db.frostSigningSessionDao().getItems(sessionId).map { Event.fromJson(it.unsignedEventJson) } - - @Test - fun `the translation leads the batch and its chapters follow`() = runBlocking { - openDevice() - - val events = itemEvents(proposeTranslation(sourceChapters(3)).id) - - // Item order is apply order, and a translation chapter row whose - // translation does not exist yet is a foreign key violation. The - // translation has to be first. - assertEquals(4, events.size) - assertEquals(TranslationArtifactVersionEvent.KIND, events.first().kind) - assertTrue(events.drop(1).all { it.kind == TranslationChapterEvent.KIND }) - } - - @Test - fun `every chapter names the translation as the group will author it`() = runBlocking { - openDevice() - - val events = itemEvents(proposeTranslation(sourceChapters(3)).id) - val translation = events.first() - - // The claim the whole `lead`/`dependents` form exists for. The id here is - // a hash over the group's key at the room's path; a caller that built the - // chapters before proposing could not have known it. - val chapters = events.drop(1).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - - assertTrue(chapters.all { it.translationArtifactVersionId() == translation.id }) - } - - @Test - fun `each chapter keeps the source chapter it stands in for, and its place`() = runBlocking { - openDevice() - - val source = sourceChapters(3) - val events = itemEvents(proposeTranslation(source).id) - val chapters = events.drop(1).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - - // A translation chapter is only ever a place to hang translated chunks - // off the right source chapter, in the right order. Lose either and the - // translation reads as some other book. - assertEquals(source.map { it.id }, chapters.map { it.chapterId() }) - assertEquals(source.map { it.index }, chapters.map { it.index() }) - } - - @Test - fun `the whole batch is stamped and authored as one act by the room`() = runBlocking { - openDevice() - - val events = itemEvents(proposeTranslation(sourceChapters(3)).id) - - // Signing runs at the path the room was derived at, so the author of - // every item is the room's own id -- chapters included, which is what - // lets one be checked without being told which key to expect. - assertTrue(events.all { it.pubKey == roomId }) - assertTrue(events.none { it.pubKey == proposer }) - - // And they carry the translation's timestamp rather than each reading - // the clock, so the batch is one act rather than events that happen to - // share a session. - assertEquals(listOf(events.first().createdAt), events.map { it.createdAt }.distinct()) - } - - @Test - fun `an artifact of the most chapters allowed still proposes`() = runBlocking { - openDevice() - - val events = itemEvents( - proposeTranslation(sourceChapters(FrostSigningManager.MAX_BATCH_SIZE - 1)).id - ) - - // The arithmetic the form is built on: the translation takes one of the - // batch's places and the chapters get the rest. If this stopped being - // true, the screen would offer a translation the session then refuses. - assertEquals( - FrostSigningManager.MAX_BATCH_SIZE, - AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION + 1 - ) - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, events.size) - } - - /** Exactly what `AddChapterViewModel.addChapter` proposes: the chapter, then its chunks. */ - private suspend fun proposeChapter(paragraphs: Int, index: Int = 0) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - lead = (1..paragraphs).joinToString("\n\n") { "Paragraph $it." }.let { text -> - ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = "Chapter ${index + 1}", - originalText = text, - index = index, - wordCount = Markdown.wordCount(text), - characterCount = Markdown.characterCount(text), - ) - }, - dependents = ChunkEvent::splitOf - ) - - /** And what it proposes straight afterwards: that chapter, into every translation. */ - private suspend fun proposeScaffolding(chapter: Event, index: Int, translationIds: List) = - FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = translationIds, - chapters = listOf(TranslationScaffold.SourceChapter(id = chapter.id, index = index)), - createdAt = chapter.createdAt, - ) - ) - - @Test - fun `a chapter's scaffolding runs beside it as a session of its own`() = runBlocking { - openDevice() - - val translationIds = listOf("1".repeat(64), "2".repeat(64), "3".repeat(64)) - - val chapterSession = proposeChapter(paragraphs = 2) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding(chapter, index = 0, translationIds = translationIds) - - // Two live sessions in one room, which is the whole point: every FROST - // message carries the session it belongs to, so neither is the room's - // "current" one and nothing had to be finished before the second - // opened. - assertNotEquals(chapterSession.id, scaffoldSession.id) - assertEquals(2, db.frostSigningSessionDao().getSessionsForChatRoom(roomId).size) - - // The chapter's batch is what it would have been with no translations - // at all: the chapter and a chunk per paragraph, and nothing else. - val chapterItems = itemEvents(chapterSession.id) - assertEquals(3, chapterItems.size) - assertEquals(ChapterEvent.KIND, chapterItems.first().kind) - assertTrue(chapterItems.drop(1).all { it.kind == ChunkEvent.KIND }) - - // And the scaffolding names that chapter, in every translation. - val scaffolded = itemEvents(scaffoldSession.id).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - assertEquals(translationIds, scaffolded.map { it.translationArtifactVersionId() }) - assertTrue(scaffolded.all { it.chapterId() == chapter.id }) - } - - @Test - fun `each session's transcript lines name it, and never the other`() = runBlocking { - openDevice() - - val chapterSession = proposeChapter(paragraphs = 2) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding( - chapter, - index = 0, - translationIds = listOf("1".repeat(64)) - ) - - val lines = db.chatMessageDao().getChatMessagesByChatRoomId(roomId) - .map { it.chatMessage } - .filter { it.messageType in ChatMessage.FROST_TYPES } - - // Both sessions announce themselves and both publish this device's nonce, - // so the transcript holds one session's lines interleaved with the other's - // -- and every line says which of the two it belongs to. - val bySession = lines.groupBy { it.frostSigningSessionId } - - assertEquals(setOf(chapterSession.id, scaffoldSession.id), bySession.keys) - assertTrue(bySession.values.all { it.isNotEmpty() }) - - // Which is what the transcript's rules are read through. Nothing else on - // these rows can tell them apart: the two sessions are running at the same - // time and write the same types, so before the sessions were on the rows a - // line of one was read as evidence about the other -- and the reader's - // second proposal lost its "Review" the moment the first was answered. - assertTrue( - ChatMessage.answeredRequests(lines).isEmpty(), - "a proposer is never asked to approve their own proposal" - ) - } - - @Test - fun `the two sessions never share nonce material`() = runBlocking { - openDevice() - - val chapterSession = proposeChapter(paragraphs = 2) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding( - chapter, - index = 0, - translationIds = listOf("1".repeat(64), "2".repeat(64)) - ) - - // The one thing concurrency could get wrong. Two partial signatures - // under a single secret nonce are two equations in one unknown, and the - // share falls out; seeds are minted per item per session precisely so - // that running two at once cannot arrange it. - val seeds = ( - db.frostSigningSessionDao().getItems(chapterSession.id) + - db.frostSigningSessionDao().getItems(scaffoldSession.id) - ).map { it.nonceRandom } - - assertEquals(5, seeds.size) - assertEquals(seeds.size, seeds.distinct().size) - } - - @Test - fun `the caps do not compete`() = runBlocking { - openDevice() - - // The reason the scaffolding is a second session rather than more items - // on the chapter's. A chapter of the longest allowed length still - // proposes with translations waiting for it; sharing one batch, every - // dialect the group worked in would have cost it a paragraph. - val translationIds = (1..8).map { it.toString().repeat(64).take(64) } - - val chapterSession = proposeChapter(paragraphs = AddChapterViewModel.MAX_CHUNKS_PER_CHAPTER) - val chapter = itemEvents(chapterSession.id).first() - val scaffoldSession = proposeScaffolding(chapter, index = 0, translationIds = translationIds) - - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, itemEvents(chapterSession.id).size) - assertEquals(translationIds.size, itemEvents(scaffoldSession.id).size) - } - - @Test - fun `an artifact longer than one session is split across two`() = runBlocking { - openDevice() - - // What `addTranslation` does with an artifact past the cap: the - // translation and as many chapters as fit, then the rest naming the - // translation the first session is about to sign. Refusing instead - // would be a cap on how long a book may be, dressed up as a cap on a - // batch. - val chapters = sourceChapters(AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION + 3) - - val first = proposeTranslation( - chapters.take(AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION) - ) - val translation = itemEvents(first.id).first() - val second = FrostSigningManager.proposeSigningBatch( - database = db, - localChatRoom = room, - userPublicKey = proposer, - events = TranslationScaffold.chaptersOf( - translationArtifactVersionIds = listOf(translation.id), - chapters = chapters.drop(AddTranslationArtifactVersionViewModel.MAX_CHAPTERS_PER_TRANSLATION) - .map(TranslationScaffold.SourceChapter::of), - createdAt = translation.createdAt, - ) - ) - - assertEquals(FrostSigningManager.MAX_BATCH_SIZE, itemEvents(first.id).size) - assertEquals(3, itemEvents(second.id).size) - - // Every chapter of the work is covered exactly once, across both, and - // each names the translation as the group will author it. - val scaffolded = (itemEvents(first.id).drop(1) + itemEvents(second.id)).map { - TranslationChapterEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig) - } - assertEquals(chapters.map { it.id }, scaffolded.map { it.chapterId() }) - assertEquals(chapters.map { it.index }, scaffolded.map { it.index() }) - assertTrue(scaffolded.all { it.translationArtifactVersionId() == translation.id }) - } - - @Test - fun `one session is still refused a chapter too many`() = runBlocking { - openDevice() - - // Refused rather than truncated: a batch that quietly dropped its last - // chapters would sign a translation the group believes covers the whole - // work while the end of it can never be translated. The screen splits - // before it gets here, so this is never what a member sees -- but the - // screen is not what enforces it. - assertFailsWith { - proposeTranslation(sourceChapters(FrostSigningManager.MAX_BATCH_SIZE)) - } - - assertEquals(emptyList(), db.frostSigningSessionDao().getSessionsForChatRoom(roomId)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt new file mode 100644 index 00000000..27e0b859 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt @@ -0,0 +1,134 @@ +package com.machankura.bennu.compose.nostr.wallet + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.managers.GroupFixtures +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.MemberWalletDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.managers.SubgroupManager +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * A group's certificate that it guards a member's wallet: believed when it is + * exactly the group's signature over the request it carries, and never mistaken + * for a birth certificate by anything that reads those. + */ +class MemberWalletCertificateEventJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletKey = walletPrivateKey.publicKey() + private val walletId = MemberWalletDerivation.walletId(walletKey) + + private fun request(guardians: List = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, emptyList(), walletId)) = + MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = groupRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletKey, chain, guardians), + label = "Savings", + createdAt = 1_700_000_000, + ) + + private fun certified(request: Event = request(), signer: KeyMaterial = group): Event { + val template = MemberWalletCertificateEvent.template(request) + return signedAsRoom(signer, MemberWalletCertificateEvent.KIND, template.tags, template.content, createdAt = template.createdAt) + } + + private fun Event.withTags(tags: Array>, signer: KeyMaterial = group): Event = + signedAsRoom(signer, kind, tags, content, createdAt) + + @Test + fun `a certificate the group signed over the request is believed`() { + val verified = assertNotNull(MemberWalletCertificateEvent.verify(certified(), groupRoom)) + assertEquals(member.xOnlyPublicKey().value.toHex(), verified.memberPublicKey) + assertEquals(walletId, verified.walletId) + assertEquals("Savings", verified.label) + assertEquals(groupRoom, verified.groupChatRoomId) + assertTrue(verified.account.isGuarded) + } + + @Test + fun `two sponsors propose one event`() { + assertEquals(certified().id, certified().id) + } + + @Test + fun `a certificate another room signed is refused`() { + assertNull(MemberWalletCertificateEvent.verify(certified(signer = stranger), groupRoom)) + } + + @Test + fun `a certificate over a request to another group is refused`() { + // The stranger signs a request that asked the group: the request is real, the group is not the one asked. + val strangerRoom = roomOf(stranger) + assertNull(MemberWalletCertificateEvent.verify(certified(signer = stranger), strangerRoom)) + } + + @Test + fun `a certificate naming another member is refused`() { + val certificate = certified() + val other = privateKey(0xb0b).xOnlyPublicKey().value.toHex() + val tags = certificate.tags.map { if (it[0] == "p") arrayOf("p", other) else it }.toTypedArray() + assertNull(MemberWalletCertificateEvent.verify(certificate.withTags(tags), groupRoom)) + } + + @Test + fun `a guardian swapped against its request is refused`() { + val certificate = certified() + val swapped = GuardianDerivation.grant(thresholdKeyOf(stranger), groupRoom, emptyList(), walletId).single() + val tags = certificate.tags.map { if (it[0] == "guardian") GuardianTag.assemble(swapped) else it }.toTypedArray() + assertNull(MemberWalletCertificateEvent.verify(certificate.withTags(tags), groupRoom)) + } + + @Test + fun `a member wallet certificate is never a subgroup`(): Unit = runBlocking { + val certificate = certified() + assertFalse(SubgroupBirthCertificateEvent.certifies(certificate, walletId, groupRoom)) + + GroupFixtures.seedRoom(db, groupRoom) + db.groupSignedEventDao().upsert( + GroupSignedEvent.fromEvent( + event = certificate, + chatRoomId = groupRoom, + derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), + frostSigningSessionId = null, + ) + ) + assertEquals(emptyList(), SubgroupManager.subgroupsOf(db, groupRoom), "a reader of 30329 never sees a 30334") + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt index 2e0c0980..675ab4a5 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/StringCatalogueJvmTest.kt @@ -5,10 +5,12 @@ import bennu.composeapp.generated.resources.Res import bennu.composeapp.generated.resources.currently_no_messages_have_been_shared import bennu.composeapp.generated.resources.don_t_sign import bennu.composeapp.generated.resources.something_went_wrong -import bennu.composeapp.generated.resources.add_chapter_to -import bennu.composeapp.generated.resources.chapter_words_characters +import bennu.composeapp.generated.resources.recovered_of_still_unreadable import bennu.composeapp.generated.resources.sent_a_private_message_to import org.jetbrains.compose.resources.getString +import org.jetbrains.compose.resources.getPluralString +import bennu.composeapp.generated.resources.about_n_hours +import bennu.composeapp.generated.resources.n_blocks import kotlin.test.Test import kotlin.test.assertEquals @@ -56,8 +58,8 @@ class StringCatalogueJvmTest { // and reads plausibly -- "Recovered 3 of 12" against "Recovered 12 of 3" -- so // the ordering is worth asserting on a multi-argument one. assertEquals( - "Add chapter to Genesis", - getString(Res.string.add_chapter_to, "Genesis"), + "Recovered 3 of 12 · 9 still unreadable.", + getString(Res.string.recovered_of_still_unreadable, "3", "12", "9", "."), ) assertEquals( "Ada sent a private message to Grace", @@ -71,8 +73,18 @@ class StringCatalogueJvmTest { // decodes it and the resource holds the character. If it had been left alone the // app would render the six characters of the escape. assertEquals( - "Chapter 3 · 900 words · 4800 characters", - getString(Res.string.chapter_words_characters, "3", "900", "4800"), + "Recovered 3 of 12 · 9 still unreadable", + getString(Res.string.recovered_of_still_unreadable, "3", "12", "9", ""), ) } + + @Test + fun `a plural picks its form by the count, and substitutes it`() = runBlocking { + // The catalogue's first plurals, for a guardian's delay. A plain + // `%1$d hours` reads "about 1 hours", and no audit catches that. + assertEquals("about 1 hour", getPluralString(Res.plurals.about_n_hours, 1, 1)) + assertEquals("about 36 hours", getPluralString(Res.plurals.about_n_hours, 36, 36)) + assertEquals("1 block", getPluralString(Res.plurals.n_blocks, 1, "1")) + assertEquals("65,535 blocks", getPluralString(Res.plurals.n_blocks, 65_535, "65,535")) + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt deleted file mode 100644 index a1ffe4fc..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt +++ /dev/null @@ -1,240 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextInput -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState -import kotlin.test.Test -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * What the broadcast screen shows before, and after, the button. - * - * Before: the event named as the signing screen would name it, the relays the - * group has said it lives at already in the list, and a way to add one. After: - * each relay's answer under its own row, in the relay's words where it gave - * any, and the sum above them -- because the sum is what the member came for and - * the words are what they can act on. - */ -@OptIn(ExperimentalTestApi::class) -class BroadcastGroupSignedEventScreenJvmTest { - - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - /** A pool that answers as told and never opens a socket. */ - private class FakeTransport( - private val answers: List - ) : EventPublishTransport { - override suspend fun publishEvent( - nostrEvent: NostrEvent, - relays: Set - ): Flow = flowOf(*answers.toTypedArray()) - } - - @Test - fun `the event is named, the group's relays are filled in, and the JSON is there to copy`() = - render(state()) { - onNodeWithText("Post").assertIsDisplayed() - onNodeWithText("The first chapter is out.").assertIsDisplayed() - - // The group's own General list, as hosts. - onNodeWithText("relay.one.example").assertIsDisplayed() - onNodeWithText("relay.two.example").assertIsDisplayed() - - onNodeWithText("Broadcast").assertIsDisplayed() - onNodeWithText("Copy raw JSON").assertIsDisplayed() - - // The relays come before the JSON: the list is the screen's job and - // the JSON is for whoever would rather use a different tool. - val relays = onNodeWithText("relay.one.example").getBoundsInRoot().top - val json = onNodeWithText("The signed event").getBoundsInRoot().top - assertTrue(relays < json, "the JSON climbed above the relay list") - } - - @Test - fun `a relay can be added, and a bad one is refused by name`() = render(state()) { - onNodeWithText("Relay url").performTextInput("wss://relay.three.example") - onNodeWithContentDescription("Add relay").performClick() - onNodeWithText("relay.three.example").assertIsDisplayed() - - onNodeWithText("Relay url").performTextInput("not a relay") - onNodeWithContentDescription("Add relay").performClick() - onNodeWithText("That isn't a relay address.", substring = true).assertIsDisplayed() - } - - @Test - fun `after the button, each relay says what it answered and the sum sits above them`() = - render( - uiState = state(), - transport = FakeTransport( - listOf( - NostrPublishResult( - result = NostrIncomingMessage.OkMessage(eventId = "b".repeat(64), success = true), - relayUrl = one.url, - ), - NostrPublishResult( - result = NostrIncomingMessage.OkMessage( - eventId = "b".repeat(64), - success = false, - message = "blocked: not on the allow list", - ), - error = NostrPublishException(message = "blocked: not on the allow list"), - relayUrl = two.url, - ), - ) - ) - ) { - onNodeWithContentDescription("Broadcast to these relays").performClick() - - waitUntil(timeoutMillis = 5_000) { - onAllNodesWithText("Accepted by 1 of 2 relays.").fetchSemanticsNodes().isNotEmpty() - } - - onNodeWithText("Accepted").assertIsDisplayed() - onNodeWithText("Rejected: blocked: not on the allow list").assertIsDisplayed() - - // The answer under the relay it came from, not in a list of its own. - val relayOne = onNodeWithText("relay.one.example").getBoundsInRoot().top - val accepted = onNodeWithText("Accepted").getBoundsInRoot().top - val relayTwo = onNodeWithText("relay.two.example").getBoundsInRoot().top - val rejected = onNodeWithText("Rejected: blocked: not on the allow list").getBoundsInRoot().top - assertTrue(relayOne < accepted && accepted < relayTwo, "the OK is not under its relay") - assertTrue(relayTwo < rejected, "the rejection is not under its relay") - } - - @Test - fun `an empty list asks nobody and says to add one`() = render( - state(relayLists = GroupRelayList.allAmong(emptyList(), chatRoomId), seedNothing = true) - ) { - onNodeWithText("No relays to broadcast to. Add one above.").assertIsDisplayed() - } - - private fun signedEvent() = GroupSignedEvent( - id = "b".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = TextNoteEvent.KIND, - tags = emptyArray(), - content = "The first chapter is out.", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - /** A General list of two relays, agreed, so the screen has something of the group's to fill in. */ - private fun agreedRelayLists(): List = - GroupRelayList.allAmong(emptyList(), chatRoomId).map { list -> - if (list.set != GroupRelaySet.General) return@map list - - GroupRelayList( - set = list.set, - signedEvent = GroupSignedEvent( - id = "a".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = list.set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - relays = listOf(GroupRelay(one), GroupRelay(two)), - ) - } - - /** - * [seedNothing] blocks every relay the seed would otherwise fall back to, so - * the screen can be seen with an empty list -- a group that has agreed - * nothing is filled in from the app's own set, which is the point of the - * fallback and the opposite of what this fixture wants. - */ - private fun state( - relayLists: List = agreedRelayLists(), - seedNothing: Boolean = false, - ) = BroadcastGroupSignedEventUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - signedEvent = signedEvent(), - relayLists = if (seedNothing) { - relayLists.map { list -> - if (list.set != GroupRelaySet.Blocked) return@map list - - GroupRelayList( - set = list.set, - signedEvent = null, - relays = Relays.eventPublishRelaySet.map { GroupRelay(it) }, - ) - } - } else { - relayLists - }, - ) - - private fun render( - uiState: BroadcastGroupSignedEventUIState, - transport: EventPublishTransport = FakeTransport(emptyList()), - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 1600) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - BroadcastGroupSignedEventScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = "b".repeat(64), - initialBroadcastGroupSignedEventUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = transport, - onNavigateBack = {} - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt index dc3ce8d2..a6b45afe 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMemberRowJvmTest.kt @@ -12,7 +12,6 @@ import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId @@ -112,7 +111,6 @@ class ChatRoomMemberRowJvmTest { initialChatRoomDetailUIState = state(), nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, onNavigateToRoute = onNavigateToRoute, onPopBackToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt deleted file mode 100644 index ef996630..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt +++ /dev/null @@ -1,153 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupNostrProfileUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The group's nostr profile on its own screen: what is drawn, what the - * broadcast under it sends, and who is offered the editor. - */ -@OptIn(ExperimentalTestApi::class) -class GroupNostrProfileScreenJvmTest { - - @Test - fun `the profile is drawn whole, with its broadcast under it`() { - var opened: Route? = null - - render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { - onNodeWithText("Translation collective").assertIsDisplayed() - onNodeWithText("group@example.com").assertIsDisplayed() - onNodeWithText("A group translating hard books into Sesotho.").assertIsDisplayed() - onAllNodesWithText("Signed by the group on", substring = true).assertCountEquals(1) - - // One, under the card it sends, and it sends the profile's event. - val buttons = onAllNodesWithText("Broadcast") - buttons.assertCountEquals(1) - val card = onNodeWithText("group@example.com").getBoundsInRoot().top - assertTrue(card < buttons[0].getBoundsInRoot().top, "the broadcast is not under the card") - - buttons[0].performClick() - } - - assertEquals( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = profile.signedEvent.id - ), - opened - ) - } - - @Test - fun `a member holding a share of the key is offered the editor`() { - var opened: Route? = null - - render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { - onNodeWithText("Edit Nostr profile").assertIsDisplayed().performClick() - } - - assertEquals( - EditGroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), - opened - ) - } - - @Test - fun `a member holding no share of the key reads the profile and is offered no edit`() = render( - state(groupNostrProfile = profile, canSign = false) - ) { - // The profile is worth reading whoever is looking; proposing one needs a - // share, and `proposeSigningBatch` throws without one. The broadcast - // stays: the signature is the group's whoever repeats it. - onNodeWithText("Translation collective").assertIsDisplayed() - onNodeWithText("Edit Nostr profile").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(1) - } - - @Test - fun `a group that has said nothing says so, and offers to say something`() = render( - state(groupNostrProfile = null) - ) { - onNodeWithText("This group hasn't said anything about itself on Nostr yet.") - .assertIsDisplayed() - onNodeWithText("Edit Nostr profile").assertIsDisplayed() - - // Nothing signed, so nothing to send. - onAllNodesWithText("Broadcast").assertCountEquals(0) - } - - @Test - fun `a group that has said nothing offers no editor to a member holding no share`() = render( - state(groupNostrProfile = null, canSign = false) - ) { - onNodeWithText("This group hasn't said anything about itself on Nostr yet.") - .assertIsDisplayed() - onNodeWithText("Edit Nostr profile").assertDoesNotExist() - } - - private fun state( - groupNostrProfile: GroupNostrProfile?, - canSign: Boolean = true - ) = GroupNostrProfileUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupNostrProfile = groupNostrProfile, - canSign = canSign - ) - - /** - * The screen at a phone's width. The state is passed in, so the NO_OP - * repository is never asked for anything: `initiate` only runs for a screen - * that arrives loading. - */ - private fun render( - uiState: GroupNostrProfileUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupNostrProfileScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupNostrProfileUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt deleted file mode 100644 index 21ee20b8..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt +++ /dev/null @@ -1,167 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.post -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupPostsUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The group's posts on their own screen: newest first and whole, under the - * group's name, each with its broadcast, and the composer for a member holding - * a share. - */ -@OptIn(ExperimentalTestApi::class) -class GroupPostsScreenJvmTest { - - @Test - fun `the posts are drawn newest first, under the group's name`() = render( - state(posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000))) - ) { - // Newest first, and whole rather than previewed -- a post is the one thing - // the group signs that exists to be read. - val newest = onNodeWithText("The second thing").getBoundsInRoot().top - val oldest = onNodeWithText("The first thing").getBoundsInRoot().top - assertTrue(newest < oldest, "the posts were drawn oldest first") - - // Under the group's name, not the member's. The whole point of signing a - // post as the group is that no member can be blamed for it. Once per - // post: there is no profile card on this screen to add a third. - onAllNodesWithText("Translation collective").assertCountEquals(2) - onNodeWithText("Add post").assertIsDisplayed() - } - - @Test - fun `a group that has not described itself bylines its posts with the key`() = render( - state(posts = listOf(post("Something the group said", 1_700_000_000)), groupNostrProfile = null) - ) { - onNodeWithText("Something the group said").assertIsDisplayed() - onNodeWithText(chatRoomId.take(16).chunked(8).joinToString(" ")).assertIsDisplayed() - } - - @Test - fun `every post offers a broadcast under its card`() { - var opened: Route? = null - - render( - state(posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000))), - onNavigateToRoute = { opened = it } - ) { - val buttons = onAllNodesWithText("Broadcast") - buttons.assertCountEquals(2) - - val newest = onNodeWithText("The second thing").getBoundsInRoot().top - val oldest = onNodeWithText("The first thing").getBoundsInRoot().top - val first = buttons[0].getBoundsInRoot().top - val second = buttons[1].getBoundsInRoot().top - - assertTrue(newest < first && first < oldest, "the first post's broadcast is not under its card") - assertTrue(oldest < second, "the second post's broadcast is not under its card") - - buttons[1].performClick() - } - - assertEquals( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = post("The first thing", 1_700_000_000).signedEvent.id - ), - opened - ) - } - - @Test - fun `a group that has posted nothing says so, and offers to post`() { - var opened: Route? = null - - render(state(posts = emptyList()), onNavigateToRoute = { opened = it }) { - onNodeWithText("This group hasn't posted anything yet.").assertIsDisplayed() - onAllNodesWithText("Broadcast").assertCountEquals(0) - onNodeWithText("Add post").assertIsDisplayed().performClick() - } - - assertEquals(AddGroupPostRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) - } - - @Test - fun `a member holding no share of the key reads the posts and is offered no composer`() = render( - state(posts = listOf(post("Something the group said", 1_700_000_000)), canSign = false) - ) { - // A post is the one thing here that is meant to be read by people who - // were not in the room, so a member without a share reads it like - // anybody else and simply cannot propose the next one. - onNodeWithText("Something the group said").assertIsDisplayed() - onNodeWithText("Add post").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(1) - } - - @Test - fun `a group that has posted nothing offers no composer to a member holding no share`() = render( - state(posts = emptyList(), canSign = false) - ) { - onNodeWithText("This group hasn't posted anything yet.").assertIsDisplayed() - onNodeWithText("Add post").assertDoesNotExist() - } - - private fun state( - posts: List, - groupNostrProfile: GroupNostrProfile? = profile, - canSign: Boolean = true - ) = GroupPostsUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupPosts = posts, - groupNostrProfile = groupNostrProfile, - canSign = canSign - ) - - private fun render( - uiState: GroupPostsUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupPostsScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupPostsUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt deleted file mode 100644 index 0e8368fa..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt +++ /dev/null @@ -1,139 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.relaySignedEvent -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.signedRelayLists -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupRelaysUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The group's relay lists on their own screen: a row per set whatever the - * group has said, a broadcast under each list it has agreed, and the editor - * for a member holding a share. - */ -@OptIn(ExperimentalTestApi::class) -class GroupRelaysScreenJvmTest { - - @Test - fun `every set gets a row, and the two absences read differently`() = render(state()) { - onNodeWithText("General").assertIsDisplayed() - onNodeWithText("relay.one.example").assertIsDisplayed() - onNodeWithText("Messages").assertIsDisplayed() - onNodeWithText("Search").assertIsDisplayed() - onNodeWithText("Blocked").assertIsDisplayed() - // Two of them, because Messages and Search are both unagreed -- and the - // count is the assertion: a row per set, not a row per set the group has - // got round to. The blocked list was agreed empty, which is a decision - // and reads as one. - onAllNodesWithText("Not set yet").assertCountEquals(2) - onNodeWithText("No relays in this list").assertIsDisplayed() - } - - @Test - fun `every agreed list offers a broadcast under its row, the withdrawn one included`() { - var opened: Route? = null - - render(state(), onNavigateToRoute = { opened = it }) { - // The two the group has agreed -- the withdrawn one included, since a - // withdrawal is a statement relays still holding the old list need to - // hear -- and not the two it has never agreed, which are not events. - val buttons = onAllNodesWithText("Broadcast") - buttons.assertCountEquals(2) - - val general = onNodeWithText("General").getBoundsInRoot().top - val blocked = onNodeWithText("Blocked").getBoundsInRoot().top - val first = buttons[0].getBoundsInRoot().top - val second = buttons[1].getBoundsInRoot().top - - assertTrue(general < first && first < blocked, "the general list's broadcast is not under its row") - assertTrue(blocked < second, "the blocked list's broadcast is not under its row") - - buttons[1].performClick() - } - - assertEquals( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = relaySignedEvent(GroupRelaySet.Blocked).id - ), - opened - ) - } - - @Test - fun `a member holding a share of the key is offered the editor`() { - var opened: Route? = null - - render(state(), onNavigateToRoute = { opened = it }) { - onNodeWithText("Edit relays").assertIsDisplayed().performClick() - } - - assertEquals(EditGroupRelaysRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) - } - - @Test - fun `a member holding no share of the key reads the relays and is offered no edit`() = render( - state(canSign = false) - ) { - onNodeWithText("General").assertIsDisplayed() - onNodeWithText("relay.one.example").assertIsDisplayed() - onNodeWithText("Edit relays").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(2) - } - - private fun state(canSign: Boolean = true) = GroupRelaysUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupRelayLists = signedRelayLists(), - canSign = canSign - ) - - private fun render( - uiState: GroupRelaysUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupRelaysScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupRelaysUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt index 197071e3..d6c1de2c 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.managers.GuardianDerivation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.ui.Modifier @@ -19,6 +20,9 @@ import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.FundingTarget +import com.vitorpamplona.quartz.nip01Core.core.Event import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.repository.ChatRepository @@ -106,6 +110,43 @@ class GroupSendScreenJvmTest { onNodeWithText("Ask the group to send").assertIsNotEnabled() } + @Test + fun `funding a guarded wallet names it, shows where it pays, and takes no address`() = render(Chain.Regtest, funded = true) { + onNodeWithText("Fund Savings's guarded wallet").assertIsDisplayed() + onNodeWithText("Savings's guarded wallet").assertIsDisplayed() + onNodeWithText("Address").assertDoesNotExist() + onNodeWithText("Address 2").assertIsDisplayed() + // This group's own leaf's delay in the funded wallet, in blocks alone on regtest. + onNodeWithText("This group can spend these coins again once they have waited 12 blocks.").assertIsDisplayed() + + onNodeWithText("Fee rate in sats per byte").performTextInput("4") + onNodeWithText("Amount in sats").performTextInput("40000") + onNodeWithText("Sends 40,000 sats to Savings's guarded wallet", substring = true).assertIsDisplayed() + onNodeWithText("Ask the group to send").assertIsEnabled() + } + + private fun funding(chain: Chain): FundingTarget { + val descendantRoomId = "c".repeat(64) + // Guarded by this room, at the default delay, as a verified statement would be. + val descendant = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), chain, + guardians = GuardianDerivation.grant(PrivateKey(ByteVector32(Hex.decode("a11ce".padStart(64, '0')))).publicKey().toString(), chatRoomId, emptyList(), descendantRoomId), + ) + val guarded = GuardianManager.GuardedWallet( + ancestorChatRoomId = chatRoomId, + descendantChatRoomId = descendantRoomId, + statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), + account = descendant, + certificate = Event("2".repeat(64), chatRoomId, 1_700_000_000, 0, arrayOf(arrayOf("name", "Savings")), "", ""), + lineage = listOf(descendantRoomId), + ) + val receive = (0 until 10).associate { index -> + GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, index.toLong()).address(chain) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) + } + return FundingTarget(guarded, GroupWalletState(descendant, WalletState(receive), WalletState.empty, tipHeight = 110)) + } + private fun ComposeUiTest.fill(address: String, amount: String) { onNodeWithText("Address").performTextInput(address) onNodeWithText("Fee rate in sats per byte").performTextInput("4") @@ -146,7 +187,7 @@ class GroupSendScreenJvmTest { return GroupSendUIState.Ready(room, wallet, walletState, reserved = emptySet()) } - private fun render(chain: Chain, assertions: ComposeUiTest.() -> Unit) = + private fun render(chain: Chain, funded: Boolean = false, assertions: ComposeUiTest.() -> Unit) = runDesktopComposeUiTest(width = 400, height = 1200) { setContent { BennuTheme { @@ -156,7 +197,7 @@ class GroupSendScreenJvmTest { activeUserPublicKey = "a".repeat(64), chatRoomId = chatRoomId, chain = chain, - initialGroupSendUIState = ready(chain), + initialGroupSendUIState = ready(chain).let { if (funded) it.copy(funding = funding(chain)) else it }, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, wallets = null, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt index f1ab7895..d04e9580 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt @@ -1,27 +1,16 @@ package com.machankura.bennu.compose.ui.composable -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GroupKeyState -import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet import kotlin.time.Instant /** - * One group's signed work, for the six screens that show it: the group's own, - * where a row names each kind, and the five behind those rows. + * One group, for the screens that show it. * - * Everything here is built rather than read out of a signed event. The reading - * checks a real signature, and these tests are about the screens rather than - * about that -- so nothing here verifies, and none of the keys derive. + * Everything here is built rather than read out of a signed event, and these + * tests are about the screens rather than about signatures -- so nothing here + * verifies, and none of the keys derive. */ internal object GroupSignedWorkFixtures { @@ -29,13 +18,7 @@ internal object GroupSignedWorkFixtures { val activeUserPublicKey = "a".repeat(64) - /** - * The room, as this device names it. - * - * The subject is deliberately not the profile's name: the room's subject is - * this device's name for it and the profile is the group's own, and a test - * that used one string for both could not tell them apart. - */ + /** The room, as this device names it. */ fun localChatRoom(mlsGroupState: String? = "state") = LocalChatRoom( chatRoom = ChatRoom( id = chatRoomId, @@ -48,9 +31,8 @@ internal object GroupSignedWorkFixtures { ) /** - * A key state, so the signing key row the identity block sits under is on - * the group's screen to be measured against. Not a real key: nothing here - * derives. + * A key state, so the signing key row is on the group's screen. Not a real + * key: nothing here derives. */ val groupKeyState = GroupKeyState( chatRoomId = chatRoomId, @@ -60,69 +42,4 @@ internal object GroupSignedWorkFixtures { announcedBy = chatRoomId, announcedAt = Instant.fromEpochSeconds(1_700_000_000) ) - - val profile = GroupNostrProfile( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - metadata = UserMetadata().apply { - displayName = "Translation collective" - about = "A group translating hard books into Sesotho." - nip05 = "group@example.com" - } - ) - - /** - * Two agreed sets and two absences, which is the only fixture that exercises - * the three things a relay row can say: a list, "not set yet", and "no - * relays". - */ - fun signedRelayLists(): List = GroupRelaySet.entries.map { set -> - when (set) { - GroupRelaySet.General -> GroupRelayList( - set = set, - signedEvent = relaySignedEvent(set), - relays = listOf(GroupRelay(RelayUrlNormalizer.normalize("wss://relay.one.example"))) - ) - // Agreed and empty: the group withdrew its list rather than never - // having had one. - GroupRelaySet.Blocked -> GroupRelayList( - set = set, - signedEvent = relaySignedEvent(set), - relays = emptyList() - ) - else -> GroupRelayList(set = set, signedEvent = null, relays = emptyList()) - } - } - - fun relaySignedEvent(set: GroupRelaySet) = GroupSignedEvent( - id = "a" + set.kind.toString().padStart(5, '0') + "0".repeat(58), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ) - - fun post(content: String, createdAt: Long) = GroupPost( - signedEvent = GroupSignedEvent( - id = createdAt.toString().padStart(64, 'b'), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = TextNoteEvent.KIND, - tags = emptyArray(), - content = content, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt) - ) - ) } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt index d652b4f6..5b20a102 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -5,214 +5,87 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.ui.Modifier import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.runDesktopComposeUiTest -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.MantraRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.post -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.signedRelayLists -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost import com.machankura.bennu.compose.ui.theme.BennuTheme import com.machankura.bennu.compose.ui.view.state.ChatRoomDetailUIState +import com.machankura.bennu.compose.wallet.GroupWalletRollout import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue /** - * The three rows on the group's screen that stand for its signed work, and what - * each one opens. + * The row on the group's screen that stands for its signed work, and what it + * opens. * - * The rows' contents need little testing -- a name and a count in a `ListItem` - * -- but three things about them do, and none is settled by reading the screen - * top to bottom. - * - * **Their place in the order.** They go under what the room *is* -- the key it - * signs as and whose child it is -- and above what the room has *made*, because - * the group's account of itself is part of its identity rather than part of its - * work; and among themselves they read as a chain, from who the group says it is - * to what it has said. That ordering is an intention a later `item {}` in - * the wrong place would silently undo, and the screen is long enough that - * nobody would notice. - * - * **What they open.** A row is a promise about the screen behind it, and three - * rows that look alike are three chances to wire one to the wrong route. - * - * **Their absence in a NIP-17 room.** A NIP-17 room's id is a conversation, not - * a key it can sign as, so it has no nostr identity and never will. A row there - * would promise something that is not coming, which is worse than saying - * nothing. + * The group's nostr profile, relay lists and posts had rows here, and a paste + * for proposing any of them; they are gone, and the wallet is what is left. */ @OptIn(ExperimentalTestApi::class) class GroupSignedWorkRowsJvmTest { @Test - fun `the rows sit under the signing key and above the group's work, in the order the block reads`() = - render(state(groupNostrProfile = profile)) { - val signingKey = onNodeWithText("Signing key").getBoundsInRoot().top - val nostrProfile = onNodeWithText("Nostr profile").getBoundsInRoot().top - val relays = onNodeWithText("Relays").getBoundsInRoot().top - val posts = onNodeWithText("Posts").getBoundsInRoot().top - val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top + fun `the wallet row sits under the signing key and above the subgroups`() = render(state()) { + if (!GroupWalletRollout.ENABLED) return@render - assertTrue(signingKey < nostrProfile, "the nostr profile row climbed above the signing key row") - assertTrue(nostrProfile < relays, "the relays row climbed above the profile") - assertTrue(relays < posts, "the posts row climbed above the relays") - assertTrue(posts < subgroups, "the identity block fell below the group's work") - } - - @Test - fun `each row says what its screen holds`() = render( - state( - groupNostrProfile = profile, - relayLists = signedRelayLists(), - posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000)), - ) - ) { - // The group's own name and address, not the room's subject: the row is - // about what the rest of nostr sees. - onNodeWithText("Translation collective · group@example.com").assertIsDisplayed() - // Counted against the four sets, the withdrawn one included: an agreed - // empty list is a decision, and the row counts decisions. - onNodeWithText("2 of 4 lists agreed").assertIsDisplayed() - onNodeWithText("2 posts").assertIsDisplayed() - } - - @Test - fun `a group that has signed nothing has rows that say so`() = render( - state(groupNostrProfile = null) - ) { - onNodeWithText("Not described yet").assertIsDisplayed() - onNodeWithText("0 of 4 lists agreed").assertIsDisplayed() - onNodeWithText("No posts yet").assertIsDisplayed() - } - - @Test - fun `a profile with no name is not named after the key`() = render( - state( - groupNostrProfile = GroupNostrProfile( - signedEvent = profile.signedEvent, - metadata = UserMetadata() - ) - ) - ) { - // The signing key row already shows the key, and showing it twice would - // say the group has a name when it has not. - onNodeWithText("No name on this profile").assertIsDisplayed() - } - - @Test - fun `each row opens the screen for its section`() { - val expected = mapOf( - "Nostr profile" to GroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), - "Relays" to GroupRelaysRoute(activeUserPublicKey, chatRoomId, relayHint = null), - "Posts" to GroupPostsRoute(activeUserPublicKey, chatRoomId, relayHint = null), - ) - - expected.forEach { (row, route) -> - var opened: Route? = null - - render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { - onNodeWithText(row).performClick() - } - - assertEquals(route, opened, "the $row row opened the wrong screen") - } - } - - @Test - fun `the contents stay off the group's screen`() = render( - state( - groupNostrProfile = profile, - relayLists = signedRelayLists(), - posts = listOf(post("Something the group said", 1_700_000_000)), - ) - ) { - // The rows summarise; the cards, their broadcasts and the gated ways in - // are on the screens behind them. A card that stayed here would be the - // old section under a new name. - onNodeWithText("A group translating hard books into Sesotho.").assertDoesNotExist() - onNodeWithText("relay.one.example").assertDoesNotExist() - onNodeWithText("Something the group said").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(0) - onNodeWithText("Edit Nostr profile").assertDoesNotExist() - onNodeWithText("Edit relays").assertDoesNotExist() - onNodeWithText("Add post").assertDoesNotExist() - } - - @Test - fun `a member holding a share of the key may propose any event the rows can open`() = render( - state(groupNostrProfile = profile) - ) { - // Last in the identity block: after the rows and before the divider, - // because it is about the whole block rather than any one row of it. - val posts = onNodeWithText("Posts").getBoundsInRoot().top - val propose = onNodeWithText("Propose event").getBoundsInRoot().top + val signingKey = onNodeWithText("Signing key").getBoundsInRoot().top + val wallet = onNodeWithText(WALLET_ROW).getBoundsInRoot().top val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top - assertTrue(posts < propose, "the paste entry climbed above the rows") - assertTrue(propose < subgroups, "the paste entry fell out of the identity block") + assertTrue(signingKey < wallet, "the wallet row climbed above the signing key row") + assertTrue(wallet < subgroups, "the wallet row fell below the group's subgroups") } @Test - fun `a member holding no share of the key is offered no paste`() = render( - state(groupNostrProfile = profile, canEditNostrProfile = false) - ) { - // The same gate as every way in behind the rows: proposing is a signature - // by the group, and `proposeSigning` throws for a device holding no share. - // The rows themselves stay, because reading takes no share. - onNodeWithText("Propose event").assertDoesNotExist() - onNodeWithText("Nostr profile").assertIsDisplayed() - onNodeWithText("Posts").assertIsDisplayed() + fun `the wallet row opens the wallet`() { + if (!GroupWalletRollout.ENABLED) return + + var opened: Route? = null + + render(state(), onNavigateToRoute = { opened = it }) { + onNodeWithText("Not opened yet").assertIsDisplayed() + onNodeWithText(WALLET_ROW).performClick() + } + + assertEquals(GroupWalletRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) } @Test - fun `a NIP-17 room has no nostr identity and so no rows`() = render( - state(groupNostrProfile = null, mlsGroupState = null, canEditNostrProfile = false) - ) { + fun `the group's screen has no nostr profile, relays, posts or paste`() = render(state()) { onNodeWithText("Nostr profile").assertDoesNotExist() - onNodeWithText("Not described yet").assertDoesNotExist() - - // The other two go with it: all three describe a nostr identity this - // room does not have, and so does the paste. onNodeWithText("Relays").assertDoesNotExist() onNodeWithText("Posts").assertDoesNotExist() onNodeWithText("Propose event").assertDoesNotExist() - // The rest of the screen is untouched, so the rows' absence is an - // absence rather than a screen that failed to draw. + // The rest of the screen is there, so the rows' absence is an absence + // rather than a screen that failed to draw. onNodeWithText("Subgroups").assertIsDisplayed() } - private fun state( - groupNostrProfile: GroupNostrProfile?, - relayLists: List = GroupRelayList.allAmong(emptyList(), chatRoomId), - posts: List = emptyList(), - canEditNostrProfile: Boolean = true, - mlsGroupState: String? = "state" - ) = ChatRoomDetailUIState.Loaded( + @Test + fun `a NIP-17 room has no key to sign with and so no wallet row`() = render( + state(mlsGroupState = null) + ) { + onNodeWithText(WALLET_ROW).assertDoesNotExist() + onNodeWithText("Subgroups").assertIsDisplayed() + } + + /** The wallet row is named for its room: the fixture's subject. */ + private val WALLET_ROW = "Translation room onchain wallet" + + private fun state(mlsGroupState: String? = "state") = ChatRoomDetailUIState.Loaded( localChatRoom = GroupSignedWorkFixtures.localChatRoom(mlsGroupState), groupKeyState = GroupSignedWorkFixtures.groupKeyState, - groupNostrProfile = groupNostrProfile, - groupRelayLists = relayLists, - groupPosts = posts, - canEditNostrProfile = canEditNostrProfile ) /** @@ -239,7 +112,6 @@ class GroupSignedWorkRowsJvmTest { initialChatRoomDetailUIState = uiState, nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - mantraRepository = MantraRepository.NO_OP_MANTRA_REPOSITORY, onNavigateToRoute = onNavigateToRoute, onPopBackToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt new file mode 100644 index 00000000..3a71f282 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt @@ -0,0 +1,230 @@ +package com.machankura.bennu.compose.ui.composable + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.LineageExample +import com.machankura.bennu.compose.managers.LineageExample.heldBy +import com.machankura.bennu.compose.ui.composable.navigation.routes.ProfilePreviewRoute +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import androidx.compose.ui.unit.Density +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.Route +import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost +import com.machankura.bennu.compose.ui.theme.BennuTheme +import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState +import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.time.Instant + +/** + * A descendant's guarded wallet on an ancestor's wallet screen: a card whose + * actions sit under the name rather than squeezing it, each one telling a + * screen reader which wallet it acts on. `docs/guarded-wallet-funding.md`, Phase 5. + */ +@OptIn(ExperimentalTestApi::class) +class GuardedWalletCardJvmTest { + private val chatRoomId = "d4c3b2a1".repeat(8) + private val descendantRoomId = "c".repeat(64) + + private fun account(seed: String) = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode(seed.padStart(64, '0')))).publicKey().toString(), Chain.Regtest, + ) + + /** A descendant's wallet guarded by this room, at the default delay, as a verified statement would be. */ + private fun guardedAccount(seed: String) = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode(seed.padStart(64, '0')))).publicKey().toString(), Chain.Regtest, + guardians = GuardianDerivation.grant(PrivateKey(ByteVector32(Hex.decode("a11ce".padStart(64, '0')))).publicKey().toString(), chatRoomId, emptyList(), descendantRoomId), + ) + + private fun holding(account: GroupWalletDerivation.Account, sats: Long, height: Long, tip: Int): GroupWalletState { + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + val next = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 1) + val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(0) + return GroupWalletState( + account, + WalletState(mapOf( + derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta))), + next.address(Chain.Regtest) to WalletState.AddressState(WalletState.AddressMeta.Derived(1), false, emptyList()), + )), + WalletState.empty, + tipHeight = tip, + ) + } + + private fun loaded(name: String): GroupWalletUIState.Loaded { + val own = account("1c0ffee") + val descendant = guardedAccount("decaf") + val guarded = GuardianManager.GuardedWallet( + ancestorChatRoomId = chatRoomId, + descendantChatRoomId = descendantRoomId, + statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), + account = descendant, + certificate = Event("2".repeat(64), chatRoomId, 1_700_000_000, 0, arrayOf(arrayOf("name", name)), "", ""), + lineage = listOf(descendantRoomId), + ) + val wallet = GroupWallet( + GroupSignedEvent( + id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupWalletStatementEvent.KIND, + tags = GroupWalletStatementEvent.template(own).tags, content = own.xpub, signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ), + own, + ) + val room = LocalChatRoom(ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "Treasury", description = null, initialGiftWrapPayloadId = "p", mlsGroupState = "state")) + return GroupWalletUIState.Loaded( + localChatRoom = room, + wallet = wallet, + walletState = holding(own, 100_000, height = 100, tip = 200), + canWatch = true, + canSign = true, + guardedWallets = listOf(GuardedWalletRow(guarded, holding(descendant, 50_000, height = 0, tip = 200))), + ) + } + + private fun render(state: GroupWalletUIState, fontScale: Float = 1f, width: Int = 400, onRoute: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = width, height = 2400) { + setContent { + BennuTheme { + ProvideSnackbarHost { + CompositionLocalProvider(LocalDensity provides Density(LocalDensity.current.density, fontScale)) { + Box(modifier = Modifier.fillMaxSize()) { + GroupWalletScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + chain = Chain.Regtest, + initialGroupWalletUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + wallets = null, + onNavigateToRoute = onRoute, + onNavigateBack = {}, + ) + } + } + } + } + } + assertions() + } + + @Test + fun `each guarded wallet offers fund beside spend, each naming its wallet`() = render(loaded("Savings")) { + onNodeWithText("Savings").assertIsDisplayed() + onNodeWithText("0 sats within this group's reach · 50,000 sats arriving").assertIsDisplayed() + onNodeWithContentDescription("Fund Savings's guarded wallet").assertIsDisplayed() + onNodeWithContentDescription("Spend from Savings's guarded wallet").assertIsDisplayed() + } + + @Test + fun `fund opens the send form paying the descendant, from the room's own wallet`() { + var opened: Route? = null + render(loaded("Savings"), onRoute = { opened = it }) { + onNodeWithContentDescription("Fund Savings's guarded wallet").performClick() + } + assertEquals( + GroupSendRoute(activeUserPublicKey = "a".repeat(64), chatRoomId = chatRoomId, relayHint = null, fundChatRoomId = descendantRoomId), + opened, + ) + } + + @Test + fun `a device that cannot sign is offered neither`() = render(loaded("Savings").copy(canSign = false)) { + onNodeWithText("Savings").assertIsDisplayed() + onNodeWithText("Fund").assertDoesNotExist() + onNodeWithText("Spend").assertDoesNotExist() + } + + @Test + fun `at twice the text size the buttons stay whole`() = render(loaded("Savings"), fontScale = 2f) { + onNodeWithContentDescription("Fund Savings's guarded wallet").assertIsDisplayed() + onNodeWithContentDescription("Spend from Savings's guarded wallet").assertIsDisplayed() + } + + // ---- Members' wallets by person: docs/member-wallet-guarding-group.md, Phase 5 + + /** R's wallet screen, guarding Alice's Savings (under M, below P) and Rent (under N). */ + private fun atR(vararg guarded: GuardianManager.GuardedWallet): GroupWalletUIState.Loaded = + loaded("Savings").copy(guardedWallets = guarded.map { GuardedWalletRow(it, walletState = null) }) + + private val savings = heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M", branchName = "#P") + private val rent = heldBy(LineageExample.r, LineageExample.rent, LineageExample.rentGuardians, label = "Rent", guardianName = "#N", branchName = "#N") + + @Test + fun `a member's two wallets under two groups are one header, each card naming its group`() = render(atR(savings, rent)) { + onNodeWithText("Members' wallets").assertIsDisplayed() + onNodeWithText("@alice").assertIsDisplayed() + onNodeWithText("2 wallets, guarded by 2 groups").assertIsDisplayed() + onNodeWithText("Rent").assertIsDisplayed() + onNodeWithText("Guarded by #N").assertIsDisplayed() + onNodeWithText("Savings").assertIsDisplayed() + onNodeWithText("Guarded by #M, below #P").assertIsDisplayed() + } + + @Test + fun `an unlabelled wallet is named by the group that guards it`() = + render(atR(heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, branchName = "#P"))) { + // No name this device can check for M: where it sits instead. + onNodeWithText("Guarded by a group below #P").assertIsDisplayed() + onNodeWithText("1 wallet, guarded by 1 group").assertIsDisplayed() + } + + @Test + fun `each of a member's buttons names its wallet`() = render(atR(savings, rent, heldBy(LineageExample.r, "9".repeat(64), LineageExample.rentGuardians, guardianName = "#N", branchName = "#N"))) { + onNodeWithContentDescription("Fund @alice's guarded wallet “Savings”").assertIsDisplayed() + onNodeWithContentDescription("Spend from @alice's guarded wallet “Savings”").assertIsDisplayed() + onNodeWithContentDescription("Fund @alice's guarded wallet “Rent”").assertIsDisplayed() + onNodeWithContentDescription("Spend from @alice's guarded wallet “Rent”").assertIsDisplayed() + onNodeWithContentDescription("Fund @alice's wallet guarded by #N").assertIsDisplayed() + onNodeWithContentDescription("Spend from @alice's wallet guarded by #N").assertIsDisplayed() + } + + @Test + fun `a wallet this group guards directly says so`() = + render(atR(heldBy(LineageExample.m, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M"))) { + onNodeWithText("Guarded by this group").assertIsDisplayed() + } + + @Test + fun `the header opens the member's profile`() { + var opened: Route? = null + render(atR(savings), onRoute = { opened = it }) { + onNodeWithText("@alice").performClick() + } + assertEquals(ProfilePreviewRoute(activeUserPublicKey = "a".repeat(64), profilePublicKey = LineageExample.alice), opened) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreenJvmTest.kt index e06e1082..fa123418 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProfilePreviewScreenJvmTest.kt @@ -21,6 +21,11 @@ import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.database.model.SynchronizeNostrEventRequest import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.managers.LineageExample +import com.machankura.bennu.compose.managers.MemberWalletManager +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription import com.machankura.bennu.compose.extensions.hexToNpubHrp import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute @@ -194,6 +199,7 @@ class ProfilePreviewScreenJvmTest { canSign: Boolean = true, nostrRepository: NostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository: ChatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, onStartChat: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit, ) = runDesktopComposeUiTest(width = 400, height = 1200) { @@ -210,6 +216,7 @@ class ProfilePreviewScreenJvmTest { chatRepository = chatRepository, onStartChat = onStartChat, onNavigateBack = {}, + memberWalletRepository = memberWalletRepository, ) } } @@ -219,4 +226,29 @@ class ProfilePreviewScreenJvmTest { assertions() } + + // --- the wallets this profile's groups guard: docs/member-wallet-guarding-group.md, D7 --- + + @OptIn(ExperimentalTestApi::class) + @Test + fun `a wallet held by two groups here is one entry, guarded by the group that signed it`() { + val held = listOf( + MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", ownerPublicKey = profilePublicKey, branchName = "#P"), holderName = "#R", canSpend = false), + MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.p, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", ownerPublicKey = profilePublicKey, guardianName = "#M", branchName = "#M"), holderName = "#P", canSpend = true), + ) + val repository = object : MemberWalletRepository by MemberWalletRepository.NO_OP { + override suspend fun guardedByGroupsHere(ownerPublicKey: String): List = held + } + + render(ProfilePreviewUIState.Loaded(profile = alice, readiness = Readiness.CanStartChat), memberWalletRepository = repository) { + waitUntil(timeoutMillis = 5_000) { onAllNodesWithText("Savings").fetchSemanticsNodes().isNotEmpty() } + onNodeWithText("Wallets your groups guard").assertIsDisplayed() + assertEquals(1, onAllNodesWithText("Savings").fetchSemanticsNodes().size, "one entry for the wallet") + onNodeWithText("Guarded by #M").assertIsDisplayed() + onNodeWithText("#P: after 12 blocks").assertIsDisplayed() + onNodeWithText("#R: after 12 blocks").assertIsDisplayed() + onNodeWithContentDescription("Spend from Savings as #P").assertIsDisplayed() + onNodeWithContentDescription("Spend from Savings as #R").assertDoesNotExist() + } + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt deleted file mode 100644 index 522e622e..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performTextInput -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.ProposeGroupEventUIState -import kotlin.test.Test - -/** - * What the paste screen says back as an event is typed into it. - * - * The screen's one job beyond a text field is to tell a member, before a quorum - * is asked, what the group would be signing or why it will not be asked. Both - * are read live off the paste, so both are tested by typing: a relay list reads back - * as the signing screen would describe it, junk is named as junk, and a kind - * with no section to land in is refused with the kinds that have one. - */ -@OptIn(ExperimentalTestApi::class) -class ProposeGroupEventScreenJvmTest { - - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val relayList = """{"kind":10002,"created_at":1735689600,""" + - """"tags":[["r","wss://relay.one.example"],["r","wss://relay.two.example","read"]],"content":""}""" - - @Test - fun `a pasted relay list is read back as the signing screen would say it`() = render(state()) { - onNodeWithText("Unsigned event").performTextInput(relayList) - - onNodeWithText("What the group would sign").assertIsDisplayed() - onNodeWithText("Kind 10002 · General relay list").assertIsDisplayed() - onNodeWithText("relay.one.example, relay.two.example").assertIsDisplayed() - } - - @Test - fun `junk is named as junk`() = - render(state()) { - onNodeWithText("Unsigned event").performTextInput("this is not an event") - onNodeWithText("That isn't JSON.").assertIsDisplayed() - onNodeWithText("What the group would sign").assertDoesNotExist() - } - - @Test - fun `a kind the screen cannot file is refused with the kinds it can`() = render(state()) { - onNodeWithText("Unsigned event").performTextInput("""{"kind": 30023, "content": "An article"}""") - - onNodeWithText("Kind 30023 has nowhere to go on the group's screen.", substring = true) - .assertIsDisplayed() - onNodeWithText("0, 1, 10002, 10006, 10007, 10050", substring = true).assertIsDisplayed() - } - - @Test - fun `a member holding no share of the key is told so and the button is inert`() = render( - state(canSign = false) - ) { - onNodeWithText("This group has no shared key, so it cannot sign an event.", substring = true) - .assertIsDisplayed() - onNodeWithContentDescription("Propose event").assertIsNotEnabled() - } - - private fun state(canSign: Boolean = true) = ProposeGroupEventUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - canSign = canSign, - ) - - private fun render( - uiState: ProposeGroupEventUIState, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 1200) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - ProposeGroupEventScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialProposeGroupEventUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = - FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt deleted file mode 100644 index 8a721014..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt +++ /dev/null @@ -1,373 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.setMain -import kotlinx.coroutines.withTimeout -import kotlinx.serialization.json.jsonPrimitive -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome -import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The three decisions the broadcast screen makes that nothing else can check. - * - * **Where an event goes before anyone says otherwise.** The seeded list is what a - * member who reads nothing and presses the button sends to, so it has to be the - * group's own answer where the group has given one, has to leave out what the - * group has blocked, and has to widen for relay lists, whose readers would not - * otherwise find them. - * - * **What each relay's answer becomes.** The pool answers once per relay in three - * shapes -- an OK, a rejection wrapped in one exception type, and any other error - * -- and the rows show them as three different things because a member can act - * on "blocked: not on the allow list" and cannot act on a red icon. - * - * **What goes on the wire.** The seven fields the group hashed and nothing else, - * so a relay checking the id and the signature finds the event the group signed. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class BroadcastGroupSignedEventViewModelJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - private val three = RelayUrlNormalizer.normalize("wss://relay.three.example") - - /** Answers each relay with whatever [answers] says, keyed by host, and remembers what it was handed. */ - private class FakeTransport( - private val answers: Map - ) : EventPublishTransport { - var sent: NostrEvent? = null - var askedRelays: Set = emptySet() - - override suspend fun publishEvent( - nostrEvent: NostrEvent, - relays: Set - ): Flow { - sent = nostrEvent - askedRelays = relays - return flowOf(*answers.values.toTypedArray()) - } - } - - @BeforeTest - fun setUp() { - Dispatchers.setMain(UnconfinedTestDispatcher()) - } - - @AfterTest - fun tearDown() { - Dispatchers.resetMain() - } - - private fun viewModel(transport: EventPublishTransport = FakeTransport(emptyMap())) = - BroadcastGroupSignedEventViewModel( - chatRoomId = chatRoomId, - signedEventId = "b".repeat(64), - activeUserPublicKey = "a".repeat(64), - relayHint = null, - initialBroadcastGroupSignedEventUIState = BroadcastGroupSignedEventUIState.Loading, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = transport, - ) - - private fun signedEvent(kind: Int = TextNoteEvent.KIND, tags: Array> = emptyArray()) = - GroupSignedEvent( - id = "b".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = kind, - tags = tags, - content = "The first chapter is out.", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - private fun relaySignedEvent(set: GroupRelaySet) = GroupSignedEvent( - id = "a" + set.kind.toString().padStart(5, '0') + "0".repeat(58), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - /** Every set unsigned, which is a group that has never said where it lives. */ - private fun nothingAgreed() = GroupRelayList.allAmong(emptyList(), chatRoomId) - - private fun agreed(vararg lists: Pair>) = - nothingAgreed().map { list -> - lists.firstOrNull { it.first == list.set } - ?.let { GroupRelayList(list.set, relaySignedEvent(list.set), it.second) } - ?: list - } - - private fun ok(relay: NormalizedRelayUrl) = NostrPublishResult( - result = NostrIncomingMessage.OkMessage(eventId = "b".repeat(64), success = true), - relayUrl = relay.url, - ) - - private fun rejected(relay: NormalizedRelayUrl, reason: String) = NostrPublishResult( - result = NostrIncomingMessage.OkMessage(eventId = "b".repeat(64), success = false, message = reason), - error = NostrPublishException(message = reason), - relayUrl = relay.url, - ) - - private fun failed(relay: NormalizedRelayUrl, reason: String) = NostrPublishResult( - error = IllegalStateException(reason), - relayUrl = relay.url, - ) - - // -- where an event goes before anyone says otherwise ------------------------ - - @Test - fun `a group that has not said where it lives sends to the app's publish set`() { - assertEquals( - Relays.eventPublishRelaySet.toList(), - BroadcastGroupSignedEventViewModel.defaultRelaysFor(nothingAgreed(), TextNoteEvent.KIND), - ) - } - - @Test - fun `a group's own general list wins, and only the relays it writes to`() { - val relayLists = agreed( - GroupRelaySet.General to listOf( - GroupRelay(one), - // Read-only: where the group looks, not where it puts things. - GroupRelay(two, read = true, write = false), - ) - ) - - // The group's answer and nothing from the app's set beside it: a member - // who edited the relays meant them, and padding the list would send the - // group's post somewhere the group decided not to be. - assertEquals( - listOf(one), - BroadcastGroupSignedEventViewModel.defaultRelaysFor(relayLists, TextNoteEvent.KIND), - ) - } - - @Test - fun `a blocked relay is dropped whatever the other lists say`() { - val relayLists = agreed( - GroupRelaySet.General to listOf(GroupRelay(one), GroupRelay(two)), - GroupRelaySet.Blocked to listOf(GroupRelay(two)), - ) - - assertEquals( - listOf(one), - BroadcastGroupSignedEventViewModel.defaultRelaysFor(relayLists, TextNoteEvent.KIND), - ) - } - - @Test - fun `a relay list also goes to the indexers, since its readers do not yet know the relays it names`() { - val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) - - val seeded = BroadcastGroupSignedEventViewModel.defaultRelaysFor( - relayLists, AdvertisedRelayListEvent.KIND - ) - - assertEquals(one, seeded.first()) - Relays.DefaultIndexerRelayList.forEach { indexer -> - assertTrue(indexer in seeded, "the relay list would not reach ${indexer.url}") - } - - // And a post does not: nobody looks an indexer up for a kind 1. - val post = BroadcastGroupSignedEventViewModel.defaultRelaysFor(relayLists, TextNoteEvent.KIND) - Relays.DefaultIndexerRelayList.forEach { indexer -> - assertFalse(indexer in post, "a post was sent to the indexer ${indexer.url}") - } - } - - @Test - fun `seeding happens once, so an emptied list stays empty`() { - val viewModel = viewModel() - val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) - val event = signedEvent() - - viewModel.seedRelays(relayLists, event.kind) - viewModel.seedRelays(relayLists, event.kind) - assertEquals(listOf(one), viewModel.relays.toList()) - - viewModel.removeRelay(one) - viewModel.seedRelays(relayLists, event.kind) - assertEquals(emptyList(), viewModel.relays.toList()) - } - - // -- what may be added ---------------------------------------------------------- - - @Test - fun `an add is refused by name, and a good one clears the refusal`() { - val viewModel = viewModel() - - assertFalse(viewModel.addRelay("https://not-a-relay.example")) - assertEquals(BroadcastGroupSignedEventViewModel.AddFailure.NotARelay, viewModel.addFailure) - - assertTrue(viewModel.addRelay(one.url)) - assertNull(viewModel.addFailure) - - assertFalse(viewModel.addRelay(one.url)) - assertEquals(BroadcastGroupSignedEventViewModel.AddFailure.AlreadyListed, viewModel.addFailure) - - assertEquals(listOf(one), viewModel.relays.toList()) - } - - // -- what each relay's answer becomes --------------------------------------------- - - @Test - fun `each relay's answer lands on its own row, and the sum counts only the OKs`() { - val transport = FakeTransport( - mapOf( - "one" to ok(one), - "two" to rejected(two, "blocked: not on the allow list"), - "three" to failed(three, "Connection refused"), - ) - ) - val viewModel = viewModel(transport) - listOf(one, two, three).forEach { assertTrue(viewModel.addRelay(it.url)) } - - var toldNoRelays = false - val job = viewModel.broadcast(signedEvent(), onNoRelays = { toldNoRelays = true }) - runBlocking { withTimeout(5_000) { job!!.join() } } - - assertFalse(toldNoRelays) - assertEquals(RelayOutcome.Accepted, viewModel.outcomes[one]) - assertEquals(RelayOutcome.Rejected("blocked: not on the allow list"), viewModel.outcomes[two]) - assertEquals(RelayOutcome.Failed("Connection refused"), viewModel.outcomes[three]) - assertEquals( - BroadcastGroupSignedEventViewModel.BroadcastSummary(accepted = 1, asked = 3), - viewModel.lastBroadcast, - ) - assertFalse(viewModel.isActionPending.value) - - // Asked as write relays: the pool would otherwise read from them too. - assertEquals( - setOf(one, two, three).map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), - transport.askedRelays, - ) - } - - @Test - fun `an answer is matched by host, since the pool may spell the relay with a trailing slash`() { - val transport = FakeTransport( - mapOf("one" to ok(one).copy(relayUrl = one.url.trimEnd('/') + "/")) - ) - val viewModel = viewModel(transport) - assertTrue(viewModel.addRelay(one.url)) - - val job = viewModel.broadcast(signedEvent(), onNoRelays = {}) - runBlocking { withTimeout(5_000) { job!!.join() } } - - assertEquals(RelayOutcome.Accepted, viewModel.outcomes[one]) - } - - @Test - fun `a relay that never answers is marked so, which is not the same as refused`() { - // The pool answers for one relay and then the flow ends, which is what a - // send that ran out of time looks like from here. - val transport = FakeTransport(mapOf("one" to ok(one))) - val viewModel = viewModel(transport) - assertTrue(viewModel.addRelay(one.url)) - assertTrue(viewModel.addRelay(two.url)) - - val job = viewModel.broadcast(signedEvent(), onNoRelays = {}) - runBlocking { withTimeout(5_000) { job!!.join() } } - - assertEquals(RelayOutcome.Accepted, viewModel.outcomes[one]) - assertEquals(RelayOutcome.NoAnswer, viewModel.outcomes[two]) - assertEquals( - BroadcastGroupSignedEventViewModel.BroadcastSummary(accepted = 1, asked = 2), - viewModel.lastBroadcast, - ) - } - - @Test - fun `an empty list asks nobody and says so`() { - val transport = FakeTransport(emptyMap()) - val viewModel = viewModel(transport) - - var toldNoRelays = false - val job = viewModel.broadcast(signedEvent(), onNoRelays = { toldNoRelays = true }) - - assertNull(job) - assertTrue(toldNoRelays) - assertNull(transport.sent) - assertFalse(viewModel.isActionPending.value) - } - - // -- what goes on the wire ------------------------------------------------------------ - - @Test - fun `what goes on the wire is the event the group signed, field for field`() { - val event = signedEvent( - kind = MetadataEvent.KIND, - tags = arrayOf(arrayOf("alt", "The group's profile")), - ) - - val wire = BroadcastGroupSignedEventViewModel.wireEventOf(event).toNostrJsonObject() - - assertEquals(event.id, wire["id"]!!.jsonPrimitive.content) - assertEquals(event.publicKey, wire["pubkey"]!!.jsonPrimitive.content) - assertEquals(event.createdAt.epochSeconds.toString(), wire["created_at"]!!.jsonPrimitive.content) - assertEquals(event.kind.toString(), wire["kind"]!!.jsonPrimitive.content) - assertEquals(event.content, wire["content"]!!.jsonPrimitive.content) - assertEquals(event.signature, wire["sig"]!!.jsonPrimitive.content) - assertEquals("""[["alt","The group's profile"]]""", wire["tags"].toString()) - } - - // -- what never goes at all ------------------------------------------------ - - @Test - fun `the group's wallet statement is never handed to a relay`() { - val transport = FakeTransport(mapOf(one.url to ok(one))) - - // The xpub on a relay is every address and the whole balance, to anyone. - // A refusal nobody tested is the one that disappears in a refactor of - // what the broadcast list accepts. - assertFailsWith { - runBlocking { - BroadcastGroupSignedEventViewModel.sendToRelays( - publishTransport = transport, - signedEvent = signedEvent(kind = GroupWalletStatementEvent.KIND), - targets = listOf(one), - ) - } - } - assertNull(transport.sent, "nothing reached the transport") - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt new file mode 100644 index 00000000..b4af35ed --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt @@ -0,0 +1,232 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.Participant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.identity.IdentityKind +import com.machankura.bennu.compose.identity.toWalletId +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull + +/** + * The one screen that starts a group's own key ceremony. + * + * What it must decide before it draws a button: whether the room can hold a + * ceremony of its own at all, and whether it already has one. A Marmot room + * cannot, and the ceremony screen offering it one anyway is how a second + * ceremony opened beside a subgroup's -- see docs/ceremony-creation.md. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class CreateSharedKeyViewModelJvmTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val chatRoomId = "9a17".repeat(16) + + private val key = PrivateKey(ByteVector32("0e".repeat(32))) + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + private val cleo = "c".repeat(64) + + private fun room( + members: List = listOf(ada, bob, cleo), + mlsGroupState: String? = null, + ) = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = ada, + subject = "Checkers", + description = null, + mlsGroupState = mlsGroupState, + ), + localParticipants = members.map { + LocalParticipant(Participant(participantPublicKey = it, chatRoomId = chatRoomId, relayHint = null), null) + }, + ) + + private fun session(id: String, stage: DkgRitualStage) = DkgSession( + id = id, + chatRoomId = chatRoomId, + coordinatorPublicKey = bob, + userPublicKey = ada, + threshold = 2, + participantCount = 3, + stage = stage, + hostPublicKey = ada, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + ) + + /** What `proposeRitual` was asked for, one entry per call. */ + private val proposed = mutableListOf() + + private fun dkgRepository(own: DkgSession? = null) = + object : DkgRepository by DkgRepository.NO_OP_DKG_REPOSITORY { + override fun observeLatestSessionForChatRoom( + chatRoomId: String, + parentChatRoomId: String?, + ): Flow = flowOf(own.takeIf { parentChatRoomId == null }) + + override suspend fun proposeRitual( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + threshold: Int, + parentChatRoomId: HexKey?, + participantPublicKeys: Set?, + subject: String?, + walletPolicy: SubgroupWalletPolicy?, + guardianDelay: Long? + ): DkgSession? { + proposed += threshold + return session("new".padEnd(64, '0'), DkgRitualStage.COLLECTING_HOST_KEYS) + } + } + + private fun chatRepository(room: LocalChatRoom?) = + object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = + room.takeIf { id == chatRoomId } + } + + private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() + } + + private fun viewModel(room: LocalChatRoom?, own: DkgSession? = null) = CreateSharedKeyViewModel( + chatRoomId = chatRoomId, + activeUserPublicKey = ada, + initialUIState = CreateSharedKeyUIState.Loading, + activeIdentityStateFlow = MutableStateFlow( + Identity.signing( + id = key.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrSecret, + nostrPrivateKey = key, + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + business = null, + ) + ), + chatRepository = chatRepository(room), + dkgRepository = dkgRepository(own), + ) + + private suspend fun CreateSharedKeyViewModel.awaitSettled(): CreateSharedKeyUIState = + withTimeout(5_000) { + while (uiState == CreateSharedKeyUIState.Loading) delay(10) + uiState + } + + @Test + fun `a group with no ceremony is offered one, at the majority default`(): Unit = runBlocking { + val viewModel = viewModel(room()) + viewModel.initiate() + + val loaded = assertIs(viewModel.awaitSettled()) + assertEquals(3, loaded.participantCount) + assertEquals(2, viewModel.threshold.value) + + val opened = CompletableDeferred() + viewModel.create { opened.complete(it) } + + assertEquals("new".padEnd(64, '0'), withTimeout(5_000) { opened.await() }) + assertEquals(listOf(2), proposed) + } + + @Test + fun `a group with a ceremony already is handed to it`(): Unit = runBlocking { + val running = session("run".padEnd(64, '0'), DkgRitualStage.COLLECTING_ROUND_1) + val viewModel = viewModel(room(), own = running) + viewModel.initiate() + + assertEquals(CreateSharedKeyUIState.Existing(running.id), viewModel.awaitSettled()) + assertEquals(emptyList(), proposed, "and nothing is proposed") + } + + @Test + fun `a failed ceremony is there to be replaced`(): Unit = runBlocking { + val failed = session("bad".padEnd(64, '0'), DkgRitualStage.FAILED) + val viewModel = viewModel(room(), own = failed) + viewModel.initiate() + + assertIs(viewModel.awaitSettled()) + } + + @Test + fun `a Marmot room is refused, and says why`(): Unit = runBlocking { + val viewModel = viewModel(room(mlsGroupState = "state")) + viewModel.initiate() + + assertEquals( + CreateSharedKeyUIState.Refused(CreateSharedKeyUIState.Refused.Reason.MARMOT_ROOM), + viewModel.awaitSettled(), + ) + + viewModel.create { error("a refused room opens nothing") } + assertEquals(emptyList(), proposed) + } + + @Test + fun `a group of one is refused`(): Unit = runBlocking { + val viewModel = viewModel(room(members = listOf(ada))) + viewModel.initiate() + + assertEquals( + CreateSharedKeyUIState.Refused(CreateSharedKeyUIState.Refused.Reason.TOO_FEW_MEMBERS), + viewModel.awaitSettled(), + ) + } + + @Test + fun `a room that cannot be read is an error with a way to retry`(): Unit = runBlocking { + val viewModel = viewModel(room = null) + viewModel.initiate() + + val error = assertIs(viewModel.awaitSettled()) + assertEquals(CreateSharedKeyUIState.Error.Reason.ROOM_NOT_FOUND, error.reason) + assertNull(proposed.firstOrNull()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt new file mode 100644 index 00000000..e30bc072 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt @@ -0,0 +1,426 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onStart +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgParticipantMessage +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.FrostSigningItem +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalFrostSigningSession +import com.machankura.bennu.compose.database.model.types.DkgApprovalStep +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.identity.IdentityKind +import com.machankura.bennu.compose.identity.toWalletId +import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectSubgroupAdminsRoute +import com.machankura.bennu.compose.ui.composable.retryRoute +import com.machankura.bennu.compose.ui.view.state.DkgRitualUIState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The ceremony screen keeping hold of its ceremony. + * + * It lost it twice over, and the second loss is what put a "Start key ceremony" + * button where "Review and join" had just been: coming back from an approval + * screen ran `initiate` again, which reset the state to "no ceremony", and five + * coroutines each copying the state to change one field could write an old + * copy back over a newer one. See docs/ceremony-creation.md, findings F3, F4 + * and F6. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DkgRitualViewModelJvmTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val chatRoomId = "c3a1".repeat(16) + private val sessionId = "5e55".repeat(16) + + private val key = PrivateKey(ByteVector32("0d".repeat(32))) + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = ada, + subject = "Checkers", + description = null, + mlsGroupState = null, + ) + ) + + private fun session(stage: DkgRitualStage = DkgRitualStage.COLLECTING_HOST_KEYS) = DkgSession( + id = sessionId, + chatRoomId = chatRoomId, + coordinatorPublicKey = bob, + userPublicKey = ada, + threshold = 2, + participantCount = 3, + stage = stage, + hostPublicKey = ada, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + ) + + private fun hostKey(from: HexKey) = DkgParticipantMessage( + sessionId = sessionId, + participantPublicKey = from, + kind = DkgRitualEvents.HOST_KEY, + payload = "02".repeat(33), + ) + + private val sessionRow = MutableStateFlow(session()) + private val messages = MutableStateFlow>(emptyList()) + private val signingSessions = MutableStateFlow>(emptyList()) + + /** How many times the screen started watching its ceremony. */ + private var sessionSubscriptions = 0 + + /** Held open so a test can see what happens before an approval returns. */ + private var approvalGate: CompletableDeferred? = null + private val approved = mutableListOf() + + private val dkgRepository = object : DkgRepository by DkgRepository.NO_OP_DKG_REPOSITORY { + override fun observeSessionById(sessionId: String): Flow = + sessionRow.onStart { sessionSubscriptions++ } + + override fun observeMessages(sessionId: String): Flow> = messages + + override fun observeSigningSessions(chatRoomId: String): Flow> = + signingSessions + + // A deliberately slow answer, so a read-modify-write around it would have + // the widest possible window to lose somebody else's write in. + override suspend fun pendingApproval(session: DkgSession): DkgApprovalStep? { + delay(5) + return if (messages.value.size >= session.participantCount) DkgApprovalStep.ROUND_1 else null + } + + override suspend fun approve( + localChatRoom: LocalChatRoom, + sessionId: String, + step: DkgApprovalStep, + nostrPrivateKey: ByteArray + ) { + approvalGate?.await() + approved += step + } + } + + private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = + localChatRoom.takeIf { id == chatRoomId } + } + + private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() + } + + private fun viewModel() = DkgRitualViewModel( + chatRoomId = chatRoomId, + activeUserPublicKey = ada, + dkgSessionId = sessionId, + initialDkgRitualUIState = DkgRitualUIState.Loading, + activeIdentityStateFlow = MutableStateFlow( + Identity.signing( + id = key.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrSecret, + nostrPrivateKey = key, + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + business = null, + ) + ), + chatRepository = chatRepository, + dkgRepository = dkgRepository, + ) + + private suspend fun DkgRitualViewModel.awaitLoaded( + predicate: (DkgRitualUIState.Loaded) -> Boolean = { true } + ): DkgRitualUIState.Loaded = withTimeout(5_000) { + while (true) { + val state = dkgRitualUIState + if (state is DkgRitualUIState.Loaded && predicate(state)) return@withTimeout state + delay(10) + } + @Suppress("UNREACHABLE_CODE") + error("unreachable") + } + + @Test + fun `coming back to the screen keeps the ceremony it was showing`(): Unit = runBlocking { + val viewModel = viewModel() + + viewModel.initiate() + assertEquals(sessionId, viewModel.awaitLoaded().session?.id) + val watchers = sessionSubscriptions + + // What the screen does each time it comes back into view. + viewModel.initiate() + viewModel.initiate() + + repeat(20) { + val state = assertIs(viewModel.dkgRitualUIState) + assertEquals(sessionId, state.session?.id, "the ceremony is never dropped from the screen") + delay(5) + } + assertEquals(watchers, sessionSubscriptions, "and its watchers are started once, not once per visit") + } + + @Test + fun `the first state the screen draws already has the ceremony on it`(): Unit = runBlocking { + val viewModel = viewModel() + + // Recorded as fast as it changes. The old path set a ceremony-less + // `Loaded` first and filled the session in afterwards, which is the moment + // a start button could be drawn. + val seen = mutableListOf() + viewModel.initiate() + withTimeout(5_000) { + while (seen.none { it is DkgRitualUIState.Loaded }) { + viewModel.dkgRitualUIState.let { if (seen.lastOrNull() != it) seen += it } + delay(1) + } + } + + seen.filterIsInstance().forEach { + assertEquals(sessionId, it.session?.id) + } + } + + @Test + fun `parts that change together all land`(): Unit = runBlocking { + val viewModel = viewModel() + viewModel.initiate() + viewModel.awaitLoaded() + + // The session row and the messages moving at once, from two directions, + // each while the other's write is waiting on `pendingApproval`. + listOf( + async(Dispatchers.IO) { + listOf(ada, bob, "c".repeat(64)).forEach { from -> + messages.value = messages.value + hostKey(from) + delay(2) + } + }, + async(Dispatchers.IO) { + repeat(10) { + sessionRow.value = session().copy(failureReason = "tick $it") + delay(1) + } + sessionRow.value = session(DkgRitualStage.COLLECTING_ROUND_1) + }, + ).awaitAll() + + val settled = viewModel.awaitLoaded { + it.session?.stage == DkgRitualStage.COLLECTING_ROUND_1 && + it.hostKeyParticipants.size == 3 && + it.pendingApproval == DkgApprovalStep.ROUND_1 + } + assertEquals(sessionId, settled.session?.id) + assertEquals(setOf(ada, bob, "c".repeat(64)), settled.hostKeyParticipants) + } + + @Test + fun `a ceremony this device has no row for is an error, not an offer`(): Unit = runBlocking { + sessionRow.value = null + val viewModel = viewModel() + viewModel.initiate() + + withTimeout(5_000) { + while (viewModel.dkgRitualUIState !is DkgRitualUIState.Error) delay(10) + } + } + + @Test + fun `a failed ceremony is tried again where its kind is started`() { + val parent = "9a7e".repeat(16) + + val group = retryRoute(ada, chatRoomId, session(DkgRitualStage.FAILED)) + assertEquals(CreateSharedKeyRoute(activeUserPublicKey = ada, chatRoomId = chatRoomId), group) + + val subgroup = retryRoute( + ada, + chatRoomId, + session(DkgRitualStage.FAILED).copy(parentChatRoomId = parent) + ) + assertEquals( + SelectSubgroupAdminsRoute(activeUserPublicKey = ada, parentChatRoomId = parent, retrying = sessionId), + subgroup, + "a subgroup's goes back to the picker, filled in from the one that failed", + ) + } + + @Test + fun `an approval screen closes after the approval has gone out`(): Unit = runBlocking { + val viewModel = viewModel() + viewModel.initiate() + viewModel.awaitLoaded() + + val gate = CompletableDeferred().also { approvalGate = it } + val closed = CompletableDeferred() + + viewModel.approve(DkgApprovalStep.HOST_KEY, onApproved = { closed.complete(Unit) }) + + delay(50) + assertFalse(closed.isCompleted, "not while the approval is still being sent") + assertTrue(viewModel.isActionPending.value, "and the button says it is working") + + gate.complete(Unit) + withTimeout(5_000) { closed.await() } + + assertEquals(listOf(DkgApprovalStep.HOST_KEY), approved) + assertFalse(viewModel.isActionPending.value) + } + + /** A signing session in this room over one event of [kind]. */ + private fun signing( + id: String, + kind: Int, + tags: Array>, + content: String, + stage: FrostSigningStage = FrostSigningStage.COMPLETE, + ): LocalFrostSigningSession { + val event = NostrSignerSync(KeyPair()).sign( + createdAt = 1_700_000_000L, + kind = kind, + tags = tags, + content = content, + ) + return LocalFrostSigningSession( + session = FrostSigningSession( + id = id, + chatRoomId = chatRoomId, + coordinatorPublicKey = bob, + userPublicKey = ada, + dkgSessionId = sessionId, + threshold = 2, + participantCount = 3, + signerId = 1, + stage = stage, + ), + unorderedItems = listOf( + FrostSigningItem( + sessionId = id, + itemIndex = 0, + unsignedEventJson = event.toJson(), + eventId = event.id, + nonceRandom = "cc".repeat(32), + ) + ), + ) + } + + @Test + fun `a parent's second subgroup is not shown its first one's signing sessions`(): Unit = runBlocking { + // The ceremony is held in the parent's room, so this room is the parent's + // -- and it already holds the first subgroup's finished certificate and + // key state, newest first, as the store returns them. + val firstKey = "02" + "1f".repeat(32) + val secondKey = "02" + "2f".repeat(32) + sessionRow.value = session(DkgRitualStage.COMPLETE).copy( + parentChatRoomId = chatRoomId, + thresholdPublicKey = secondKey, + ) + signingSessions.value = listOf( + signing( + id = "first-key-state", + kind = GroupKeyStateEvent.KIND, + tags = GroupKeyStateEvent.assembleTags(chatRoomId = "f1".repeat(32), dkgSessionId = "f1"), + content = firstKey, + ), + signing( + id = "first-certificate", + kind = SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = "f1".repeat(32), + parentChatRoomId = chatRoomId, + thresholdPublicKey = firstKey, + adminPublicKeys = listOf(ada, bob), + name = "First", + ), + content = "f1".repeat(32), + ), + ) + + val viewModel = viewModel() + viewModel.initiate() + + val before = viewModel.awaitLoaded() + assertNull(before.certificateSession, "the first subgroup's certificate is not this one's") + assertNull(before.keyStateSession, "nor is its key state") + + // Its own, once asked for, is the one shown. + signingSessions.value = listOf( + signing( + id = "second-certificate", + kind = SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = "f2".repeat(32), + parentChatRoomId = chatRoomId, + thresholdPublicKey = secondKey, + adminPublicKeys = listOf(ada, bob), + name = "Second", + ), + content = "f2".repeat(32), + stage = FrostSigningStage.COLLECTING_NONCES, + ), + ) + signingSessions.value + + assertEquals( + "second-certificate", + viewModel.awaitLoaded { it.certificateSession != null }.certificateSession?.id, + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt deleted file mode 100644 index 007312ca..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt +++ /dev/null @@ -1,224 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupRelaysUIState -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The two decisions the relay editor makes that nothing else can check. - * - * **What counts as a change.** The button proposes only the lists that differ, so - * this is what decides whether a quorum is asked at all -- and getting it wrong in - * either direction is quiet. Too eager and every visit re-signs four lists nobody - * touched, dating a decision the group did not make; too shy and an edit is - * silently dropped on a screen that said it had been sent. - * - * **What a NIP-65 marker is allowed to become.** A relay that is neither read nor - * write has no tag in the format, so the state must not be reachable. - * `GroupRelaySet.template` drops one as a last resort; this is where it is actually - * prevented. - */ -class EditGroupRelaysViewModelJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - private fun viewModel() = EditGroupRelaysViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = "a".repeat(64), - relayHint = null, - initialEditGroupRelaysUIState = EditGroupRelaysUIState.Loading, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - ) - - private fun signedEvent(set: GroupRelaySet) = GroupSignedEvent( - id = "a" + set.kind.toString().padStart(5, '0') + "0".repeat(58), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - /** Every set unsigned, which is a group opening the editor for the first time. */ - private fun nothingSigned() = GroupRelayList.allAmong(emptyList(), chatRoomId) - - private fun signed(set: GroupRelaySet, relays: List) = - nothingSigned().map { - if (it.set == set) GroupRelayList(set, signedEvent(set), relays) else it - } - - @Test - fun `a first-time group is seeded with the app's own relay and that is a change`() { - val signed = nothingSigned() - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - assertEquals( - listOf(Relays.ephemeral), - viewModel.relaysOf(GroupRelaySet.General).map { it.url }, - ) - - // Seeded and therefore proposable. A group whose editor filled itself in - // and then refused to send it would be showing a plan it will not carry out. - assertEquals( - listOf(GroupRelaySet.General, GroupRelaySet.Messages, GroupRelaySet.Search), - viewModel.changedSets(signed), - ) - } - - @Test - fun `blocked is never seeded and so is never proposed by simply opening the screen`() { - val signed = nothingSigned() - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - assertEquals(emptyList(), viewModel.relaysOf(GroupRelaySet.Blocked)) - assertFalse(GroupRelaySet.Blocked in viewModel.changedSets(signed)) - } - - @Test - fun `opening a group that has agreed everything proposes nothing`() { - // The case that has to be silent. A member opening the editor, reading it - // and pressing the button must not spend a quorum on four identical lists. - val signed = GroupRelaySet.entries.map { set -> - GroupRelayList(set, signedEvent(set), listOf(GroupRelay(one))) - } - - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - assertEquals(emptyList(), viewModel.changedSets(signed)) - } - - @Test - fun `only the set that was edited is proposed`() { - val signed = GroupRelaySet.entries.map { set -> - GroupRelayList(set, signedEvent(set), listOf(GroupRelay(one))) - } - - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - viewModel.selectSet(GroupRelaySet.Search) - assertTrue(viewModel.addRelay(two.url)) - - assertEquals(listOf(GroupRelaySet.Search), viewModel.changedSets(signed)) - } - - @Test - fun `reordering a list is a change`() { - // A relay list is written in the order it is read back, and a member who - // moved a relay to the front meant to. Comparing as sets would call this no - // change and refuse to propose it. - val signed = signed(GroupRelaySet.General, listOf(GroupRelay(one), GroupRelay(two))) - - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - viewModel.selectSet(GroupRelaySet.General) - viewModel.removeRelay(GroupRelaySet.General, GroupRelay(one)) - assertTrue(viewModel.addRelay(one.url)) - - assertEquals( - listOf(two, one), - viewModel.relaysOf(GroupRelaySet.General).map { it.url }, - ) - assertTrue(GroupRelaySet.General in viewModel.changedSets(signed)) - } - - @Test - fun `emptying an agreed list is a change, and emptying an unagreed one is not`() { - // Withdrawing a list the group agreed is a decision worth a signature. - // "Still nothing" is not a decision at all, and proposing an empty list for - // a set nobody ever set would be a signature over silence. - val agreed = signed(GroupRelaySet.Messages, listOf(GroupRelay(one))) - val withdrawing = viewModel() - withdrawing.seedWorkingCopy(agreed) - withdrawing.removeRelay(GroupRelaySet.Messages, GroupRelay(one)) - - assertTrue(GroupRelaySet.Messages in withdrawing.changedSets(agreed)) - - val untouched = nothingSigned() - val quiet = viewModel() - quiet.seedWorkingCopy(untouched) - // Clear the seeded default so the set is unagreed *and* empty. - quiet.removeRelay(GroupRelaySet.Search, GroupRelay(Relays.ephemeral)) - - assertFalse(GroupRelaySet.Search in quiet.changedSets(untouched)) - } - - @Test - fun `a relay cannot be turned into one that is neither read nor write`() { - // NIP-65 has no tag for it, so the state has to be unreachable. What it - // would mean is that the relay is not in the list, and removing it is the - // row's own button. - val signed = signed(GroupRelaySet.General, listOf(GroupRelay(one))) - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - viewModel.toggleWrite(GroupRelaySet.General, GroupRelay(one)) - assertEquals( - listOf(GroupRelay(one, read = true, write = false)), - viewModel.relaysOf(GroupRelaySet.General), - ) - - // The second toggle is the one that would leave it as neither. - viewModel.toggleRead( - GroupRelaySet.General, - viewModel.relaysOf(GroupRelaySet.General).first(), - ) - assertEquals( - listOf(GroupRelay(one, read = true, write = false)), - viewModel.relaysOf(GroupRelaySet.General), - "a relay was left neither read nor write, which NIP-65 cannot express", - ) - } - - @Test - fun `a url that is not a relay is refused and named`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(nothingSigned()) - viewModel.selectSet(GroupRelaySet.Search) - - assertFalse(viewModel.addRelay("http://relay.one.example")) - assertEquals(EditGroupRelaysViewModel.AddFailure.NotARelay, viewModel.addFailure) - - // And a duplicate is a no-op rather than a mistake, said differently. - assertTrue(viewModel.addRelay(one.url)) - assertFalse(viewModel.addRelay(one.url)) - assertEquals(EditGroupRelaysViewModel.AddFailure.AlreadyListed, viewModel.addFailure) - } - - @Test - fun `seeding again leaves an edit alone`() { - // The effect that seeds is keyed on a state the view model can re-emit, so - // running twice has to be harmless -- otherwise a reload halfway through - // typing throws the typing away. - val signed = signed(GroupRelaySet.General, listOf(GroupRelay(one))) - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - viewModel.selectSet(GroupRelaySet.General) - assertTrue(viewModel.addRelay(two.url)) - - viewModel.seedWorkingCopy(signed) - - assertEquals( - listOf(one, two), - viewModel.relaysOf(GroupRelaySet.General).map { it.url }, - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt index a7656d60..bd9cc020 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt @@ -10,6 +10,9 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.FundingTarget +import com.vitorpamplona.quartz.nip01Core.core.Event import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.repository.ChatRepository @@ -180,9 +183,11 @@ class GroupSendViewModelJvmTest { val transactions = MutableStateFlow>(emptyList()) @Volatile var heldCoins: Set = emptySet() @Volatile var heldChange: Set = emptySet() + @Volatile var heldFunding: Set = emptySet() override fun observeGroupTransactions(chatRoomId: String): Flow> = transactions override suspend fun reservedOutPoints(chatRoomId: String): Set = heldCoins override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = heldChange + override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = heldFunding } /** Two confirmed coins, 60,000 and 40,000 sats, on the first two receive addresses. */ @@ -241,4 +246,115 @@ class GroupSendViewModelJvmTest { assertEquals(Satoshi(100_000), built.amount + built.fee) assertNull(built.change) } + + // ---- Funding a descendant's guarded wallet --------------------------------- + + private val descendantRoomId = "c".repeat(64) + private val descendant: GroupWalletDerivation.Account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), Chain.Regtest, + ) + private val guarded = GuardianManager.GuardedWallet( + ancestorChatRoomId = chatRoomId, + descendantChatRoomId = descendantRoomId, + statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), + account = descendant, + certificate = Event("2".repeat(64), chatRoomId, 1_700_000_000, 0, arrayOf(arrayOf("name", "Savings")), "", ""), + lineage = listOf(descendantRoomId), + ) + + /** The descendant's receive branch as Electrum reports it: its first ten addresses watched, [paid] of them used. */ + private fun descendantState(paid: Set = emptySet()): GroupWalletState { + val receive = (0 until 10).associate { index -> + GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, index.toLong()).address(Chain.Regtest) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = index in paid, utxos = emptyList()) + } + return GroupWalletState(descendant, WalletState(receive), WalletState.empty, tipHeight = 110) + } + + private fun fundingForm(signing: FrostSigningRepository, fundingState: Flow): GroupSendViewModel { + val ready = GroupSendUIState.Ready(localChatRoom, wallet, walletState = null, reserved = emptySet(), funding = FundingTarget(guarded, walletState = null)) + return viewModel(ready, signing = signing).apply { + follow(ready, flowOf(walletState), fundingState) + feerateField.setTextAndPlaceCursorAtEnd("4") + amountField.setTextAndPlaceCursorAtEnd("30,000") + } + } + + @Test + fun `a funding pays two past the descendant's current address, and says so in the PSBT`() { + val signing = RecordingSigning() + val model = fundingForm(signing, flowOf(descendantState())) + + val built = eventually { model.preview() as? GroupSpendBuilder.Result.Built } + assertEquals(2L, built.funded?.derived?.index) + assertEquals(GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, 2).pubkeyScript, built.psbt.global.tx.txOut[0].publicKeyScript) + assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(built.psbt, descendant)) + + // The address field plays no part: whatever is typed there, the funding goes where it goes. + model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") + assertEquals(built.psbt, assertIs(model.preview()).psbt) + + model.propose(onSuccess = {}, onFailure = {}) + runBlocking { withTimeout(5_000) { while (signing.proposed == null) delay(10) } } + assertEquals(built.psbt, signing.proposed, "proposed as the room's own spend") + } + + @Test + fun `an open funding moves the next one on`() { + val signing = Reserving() + val model = fundingForm(signing, flowOf(descendantState())) + assertEquals(2L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded }.derived.index) + + signing.heldFunding = setOf(2L) + signing.transactions.value = listOf( + GroupTransaction(frostSigningSessionId = "theirs", chatRoomId = chatRoomId, chain = "regtest", account = 0, psbt = "", txid = "t".repeat(64)) + ) + assertEquals(3L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded?.takeIf { it.derived.index != 2L } }.derived.index) + } + + @Test + fun `a payment to the address while the form is open moves it on`() { + val chain = MutableStateFlow(descendantState()) + val model = fundingForm(RecordingSigning(), chain) + assertEquals(2L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded }.derived.index) + + chain.value = descendantState(paid = setOf(2)) + assertEquals(3L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded?.takeIf { it.derived.index != 2L } }.derived.index) + } + + @Test + fun `nothing is built while the descendant's addresses are not known, or every one is held`() { + val waiting = fundingForm(RecordingSigning(), flowOf(null)) + val state = eventually { (waiting.groupSendUIState as GroupSendUIState.Ready).takeIf { it.walletState != null } } + assertNull(waiting.preview()) + assertEquals(false, state.funding?.allHeld) + + val signing = Reserving().apply { heldFunding = (2L until 10L).toSet() } + val full = fundingForm(signing, flowOf(descendantState())) + val held = eventually { (full.groupSendUIState as GroupSendUIState.Ready).takeIf { it.funding?.walletState != null } } + assertEquals(true, held.funding?.allHeld) + assertNull(full.preview()) + } + + @Test + fun `a route naming a source and a destination is not opened, nor one funding a wallet the room does not hold`() { + var asked = 0 + val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(identifier: String) = localChatRoom + override suspend fun canSign(chatRoomId: String) = true + override suspend fun groupWallet(chatRoomId: String, chain: Chain) = wallet + override suspend fun guardedWallets(chatRoomId: String): List { asked++; return emptyList() } + } + val both = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = null, + guardedChatRoomId = descendantRoomId, fundChatRoomId = descendantRoomId).apply { initiate() } + runBlocking { withTimeout(5_000) { while (both.groupSendUIState == GroupSendUIState.Loading) delay(10) } } + assertEquals(GroupSendUIState.Unavailable, both.groupSendUIState) + assertEquals(0, asked, "refused before either wallet is looked for") + + val unknown = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = null, + fundChatRoomId = descendantRoomId).apply { initiate() } + runBlocking { withTimeout(5_000) { while (unknown.groupSendUIState == GroupSendUIState.Loading) delay(10) } } + assertEquals(GroupSendUIState.Unavailable, unknown.groupSendUIState) + assertEquals(1, asked) + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt index cd416648..096be9ac 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.ui.view.model +import kotlin.test.assertTrue +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.GroupSignedEvent @@ -11,6 +14,7 @@ import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.FrostSigningRepository import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState import com.machankura.bennu.compose.ui.view.state.SpendStatus +import com.machankura.bennu.compose.wallet.GroupWalletRollout import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind @@ -106,11 +110,11 @@ class GroupWalletViewModelJvmTest { } } - private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning()) = + private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning(), chain: Chain = Chain.Mainnet) = GroupWalletViewModel( activeUserPublicKey = me, chatRoomId = chatRoomId, - chain = Chain.Mainnet, + chain = chain, initialGroupWalletUIState = GroupWalletUIState.Loading, chatRepository = chat, frostSigningRepository = signing, @@ -169,6 +173,126 @@ class GroupWalletViewModelJvmTest { runBlocking { withTimeout(5_000) { while (!failed) delay(10) } } } + // ---- a guarded wallet --------------------------------------------------- + + /** What the repository would hand a subgroup whose certificate grants it guardians; the checks behind it are `GroupWalletStatementEventTest`'s. */ + private val certificate = com.vitorpamplona.quartz.nip01Core.core.Event( + "c".repeat(64), "b".repeat(64), 1_700_000_000, 30329, emptyArray(), chatRoomId, "f".repeat(128) + ) + private val guardians = com.machankura.bennu.compose.managers.GuardianDerivation.grant( + PrivateKey(ByteVector32(Hex.decode("9a4e47".padStart(64, '0')))).publicKey().toString(), + "b".repeat(64), emptyList(), chatRoomId, + ) + + private fun guardedRepository( + chain: Chain, + policy: WalletPolicyReading? = WalletPolicyReading.Undecided, + ) = object : ChatRepository by repository(opened = null) { + override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = policy + + override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain) = + com.machankura.bennu.compose.managers.GroupWalletManager.GuardedOpening( + GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), + chain, guardians = guardians, + ), + certificate, + ) + } + + @Test + fun `a subgroup is offered a guarded wallet on a test network and on mainnet`() { + val regtest = assertIs( + viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() + ) + assertEquals(guardians, regtest.guarded?.account?.guardians) + + // Mainnet follows GroupWalletRollout.GUARDIANS_ON_MAINNET, which is on. + val mainnet = assertIs( + viewModel(guardedRepository(Chain.Mainnet)).apply { initiate() }.settled() + ) + assertEquals(GroupWalletRollout.GUARDIANS_ON_MAINNET, mainnet.guarded != null) + assertEquals(guardians, mainnet.guarded?.account?.guardians) + } + + @Test + fun `opening a guarded wallet proposes a statement naming the guardians and carrying the certificate`() { + val signing = RecordingSigning() + val model = viewModel(guardedRepository(Chain.Regtest), signing, chain = Chain.Regtest).apply { initiate() } + model.settled() + + model.openWallet(guarded = true, onSuccess = {}, onFailure = {}) + runBlocking { withTimeout(5_000) { while (signing.proposed == null || model.isActionPending.value) delay(10) } } + + val (_, tags, content) = assertNotNull(signing.proposed) + val reading = assertNotNull(GroupWalletStatementEvent.read(tags, content)) + assertEquals(guardians, reading.guardians) + assertEquals(certificate.id, reading.certificate?.id) + } + + // ---- the parent's decision: docs/subgroup-wallet-policy.md ------------- + + @Test + fun `a subgroup whose parent decided guarded is offered the guarded wallet alone`() { + val state = assertIs( + viewModel(guardedRepository(Chain.Regtest, WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED)), chain = Chain.Regtest) + .apply { initiate() }.settled() + ) + + assertNotNull(state.guarded) + assertFalse(state.offersPlain) + } + + @Test + fun `a subgroup whose parent decided unguarded is offered the plain wallet alone`() { + val state = assertIs( + viewModel(guardedRepository(Chain.Regtest, WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED)), chain = Chain.Regtest) + .apply { initiate() }.settled() + ) + + assertNull(state.guarded) + assertTrue(state.offersPlain) + assertEquals(account, state.account) + } + + @Test + fun `an undecided subgroup is offered both, and a root group the plain one`() { + val undecided = assertIs( + viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() + ) + assertNotNull(undecided.guarded) + assertTrue(undecided.offersPlain) + + val root = assertIs(viewModel(repository(opened = null)).apply { initiate() }.settled()) + assertNull(root.guarded) + assertTrue(root.offersPlain) + } + + @Test + fun `each guardian is named by the room this device holds for it`() { + val state = assertIs( + viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() + ) + + // The fixture's repository answers every room id with the one room. + assertEquals(mapOf(guardians.single().chatRoomId to localChatRoom.chatRoom.subject!!), state.guardianNames) + } + + @Test + fun `a plain wallet is never proposed under a parent that decided guarded`() { + val signing = RecordingSigning() + val model = viewModel( + guardedRepository(Chain.Regtest, WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED)), signing, chain = Chain.Regtest + ).apply { initiate() } + model.settled() + + model.openWallet(guarded = false, onSuccess = {}, onFailure = {}) + runBlocking { delay(200) } + + assertNull(signing.proposed) + assertFalse(model.isActionPending.value) + } + // ---- spends ------------------------------------------------------------ private val coinTx = fr.acinq.bitcoin.Transaction( diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt new file mode 100644 index 00000000..c9648628 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt @@ -0,0 +1,141 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupFixtures +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.MemberWalletPolicyUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Opening a group to its members' wallets, changing the delay, and closing it -- + * `docs/member-wallet-delay.md`, Phase 6. The repositories are fakes: what is + * under test is what the screen offers and what it proposes. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class MemberWalletPolicyViewModelJvmTest { + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private val group = GroupFixtures.keyMaterial("6a0b") + private val chatRoomId = GroupFixtures.roomOf(group) + private val me = "a".repeat(64) + + private val room = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "#Council", description = null, mlsGroupState = "state") + ) + + private fun chat(canSign: Boolean) = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(identifier: String): LocalChatRoom? = room + override suspend fun canSign(chatRoomId: String): Boolean = canSign + } + + private fun members(policy: MemberWalletPolicyEvent.Policy?) = object : MemberWalletRepository by MemberWalletRepository.NO_OP { + override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = policy + } + + private class Proposing : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + var proposed: Pair>>? = null + override suspend fun proposeSigning( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + kind: Kind, + tags: Array>, + content: String, + ): FrostSigningSession? { + proposed = kind to tags + return null + } + } + + private fun open(delay: Long) = MemberWalletPolicyEvent.verify(GroupFixtures.memberWalletPolicy(group, delay), chatRoomId) + private fun closed() = MemberWalletPolicyEvent.verify(GroupFixtures.memberWalletPolicy(group, null), chatRoomId) + + private fun loaded(policy: MemberWalletPolicyEvent.Policy?, canSign: Boolean = true, signing: FrostSigningRepository = Proposing()) = + MemberWalletPolicyViewModel(me, chatRoomId, MemberWalletPolicyUIState.Loading, chat(canSign), members(policy), signing).apply { + initiate() + runBlocking { withTimeout(5_000) { while (uiState !is MemberWalletPolicyUIState.Loaded) delay(10) } } + } + + private fun Proposing.awaitProposed() = runBlocking { withTimeout(5_000) { while (proposed == null) delay(10) } }.let { assertNotNull(proposed) } + + @Test + fun `a group opening for the first time starts at 12, an open one at its own delay`() { + assertEquals(12L, loaded(null).delay.delay()) + assertEquals(12L, loaded(closed()).delay.delay()) + assertEquals(4_320L, loaded(open(4_320)).delay.delay()) + assertTrue(loaded(open(4_320)).delay.isCustom.value.not(), "a preset comes back as its chip") + assertTrue(loaded(open(2_016)).delay.isCustom.value, "anything else in the field") + } + + @Test + fun `opening proposes an open policy at the chosen delay`() { + val signing = Proposing() + val viewModel = loaded(null, signing = signing) + viewModel.delay.pick(1_008) + assertNull(viewModel.openProblem()) + + viewModel.proposeOpen(onSuccess = {}, onFailure = {}) + val (kind, tags) = signing.awaitProposed() + assertEquals(MemberWalletPolicyEvent.KIND, kind) + assertTrue(tags.any { it.toList() == listOf("guardian_delay", "1008") }) + } + + @Test + fun `a delay out of range, or the group's own, is not proposed`() { + val viewModel = loaded(open(144)) + assertEquals("That is already this group's delay.", viewModel.openProblem()) + + viewModel.delay.useCustom() + viewModel.delay.type("5") + assertEquals("A delay is at least 6 blocks.", viewModel.openProblem()) + viewModel.delay.type("65536") + assertEquals("A delay is at most 65,535 blocks.", viewModel.openProblem()) + } + + @Test + fun `closing is offered only to an open group, and proposes a closed policy`() { + assertFalse(loaded(null).canClose()) + assertFalse(loaded(closed()).canClose()) + + val signing = Proposing() + val viewModel = loaded(open(144), signing = signing) + assertTrue(viewModel.canClose()) + viewModel.proposeClose(onSuccess = {}, onFailure = {}) + val (_, tags) = signing.awaitProposed() + assertTrue(tags.any { it.toList() == listOf("closed") }) + } + + @Test + fun `a device that cannot sign is offered nothing to propose`() { + val viewModel = loaded(open(144), canSign = false) + assertIs(viewModel.uiState) + assertNotNull(viewModel.openProblem()) + assertFalse(viewModel.canClose()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt new file mode 100644 index 00000000..3479f48c --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt @@ -0,0 +1,81 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.MemberWalletManager.Refusal +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.NewMemberWalletUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs + +/** + * Which groups the *Choose a group to guard it* list offers -- + * `docs/member-wallet-delay.md`. Only a group that guards members' wallets, or + * may: one whose key this device has not been told is kept, with the button + * that asks, because the answer is how it would learn the group is open. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class NewMemberWalletViewModelJvmTest { + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private val me = "a".repeat(64) + + private fun room(id: Char) = LocalChatRoom( + chatRoom = ChatRoom(id = id.toString().repeat(64), userPublicKey = me, subject = "#$id", description = null, mlsGroupState = "state") + ) + + /** One group per refusal, and one that can be asked. */ + private val refusals: Map = mapOf( + room('1') to null, + room('2') to Refusal.KEY_UNKNOWN, + room('3') to Refusal.NOT_OFFERED, + room('4') to Refusal.CLOSED, + room('5') to Refusal.GUARDIANS_UNREADABLE, + ) + + private fun repository(groups: Map) = object : MemberWalletRepository by MemberWalletRepository.NO_OP { + override suspend fun groupsOf(ownerPublicKey: HexKey): List = groups.keys.toList() + override suspend fun refusal(chatRoomId: String, chain: Chain): Refusal? = + groups.entries.first { it.key.chatRoom.id == chatRoomId }.value + } + + private fun picking(groups: Map): NewMemberWalletUIState.Picking { + val viewModel = NewMemberWalletViewModel(me, null, Chain.Regtest, canWatch = true, NewMemberWalletUIState.Loading, repository(groups)) + viewModel.initiate() + runBlocking { withTimeout(5_000) { while (viewModel.uiState == NewMemberWalletUIState.Loading) delay(10) } } + return assertIs(viewModel.uiState) + } + + @Test + fun `a group that never opened, or has closed, is not on the list`() { + val listed = picking(refusals).groups.associate { it.room.chatRoom.subject to it.refusal } + + assertEquals( + mapOf("#1" to null, "#2" to Refusal.KEY_UNKNOWN, "#5" to Refusal.GUARDIANS_UNREADABLE), + listed, + "an open group, one whose key is not known yet, and one this build cannot read stay, each with its reason", + ) + } + + @Test + fun `a member none of whose groups guards members' wallets sees an empty list`() { + assertEquals(emptyList(), picking(mapOf(room('3') to Refusal.NOT_OFFERED, room('4') to Refusal.CLOSED)).groups) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt new file mode 100644 index 00000000..4f2bb945 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt @@ -0,0 +1,345 @@ +package com.machankura.bennu.compose.ui.view.model + +import kotlin.test.assertTrue +import kotlin.test.assertFalse +import kotlin.test.assertNull +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.MarmotKeyPackage +import com.machankura.bennu.compose.database.model.Participant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.nostr.MarmotProfile +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.ui.view.state.SelectSubgroupAdminsUIState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * Trying a failed subgroup ceremony again starts from what it was. + * + * The ceremony screen used to retry any failed ceremony by opening a group's own + * -- in a parent's room, a whole-room ceremony that was never the subgroup at + * all. It now sends a subgroup's back to this picker, and the picker has to + * start from the name, the admins and the quorum that failed. See + * docs/ceremony-creation.md, finding F7. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class SelectSubgroupAdminsViewModelJvmTest { + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val parentChatRoomId = "9a7e".repeat(16) + private val failedId = "fa11".repeat(16) + + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + private val cleo = "c".repeat(64) + + /** Was an admin of the failed ceremony, and has since left the parent. */ + private val dora = "d".repeat(64) + + private val parent = LocalChatRoom( + chatRoom = ChatRoom( + id = parentChatRoomId, + userPublicKey = ada, + subject = "#Checkers", + description = null, + mlsGroupState = "state", + ), + localParticipants = listOf(ada, bob, cleo).map { + LocalParticipant(Participant(participantPublicKey = it, chatRoomId = parentChatRoomId, relayHint = null), null) + }, + ) + + private fun failed( + parentChatRoomId: String? = this.parentChatRoomId, + walletPolicy: SubgroupWalletPolicy? = null, + guardianDelay: Long? = null, + ) = DkgSession( + id = failedId, + chatRoomId = this.parentChatRoomId, + coordinatorPublicKey = ada, + userPublicKey = ada, + threshold = 3, + participantCount = 4, + participantPublicKeys = DkgSession.formatParticipants(setOf(ada, bob, cleo, dora)), + subject = "Tapscript", + stage = DkgRitualStage.FAILED, + hostPublicKey = ada, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + parentChatRoomId = parentChatRoomId, + walletPolicy = walletPolicy?.tagValue, + guardianDelay = guardianDelay, + ) + + private fun chatRepository( + parentPolicy: WalletPolicyReading? = null, + parentGuardians: List? = emptyList(), + ) = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = + parent.takeIf { id == parentChatRoomId } + + override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = + parentPolicy.takeIf { chatRoomId == parentChatRoomId } + + override suspend fun guardiansOf(chatRoomId: String): List? = + parentGuardians.takeIf { chatRoomId == parentChatRoomId } + + // Never answers, so the lookup is still out while the test looks: what is + // under test is what the form starts from, not who has a key package. + override suspend fun observeMarmotKeyPackageForPublicKey( + publicKey: HexKey, + roomProfile: MarmotProfile, + ): Flow = flow { awaitCancellation() } + } + + private fun viewModel( + session: DkgSession?, + retrying: String? = failedId, + chatRepository: ChatRepository = chatRepository(), + ) = SelectSubgroupAdminsViewModel( + activeUserPublicKey = ada, + parentChatRoomId = parentChatRoomId, + retrying = retrying, + initialUIState = SelectSubgroupAdminsUIState.Loading, + activeIdentityStateFlow = MutableStateFlow(null), + chatRepository = chatRepository, + dkgRepository = object : DkgRepository by DkgRepository.NO_OP_DKG_REPOSITORY { + override fun observeSessionById(sessionId: String): Flow = + flowOf(session?.takeIf { it.id == sessionId }) + }, + ) + + private suspend fun SelectSubgroupAdminsViewModel.awaitLoaded() = withTimeout(5_000) { + while (uiState !is SelectSubgroupAdminsUIState.Loaded) delay(10) + delay(50) + } + + @Test + fun `a retry starts from the failed ceremony's name, admins and quorum`(): Unit = runBlocking { + val viewModel = viewModel(failed()) + viewModel.initiate() + viewModel.awaitLoaded() + + assertEquals("Tapscript", viewModel.name.value) + assertEquals( + setOf(bob, cleo), + viewModel.selectedPublicKeys.toSet(), + "everyone it was with who is still in the parent, the coordinator not among them", + ) + assertEquals(3, viewModel.threshold.value) + } + + @Test + fun `a member's edits survive the screen coming back into view`(): Unit = runBlocking { + val viewModel = viewModel(failed()) + viewModel.initiate() + viewModel.awaitLoaded() + + viewModel.setName("Tapscript II") + viewModel.initiate() + viewModel.awaitLoaded() + + assertEquals("Tapscript II", viewModel.name.value) + } + + @Test + fun `a ceremony that was not this parent's subgroup fills nothing in`(): Unit = runBlocking { + val viewModel = viewModel(failed(parentChatRoomId = null)) + viewModel.initiate() + viewModel.awaitLoaded() + + assertEquals("", viewModel.name.value) + assertEquals(emptySet(), viewModel.selectedPublicKeys.toSet()) + } + + private val guarded = WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) + + /** A guarded parent's view model, loaded, with a name typed so a refusal is about the policy. */ + private suspend fun underGuardedParent(session: DkgSession? = null) = + viewModel(session, chatRepository = chatRepository(parentPolicy = guarded)).apply { + initiate() + awaitLoaded() + setName("Tapscript") + } + + @Test + fun `a subgroup is guarded unless the coordinator says otherwise`(): Unit = runBlocking { + val viewModel = viewModel(null, retrying = null) + viewModel.initiate() + viewModel.awaitLoaded() + + assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value) + + viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) + assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value, "a root group may make either") + } + + @Test + fun `a guarded parent's subgroup is guarded, and stays so`(): Unit = runBlocking { + val viewModel = underGuardedParent() + + assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value) + viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) + assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value, "D4: the choice is not the coordinator's") + assertNull(viewModel.refusal()?.takeIf { "guarded" in it }) + } + + @Test + fun `a guarded parent refuses an unguarded subgroup that got past the screen`(): Unit = runBlocking { + val viewModel = underGuardedParent() + + // The state forced, as a bug or a skipped screen would leave it. + viewModel.walletPolicy.value = SubgroupWalletPolicy.UNGUARDED + + assertEquals("This group is guarded, so its subgroups are too.", viewModel.refusal()) + } + + @Test + fun `a retry of an unguarded ceremony under a guarded parent comes back guarded`(): Unit = runBlocking { + val viewModel = underGuardedParent(failed(walletPolicy = SubgroupWalletPolicy.UNGUARDED)) + + assertEquals("Tapscript", viewModel.name.value) + assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value) + } + + @Test + fun `a retry starts from the failed ceremony's wallet policy`(): Unit = runBlocking { + val viewModel = viewModel(failed(walletPolicy = SubgroupWalletPolicy.UNGUARDED)) + viewModel.initiate() + viewModel.awaitLoaded() + + assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value) + } + + @Test + fun `an unguarded or undecided parent may make either`(): Unit = runBlocking { + listOf(WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED), WalletPolicyReading.Undecided).forEach { policy -> + val viewModel = viewModel(null, retrying = null, chatRepository = chatRepository(parentPolicy = policy)) + viewModel.initiate() + viewModel.awaitLoaded() + + viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) + assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value, "under $policy") + viewModel.setWalletPolicy(SubgroupWalletPolicy.GUARDED) + assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value, "under $policy") + } + } + + @Test + fun `a parent whose guardian keys do not read cannot make a guarded subgroup`(): Unit = runBlocking { + val viewModel = viewModel(null, retrying = null, chatRepository = chatRepository(parentGuardians = null)) + viewModel.initiate() + viewModel.awaitLoaded() + viewModel.setName("Tapscript") + + assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value) + viewModel.setWalletPolicy(SubgroupWalletPolicy.GUARDED) + assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value) + + viewModel.walletPolicy.value = SubgroupWalletPolicy.GUARDED + assertEquals( + "This group's own guardian keys can't be read, so it can't guard a subgroup.", + viewModel.refusal(), + "refused here, not after a ceremony", + ) + } + + // ---- the guardian delay: docs/guardian-delay.md, Phase 5 --------------- + + private suspend fun loadedWithName(session: DkgSession? = null) = viewModel(session).apply { + initiate() + awaitLoaded() + setName("Tapscript") + } + + @Test + fun `a guarded subgroup's delay starts at the default`(): Unit = runBlocking { + val viewModel = loadedWithName() + + assertEquals(12L, viewModel.guardianDelay()) + assertFalse(viewModel.isCustomDelay.value) + assertNull(viewModel.guardianDelayProblem()) + } + + @Test + fun `a preset and a typed delay are what refusal judges`(): Unit = runBlocking { + val viewModel = loadedWithName() + + viewModel.setGuardianDelay(4_320) + assertEquals(4_320L, viewModel.guardianDelay()) + assertNull(viewModel.refusal()?.takeIf { "delay" in it }) + + viewModel.useCustomDelay() + viewModel.setGuardianDelayInput("2,016") + assertEquals(2_016L, viewModel.guardianDelay(), "grouping is dropped as it is typed") + assertTrue(viewModel.isCustomDelay.value) + } + + @Test + fun `a delay below six or above 65535 is refused with its reason`(): Unit = runBlocking { + val viewModel = loadedWithName() + viewModel.useCustomDelay() + + viewModel.setGuardianDelayInput("5") + assertEquals("A delay is at least 6 blocks.", viewModel.refusal()) + + viewModel.setGuardianDelayInput("65536") + assertEquals(65_536L, viewModel.guardianDelay(), "kept as typed, so the field can say what is wrong with it") + assertEquals("A delay is at most 65,535 blocks.", viewModel.refusal()) + + viewModel.setGuardianDelayInput("") + assertEquals("Give the delay in blocks.", viewModel.refusal()) + } + + @Test + fun `an unguarded subgroup is not held to a delay`(): Unit = runBlocking { + val viewModel = loadedWithName() + viewModel.useCustomDelay() + viewModel.setGuardianDelayInput("5") + viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) + + assertNull(viewModel.refusal()?.takeIf { "delay" in it }) + } + + @Test + fun `a retry starts from the failed ceremony's delay`(): Unit = runBlocking { + val preset = loadedWithName(failed(walletPolicy = SubgroupWalletPolicy.GUARDED, guardianDelay = 1_008)) + assertEquals(1_008L, preset.guardianDelay()) + assertFalse(preset.isCustomDelay.value, "a preset comes back as the preset") + + val typed = loadedWithName(failed(walletPolicy = SubgroupWalletPolicy.GUARDED, guardianDelay = 2_016)) + assertEquals(2_016L, typed.guardianDelay()) + assertTrue(typed.isCustomDelay.value, "anything else comes back in the field") + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt index f2d51fbe..83558bbc 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt @@ -41,6 +41,9 @@ internal class FakeElectrum : IElectrumClient { /** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */ private val history = mutableMapOf() + /** The transactions that touched each script, in order: what `get_history` answers. */ + private val historyTxs = mutableMapOf>() + private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" } /** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */ @@ -55,6 +58,7 @@ internal class FakeElectrum : IElectrumClient { val hash = scriptHash(script) unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height) history[hash] = (history[hash] ?: 0) + 1 + historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) } @@ -66,6 +70,17 @@ internal class FakeElectrum : IElectrumClient { notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) } + /** The transaction paying [script] most recently, as [pay] made it. */ + fun fundingOf(script: ByteVector): Transaction = txs.getValue(historyTxs.getValue(scriptHash(script)).last()) + + /** Spends what [script] holds with [tx] itself, which joins its history as a real spend would. */ + suspend fun spendWith(script: ByteVector, tx: Transaction) { + val hash = scriptHash(script) + txs[tx.txid] = tx + historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid + spend(script) + } + override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse { subscribed += scriptHash return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash)) @@ -76,7 +91,8 @@ internal class FakeElectrum : IElectrumClient { override suspend fun getHeader(blockHeight: Int): BlockHeader? = null override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = + historyTxs[scriptHash].orEmpty().map { TransactionHistoryItem(100, it) } override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt index 61150c11..d1915e8b 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt @@ -7,6 +7,7 @@ import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.Satoshi import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.WalletState import fr.acinq.secp256k1.Hex import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -242,4 +243,79 @@ class GroupOnchainWalletJvmTest { assertEquals(Satoshi(7_000), used.balance) assertEquals(before.listed(), state.listed()) } + + @Test + fun `a fresh wallet is funded two past the current address`() { + val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) + + val state = eventually { wallet.state.first { it.receive.addresses.size == GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() } } + val funding = state.fundingAddress()!! + assertEquals(receive(2), funding.derivation) + assertEquals(receive(2).address(Chain.Regtest), funding.address) + assertEquals(GroupAddress.Status.NEXT, funding.status) + } + + @Test + fun `an open funding holds its address and the window ends where the watching does`() { + val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) + val lookAhead = GroupOnchainWallet.RECEIVE_LOOKAHEAD.toLong() + + val state = eventually { wallet.state.first { it.receive.addresses.size == lookAhead.toInt() } } + assertEquals(receive(3), state.fundingAddress(setOf(2L))!!.derivation) + val held = (GroupOnchainWallet.ADDRESSES_AHEAD.toLong() until lookAhead).toSet() + assertEquals(receive(lookAhead - 1), state.fundingAddress(held - (lookAhead - 1))!!.derivation) + assertNull(state.fundingAddress(held), "past the last watched address the child would not see the payment") + } + + @Test + fun `being paid moves the funding address on`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddress != null } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } + + val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } + assertEquals(receive(3), state.fundingAddress()!!.derivation) + } + + @Test + fun `a paid address above the current one is never funded`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddress != null } } + eventually { electrum.pay(receive(4).pubkeyScript, Satoshi(10_000)) } + + val state = eventually { wallet.state.first { it.receiveAddresses?.any { it.status == GroupAddress.Status.USED } == true } } + assertEquals(receive(0).address(Chain.Regtest), state.receiveAddress) + assertEquals(receive(2), state.fundingAddress()!!.derivation) + assertEquals(receive(3), state.fundingAddress(setOf(2L))!!.derivation) + assertEquals(receive(5), state.fundingAddress(setOf(2L, 3L))!!.derivation) + } + + @Test + fun `no funding address before Electrum has answered`() { + val state = GroupWalletState(account, WalletState.empty, WalletState.empty, tipHeight = null) + assertNull(state.fundingAddress()) + } + + @Test + fun `every funding address is one the wallet watches`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddress != null } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(1_000)) } + + val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } + val watched = state.receive.addresses.keys + var reserved = emptySet() + while (true) { + val funding = state.fundingAddress(reserved) ?: break + assertTrue(funding.address in watched, "${funding.derivation.index} is funded but not watched") + reserved = reserved + funding.derivation.index + } + assertEquals(GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() - GroupOnchainWallet.ADDRESSES_AHEAD, reserved.size) + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt index 2d8bc5b1..c80bb318 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt @@ -59,17 +59,21 @@ class GroupTransactionWatcherJvmTest { val broadcasts = mutableListOf() /** Confirmations by txid; absent is "Electrum has not heard of it". */ val confirmations = mutableMapOf() + /** What each script hash still holds, has seen, and the transactions behind both. */ + val unspents = mutableMapOf>() + val histories = mutableMapOf>() + val txs = mutableMapOf() override val notifications = MutableSharedFlow() override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid.also { broadcasts += it } override suspend fun getConfirmations(tx: Transaction): Int? = confirmations[tx.txid] - override suspend fun getTx(txId: TxId): Transaction? = null + override suspend fun getTx(txId: TxId): Transaction? = txs[txId] override suspend fun getHeader(blockHeight: Int): BlockHeader? = null override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() - override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = emptyList() + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = histories[scriptHash].orEmpty() + override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null override suspend fun startScriptHashSubscription(scriptHash: ByteVector32) = ScriptHashSubscriptionResponse(scriptHash, null) override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) @@ -198,4 +202,70 @@ class GroupTransactionWatcherJvmTest { assertEquals(1, lines.size) assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "neither signed spend is still on its way") } + + // ---- Coins another room's transaction took ------------------------------ + + /** The script the guarded coin sits at, and its Electrum script hash. */ + private val coinScript = ByteVector("5120" + "ab".repeat(32)) + private val coinHash = ByteVector32(fr.acinq.bitcoin.Crypto.sha256(coinScript.toByteArray()).reversedArray()) + + /** A signed spend of [coin] whose PSBT names the output it spends, as every real proposal's does. */ + private suspend fun signedSpendOfCoin(id: String, tx: Transaction) { + db.frostSigningSessionDao().upsert( + FrostSigningSession( + id = id, chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, dkgSessionId = "dkg", + threshold = 2, participantCount = 3, signerId = 0, stage = FrostSigningStage.COMPLETE, subject = FrostSigningSubject.TRANSACTION, + ) + ) + val psbt = Psbt(tx).updateWitnessInput(coin, TxOut(Satoshi(10_000), coinScript)).right!! + db.groupTransactionDao().insertIfAbsent( + GroupTransaction( + frostSigningSessionId = id, chatRoomId = room, chain = "regtest", account = 0, + psbt = GroupSpend.encode(psbt), txid = tx.txid.toString(), signedTransaction = Hex.encode(Transaction.write(tx)), + ) + ) + } + + /** Somebody else -- a guardian, or the guarded group itself -- spends [coin], at [height] (0 for the mempool). */ + private fun takenElsewhere(height: Int): Transaction { + val theirs = spending(coin, pay = 7_000).copy(txOut = listOf(TxOut(Satoshi(7_000), ByteVector("0014" + "11".repeat(20))))) + electrum.txs[theirs.txid] = theirs + electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid), TransactionHistoryItem(height, theirs.txid)) + return theirs + } + + @Test + fun `a spend whose coin another transaction took is replaced once that transaction confirms`(): Unit = runBlocking { + seed() + val ours = spending(coin, pay = 9_000) + signedSpendOfCoin("ours", ours) + // Another of this room's spends of the same coin, still collecting. + spend("collecting", spending(coin, OutPoint(TxId(ByteVector32(ByteArray(32) { 6 })), 0), pay = 12_000), FrostSigningStage.COLLECTING_NONCES, signed = false) + + val theirs = takenElsewhere(height = 101) + watcher.pass() + + assertEquals(theirs.txid.toString(), db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + assertEquals(FrostSigningStage.COMPLETE, db.frostSigningSessionDao().getSessionById("ours")?.stage, "it was signed, and stays so") + assertEquals(FrostSigningStage.FAILED, db.frostSigningSessionDao().getSessionById("collecting")?.stage) + assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "nothing is left being sent again every ten minutes") + } + + @Test + fun `a coin taken only in the mempool, or not taken at all, settles nothing`(): Unit = runBlocking { + seed() + signedSpendOfCoin("ours", spending(coin, pay = 9_000)) + + // Still unspent where it sits. + electrum.unspents[coinHash] = listOf(UnspentItem(coin.txid, coin.index.toInt(), 10_000, 90)) + electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid)) + watcher.pass() + assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + + // Spent by something unconfirmed: ours may yet be the one that confirms. + electrum.unspents.remove(coinHash) + takenElsewhere(height = 0) + watcher.pass() + assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt new file mode 100644 index 00000000..3ad1afa0 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt @@ -0,0 +1,91 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptWitness +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A guarded wallet reading its own history for spends its guardians made -- + * the child's only notice of one, since nobody in its room signed it. + * + * The witnesses here are the right shape and carry no valid signature: what is + * under test is which leaf a spend used, which the chain records whether or not + * anybody checks the signature again. `GuardianSigningJvmTest` spends for real. + */ +class GuardianSpendNoticeJvmTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @AfterTest + fun stop() = scope.cancel() + + private fun key(seed: Int): String = PrivateKey(ByteVector32(ByteArray(32) { seed.toByte() })).publicKey().toString() + + private val chain = Chain.Regtest + private val parentRoom = SharedKeyDerivation.marmotGroupId(key(1)) + private val childKey = key(2) + private val childRoom = SharedKeyDerivation.marmotGroupId(childKey) + private val grant = GuardianDerivation.grant(key(1), parentRoom, emptyList(), childRoom) + private val account = GroupWalletDerivation.account(childKey, chain, guardians = grant) + private val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) + + /** The wallet after its one coin has been spent: the address used, nothing left on it. */ + private val spentState = GroupWalletState( + account, + WalletState(mapOf(coin.address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), alreadyUsed = true, utxos = emptyList()))), + WalletState(emptyMap()), + tipHeight = 200, + ) + + private fun spending(funding: Transaction, witness: ScriptWitness) = Transaction( + 2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GuardianDerivation.DEFAULT_DELAY, witness)), + listOf(TxOut(Satoshi(49_000), elsewhere)), 0, + ) + + @Test + fun `a spend through the parent's leaf is read off the address's history`(): Unit = runBlocking { + val electrum = FakeElectrum() + electrum.pay(coin.pubkeyScript, Satoshi(50_000)) + val funding = electrum.fundingOf(coin.pubkeyScript) + val leaf = GuardianDerivation.leaves(grant, chain, 0, coin.change, coin.index)[0] + val taken = spending(funding, Script.witnessScriptPathPay2tr(coin.internalKey, leaf, ScriptWitness(listOf(ByteVector(ByteArray(64)))), coin.tree!!)) + electrum.spendWith(coin.pubkeyScript, taken) + + val wallets = GroupOnchainWallets(electrum, scope) + assertEquals( + listOf(GuardianManager.Taken(taken.txid, grant[0], Satoshi(50_000))), + wallets.guardianSpends(spentState), + ) + } + + @Test + fun `the group's own key-path spend names no guardian`(): Unit = runBlocking { + val electrum = FakeElectrum() + electrum.pay(coin.pubkeyScript, Satoshi(50_000)) + val own = spending(electrum.fundingOf(coin.pubkeyScript), Script.witnessKeyPathPay2tr(fr.acinq.bitcoin.ByteVector64.Zeroes)) + electrum.spendWith(coin.pubkeyScript, own) + + assertEquals(emptyList(), GroupOnchainWallets(electrum, scope).guardianSpends(spentState)) + } +} diff --git a/docs/README.md b/docs/README.md index 8451daa3..146a0a65 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,9 +9,18 @@ silent, or a decision that looked arbitrary and was not. | [shared-key-ceremony.md](./shared-key-ceremony.md) | ChillDKG over NIP-17: the rounds, the approval gates, the chat transcript, participant ordering | | [shared-key-derivation.md](./shared-key-derivation.md) | deriving further keys from the group's threshold key with FROST tweaks — why not BIP32, why no chain code, and the one rule that must not be broken | | [subgroups.md](./subgroups.md) | a group making another group — the four ceremonies, what the parent's signature actually covers, and why the child's key is fresh rather than derived | +| [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | | [frost-batch-signing.md](./frost-batch-signing.md) | signing several events in one ceremony — why one nonce can never cover two messages, and the phased schema, wire and UI work that follows from it | | [group-chain-wallet.md](./group-chain-wallet.md) | an on-chain wallet the group's threshold key holds, modelled on Phoenix's final wallet — why the path is BIP86's unhardened tail under a public account step, why each input is a batch item with its own cache, and the seven checks a member makes before signing a spend | | [group-send-an-amount.md](./group-send-an-amount.md) | sending an amount in sats from the group's wallet, with change — why the gate as written could never lift and is removed in favour of the mainnet cap, the decimal point the gated form multiplies by ten, and change addresses reserved like coins | +| [group-wallet-guardians.md](./group-wallet-guardians.md) | letting an ancestor group spend from a subgroup's wallet through a taproot leaf — why the parent signs the guardian keys into the child's certificate, why every inherited key is derived one step further per child, and why every ancestor waits 12 blocks | +| [subgroup-wallet-policy.md](./subgroup-wallet-policy.md) | the parent deciding, at a subgroup's birth, whether its wallet is guarded or unguarded — why the choice is signed three times, why *unguarded* means no keys in the certificate, why a guarded group's subgroups are all guarded, and why the rule is every honest client's rather than the chain's | +| [member-wallet-delay.md](./member-wallet-delay.md) | a group deciding whether it guards members' wallets, at what delay, and closing again -- why a group-signed event of its own rather than the birth certificate, why no event means not offered, why the request carries the policy it was built under, and why closing never releases a wallet already guarded | +| [guardian-delay.md](./guardian-delay.md) | a parent choosing how long a coin waits before a guardian can take it, from 6 blocks to BIP68's 65,535 -- why each ancestor keeps the delay it chose as its key goes down the tree, what a long delay gives the child, and how a number of blocks is said in time | +| [member-guarded-wallets.md](./member-guarded-wallets.md) | a guarded wallet a group keeps for one member — why the member makes the key and the leaves before asking, why the group signs a certificate of its own kind rather than a birth certificate, and why a member's wallet shows as `@name` and opens their profile | +| [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md) | telling the groups above about a guarded wallet without anybody pressing *Share* — why it goes upward only, why one device sends at once and the rest catch up, and the two bugs in the button it fixes on the way | +| [member-wallet-guarding-group.md](./member-wallet-guarding-group.md) | naming the group that directly guards each member wallet in an ancestor's list, and gathering a person's wallets under them -- why the direct guardian is the certificate's signer, why the founding name comes before the live one, and why the forwarding notice carries the guardian's birth certificate as a tag | +| [guarded-wallet-funding.md](./guarded-wallet-funding.md) | a group paying into a descendant's guarded wallet — why the address is the first unreserved one from `current + 2`, why the claim rides in the PSBT output's derivation and every signer rederives it, and how the guarded wallet row makes room for *Fund* beside *Spend* | | [group-wallet-addresses.md](./group-wallet-addresses.md) | listing the group wallet's receive addresses as Phoenix lists its swap-in ones — why the list stops at the current address plus two, why a paid address past that still shows, and why a used address can be copied but never shown as a QR code | | [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device | | [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite | @@ -38,9 +47,10 @@ failures a resend repairs and which heal on their own. The sync note stands alone, and the dead-code inventory reads as a follow-up to it. The batch-signing note is a phased plan that has been built: read it after the derivation note, whose one rule is the same one it is built around. The member -chronicle note is a phased plan that has not been built, and reads as the -membership note's unanswered half: what a member who joins late can be given, -and the one thing they cannot. The +chronicle note is a phased plan that has been built and now carries nothing -- +the document kinds it was for are gone -- and reads as the membership note's +unanswered half: what a member who joins late can be given, and the one thing +they cannot. The jvm-target note is unrelated to all of them: it is a build and packaging story. The subgroups note is a phased plan that has been built; it assumes both shared-key notes and reads as the ceremony's second half — what a group does @@ -49,6 +59,40 @@ The group-wallet-addresses note is a phased plan that has been built, and is the group-chain-wallet note's Phase 5 taken one screen further: read that note's Phases 4 and 5 first, and its own table of where the build chose differently before the code. +The group-wallet-guardians note is a phased plan that has been built; it assumes the subgroups and group-chain-wallet notes, and changes one sentence in +each. +The member-guarded-wallets note is a phased plan that has been built. It +takes the guardians note's derivation unchanged and gives the key path to one +person: read that note and the policy note's D2 first, then this note's table +of why a birth certificate will not do, its Phase 0, and its table of where the +build chose differently before the code. +The member-wallet-guarding-group note is a phased plan that has been built, +and changes what the member-guarded-wallets note's Phases 10 and 11 draw, not +what they verify: read those two phases first. +The subgroup-wallet-policy note is a phased plan that has been built. It +reads as the guardians note's *whose choice it is* reversed: read +that section, then this note's Phase 0, whose five decisions shape every phase +after it, and its table of where the build chose differently before the code. +The guardian-delay note is a phased plan that has been built. It changes +the guardians note's *Why 12, and why for everybody* and reuses the +wallet-policy note's plumbing one field further: read both, then its table of +what is already per leaf, then its Phase 0, and its table of where the build +chose differently before the code. +The member-wallet-delay note is a phased plan that has been built. It +reads as the guardian-delay note's last build-table row answered: read the +member-wallets note and the guardian-delay note first, then its table of where +the delay should live, then its Phase 0, and its table of where the build chose +differently before the code. +The guarded-wallet-forwarding note is a phased plan that has been built. +It changes who sends a 30333 notice and when, and no format: read the guardians +note's *How an ancestor finds the coins* and the member-guarded-wallets note's +Phase 10 first, then its two bugs, its Phase 0, and its table of where the build +chose differently before the code. +The guarded-wallet-funding note is a phased plan that has been built. It +reads as the guardians note run the other way, coins in rather than out: read +that note and the address note's *Why `+ 2`* first, then its seven decisions +before its phases, and its table of where the build chose differently before +the code. The Material Design note is a phased plan that has not been built, and is the only one about what the app looks like rather than what it does; read the jvm-target note first if you want to know why its adaptive-layout phase exists. @@ -88,8 +132,16 @@ The group send-an-amount note is a phased plan that has been built, and reads as the third gate of the group chain wallet note's Phase 10: why that gate could not lift as written, and what stands in for it now that it is gone. Read its list of what the gated code got wrong before its phases. -The group Lightning wallet note is a phased plan that has not been built. It -assumes the group chain wallet note and the ceremony note, and reads as the -lightning-kmp fork's `FEATURE-PARITY.md` taken past its "out of scope" line: -read its eight constraints and its decision table before any phase, and its -trust table before arguing with either. +The ceremony-creation note is a phased plan that has been built. It reads as +the subgroups note's Phase 10 followed through to the screens: read it after +that phase, and its table of findings before any phase. Its second half +removes the nip30303 documents and leaves the member chronicle built but +carrying no kinds, so read it before building on the chronicle note. + +The group Lightning wallet note is a phased plan that has been built, except +for splicing out, and run end to end on regtest. It assumes the group chain +wallet note and the ceremony note, and reads as the lightning-kmp fork's +`FEATURE-PARITY.md` taken past its "out of scope" line: read its eight +constraints and its decision table before any phase, its trust table before +arguing with either, and its two tables of what the build found before +changing anything it describes. diff --git a/docs/ceremony-creation.md b/docs/ceremony-creation.md new file mode 100644 index 00000000..b4e8db37 --- /dev/null +++ b/docs/ceremony-creation.md @@ -0,0 +1,667 @@ +# One place to start a key ceremony + +A plan to fix the bug where joining a subgroup's key ceremony could start a +second, unrelated one. It also removes the nip30303 document and translation +code, whose event kinds overlap the ceremony's own. The member chronicle, which +carried nothing but nip30303 events, is kept as an empty shell that no longer +asks for or sends anything. + +Read [shared-key-ceremony.md](./shared-key-ceremony.md) and +[subgroups.md](./subgroups.md) first, Phase 10 of the second in particular: the +bug exists because a subgroup's ceremony moved into the parent's Marmot room, and +the screens that start and show ceremonies were written for a room that only ever +held its own. + +**Built**, one commit per phase on `claude/ceremony-creation` (Phase 7 in two), +against the code as it stood at `e3839da5`. `CreateSharedKeyScreen` is the one +screen that starts a group's own ceremony, and `DkgRitualScreen` only ever shows +one. The phases are kept as written because they are the reasoning; where the +build chose differently it did so these times: + +| what the plan said | what it turned out to be | +|---|---| +| Phase 7 deletes the 103 files, Phase 8 the tables | the line moved. The `Mantra*` entities convert to and from the nip30303 event classes, so the classes, entities and DAOs went in Phase 8 with the tables. Phase 7 removed the screens (part 1) and the inbound handling, `ProposedEvent`'s arms and the chronicle's document parts (part 2) | +| the group details' **Shared key** opens an existing ceremony itself, else the creation screen | it always opens `CreateSharedKeyRoute`, which hands over to an existing ceremony. One place decides, and back from the ceremony still returns to the details | +| only `DkgRitualRoute.dkgSessionId` becomes required | the three approval routes' too, and `DkgRitualUIState.Loaded.session` is non-null. Every approval was already named by the ceremony screen that opened it | +| the subgroup picker's quorum stepper and the shared-key one are one component | two. The picker's asks a different question ("how many admins have to approve a change"), so the shared-key one is `SharedKeyQuorumStepper`, private to the creation screen | +| `requestIfEmpty` keeps its "holds work" check | it had to change: the check read the dialect and artifact tables. A room now holds work if it holds a `GroupSignedEvent` of a chroniclable kind, and with none chroniclable it never asks | +| the chronicle's tests re-fixture | three of four did, with `TEST_KINDS` (a relay list, a profile, a post -- group-signed kinds whose arrival writes no row of its own, so the `GroupSignedEvent` rows are the observable). `ChronicleRoundTripTest` was entirely the rebuild through document rows and is deleted. The positive invite push could not take a test set -- `deliveryWelcome` calls `sendTo` with the app's kinds -- and became the "sends nothing" case | +| `SignedGroupKeyStateTest` and `GroupSignedEventDaoJvmTest` re-fixture in Phase 8 | Phase 7: they failed at runtime the moment document arms stopped writing rows. They sign posts now, and "the row a signed event becomes points back at it" is deleted -- no kept kind writes a row | +| a migration test with tables copied from `26.json` | built from the exported `26.json` at run time and compared with `27.json`, so it cannot drift from what Room expects | +| `CLAUDE.md`'s literal count goes to 20 | 19, after Phase 5 took another | +| 61 strings plus four already unused | 65 in all: the string catalogue test's two chapter strings went once it checked its escapes on `recovered_of_still_unreadable` instead | + +**Checked on the three emulators that found the bug**, upgraded in place from +v26 with their data. The migration ran on each: v27, no document tables, and the +raw-hex bubbles gone from Bob's and Charlie's `#Checkers`. Bob abandoned the +stray whole-room ceremony `8199d186` from its screen and it ended on all three; +its **Try again** led to the creation screen's Marmot-room refusal. Then +Tapscript (`89d4c4d0`) ran to completion: Bob and Charlie each approved round +one and came back to its screen with no start button on it -- the step where +Charlie had opened the second ceremony -- and all three confirmed round two and +hold the same key. No new ceremony, no `unsupported` line, and no chronicle +request, page or line on any device. The NIP-17 `Checkers` group's **Shared +key** handed over to its finished ceremony, and back returned to its details. +Not exercised on a device: the certificate and key state after Tapscript, and +starting a ceremony from `CreateSharedKeyScreen` in a group without a key. + +**A regression Phase 6 shipped, and its fix.** `FrostSigningEvents.DECLINE` and +`MarmotDirectMessage.ENVELOPE_KIND` are both 30330. Phase 6 returned early for +every protocol kind before the direct-message branch, so every direct message in +a current-profile room was dropped unopened. Found while mapping this fix onto +Curare. An event of kind 30330 that holds a gift wrap is now an envelope, never a +decline -- the test `MarmotDirectMessage.wrapInside` already made -- and +`ProtocolKindDispatchJvmTest` opens one. Any port of Phase 6 has to carry this. + +The headline: **a ceremony is started only from a screen that knows what it is +for, and the screen that shows a ceremony can never start one.** Today +`DkgRitualScreen` does three jobs (showing progress, asking for approvals, and +starting a ceremony) and puts the button for the first and the last in the same +place. Separating them makes the bug impossible, not just this path to it. A +guard in `proposeRitual` makes it impossible a second time, in case a future +screen gets it wrong. + +--- + +## What happened + +Three emulators, all admins of `#Checkers` (`639f795d…`, a Marmot room): Bob +(`44d9ed79`), Charlie (`73015ef7`) and Medium (`e51b5720`). Bob made a subgroup +called *Tapscript* over all three of them, 2-of-3. From each device's logcat and +`aux.db`: + +| time | device | what | +|---|---|---| +| 13:17:00 | Bob | proposes `89d4c4d0`, 2-of-3, `parent_group` = `#Checkers`, subject *Tapscript* | +| 13:17:00 | Charlie, Medium | record it, awaiting approval | +| 13:17:23 | Medium | approves joining; 2 of 3 host keys | +| 13:17:35 | Charlie | approves joining; now 3 of 3 host keys | +| 13:17:39 | Charlie | **proposes `8199d186`**: 2-of-3 over the whole room, **no `parent_group`**, subject `#Checkers` | +| 13:17:40 | Bob, Medium | record `8199d186` as a new ceremony awaiting approval | +| 13:17:53 | Medium | approves round 1 of Tapscript | +| 13:18:03 | Medium | approves joining `8199d186` | + +Tapscript never failed. All three devices hold all three host keys, Medium has +sent its round-1 contribution, and Bob and Charlie are each waiting for their own +round-1 approval. No approval threw on any device. The "errors" seen while +joining and confirming were screens showing the wrong state, and one chat line: +on Bob and Charlie, Medium's round-1 contribution also appears as an +`unsupported` bubble of raw hex (`ChatMessage` rows 66 and 62), because kind +30312 is read as a nip30303 `SubmissionEvent` first. That is the +`Leading zeroes not allowed` warning in both logs at 13:17:53. + +`8199d186` could only have come from `DkgRitualViewModel.startRitual()`. It is +the one caller of `proposeRitual` that passes no participants, no parent and no +subject, which is what produces a whole-room ceremony named after the room. +Charlie pressed **Start key ceremony** four seconds after approving, in the +place where **Review and join** had just been. + +--- + +## The findings + +| # | finding | where | fixed in | +|---|---|---|---| +| F1 | `proposeRitual` will open a group's own ceremony in a Marmot room. The key it makes can never be that room's, since a Marmot room's id is derived from the key it already has. `ChatRoomDetailScreen` hides the button there; nothing refuses the call | `ChillDkgRitualManager.kt:178` | Phase 1 | +| F2 | `DkgRitualScreen` shows progress, asks for approvals *and* starts ceremonies, and the approval button and the start button share one slot in the bottom bar | `DkgRitualScreen.kt:194-262` | Phases 3, 4 | +| F3 | `initiate()` runs again every time the screen comes back into view, because its `LaunchedEffect` checks the *parameter* `initialDkgRitualUIState`, which is always `Loading`. Each run resets the state to `Loaded(session = null)` and starts another set of collectors without stopping the last | `DkgRitualScreen.kt:344`, `DkgRitualViewModel.kt:136` | Phase 2 | +| F4 | Five coroutines on `Dispatchers.IO` each read `dkgRitualUIState`, copy one field and write it back. The session collector suspends on a database query between its read and its write. A write based on an old copy wipes out `session` and `pendingApproval`, and nothing re-sends them | `DkgRitualViewModel.kt:174-235, 251-347` | Phase 2 | +| F5 | `roomHasCeremony` counts only the room's *own* ceremonies (`observeLatestSessionForChatRoom` defaults `parentChatRoomId` to null), so in a parent room hosting a subgroup's ceremony it says there is none | `DkgRitualViewModel.kt:175` | Phase 4 (deleted) | +| F6 | The approval button calls `approve(step)` and then `onDone()` straight away. Popping the screen clears its view model and cancels the approval's coroutine, so a slow publish can be cut off. On the last approval of a round nothing arrives afterwards to resume it | `DkgApprovalScaffold.kt:205` | Phase 2 | +| F7 | A failed ceremony's **Try again** calls `startRitual()`, which opens a group's own ceremony whatever the failed one was for. A failed subgroup ceremony is retried as a whole-room ceremony in the parent's room, which is F1 again | `DkgRitualScreen.kt:239-251` | Phase 4 | +| F8 | There is no way to abandon a ceremony. `DkgApprovalScaffold.kt:191-195` says "Abandoning is on the ritual screen"; nothing implements it. A ceremony opened by mistake, like `8199d186`, can only be left running | `DkgApprovalScaffold.kt:191` | Phase 5 | +| F9 | `record()` accepts a FAILURE message from any sender. In a parent room, a member who is not in the subgroup can read its proposal and end it | `ChillDkgRitualManager.kt:636` | Phase 5 | +| F10 | In a Marmot room, `ChatMessage.applyInnerEvent` matches `TranslationContributorListEvent.KIND` (30310) and `TranslationEvent.KIND` (30311) before `in DkgRitualEvents.ALL`. A subgroup's proposal and host keys reach the translation arms first. It does nothing today only because one arm is an empty TODO and the other's parser returns null without translation tags | `ChatMessage.kt:1439-1493` | Phase 6 | +| F11 | Kind 30312 is both the ceremony's round 1 and nip30303's `SubmissionEvent`. `ChatMessage.fromGroupEventResult` checks for a submission *before* `applyInnerEvent` runs, tries to parse the round-1 hex as an event, fails, and writes an `unsupported` chat line with the raw hex. Reordering `applyInnerEvent` does not reach it. Seen on Bob and Charlie | `ChatMessage.kt:880, 986-1012` | Phase 6 | +| F12 | The comments that call the kind overlap safe are out of date: they say ceremony kinds only travel in NIP-17 gift wraps, which stopped being true with subgroups' Phase 10 | `FrostSigningEvents.kt:52-70`, `ChronicleEvent.kt:89-101`, `DkgRitualEvents.kt:15` | Phase 6 | +| F13 | The nip30303 document and translation feature is unreachable: nothing constructs `ArtifactDetailRoute`, `AddArtifactRoute` or `AddDialectRoute`, and the other six routes are only built from inside those screens. It is still wired into inbound dispatch, `ProposedEvent`, the chat transcript and 12 database tables | `nostr/nip30303/` and below | Phases 7, 9 | +| F14 | The member chronicle can carry only nip30303 kinds (`ChronicleEvent.APPLY_ORDER`), yet it is live: every room asks for one when it opens (`ChatMessageListViewModel.kt:206`) and every invite sends one (`MarmotOutboundDao.kt:1086`). Without nip30303 it has nothing it is allowed to carry | `managers/ChronicleManager.kt`, `nostr/chronicle/` | Phase 7 | + +--- + +## Phase 0 — before any code + +**An hour, to settle five things the phases assume.** + +1. **Ceremonies start in exactly three places.** Group creation + (`SelectChatRoomTypeViewModel`) and the subgroup picker + (`SelectSubgroupAdminsViewModel`) already know what their ceremony is for and + stay as they are. The third is new: `CreateSharedKeyScreen`, for a NIP-17 + group that has no key yet. `DkgRitualScreen` starts nothing. +2. **`DkgRitualRoute.dkgSessionId` becomes required.** Every caller that has a + ceremony to show knows which one it is. A caller that does not is asking to + *start* one, and goes to the creation screen instead. +3. **Abandoning is open to any participant, and only to participants.** ChillDKG + has no way to say no short of ending the ceremony, and any participant can + already end it by never approving. Making it explicit just lets the others + stop waiting. +4. **The whole nip30303 family goes, not only translation.** Artifacts, + versions, chapters, chunks, dialects and translations share one entry point, + and it is unreachable. Removing only the translation kinds would leave the + rest of the screens and the database tables behind them, and would leave + 30312 colliding with round 1. +5. **The member chronicle stays, empty and quiet.** It was built to hand a late + member the group's signed document history, and `CHRONICLABLE_KINDS` + deliberately excludes everything else (posts, profiles, relay lists, key + states, subgroup certificates, wallet statements). With nip30303 gone it + carries nothing. Its machinery (paging, verification against the room's + key, the request and the push) is kept for the next kind that should join + it, and the set it may carry becomes empty. "Quiet" means that with an empty + set it puts nothing on the wire and nothing in the transcript: no request + when a room opens, no pages on an invite, no reply to a request from an + older build. Adding a kind back is a decision that set's comment asks for, + not a side effect. + +--- + +## Phase 1 — `proposeRitual` refuses a group's own ceremony in a Marmot room + +**An hour. Closes F1 whatever any screen does.** + +In `ChillDkgRitualManager.proposeRitual`, beside the existing `require`s: + +```kotlin +// A Marmot room's id is derived from the key it already has, so a ceremony of +// its own would make a key the room could never answer to. It hosts its +// subgroups' ceremonies and nothing else. +require(parentChatRoomId != null || localChatRoom.chatRoom.mlsGroupState == null) { + "${localChatRoom.chatRoom.id} is a Marmot room; it can only host a subgroup's ceremony" +} +``` + +It goes *after* the "already running" lookup, like the other `require`s, so a +caller who asks again for a running ceremony still gets it back. + +`acceptProposal` gets the matching refusal: a proposal with no `parent_group` +arriving in a Marmot room is dropped with a warning and no session is recorded. +Without it, a build that predates this phase can still put one on the wire and +every member's device would show it. + +**Tests**, in `SubgroupCeremonyInParentRoomTest` (it already builds a parent +Marmot room with `parentRoom()`): + +- proposing with no parent in a Marmot room throws, and writes no session and + no inner event; +- a proposal with no `parent_group` arriving in a Marmot room records nothing; +- proposing a subgroup in the same room still works (the existing tests cover + this; check they still pass). + +--- + +## Phase 2 — the ceremony screen stops losing its ceremony + +**Half a day. Closes F3, F4 and F6.** + +### `initiate()` runs once + +`DkgRitualViewModel` gets an `initiated` flag that `initiate()` checks and sets +first. `DkgRitualScreen`'s `LaunchedEffect` stays as it is; it is the view model +that decides whether starting again means anything. Returning from an approval +screen then reuses the collectors already running, and the state is never reset +to "no session". + +### One writer + +Replace the five read-copy-write collectors with one state built by `combine`: + +```kotlin +combine( + sessionFlow, // observeSessionById(dkgSessionId) + dkgRepository.observeMessages(dkgSessionId), + keyStateFlow, + certificateFlow, +) { session, messages, keyState, certificate -> … } + .mapLatest { parts -> parts.toLoaded(pendingApproval = dkgRepository.pendingApproval(parts.session)) } + .collect { dkgRitualUIState = it } +``` + +`pendingApproval` is computed inside the pipeline, before the single write, so +there is no suspension between reading the state and writing it. +`adminGroupBlockedOn` is the one field set by an action rather than a flow; it +becomes a `MutableStateFlow` that is a fifth input to `combine`. + +This is easier once Phase 4 makes `dkgSessionId` required, because the +"which session" question disappears. The two phases can be done in one commit +if that reads better; the order here keeps Phase 2 small enough to land first. + +### Approving finishes before the screen closes + +`DkgRitualViewModel.approve(step, onApproved: () -> Unit)` calls `onApproved` on +`Dispatchers.Main` after `dkgRepository.approve` returns. `DkgApprovalScaffold` +passes `onDone` there instead of calling it straight after. The button already +shows a spinner while `isActionPending` is true, so the member sees the +approval being sent rather than a screen that closed and might not have. + +**Tests**, a new `DkgRitualViewModelJvmTest` beside the other view model tests +in `jvmTest/.../ui/view/model/`: + +- calling `initiate()` twice leaves one set of collectors and never emits a + state with `session == null` after the first non-null one; +- a burst of message inserts while the session row changes ends with the state + holding both the session and the messages (the lost-update case); +- `approve` calls `onApproved` only after the repository call returns. + +--- + +## Phase 3 — `CreateSharedKeyScreen` + +**A day. The first half of F2.** + +A screen that does one thing: start a group's own key ceremony in a NIP-17 room +that has no key and no ceremony running. + +- `CreateSharedKeyRoute(activeUserPublicKey, chatRoomId)`. +- `CreateSharedKeyViewModel` takes over from `DkgRitualViewModel` the parts that + are about starting: `threshold`, `quorumRange()`, `setThreshold()`, the + minimum-participants check, and `startRitual()` as `create()`. +- `CreateSharedKeyScreen` shows what `DkgRitualScreen` shows today when + `session == null`: the two paragraphs about holding one key between the group + and needing everyone online, the `QuorumStepper`, and one button, + **Start key ceremony**. Its app bar has `NavigateBackButton`. +- The four states: loading while the room loads; an `ErrorState` with a retry + if the room cannot be read; an `EmptyState` saying why not when the group is + too small or is a Marmot room; loaded otherwise. +- The view model refuses, rather than hides, the cases Phase 1 refuses, so the + screen can say why. A room that already has a ceremony running sends the + member to that ceremony instead of offering a second. +- On success it navigates to `DkgRitualRoute(chatRoomId, dkgSessionId)` with + `popUpTo { inclusive = true }`. Back from the new + ceremony goes to wherever the member came from, never to the creation screen. + +**Entry points:** + +- `ChatRoomDetailScreen`'s **Shared key** button (NIP-17 rooms only, as now). + If the room has its own ceremony that has not failed, it opens that one with + `DkgRitualRoute(…, dkgSessionId = it.id)`. Otherwise it opens + `CreateSharedKeyRoute`. The detail view model reads this with + `getLatestSessionFor(chatRoomId, parentChatRoomId = null)`, which is the + right question here because a NIP-17 room hosts no subgroups. +- The error card `SelectChatRoomTypeScreen` shows when a robust group was + created but its ceremony was not (`keyCeremonyNotStarted`, + `was_created_but_its_shared_key_ceremony`) gets a button to + `CreateSharedKeyRoute` for the room it just made. Today the only way back is + through the group's details, which the card does not mention. + +Strings go in `strings.xml` in sentence case. Spacing comes from +`MaterialTheme.spacing`, the content root gets `readableContent()`, and +`./gradlew :composeApp:m3Audit` passes with no budget raised. + +**Tests**: `CreateSharedKeyViewModelJvmTest` — a NIP-17 room with no ceremony +can create one; a room with one running is sent to it; a Marmot room and a +one-member room are refused with a reason. + +--- + +## Phase 4 — `DkgRitualScreen` only shows a ceremony + +**Half a day. The second half of F2, and F5 and F7.** + +- `DkgRitualRoute.dkgSessionId` becomes non-null. The two callers left + (`ChatRoomMessagingScreen`'s transcript links and the detail screen's + **Shared key** from Phase 3) already pass one. A transcript line that somehow + has no `dkgSessionId` shows no link rather than opening the room's newest. +- `DkgRitualViewModel` loses `startRitual()`, `canStartRitual()`, `threshold`, + `quorumRange()`, `setThreshold()` and the fallback to + `observeLatestSessionForChatRoom`. `DkgRitualUIState.Loaded` loses + `roomHasCeremony` and its comment, and `session` becomes non-null once + loaded. A session id that matches no row is the error state, not an + invitation to start one. +- `DkgRitualScreen` loses the `session == null` branch and the start button. + Its bottom bar has one job: the pending approval, when there is one. +- The app bar title comes from the ceremony, not the room: a subgroup's ceremony + in `#Checkers` reads as *Tapscript*, not *Shared key for #Checkers*. +- **Try again** on a failed ceremony goes back to the screen that knows what it + was for: + - a group's own ceremony → `CreateSharedKeyRoute(chatRoomId)`; + - a subgroup's → `SelectSubgroupAdminsRoute(parentChatRoomId, retrying = dkgSessionId)`. + `SelectSubgroupAdminsViewModel` fills in the name, the admins and the + quorum from the failed session (`subject`, `participantPublicKeys` minus + this device, `threshold`). The member can change any of them before + confirming, and the usual refusals run again. +- `SelectSubgroupAdminsViewModel.kt:263-276`, the comment about the coordinator + landing on a **Start key ceremony** button, is shortened to say why the + transcript is still the right place to land: that is where every admin + answers from. + +After this phase `proposeRitual` has exactly three callers, which is the +promise in the title. A test that greps `commonMain` for `proposeRitual(` and +counts three, with a comment naming them, is cheap and fails the day a fourth +appears without anyone deciding it should. + +**Tests**: extend `DkgRitualViewModelJvmTest` — the view model has no way to +start a ceremony; a failed subgroup ceremony's retry route carries the parent +and the session; a failed group ceremony's goes to the creation screen. Extend +the subgroup picker's tests with prefilling from a failed session. + +--- + +## Phase 5 — abandoning a ceremony + +**Half a day. Closes F8 and F9.** + +- `ChillDkgRitualManager.abandon(database, localChatRoom, sessionId, + nostrPrivateKey)`: refuses unless this device is a participant and the + ceremony is neither complete nor failed; then calls `fail(...)` with this + device as the culprit and broadcasts `DkgRitualEvents.FAILURE`, exactly as a + local fault does today. `DkgRepository.abandon` wraps it. +- `record()`'s FAILURE arm ignores a sender who is not in + `participantsOf(session, room)`, with a warning like `isFromCoordinator`'s. +- `DkgRitualScreen` gets **Abandon ceremony** as a secondary action, shown while + the ceremony is running and this member is a participant. It opens a + confirmation dialog saying what happens: the ceremony ends for everyone, no + key is created, and it can be started again. That matches what the existing + `TYPE_DKG_FAILED` line already tells the room. +- `DkgApprovalScaffold.kt:191-195` then describes something that exists. The + approval screens keep **Not now** and do not get an abandon button: the + consequence belongs on the screen that shows the whole ceremony. + +**Tests**, in `SubgroupCeremonyInParentRoomTest`: a participant's abandon fails +the session on every device; a FAILURE from a parent member outside the +subgroup is ignored; abandoning a completed ceremony does nothing. + +**On the test devices**, once this lands: abandon `8199d186` from any of the +three. Tapscript (`89d4c4d0`) is untouched and finishes once Bob and Charlie +approve round 1. Until this lands, do not approve `8199d186` on Bob. Medium has +already joined it, so Bob's approval would complete a key for `#Checkers` that +the room can never use. + +--- + +## Phase 6 — the kind overlap, closed first + +**Two hours. Closes F10, F11 and F12 before the removal, so the removal is only +deletion, and so the fix can ship on its own if the removal waits.** + +- In `ChatMessage.fromGroupEventResult`, decide on protocol kinds first: an + inner event whose kind is in `DkgRitualEvents.ALL` or `FrostSigningEvents.ALL` + is stored as a `MarmotInnerEvent` as now, never treated as a submission + envelope, and produces no chat line. Their managers are dispatched separately + from `NostrDao.fileGroupEventResult` and write their own transcript lines. A + real `SubmissionEvent` loses its envelope handling until Phase 7 removes it; + nothing can send one, because the screens that did are unreachable. +- In `ChatMessage.applyInnerEvent`, move `in FrostSigningEvents.ALL -> null` and + `in DkgRitualEvents.ALL -> null` to the top of the `when`. Protocol kinds are + never content, whatever else shares their number, and the first match wins. +- Rewrite the comments in `FrostSigningEvents.kt`, `ChronicleEvent.kt` and + `DkgRitualEvents.kt` to say what is true now: ceremony kinds travel as Marmot + inner events in a parent room, and they stopped colliding when the dispatch + order above was fixed. After Phase 7 they shrink again, to say 30300-30309 are + free and 30310-30316 are the ceremony's alone. +- Lower `NostrDao.fileGroupEventResult`'s `No app logic to handle` from info to + debug, or skip it for ceremony and signing kinds. It reads like a failure on + every application message and sent this investigation the wrong way. +- **Tests**, in a new `ProtocolKindDispatchJvmTest`: every kind in + `DkgRitualEvents.ALL`, arriving as a Marmot application message with a real + ceremony payload (round 1's hex content in particular), writes no chat line + and no row outside the DKG tables; the same for `FrostSigningEvents.ALL`. + +The `unsupported` rows already on devices are cleaned up by Phase 8's +migration, which can find them by kind. + +--- + +## Phase 7 — removing the nip30303 code + +**A day and a half: a day of deletion, and half a day giving the chronicle's +tests a kind set of their own. Closes F13 and F14 in code; the tables go in +Phase 8.** + +Paths below are under `composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/` +unless they say otherwise. Line numbers were right at `e3839da5`; confirm them +with a grep. + +### Deleted outright (103 files) + +| what | where | files | +|---|---|---| +| the 14 event classes and their 22 tags | `nostr/nip30303/`, `nostr/nip30303/tags/` | 36 | +| the 12 `Mantra*` entities, plus `MantraTranslationChunkProposal`, which is annotated `@Entity` but never registered | `database/model/Mantra*.kt` | 13 | +| the 12 table DAOs and `MantraDao` | `database/dao/Mantra*Dao.kt` | 13 | +| `MantraRepository`, `DatabaseMantraRepository` | `repository/`, `database/repository/` | 2 | +| `TranslationScaffold` | `managers/` | 1 | +| nine screens, nine view models, nine UI states, nine routes: AddArtifact, AddChapter, AddDialect, AddTranslationArtifactVersion (route `AddTranslation`), ArtifactDetail, ChapterDetail, TranslateChunk, TranslationArtifactVersionDetail, TranslationChapter | `ui/composable/`, `ui/view/model/`, `ui/view/state/`, `ui/composable/navigation/routes/` | 36 | +| helpers nothing else uses: `Markdown.kt`, `DetailRow.kt` | `text/`, `ui/composable/widgets/` | 2 | + +### Edited + +- **`BennuNavHost.kt`**: the feature's imports, `databaseMantraRepository`, + the `mantraRepository =` argument in the chat room detail block, and the + `composable<>` blocks for the nine routes. +- **`ChatRoomDetailScreen.kt`, `ChatRoomDetailViewModel.kt`**: the + `mantraRepository` parameter and field, which is stored and never read, and + the preview's `NO_OP_MANTRA_REPOSITORY`. +- **`ChatMessage.kt`**: + - the nip30303 imports; + - the submission envelope in `fromGroupEventResult` (`submission`, `payload`, + `payloadEventId = payload?.id`, and the `unsupported` branch, whose `else` + becomes a plain `applyInnerEvent(event = event)`); + - the eleven nip30303 arms of `applyInnerEvent` and the KDoc above it. + - The `messageType`s those arms wrote (`artifact`, `chapter`, `dialect`, + `translationArtifactVersion`, `translation`) have no renderer; Phase 8 + deletes any rows of them. +- **`text/ProposedEvent.kt`**: the seven nip30303 arms of `summaryOf`. The rest + (key state, subgroup certificate, metadata, text note, relay lists, wallet) + stays. +- **`MarmotInnerEventDao.deleteByPayloadEventId`**: deleted; it has no callers. + The `payloadEventId` column goes in Phase 8. +- **`strings.xml`**: the 61 keys only the deleted files use (59, plus + `add_chapter_to` and `chapter_words_characters` once `StringCatalogueJvmTest` + stops asserting them), and four feature strings that are already unused: + `add_artifact_to_library`, `dialects`, + `no_artifacts_exists_in_this_groups_library`, + `no_dialects_have_been_defined_in_this_group_2`. Keep `direct_message_detail` + and `direct_message_functionality_will_be_here`, which chat screens share. +- **Leave alone**: the `mantra/` prefix in `SharedKeyDerivation.kt:74` and + `ChillDkgRitualManager.kt:101`, which is hashed into derived keys and must + never change; the relay host in `Relays.kt`; preview and sample text that + only *says* "translation" (`ProposalListScreen` previews, "Translation room" + subjects), which uses no removed type. + +### Tests + +- **Delete** the twelve that test only the feature: + - commonTest: `nostr/nip30303/{ArtifactEventTest, ChapterChunkSplitTest, InitialArtifactVersionTest, SubmissionEventTest}`, `managers/{TranslationScaffoldTest, SignedArtifactTest, SignedChapterTest}`, `database/model/RumorIdAgreementTest`; + - jvmTest: `database/dao/MantraDaoJvmTest`, `database/model/TranslationChunkApplyJvmTest`, `managers/{ChapterBatchProposalJvmTest, TranslationBatchProposalJvmTest}`. +- **Re-fixture** the ones that used a nip30303 event as an arbitrary payload: + - `GroupKeyStateTest` and `GroupSignedEventDaoJvmTest` need any kind; + `TextNoteEvent` or a relay list works. + - `SignedGroupKeyStateTest` (tests at 1046 and 1221) checks that a batch the + group signs lands on every device. It needs a kind that writes a row on + arrival, and `GroupWalletStatementEvent` or the relay lists do. + - `MarmotPayloadBoundsTest`'s chronicle cases (at 75 and 88) size a page of + nip30303 events; they re-fixture with the test kind set described under + "The chronicle, emptied and quiet" below. +- **Edit** `ChatRoomMemberRowJvmTest`, `GroupSignedWorkRowsJvmTest` (the + `NO_OP_MANTRA_REPOSITORY` argument) and `StringCatalogueJvmTest` (the two + chapter strings). + +**Audit**: neither floor moves; the deleted screens hold none of the 12 +adaptive uses or the 2 navigation components. The unbudgeted string-literal +count drops from 29 to 20; update the number in `CLAUDE.md`'s "39 remain" line +while there, which is already stale. + +### The chronicle, emptied and quiet + +Kept, per Phase 0 decision 5. What changes is what it may carry, and that it +says nothing when the answer is nothing. + +- **`ChronicleEvent.APPLY_ORDER` becomes empty**, and with it + `CHRONICLABLE_KINDS`. Its comment says why: the document kinds it was built + for were removed by this plan, everything else is excluded for the reasons + already listed there, and a kind joins only by a decision that edits this + list. `applyPage`'s and the outbound filter's existing checks then refuse + everything without any change of their own, including a page from an older + build that still carries document kinds. +- **`ChronicleManager.requestIfEmpty` returns false while that set is empty**, + before it queues anything, stamps `chronicleRequestedAt` or writes a + transcript line. Its "holds work" check (`ChronicleManager.kt:169-170`) reads + the Mantra DAOs and goes; the empty-set check replaces it. Opening a room then + sends nothing, and `ChatMessageListViewModel.askForGroupHistory` needs no + change. +- **`sendTo` needs no change.** It already sends nothing and writes no line + when `assemble` comes back empty ("silence is the honest reply"), which is + what an empty set makes it do. That covers the push on every invite + (`MarmotOutboundDao.kt:1086`) and the reply to a request from an older build + (`ChatMessage.kt:972`). Phase 7's tests assert both stay silent. +- **Removed** from `ChronicleManager`: the rebuild fallback that reads the Mantra + tables (`rebuiltEventsOf`, 748-811) and `currentTranslationsOnly` (657-718), + which exists only for translation chunks. `signedEventsOf` stays; it reads + `GroupSignedEvent` by kind and will find nothing. +- **Kept as they are**: `ChronicleRequestEvent`, the three chronicle tags, + `TYPE_CHRONICLE_*` and `CHRONICLE_TYPES`, `ChatRoom.chronicleRequestedAt`, + and the comments that say why a kind is *not* chronicled. All of them still + describe the machinery accurately. Rows already written stay too. +- **Tests.** `ChronicleEventTest`, `ChronicleRoundTripTest`, + `ChronicleApplyJvmTest` and `ChronicleAssemblyJvmTest` exercise paging, + verification and ordering with document events as the payload. With an empty + production set they have nothing to page. So `ChronicleEvent` and + `ChronicleManager` take the chroniclable kinds as a parameter, defaulting to + the production set, and those tests pass a test set (`TextNoteEvent` and a + relay list, say) built in a shared fixture. That keeps the machinery covered + without making any kind chroniclable in the app. Assertions of the count + (`ChronicleEventTest:195` expects 8; `ChronicleRoundTripTest:418`, + `ChronicleApplyJvmTest:801`, `ChronicleAssemblyJvmTest:336, 511`) assert + against the test set, and one new test asserts the production set is empty. + The other new tests: `requestIfEmpty` sends nothing and writes no line; + `sendTo` on an invite sends nothing and writes no line; a page from an older + build carrying document kinds applies nothing. + +--- + +## Phase 8 — schema 26 → 27 + +**Half a day, most of it the migration test.** + +One manual `MIGRATION_26_27` in `database/migrations/RemoveDocumentsMigration.kt`, +registered in `getRoomDatabase` beside the other four. Manual rather than an +`AutoMigration`, because it deletes chat rows as well as changing shape, which +is the line that file's comment already draws. + +```sql +-- the chat lines the removed arms wrote, and the ceremony round-1 lines +-- misread as submissions (F11) +DELETE FROM ChatMessage WHERE messageType IN + ('artifact', 'chapter', 'dialect', 'translationArtifactVersion', 'translation'); +DELETE FROM ChatMessage WHERE messageType = 'unsupported' AND marmotInnerEventId IN + (SELECT id FROM MarmotInnerEvent WHERE kind BETWEEN 30310 AND 30316); + +DROP TABLE MantraArtifact; -- … and the other eleven, children before parents +ALTER TABLE MarmotInnerEvent DROP COLUMN payloadEventId; +``` + +The chronicle's column (`ChatRoom.chronicleRequestedAt`) and its chat lines +stay, since the chronicle does. + +- The table names come from `composeApp/schemas/…/26.json`; check them there, + not here. `MarmotInnerEvent.kind` is the column the second `DELETE` reads. +- `DROP COLUMN` is safe because `getRoomDatabase` pins `BundledSQLiteDriver` on + every platform, the argument `ChronicleRenameMigration` already makes for + `RENAME COLUMN`. Check first that `payloadEventId` is not indexed or part of + a foreign key, since SQLite refuses to drop a column that is. +- No kept table has a foreign key into a Mantra table, so dropping them cascades + into nothing that stays. Drop children before parents anyway, so the order + holds if foreign keys are ever enforced during migration. +- `GroupSignedEvent` keeps any rows of kinds 30300-30309. The table is generic + and keyed by kind, nothing reads those kinds any more, and deleting a group's + signed record is not this plan's call. +- `BennuDatabase`: `version = 27`, the twelve entities and thirteen DAO + accessors removed, and the migration-history comment gets a line for 26 → 27. + Commit `27.json`. + +**Test**, `RemoveDocumentsMigrationJvmTest`, in the same style as the three +migration tests already there: the version-26 tables created by hand from +`26.json`, seeded with a Mantra row, a `translation` chat line, an `unsupported` +line pointing at a kind-30312 inner event, and an `unsupported` line pointing at +some other kind. After the migration, the Mantra tables and `payloadEventId` +are gone, `chronicleRequestedAt` is still there, the first two lines are +deleted, and the last one is still there. + +--- + +## Phase 9 — docs, and checking it on the emulators + +**Half a day.** + +- `shared-key-ceremony.md`: a section on where a ceremony can be started (the + three places), on abandoning, and the kind table noting that 30310-30316 now + travel in both transports. +- `subgroups.md`: a line under Phase 10 pointing here for the retry path and the + guard. Its chronicle mentions stay true: a subgroup certificate is still not + chroniclable. +- `member-chronicle.md`: a status line at the top saying the chronicle is built + but carries no kinds since this plan removed the document kinds, that it is + silent while that is so, and that adding a kind means editing + `ChronicleEvent.APPLY_ORDER` on purpose. `docs/README.md:39` already + contradicts the note's status (it says the chronicle was never built); fix + both together. +- `frost-batch-signing.md` (its first caller was a chapter and its chunks, + 519-546) and `mls-skipped-keys.md` (`MantraDao.addArtifact`): a line each + saying the example was removed, rather than rewriting history. + `marmot-v2.md` and `group-chain-wallet.md` mention the chronicle, not the + documents, and need nothing. +- `material-design-conformance.md`: the screen count (43) and the + "artifacts → chapters" list-detail family. +- `docs/README.md`: a row for this note, and its place in the reading order + (after the subgroups note). +- This note: mark it built, and add a table of where the build chose + differently, as the other plans do. + +Then the scenario that found the bug, on the same three emulators: + +1. Bob makes a subgroup over all three admins of a parent room. +2. Charlie and Medium each open it from the transcript, approve joining, and + land back on the ceremony screen. It shows the subgroup's ceremony and + offers **Review and contribute** once all host keys are in, and there is no + start button anywhere on it. +3. All three approve round 1 and round 2; the ceremony completes; the + certificate and key state follow as `subgroups.md` describes. +4. In a NIP-17 group without a key, **Shared key** from the group's details opens + `CreateSharedKeyScreen`, and starting a ceremony there lands on its progress + screen, with back returning to the details. +5. Abandon a ceremony from one device and watch it end on the other two. +6. No `unsupported` bubble appears in the parent room at any point, and the + two left over from the original run (Bob and Charlie) are gone after the + upgrade. +7. Inviting a member to a group and opening a room both work, and neither + puts a chronicle request, a chronicle page, or a chronicle line in the + transcript on any device (Phase 7's quiet shell). + +`./gradlew check` passes, which runs the m3 audit. + +--- + +## What this does not do + +- **It does not change the protocol.** No new kinds, no new tags; the FAILURE + message `abandon` sends is the one a fault already sends. +- **It does not migrate ceremonies already on devices.** A whole-room ceremony + already recorded in a Marmot room, like `8199d186`, stays until it is + abandoned. Phase 1 stops new ones being opened or recorded. +- **It does not touch the group's signed record.** Rows of kinds 30300-30309 + in `GroupSignedEvent` stay; see Phase 8. +- **It does not remove the member chronicle.** Its machinery stays, carrying + nothing and saying nothing, until a kind is chosen to join it. +- **It does not free the `mantra/` derivation prefix.** It is an input to the + host-key and shared-key hashes, not a reference to the removed feature. + +--- + +## Order and size + +| phase | what | size | depends on | +|---|---|---|---| +| 0 | decisions | an hour | — | +| 1 | `proposeRitual` guard | an hour | — | +| 2 | ceremony screen keeps its ceremony | half a day | — | +| 3 | `CreateSharedKeyScreen` | a day | 1 | +| 4 | ceremony screen only shows | half a day | 2, 3 | +| 5 | abandoning | half a day | 4 | +| 6 | protocol kinds dispatched first | two hours | — | +| 7 | remove nip30303 code, quiet the chronicle | a day and a half | 6 | +| 8 | schema 26 → 27 | half a day | 7 | +| 9 | docs and emulator check | half a day | all | + +Phases 1, 2 and 6 are independent and the most urgent; each can ship alone. +Phases 3-5 are one line of work on the ceremony screens, and 7-8 another on the +removal, and the two lines touch different files apart from `ChatMessage.kt` +(Phase 6 against Phase 7), so they can run side by side once Phase 6 is in. diff --git a/docs/frost-batch-signing.md b/docs/frost-batch-signing.md index 79fbfc51..c2a0393a 100644 --- a/docs/frost-batch-signing.md +++ b/docs/frost-batch-signing.md @@ -13,6 +13,11 @@ implementation chose differently from the first draft the section says so. chapter is the first caller, and needed a second form of them; see [The first caller](#the-first-caller-a-chapter-and-its-chunks). +*The chapter, the dialect and the artifact screens this note cites have since +been removed, with the rest of the nip30303 documents +([ceremony-creation.md](./ceremony-creation.md)). The batch machinery stays; the +group wallet's spends are its callers now.* + The headline: **there is no such thing as one FROST signature over many messages, and no way to reuse a nonce across them.** What can be batched is the ceremony — the rounds, the group events, and the approval a human is asked for. diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index c0ee5df7..329fbde0 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -236,6 +236,12 @@ address with a hidden script path is an address no member's device recognises which is the whole defence, and why the app never displays, accepts or signs for an address it did not derive. +A subgroup's *guarded* wallet does have a tree -- one leaf per ancestor, see +[group-wallet-guardians.md](./group-wallet-guardians.md) -- and the defence is the +same with one word changed: every member derives every address, tree included, +from the child's key and a certificate every member verifies, and compares it byte +for byte. The tree is computed, never proposed. + ### The rule this inherits, made more expensive Every tweak above is publicly computable from `K`. So the derivation note's rule @@ -444,12 +450,13 @@ is a record that the group agreed, not a source of keys. The app never reads an address out of it. **Never broadcast.** The xpub on a public relay is the group's whole history on -chain, to anyone. `BroadcastGroupSignedEventScreen` refuses this kind, and a test -says it refuses it, because a refusal nobody tested is the one that disappears -in a refactor of the broadcast list. +chain, to anyone. `BroadcastGroupSignedEventScreen` refused this kind, and a test +said it refused it. That screen has since been removed with the group's nostr +profile, relay lists and posts, and nothing in the app now sends a group-signed +event to a relay. -`GroupWallet` is a read model over `GroupSignedEvent`, in the shape of -`GroupRelayList.of`/`newestAmong`. There is no table: a wallet is a signed event +`GroupWallet` is a read model over `GroupSignedEvent`, in the shape the +since-removed `GroupRelayList.of`/`newestAmong` had. There is no table: a wallet is a signed event and a derivation. **Not batched** with anything. A wallet statement is what every spend proposal is diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index 2ab41808..d82ebcac 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -34,13 +34,13 @@ build chose differently, this table says so. | 2 | done, in the fork (`4bc973df`): the three signing methods suspend, `RemoteIcebergFundingSigner`, pings answered outside the channel loop. lightning-kmp's JVM suite, 985 tests, passes | | 3 | done: in the fork (`e15e31ba`), `withGroupBasepoints`, `GroupHeldOutputs` and `KeyManager.defaultFinalScriptPubKey`, 991 tests passing. In the app, `GroupLightningDerivation`, pinned, with a FROST quorum spending `to_remote` and `to_local` | | 4 | done: `GroupChainClients`, one Electrum connection per network for the wallets and the watcher; the wallet routes carry a chain; a second wallet row for testnet3 behind `GroupLightningRollout`, which is off | -| 5 | done: `IcebergRitualManager`, schema 27 (`IcebergKeySession`, `IcebergParticipantMessage`), the ceremony screen and its transcript lines. Seven four-device tests, and the app's 1,391 JVM tests pass | -| 6, 7 | done together, as their screen and summaries are one piece: the wallet and operator statements, the node seed (schema 28), `GroupLightningWalletManager`, `GroupLightningOperatorManager` and the Lightning wallet screen. Twelve new tests; the app's 1,403 JVM tests pass | -| 9 | done before 8, because the node's transport is half of it: `GroupLightningCoSigner`, `CoSignerPolicy`, `GroupIcebergTransport`, schema 29, and the fork's `SigningContext` (`bd78ed62`). A four-device test co-signs a real commitment that spends its funding output beside a stock counterparty, and five refusals hold. The app's 1,415 JVM tests and the fork's 993 pass | +| 5 | done: `IcebergRitualManager`, schema 27, now part of 32 (`IcebergKeySession`, `IcebergParticipantMessage`), the ceremony screen and its transcript lines. Seven four-device tests, and the app's 1,391 JVM tests pass | +| 6, 7 | done together, as their screen and summaries are one piece: the wallet and operator statements, the node seed (schema 28, now part of 32), `GroupLightningWalletManager`, `GroupLightningOperatorManager` and the Lightning wallet screen. Twelve new tests; the app's 1,403 JVM tests pass | +| 9 | done before 8, because the node's transport is half of it: `GroupLightningCoSigner`, `CoSignerPolicy`, `GroupIcebergTransport`, schema 29, now part of 32, and the fork's `SigningContext` (`bd78ed62`). A four-device test co-signs a real commitment that spends its funding output beside a stock counterparty, and five refusals hold. The app's 1,415 JVM tests and the fork's 993 pass | | 8 | done: `GroupLightningNode`, `GroupNodeKeyManager` and `GroupLightningNodes`, wired into the app behind `GroupLightningRollout`. Four tests with a stand-in peer cover the keys, the start gate and the handover. The node has not connected to an LSP: that needs Phase 0's testnet3 run | -| 10 | done: `GroupLightningReports`, the node's reporting loop, schema 30 (`GroupLightningSnapshotRow`, `GroupLightningPaymentRow`, `GroupLightningInvoiceRow`), and balance, channels and payments on the wallet screen, each channel checked against the device's own co-signing ledger. Four new tests | +| 10 | done: `GroupLightningReports`, the node's reporting loop, schema 30, now part of 32 (`GroupLightningSnapshotRow`, `GroupLightningPaymentRow`, `GroupLightningInvoiceRow`), and balance, channels and payments on the wallet screen, each channel checked against the device's own co-signing ledger. Four new tests | | 11 | done: invoice requests and answers through `GroupLightningReports`, the running node answering each request once, and the receive screen (`GroupLightningReceiveScreen`). A member files an invoice only from the operator, and only if it pays the node the statement names. Three new tests | -| 12 | done: `GroupLightningAuthorisationEvent` (kind 30346, `pay`), budgets read from the signed authorisations, the node paying each once, its summary and transcript line, and the send screen (`GroupLightningSendScreen`). The co-signers now hold offered HTLCs under the statement's in-flight cap. Seven new tests | +| 12 | done: `GroupLightningAuthorisationEvent` (kind 30363, `pay`), budgets read from the signed authorisations, the node paying each once, its summary and transcript line, and the send screen (`GroupLightningSendScreen`). The co-signers now hold offered HTLCs under the statement's in-flight cap. Seven new tests | | 13 | done, except splicing out. `close` and `force-close` authorisations, the node acting on each once, the co-signers signing our own commitment only under a force-close authorisation and only after rebuilding it, and the channel menu on the wallet screen. Sweeps: the snapshot lists what closed channels left the group, any member proposes a sweep (`GroupSweep`, a new FROST subject), every member checks it against its own basepoints and the onchain wallet, and the watcher sends it. Five new tests: a force close and a two-input sweep both pass the script interpreter | | 14 | done: a room can have several Lightning wallets on a network, the highest-numbered current. A member who leaves is named on the wallet screen until a new wallet replaces it; the new key is made over the onchain key's holders who are still in the room; the old wallet keeps its operator and node until its channels are closed, in one decision for all of them; and removing a share holder says what it leaves. A five-device test re-keys after a removal | | 15 | the gates are in code and closed. `GroupLightningRollout.ENABLED` stays `false`. The JVM suite and the regtest run pass; what is left of its condition is Phase 0's testnet3 measurement of how long the LSP waits for a signature, and lifting it is a product decision either way. Mainnet is refused by `GroupLightningRollout.allows`, whatever a screen offers. The ceremony screen names every participant who has not answered, with a word that their build may not know the new kinds | @@ -111,7 +111,9 @@ build chose differently, this table says so. | a new wallet statement with the next `wallet` number | as written, opened under the newest completed Iceberg key no statement uses yet (`GroupLightningWalletManager.unusedKey`). The screen shows the highest-numbered wallet, and the ones before it as earlier wallets with their balance and a way to close them | | close the old wallet's channel, signed by the old co-signers | the old wallet keeps its own operator statement and node, and `GroupLightningNodes` runs one node per wallet a device operates. Closing every channel it still has is one signing session over one `close` authorisation per channel. If its operator was the member who left, any remaining participant can nominate themselves for it | | the member-removal flow says so, as it already does for the onchain wallet | the removal flow said nothing about either wallet. It now says what a removal leaves when the member holds a share of the Lightning wallet's key. The onchain wallet's own sentence is left to that wallet's plan | -| the kinds are reserved | in code: `GroupLightningEvents`, 30333-30349, with a test asserting the run is unbroken and touches no kind the app already dispatches on | +| one schema version per phase, 27 to 30 | **one, 32.** The main branch used 27 to 31 meanwhile. The four versions this branch made were never on an installed database, so at the merge they became one migration, 31 to 32, that adds every Lightning table | +| the kinds are taken from 30333 | from **30350**: the guarded-wallet family took 30333-30337 on the main branch meanwhile, and nothing failed when the two met, since each reads the other's events by kind. The family moved at the merge, which costs nothing for rumor kinds that never shipped, and the test now also asserts that it starts past every kind the app uses | +| the kinds are reserved | in code: `GroupLightningEvents`, 30350-30366, with a test asserting the run is unbroken and touches no kind the app already dispatches on | | library phases land in the forks' `threshold` branches | on a new branch, `claude/group-lightning-wallet`, in `lightning-kmp-app` and in `experimental/lightning-kmp`. It is local and not pushed. The app's submodule pointer follows it, so a checkout of this branch needs those commits from the same machine until they are pushed | The headline: **Iceberg on the funding key is necessary but not enough.** The @@ -353,30 +355,31 @@ quicker and saves fees, but safety does not depend on it. ## Kinds -These are proposed, and taken from 30333 upward. 30330-30332 are the highest kinds -in use. Every one is an MLS inner event, and none is ever broadcast. Check again -before Phase 5. As the batch-signing note says, a new family should not rely on a +These are taken from 30350 upward. They were first 30333-30349, the run after the highest kinds +then in use; the guarded-wallet family took 30333-30337 on the main branch while this was being +built, and the whole family moved here when the two merged. Every one is an MLS inner event, and +none is ever broadcast. As the batch-signing note says, a new family should not rely on a routing accident to keep it apart from the others. | kind | from | carries | phase | |---|---|---|---| -| 30333 | proposer | Iceberg ceremony proposal: `t`, the participants | 5 | -| 30334 | participant | DKG round 1: commitments to seed contributions | 5 | -| 30335 | participant | DKG round 2: seed contributions, each encrypted to its recipient | 5 | -| 30336 | participant | DKG round 3: public share and a transcript signature | 5 | -| 30337 | anyone | ceremony failure | 5 | -| 30338 | group (FROST) | Lightning wallet statement | 6 | -| 30339 | group (FROST) | operator statement | 7 | -| 30340 | opener or operator | node seed, encrypted to each participant | 6 | -| 30341 | operator | signing request: label, transaction, context | 9 | -| 30342 | participant | echo: `(label, message hash)` | 9 | -| 30343 | participant | round-one contributions, in batches of labels | 9 | -| 30344 | participant | round-two signature share | 9 | -| 30345 | operator | wallet snapshot | 10 | -| 30346 | group (FROST) | authorisation: pay, close, force-close or splice-out | 12, 13 | -| 30347 | member | invoice request | 11 | -| 30348 | operator | invoice | 11 | -| 30349 | old operator | stopped, with its last commitment numbers | 7 | +| 30350 | proposer | Iceberg ceremony proposal: `t`, the participants | 5 | +| 30351 | participant | DKG round 1: commitments to seed contributions | 5 | +| 30352 | participant | DKG round 2: seed contributions, each encrypted to its recipient | 5 | +| 30353 | participant | DKG round 3: public share and a transcript signature | 5 | +| 30354 | anyone | ceremony failure | 5 | +| 30355 | group (FROST) | Lightning wallet statement | 6 | +| 30356 | group (FROST) | operator statement | 7 | +| 30357 | opener or operator | node seed, encrypted to each participant | 6 | +| 30358 | operator | signing request: label, transaction, context | 9 | +| 30359 | participant | echo: `(label, message hash)` | 9 | +| 30360 | participant | round-one contributions, in batches of labels | 9 | +| 30361 | participant | round-two signature share | 9 | +| 30362 | operator | wallet snapshot | 10 | +| 30363 | group (FROST) | authorisation: pay, close, force-close or splice-out | 12, 13 | +| 30364 | member | invoice request | 11 | +| 30365 | operator | invoice | 11 | +| 30366 | old operator | stopped, with its last commitment numbers | 7 | --- @@ -634,7 +637,7 @@ completes. A device on an old build ignores the new kinds. **About three days.** -`GroupLightningWalletStatement`, kind **30338**, is FROST-signed through +`GroupLightningWalletStatement`, kind **30355**, is FROST-signed through `proposeSigning`. It is never broadcast. `BroadcastGroupSignedEventScreen` refuses it, and a test checks that refusal. `ProposedEvent.summarize` reads *Open a Lightning wallet on testnet3*. @@ -655,7 +658,7 @@ onchain statement it names verifies. The Iceberg key matches the reader's own who is not an Iceberg participant checks everything except the last two. **The node seed.** The member who proposes the statement generates 32 random -bytes. They send them, kind **30340**, NIP-44 encrypted to each participant inside +bytes. They send them, kind **30357**, NIP-44 encrypted to each participant inside the room, once the statement completes. The seed is stored beside the Iceberg share. A participant who joins the ceremony later, or whose device was restored, asks the operator for it, and the reply is checked against the statement's `node` @@ -670,7 +673,7 @@ tag. **About a week.** -**The operator statement,** kind **30339**, is FROST-signed and never broadcast. +**The operator statement,** kind **30356**, is FROST-signed and never broadcast. | tag | carries | |---|---| @@ -694,7 +697,7 @@ tag. | device | does | |---|---| | every co-signer | refuses any request with an older term, or from any sender other than the new operator (constraint 2: the MLS sender is the identity checked) | -| the old operator | stops its `Peer`, sends **30349** with its last commitment numbers, and deletes its channel database once the new operator's first snapshot shows the channel open. Until then it keeps the database, read-only, never started | +| the old operator | stops its `Peer`, sends **30366** with its last commitment numbers, and deletes its channel database once the new operator's first snapshot shows the channel open. Until then it keeps the database, read-only, never started | | the new operator | starts the node from the wallet's seed (Phase 8). Its channels come back from the LSP's peer storage. It reconnects and sends a snapshot | **The start gate.** A device starts the group node only if the newest operator @@ -706,7 +709,7 @@ old node from becoming the griefing case. **The new node is behind.** If the LSP's backup is newer than what the new node restored, lightning-kmp's data-loss protection waits for the LSP to force-close. That costs fees and the channel, but D5 means the money arrives under the group's -key. The 30349 commitment numbers and the co-signers' ledgers (Phase 9) let the +key. The 30366 commitment numbers and the co-signers' ledgers (Phase 9) let the screen say what happened. --- @@ -730,8 +733,8 @@ current operator's device, one per wallet: applies `withFundingSigner(RemoteIcebergFundingSigner)` and `withGroupBasepoints`, as the fork's `SignerInjectingKeyManager` does in tests. The final script provider is the onchain wallet's next receive address. -- **The transport** for the remote signer sends 30341 and collects 30344 from the - room. It keeps the round-one pools from 30343, and asks for more when a pool +- **The transport** for the remote signer sends 30358 and collects 30361 from the + room. It keeps the round-one pools from 30360, and asks for more when a pool falls below a few commitments' worth. - **On Android, a foreground service** with a notification keeps the node running while the device is the operator. iOS cannot keep it running in the @@ -753,13 +756,13 @@ started whether or not anybody opens the wallet, because the group's payments depend on it. **Round one, ahead of time.** When the operator asks, or when the pool shown in a -snapshot runs low, the co-signer publishes 30343. That is a batch of nonce +snapshot runs low, the co-signer publishes 30360. That is a batch of nonce contributions for the next labels of each channel. It covers the verification labels for commit indices `N…N+W` and the fresh labels for counters `C…C+W`. A contribution depends only on the share and the label, so publishing it early gives nothing away. -**Round two, per request.** When a 30341 arrives, the co-signer runs these +**Round two, per request.** When a 30358 arrives, the co-signer runs these checks. If any fails, it refuses, and the reason goes in the log: 1. **The sender is the current operator**, the request's term is the current @@ -782,15 +785,15 @@ checks. If any fails, it refuses, and the reason goes in the log: is checked against its output key. Every outgoing HTLC's payment hash is in an open authorisation. The total in flight is under the statement's cap. 6. **Our own commitment** (force close) requires a group-signed force-close - authorisation (30346). + authorisation (30363). 7. **A mutual close.** Our output pays an onchain wallet address the co-signer derives itself, and its amount is our balance minus a capped fee. 8. **A splice.** The new funding output is again the group key with the LSP's. Spliced-out outputs go only to addresses in a splice-out authorisation. -Once the checks pass, the co-signer **echoes**: it sends 30342 with the label and +Once the checks pass, the co-signer **echoes**: it sends 30359 with the label and the message hash, and records both in its ledger before sending. It answers round -two (30344) only once `n-t+1` participants, counting itself, have echoed the same +two (30361) only once `n-t+1` participants, counting itself, have echoed the same hash for that label. It signs with the `2t-1` contributions the request names, and accepts each one only from the MLS sender that its index names. If it sees two hashes echoed for one label, it never answers that label. Then it raises the @@ -801,7 +804,7 @@ co-signer has already seen and to authorisations the group has signed. So a co-signer never shows a commitment to its owner. A person only sees a refusal, as a transcript line. -**The ledger,** schema 27 to 28, is never pruned: +**The ledger,** schema 27, now part of 32 to 28, is never pruned: ```kotlin @Entity data class IcebergLabel(@PrimaryKey val label: HexKey, val wallet: String, val messageHash: HexKey, val echoedAt: Long, val signedAt: Long?) @@ -816,8 +819,8 @@ does not answer anything until it has collected high-water marks from `t` other participants. Those are the highest commitment number and fresh counter each has answered, per channel. After that it answers only above the highest of them. -**Tests,** in the four-device harness, a hand-built 30341 for each numbered check, -each asserting that no 30344 was published. Two more: an operator that sends two +**Tests,** in the four-device harness, a hand-built 30358 for each numbered check, +each asserting that no 30361 was published. Two more: an operator that sends two messages under one label never gets a share from anyone, and a co-signer with a restored database answers nothing until it has the marks. @@ -827,7 +830,7 @@ a restored database answers nothing until it has the marks. **About a week.** -The operator sends **30345** whenever something changes, debounced, and every few +The operator sends **30362** whenever something changes, debounced, and every few minutes while the node runs: | field | | @@ -864,8 +867,8 @@ onchain wallet screens: amounts as format arguments, QR modules **About four days.** -- **An invoice for an amount.** A member sends 30347 with the amount and a - description. The operator's node creates a bolt11 and replies with 30348. The +- **An invoice for an amount.** A member sends 30364 with the amount and a + description. The operator's node creates a bolt11 and replies with 30365. The member's screen shows it as a QR code, and checks that its payee is the statement's node id. If there is no operator, or no reply within a minute, the screen says the wallet cannot receive right now, and why. @@ -886,7 +889,7 @@ HTLC waits, and eventually the payer's side fails it. **About a week.** -- **An authorisation, kind 30346 `pay`,** proposed with `proposeSigning`. It +- **An authorisation, kind 30363 `pay`,** proposed with `proposeSigning`. It carries the invoice or offer, the amount, a fee cap, an expiry, and the payment hash. `summarize` reads *Pay 12,000 sats to …*. Any member can propose one, and `t` approve it, like any other group decision. @@ -907,9 +910,9 @@ choice belongs to the group, not to this plan. **About a week and a half.** -- **Close:** a 30346 `close` authorisation, then a mutual close to the onchain +- **Close:** a 30363 `close` authorisation, then a mutual close to the onchain wallet. Check 7 holds on each co-signer. -- **Force close:** a 30346 `force-close` authorisation, needed when the LSP has +- **Force close:** a 30363 `force-close` authorisation, needed when the LSP has gone away. Co-signers then sign our own commitment. - **Sweeping into the onchain wallet.** The `ChannelAction`s from Phase 3 become rows that `GroupTransactionWatcher` follows. Once an output's CSV has expired, any @@ -918,7 +921,7 @@ choice belongs to the group, not to this plan. the two leaves Phase 3 defines, derived by the member. The output must go to an onchain wallet address. That rule is new to the onchain wallet's checks, and its tests go beside the seven it already has. -- **Splice out** to an onchain wallet address: a 30346 `splice-out` +- **Splice out** to an onchain wallet address: a 30363 `splice-out` authorisation. It is design B from the parity plan, which serves the same group key at every funding index. - **Splice in from the onchain wallet** is left for its own plan. It needs the diff --git a/docs/group-wallet-addresses.md b/docs/group-wallet-addresses.md index 44f4e207..2ff4b332 100644 --- a/docs/group-wallet-addresses.md +++ b/docs/group-wallet-addresses.md @@ -90,7 +90,9 @@ wallet to two payers in the same hour hand out the same address, and the group reuses it. Offering `current + 1` and `current + 2` beside it gives a second and third member something else to hand out. Both are already watched, because the look-ahead keeps the wallet subscribed to `current … current + 9`, so a payment -to either is seen the moment it reaches the mempool. +to either is seen the moment it reaches the mempool. An ancestor funding a +guarded wallet starts at the top of that window, `current + 2`, and goes up, so +it stays out of the members' way -- [guarded-wallet-funding.md](./guarded-wallet-funding.md), D2. **Why `highest used`.** `firstUnusedDerivedAddress` takes the *lowest* unused index, so a payment above `current` does not move `current`. If `/0/3` is diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md new file mode 100644 index 00000000..e869537d --- /dev/null +++ b/docs/group-wallet-guardians.md @@ -0,0 +1,493 @@ +# Guardians: an ancestor group's leaf in a subgroup's wallet + +A subgroup's onchain wallet can carry its ancestry in its addresses: one taproot +leaf per ancestor group, each spendable by that ancestor's quorum, so the root of +a hierarchy can move the coins of any group beneath it. The child's own spends +stay on the key path, look like any single-key taproot spend, and never reveal +that the tree exists. + +Read [subgroups.md](./subgroups.md) and [group-chain-wallet.md](./group-chain-wallet.md) +first. This builds on the birth certificate from the first and the account +derivation from the second, and it changes one sentence in each. + +**Built**, phases 1-9, one commit each, written against the code as it stood at +`409be6db` with the `lightning-kmp-app` submodule at `e0d2b82`. `GuardianDerivation`, +`GuardianManager` and `FrostSigningManager.proposeGuardianSpend` are the entry +points, and `GroupWalletRollout.GUARDIANS_ON_MAINNET` is the gate. The phases +below are kept as written; where the build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 4 is the statement, Phase 5 the addresses | Phase 4 did both: a statement cannot be verified without rebuilding the descriptors it carries, so `Account` learned its guardians and `deriveBelow` its tree in the same commit | +| Phase 9 adds the rollout gate | the gate came with Phase 5, because that is where a guarded wallet is first offered; a way in shipped before its gate would have been offered on mainnet for four commits. Phase 9 is this table | +| forwarded statements are stored for the ancestor to watch | no table: the 30333 notice is the `MarmotInnerEvent` row the inbound path files for every inner event, and `GuardianManager.guardedWalletsOf` checks each one again on every read -- the economy `GroupWallet` already has | +| the proposal carries `["input", …]` tags | it carries one tag, `["guarded", ]`. Each input's `tap_bip32_derivation` already names its place under the descendant's account, exactly as the child's own spend does, so a second place to say it would be a second thing to disagree | +| `check` asks the proposer's device whether a coin has 12 confirmations | the builder does: it only offers a guardian coins its lock has already let go of. `check` cannot ask, because a signer with no node has no tip, and a coin spent too early is a transaction nobody can mine rather than a loss | +| `GroupTransactionWatcher` notices a guardian's spend | the wallet screen's view model does, each time the guarded wallet's coins change, by reading every used address's history off Electrum -- so a device asleep when the coin moved still finds it, and whichever device reads first writes the one line. A device that never opens the wallet screen writes nothing | +| schema unchanged | v28 (v27 on this branch until the default branch's document-table removal took that number): `GroupTransaction.guardedChatRoomId`, the descendant a guardian's spend draws from. A spend's account is otherwise read from the statement, and a guardian's is the descendant's statement, not the room's | +| a spend that lost its coins to the other side is never settled -- this note's own *What this does not do*, as first written | settled. `GroupTransactionWatcher` asks the chain, for a signed spend Electrum has not heard of, whether each coin is still unspent at its address and, if not, which transaction in that address's history took it; once that transaction is confirmed, `FrostSigningManager.recordReplaced` marks the spend replaced and settles every other spend of the coin, as `recordConfirmed` does for the room's own. A conflict still in the mempool settles nothing | +| nothing outside the plan | a bug older than it: bitcoin-kmp reads a taproot derivation's fingerprint back from a PSBT as a signed int, so for half of all accounts every member but the proposer refused every spend as not the wallet's own. Fixed on its own, in `fix(wallet): read a PSBT's key fingerprint as unsigned`, because it reaches every plain wallet too | + +**The mainnet gate is open.** It was to lift on a guardian spend made on signet +by a real three-level hierarchy, every member's device watching, and the +grandchild's transcript naming the root; it was lifted by decision before that +run. The run is still worth making, and the mixed-version risk below is still +open: a group whose members are not all on a build that reads guarded statements +should not open one. Guardian spends on mainnet are held to the same per-spend +cap as every other spend, `GroupWalletRollout.MAINNET_CAP`. + +The headline: **the parent puts a guardian key for the child into the child's +birth certificate, beside the keys its own ancestors gave it, each derived one +public step further for this child. Each becomes a leaf +` OP_CHECKSIGVERIFY OP_CHECKSEQUENCEVERIFY` in every address of the child's +wallet.** Every ancestor can take a coin once it has `d` confirmations, where `d` +is the delay that ancestor chose when it made the group below it — 12 unless it +chose otherwise, see [guardian-delay.md](./guardian-delay.md). The +ancestor's quorum signs for its leaf with the FROST session it already runs, +under plain tweaks of its own threshold key. + +--- + +## What this reverses, and whose choice it is + +[subgroups.md](./subgroups.md#what-this-does-not-do) says: + +> A subgroup cannot sign for its parent, and the parent cannot sign for it. […] +> If delegation is ever wanted it is a different mechanism and it should not be +> built on top of this one silently. + +This is that mechanism, and it is not silent. It takes two signatures, one from +each side: + +- the **parent's** quorum signs the guardian keys into the certificate, so the + parent agrees to be a guardian and every one of its signers' devices has + checked the keys it is vouching for; +- the **child's** quorum signs a wallet statement that names them, so the child + agrees to be guarded. + +The certificate on its own delegates nothing. A child that never opens a guarded +wallet has a certificate with keys in it and no address that uses them. + +**The parent decides, and the chain does not enforce it.** Since +[subgroup-wallet-policy.md](./subgroup-wallet-policy.md), the parent decides when +it makes the child: the coordinator picks *guarded* or *unguarded* on the +subgroup picker, every admin is told at the join gate, the parent's quorum signs +the choice into the certificate as a `["wallet", …]` tag, and the child's quorum +signs it again in its key state. Every client running this app then offers, +signs, derives and watches only the wallet the certificate allows. A guarded +group's subgroups are all guarded. + +What has not changed is the cryptography. The child's threshold key is the +child's. Its quorum can always pay to a plain BIP86 address under its own key, +and no script in any address can stop it. The parent's decision is a signed rule +every honest client keeps, not a rule the chain enforces, and the UI never +describes it as more than that. + +A certificate from before policies carries no `wallet` tag and decides nothing. +Its child is offered a guarded wallet by default when the certificate carries +keys, and a plain one beside it, as this note first described. There, being +guarded is still the child's own choice. + +**The child gives up a real thing.** An ancestor can take any coin in the wallet +that has been confirmed for two hours, without the child's agreement and without +warning — the first the child learns of it is a spend none of its members +signed. That is the honest description of "the root can spend from its +descendants". + +--- + +## The shape of an address + +``` + Q = P + H_TapTweak(P ‖ root)·G output key + ╱ ╲ + key path: P the child's own key, as today + root + ╱ ╲ + leaf(parent) • + ╱ ╲ + leaf(grandparent) • + ╱ ╲ + … leaf(root group) +``` + +- `P` is exactly today's internal key, `account(K_child, network, n)/change/index`. + A spend by the child is a key-path spend, signed exactly as today; the only + change on that side is that the final tweak is BIP341's script-path tweak over + `root` rather than BIP86's empty one. +- The leaves form a caterpillar, nearest ancestor shallowest. Every ancestor can + act at the same moment, so the order decides only cost: the parent's control + block is the shortest and the root's the longest, at `33 + 32·(k − 1)` bytes + for `k` ancestors. +- One ancestor is a tree of one leaf, with a 33-byte control block. + +### The leaf + +``` + OP_CHECKSIGVERIFY 12 OP_CHECKSEQUENCEVERIFY +``` + +Miniscript's `and_v(v:pk(L),older(12))`. The delay is a BIP68 relative lock in +blocks and counts from the confirmation of the coin being spent, not from +anything the group did: a coin with 12 confirmations is the guardian's to take, +and one that arrived or was moved within the last two hours is not. `12` is the +single opcode `OP_12`, so the script is 36 bytes. + +**Why a delay, and who sets it.** This section was *Why 12, and why for +everybody*: 12 was one constant, the same at every distance. Since +[guardian-delay.md](./guardian-delay.md), each parent chooses its own leaf's delay +when it makes a guarded subgroup, from `GuardianDerivation.MIN_DELAY` (6, about an +hour) to `MAX_DELAY` (65,535, BIP68's block-based ceiling, about 15 months), with +12 as `DEFAULT_DELAY`. Every inherited key keeps the delay its own ancestor chose, +so each group's terms follow its key down the tree. What 12 buys, and what a floor +of 6 keeps: + +- **Not autonomy, at 12.** Two hours is not long enough for a child to notice a + coin coming within reach and move it. In practice this is an override, and it + is meant as one: ancestors have control now, not as a last resort. A long delay + changes that: the clock is per coin and moving a coin restarts it, so a child + that moves its coins before a month-long lock runs out keeps them out of reach. + A long delay is a backstop for a group that falls silent, not an override. +- **The child's own spends always go first.** A guardian cannot race the child + for a payment that has only just arrived, nor take change from a spend the + child made an hour ago. +- **It is a relative lock**, so every guardian input carries `nSequence = d` in + a version-2 transaction. That is far below `GroupSpend.MAX_SEQUENCE`, so a + guardian spend still signals replaceability and *Bump the fee* still works. + +The delay is written into every `guardian` tag rather than assumed, so a later, +different delay is a later account's tags, not a new format. + +--- + +## The guardian keys + +### Each group has one guardian root, which it never hands out + +``` +I = HMAC-SHA512(key = "bennu/group-wallet/guardian/v1", + data = serP(K_A)) +R_A = K_A + I[0:32]·G plain tweak, like the wallet's account step +c_A = I[32:64] + +(R_A, c_A) A's guardian root, an xpub at depth 0 +``` + +The same shape as `GroupWalletDerivation.account` without the network and the +account number, which come lower down. It is not the room key: a room id is the +`h` tag on every message the room publishes, so a relay knows it, and a leaf +built on it would tie an onchain spend to a Marmot room for anyone who has +watched the relay. Nothing about `R_A` is published anywhere. + +### A child's index comes from its room id + +``` +i(C) = taggedHash("bennu/group-wallet/guardian/child/v1", C)[0:4] & 0x7fffffff +``` + +Unhardened, so anyone holding the parent's copy of an xpub can take the next +step, and nobody holding only the child's copy can go back up or across to a +sibling. + +### What A writes into C's certificate + +``` +guardians(C) = [ R_A / i(C) ] A's own key, granted to C + ++ [ g / i(C) for g in guardians(A) ] A's ancestors' keys, as A received them +``` + +Nearest first, each tagged with the room it belongs to. A root group — or any +group whose own certificate carries no guardian keys — writes only its own entry. + +For root → middle `M` → grandchild `C`: + +``` +cert(M), signed by root: [ R_root/i(M) ] +cert(C), signed by M: [ R_M/i(C), R_root/i(M)/i(C) ] +``` + +Re-deriving each inherited key at every level is what keeps a parent's wallet and +its child's from sharing a leaf: the root's key in `M`'s wallet is +`…/i(M)/n/a/…` and in `C`'s it is `…/i(M)/i(C)/n/a/…`. And siblings cannot link +each other: `C₁` holds `R_A/i(C₁)` and cannot compute `R_A/i(C₂)` without `R_A`'s +chain code. + +`i(C)` is 31 bits, so two siblings could share an index; the odds pass even at +around 55,000 children of one parent, and the consequence is only that those two +siblings' guardian leaves become linkable onchain. + +### The leaf for one of C's addresses + +At network `n`, account `a` and address `change/index`: + +``` +L = xonly( guardian / n / a / change / index ) + n: 0 mainnet, 1 testnet3, 2 testnet4, 3 signet, 4 regtest +``` + +So the root's leaf in `C`'s receive address 7 of mainnet account 0 is +`R_root / i(M) / i(C) / 0 / 0 / 0 / 7`. Everything below the guardian root is +ordinary CKDpub, so the descriptor stays one Bitcoin Core imports: + +``` +tr([fp]xpub_C/0/*,{and_v(v:pk(xpub_M→C/0/0/0/*),older(12)),and_v(v:pk(xpub_root→C/0/0/0/*),older(12))}) +``` + +### Who checks what + +- **When A's quorum signs C's certificate**, each signer's device rederives + `R_A/i(C)` from `K_A`, and checks every inherited entry is exactly the matching + entry of A's own verified certificate one step further, in the same order. A + coordinator cannot add, drop or swap a key without every honest signer's + device refusing the proposal. +- **The child trusts the parent's quorum for the inherited entries**, and it is + no new trust: that quorum can already take every coin through its own leaf. + A reader holding the parent's certificate can check them anyway, since each is + a public step from an entry one certificate up. +- **When ancestor X signs for a coin in descendant C**, its FROST cache is plain + tweaks all the way down the line of descent from X: + +```kotlin +TweakCache.create(K_X) + .tweak(I[0:32], isXonly = false) // guardian root + .tweak(IL(i(A1)), isXonly = false) // one step per generation, X's child first + … + .tweak(IL(i(C)), isXonly = false) + .tweak(IL(n), isXonly = false) + .tweak(IL(a), isXonly = false) + .tweak(IL(change), isXonly = false) + .tweak(IL(index), isXonly = false) +// xonly(cache.tweakedPublicKey) == L; no TapTweak, since it signs as the leaf key itself +``` + + X reads the line of descent off the room ids in C's certificate, and checks + that the entry there for X is the key this walk reaches before it signs + anything. There are no x-only tweaks before the last step, so there is no + parity to get wrong. + +--- + +## The statement + +The opt-in is the child's `GroupWalletStatementEvent`, signed by its quorum as +today, with two kinds of tag added: + +``` +["guardian", , , , "12"] one per ancestor, nearest first +["birth_certificate", ] +["descriptor", tr(…,{…}), "receive"] as today, with the tree +["descriptor", tr(…,{…}), "change"] +``` + +`verifiedAgainst` grows the same way: it rederives the account from `K_child`, +checks the certificate certifies this room, checks the `guardian` tags are +exactly the certificate's entries with the delay this build writes, rebuilds the +tree, and compares the descriptors. The statement stays *a record that the group +agreed, not a source of keys*. Carrying the certificate makes it self-contained: +a member welcomed into the child after its birth, who holds no key state, can +still check every address — the gap [subgroups.md](./subgroups.md#what-this-does-not-do) +names, closed for the wallet. + +Three rules, each closing a way to lose coins: + +1. **A guarded statement outranks a plain one for the same account.** An account + opened guarded stays guarded; a later plain statement for it, from a client + that predates this, is ignored rather than allowed to move every address. +2. **A guardian set is fixed for its account.** Among guarded statements for one + account the earliest decides the guardians, and a later one naming others is + ignored. Changing who guards a wallet is another account. +3. **Old clients refuse it**, which is the right failure: `verifiedAgainst` + compares the descriptors byte for byte, and theirs have no tree, so a client + that predates this rejects the statement rather than handing out unguarded + addresses under the guarded account's name. + +What an old client can still do is see no wallet and open a plain one. Rule 1 +keeps every new client on the guarded addresses, but the old client then hands +out plain ones that new clients do not watch. That is a mixed-version risk, and +it is why the guarded wallet first shipped behind a gate shut on mainnet -- since +opened, so the risk is now the group's to manage. + +### The rule from the wallet note, restated + +[group-chain-wallet.md](./group-chain-wallet.md#why-each-level-is-what-it-is) +says having no script tree is a security property: a member can check alone that +no back door is hidden in an address. That stays true with one word changed — +**every member derives every address, tree included, and compares it byte for +byte.** The tree is a pure function of the child's key, the account and a +certificate every member verifies, so a proposer still cannot slip a leaf in. + +--- + +## How an ancestor finds the coins + +To spend from a descendant, an ancestor's members need the descendant's account +xpub and its tree. Both are in the descendant's guarded statement, which checks +out against things the ancestor can verify alone: it is signed by the +descendant's room id, the certificate inside it is signed by the descendant's +parent and certifies that room, the certificate's `subgroup_key` is the key the +xpub rederives from, and the guardian entry for the ancestor is the key its own +walk reaches. + +What the ancestor does not have is the statement: it is signed in the child's +room, and the root's members are not in it. So a member who sits in both rooms +**forwards** it, as an ordinary message in the ancestor's MLS room — never to a +relay, under the same `NEVER_BROADCAST` rule. The forwarder is trusted with +nothing but the act of forwarding. + +That depends on membership overlapping, which it does at birth — a child's +admins are chosen from its parent's members — and may not later. A grandchild +whose middle group no longer shares a member with the root has a root leaf in +every address and a root that cannot find a coin to use it on. A statement +forwarded into the middle group can be forwarded again from there, so overlap is +needed one level at a time, not between the grandchild and the root directly. + +Since [member-guarded-wallets.md](./member-guarded-wallets.md) the thing +forwarded may also be a member wallet certificate, which the guarding group +signed itself and so needs no forwarding into that group. Since +[member-wallet-guarding-group.md](./member-wallet-guarding-group.md) the notice +carrying one also carries, as a `certificate` tag, the guarding group's own +birth certificate, so a group above that was never in its room can name it. +Like the statement, the tag is checked rather than trusted, and an older build +ignores it. + +Since [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md) nobody has to +remember to. A device that files a guarded wallet it believes tells the groups +above it is in -- upward only, never a group that already holds it, one elected +device at once and the rest when a group's chat or wallet screen next opens -- +and *Share* is the fallback for a notice lost on the wire. Overlap is still what +it needs: a device in both rooms, one generation at a time. + +Once it has the statement, the ancestor watches the descendant's addresses on the +Electrum client it already holds — unknown script hashes are ignored, so this +costs subscriptions and nothing else — and its wallet screen grows a *Guarded +wallets* section. + +--- + +## A guardian spend, end to end + +An ancestor's FROST session in the ancestor's room, with the existing proposal, +approval and completion steps, and three differences. + +**The claim rides in tags, not PSBT fields.** bitcoin-kmp does not parse +`tap_leaf_script`, `tap_merkle_root` or `tap_script_sig` — they land in +`unknown`, which is why `GroupSpend.check` refuses any input carrying them. +Rather than teach the library those fields, keep the refusal and put the claim +where a spend's other claims already go: the proposal names the descendant +wallet, and each input's `tap_bip32_derivation` names its place under the +descendant's account, exactly as a child's own spend does. Every signer then +rebuilds the leaf, the tree, the control block and the script-path sighash from +the forwarded statement it holds. A proposer who names the wrong place gets a +sighash nobody else computes. + +**Sequence and version.** `check` grows one rule: a guardian input's sequence is +exactly 12, and — on the proposer's device, which can see the chain — the coin +already has 12 confirmations, so a spend that cannot go in the next block is not +put in front of a quorum. Signers without a node rely on the script: a coin +spent too early is a transaction nobody can mine, never a loss. + +**The witness** is `[sig, script, control block]`, from +`Script.witnessScriptPathPay2tr`, and `correctlySpends` is still the last word. + +### What the child sees + +Nothing until it happens. A child's device reads the history of every address +its guarded wallet has used, finds a transaction whose witness carries one of +its guardians' leaves for the coin it spent, and writes a transcript line saying +which ancestor took how much -- `GuardianManager.takenIn` and `recordTaken`. + +### What it costs onchain + +A key-path input's witness is 66 weight units. A guardian input with one ancestor +is about 137 — the signature, the 36-byte script and a 33-byte control block — +so about 18 vbytes more, and 8 vbytes more for each further level of depth. Only +paid when a guardian spends; the child's own spends cost exactly what they cost +today. + +### What it reveals + +| spend | a chain observer learns | +|---|---| +| the child, key path | nothing beyond any single-key taproot spend, as today | +| a guardian | that the output had a script tree; the one leaf used and its delay; its depth in the tree, so a lower bound on the hierarchy's depth. The leaf key is unlinkable to any room id | + +--- + +## Phases + +One commit each. + +1. **`GuardianDerivation`**, pure, commonMain: `ANCESTOR_DELAY`, the guardian + root, the child index, the grant, the leaf key, script and tree, the + descriptor fragment, and the signing cache. Vectors: the root and grant by + point arithmetic and by cache, agreeing; a three-level grant; a tree of one + and of three; the descriptor through bitcoin-kmp's checksum. +2. **Signing a leaf.** A jvmTest in the shape of `GroupSpendSigningJvmTest`: a + parent ceremony's shares sign a script-path spend of a child's coin, and + `correctlySpends` accepts it at sequence 12 and refuses it at 11. +3. **The certificate carries the keys.** `guardian` tags on + `SubgroupBirthCertificateEvent`, written by `proposeBirthCertificate` from + the parent's key and its own verified certificate, and checked by every + parent signer before a certificate proposal is accepted. +4. **The guarded statement.** Tags, `read`, `verifiedAgainst`, an `Account` that + knows its guardians, and the three rules in `GroupWallet`. +5. **The child's side.** Addresses with the tree, `GroupSpend` checking against + them, and the wallet screen opening a guarded wallet when the room's + certificate carries guardian keys. +6. **Forwarding upward**, and the ancestor watching what it was forwarded. +7. **The guardian spend**: the builder, the proposal, `GroupSpend`'s guardian + arm, `FrostSigningManager` signing with the guardian cache over the + script-path sighash, and the witness at completion. +8. **The child's notice**: the watcher naming the ancestor that spent. +9. **Rollout**: `GroupWalletRollout.GUARDIANS`, on for test networks, shut on + mainnet until a guardian spend has been made on signet by a real three-level + hierarchy. + +--- + +## What this does not do + +**It does not, on its own, guard one person.** That is +[member-guarded-wallets.md](./member-guarded-wallets.md): a wallet whose key +path is one member's random key, carrying exactly the leaves a guarded subgroup +of their group would, under a member wallet certificate (30334) the group signs +over the member's own request. Forwarding, the ancestor's walk and the guardian +spend are the ones here, with the line of descent ending in the wallet's id. + +**It does not guard a wallet that is already open.** A subgroup that opened a +plain wallet before its certificate carried keys keeps it. Guarding it would be a +second account and a spend into it, and the wallet screen shows one account per +room today. + +**It does not reach a subgroup certified before this.** Its certificate has no +keys. Its parent can sign a fresh one — certificates are replaceable per child, +newest winning — but nothing here prompts it to. + +**It does not, on its own, let the parent decide.** That is +[subgroup-wallet-policy.md](./subgroup-wallet-policy.md): a policy the parent +signs into the certificate at the child's birth, which the child's own quorum +agrees to. + +**It does not survive a re-keyed ancestor.** A leaf is bound to the ancestor's +threshold key, so to the shares of the ceremony that made it, including the +shares of members who have since left. This is the wallet note's *removal from +the group does not un-know a key*, inherited one level down. + +**It does not tell the child before it happens**, and it does not constrain where +the coins go. "Only back into the child, at a new address" is a covenant, and +there is none on mainnet to write it with (`OP_CHECKTEMPLATEVERIFY`, +`OP_VAULT`). The other direction is supported: an ancestor paying coins *into* +a guarded wallet is [guarded-wallet-funding.md](./guarded-wallet-funding.md). + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| derive the child's key from the parent's | the child is then the parent wearing a different hat — [subgroups.md](./subgroups.md#why-the-key-is-fresh-rather-than-derived) | +| the ancestor's room key as the leaf key, tweaked by the child's chain code | the parent never agrees to anything, the child has to find every ancestor's room key itself, and the first tweak has to be x-only to agree on parity. A key the parent signs into the certificate fixes all three | +| the ancestor's threshold key `K_A` | the child does not have it, and handing it over gives every child member the ancestor's whole wallet and room identity | +| a `k`-of-`n` `OP_CHECKSIGADD` over the ancestor's admins' own keys | it reveals the admins onchain, changes with every membership change, and bypasses the quorum the ancestor's FROST key already is | +| passing inherited keys down unchanged | a grandchild's leaves would equal its parent's wallet's at the same index, and a guardian spend from one would link the two | +| the whole certificate chain in the statement | nobody needs it to be safe — the parent's quorum vouches for the inherited keys and already holds more power than they give — and nesting signed events inside signed events escapes JSON once per level | +| the tree in PSBT fields | bitcoin-kmp does not parse them; every signer rebuilds them anyway | +| delays escalating with distance | asked for and replaced: every ancestor at 12 blocks, for now. Since [guardian-delay.md](./guardian-delay.md) each ancestor's delay is its own choice instead | diff --git a/docs/guarded-wallet-forwarding.md b/docs/guarded-wallet-forwarding.md new file mode 100644 index 00000000..518c160a --- /dev/null +++ b/docs/guarded-wallet-forwarding.md @@ -0,0 +1,422 @@ +# Forwarding guarded wallets upward, without anybody pressing a button + +A guarded wallet carries a leaf for every group above it, but a group above can +use its leaf only once it has been *told* about the wallet. Today that telling +is a button. A member who sits in both rooms opens the lower group's wallet +screen, finds *Tell the groups above*, and taps *Share* for each wallet. One tap +carries one wallet one generation up. Nobody is prompted to do it. A root whose +grandchildren's wallets nobody shared has a leaf in every address and no way to +find a single coin. + +This plan makes the telling automatic. **Whenever a device files a guarded +wallet it believes -- a subgroup's own guarded statement, a member wallet +certificate its group signed, or a notice forwarded to it from below -- and it +sits in a group above that has not been told, it tells that group. The same +check runs again each time a group's room or wallet screen is opened, which +catches up on everything filed before this existed or missed while offline.** +The button stays, for the case a notice was lost on the wire. + +Read [group-wallet-guardians.md](./group-wallet-guardians.md), *How an ancestor +finds the coins*, and [member-guarded-wallets.md](./member-guarded-wallets.md), +Phase 10, first. This plan changes no format: the notice is the 30333 +`GuardedWalletNoticeEvent` it has always been, and everything an ancestor checks +before believing one is unchanged. What changes is who sends it, when, and to +which groups. + +**Built**, phases 1-7, one commit each, written against the code as it stood at +`263a25a7`, schema v30; the build changes no schema and no format. +`GuardianManager.believable`, `upwardOf`, `forward`, `forwardOnArrival` and +`forwardAll` are the entry points, and `GroupWalletRollout.FORWARDS_GUARDED_WALLETS` +is the switch. The phases below are kept as written; where the build chose +differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 1's tests are in commonTest | jvmTest, `GuardedWalletForwardingRulesJvmTest`: `believable` is tested against certificates a real quorum signed, and FROST runs on the JVM | +| Phase 2: `forward` writes the forwarder's own line | `share` writes it, so the button writes it too -- the forwarder never seeing its own line was the button's gap as much as the automation's (Phase 5) | +| Phase 3: the notice arm forwards after `describeNotice` believes it | before, and whether or not it does. `describeNotice` needs this room's key to make the ancestor's walk; forwarding needs only `believable`, so a device in a middle group that holds no key state for it still carries a notice on up | +| Phase 3: a test with the switch off | not written: the switch is a `const`, and a test cannot turn it. Each trigger reads it in one line, `forwardOnArrival` and `forwardAll` | +| Phase 3's notice test arrives through the inbound path | through `GuardianManager.forwardOnArrival`, which the inbound path calls: the 30333 arm sits inside MLS decryption, which a jvmTest does not drive. The certificate and statement arms are driven through `ChatMessage.applyInnerEvent` itself | +| Phase 4: `ChatRepository.forwardGuardedWallets` | with a default body, so every fake repository in the tests needed no change | +| Phase 5: nothing else changes | two older tests described a notice under an id other than the one they filed. Under the one-line rule that is a second notice, and silent; they now describe the notice they filed | +| Phase 6: each row's supporting line explains the fallback | one line under the section's heading says it, and each row keeps *Not yet shared with the groups above that you're in*: the same sentence on every row was the same sentence N times | +| Phase 7: the three-device run | not made | + +Still to do by hand: Phase 7's run on signet. + +--- + +## What is there, and the two things wrong with it + +`GuardianManager.shareableFrom(chatRoomId, chain)` lists what a device could +tell from a room. That is the room's own guarded wallet, if it has one, plus +every guarded wallet the room holds: those it was told about, and those of its +members it signed itself. Each comes with the guarding rooms this device is in +and has not told yet (`targetsFor`). `GuardianManager.share` posts one notice +per room. `GroupWalletViewModel.share` is the only caller, behind the button. + +Read as the basis for doing this without a person, two of its rules are wrong. + +**1. It tells groups below as well as above.** `targetsFor` takes every room +the statement's guardian list names, except the room it is in. The list names +*all* the wallet's guardians, nearest first. So from a middle group `M`, the +targets of a grandchild `C`'s statement include the root `R`, which is right, +and nothing below `M`. But from the root `R`, holding the same statement, the +targets include `M`, which already holds it. Each tap there tells a group +something it was told first. By hand that is a wasted tap. Automatically it is +a notice into `M` from every device in both rooms, every time `R` is opened. + +**2. A guarding group's own certificate never counts as told.** `alreadyTold` +reads the target room's 30333 notice rows. A member wallet certificate is held +in the group that signed it as a `GroupSignedEvent` and never as a notice. So +`R` holding a member's wallet that `G` signed would tell `G` again, for the +same reason as above. + +Both are fixed by one rule: **a statement is told upward only**, to the guardian +rooms after the room it is in. A room that holds the statement in any form, +signed or as a notice, has been told. + +--- + +## Phase 0 — decisions, before any code + +### D1. Which statements are forwarded + +**Recommended: exactly what `shareableFrom` lists today**, from a room this +device is in: + +| statement | held in the room as | forwarded to | +|---|---|---| +| the room's own guarded wallet statement (30331) | a `GroupSignedEvent` the room's quorum signed | every guardian it names | +| a member wallet certificate (30334) the room signed | a `GroupSignedEvent` | the guardians after the room, which is guardian 0 | +| a statement or certificate a notice carried here (30333) | a `MarmotInnerEvent` row | the guardians after the room in the statement's list | + +A plain (unguarded) wallet statement is never forwarded: it names nobody. + +### D2. What the forwarder believes first + +The forwarder vouches for nothing. Every device in the target room runs +`GuardianManager.verify` on what arrives, including the walk down from its own +guardian root. But the forwarder should not pass on what it cannot believe +itself, or a single bad notice is copied into every group above. + +**Recommended: everything `verify` checks except the ancestor's own walk**, +which only a device holding that ancestor's key can make: + +- a 30331 statement: signed by its room, guarded, carrying a certificate whose + key makes that room, and with every value rederiving from it + (`Reading.verifiedAgainst`); +- a 30334 certificate: `MemberWalletCertificateEvent.verify(certificate, certificate.pubKey)`. + +This is `GuardianManager.believable(statement)`, split out of `verify` so the +two cannot drift. `verify` becomes `believable` plus the walk. + +### D3. Which groups count as "above" + +**Decided by the bug above: upward only.** In room `X`, a statement's targets are +the guardians listed *after* `X`'s own position in its guardian list, nearest +first. A room not in the list at all is the wallet's own room (a subgroup's own +statement), and gets every guardian. For a member's wallet signed by `G`, `G` is +guardian 0, so the targets start at `G`'s parent. + +A target counts as told when it holds the statement in any form: a 30333 row +carrying it, or a `GroupSignedEvent` with its id. + +### D4. Who sends it, when several devices could + +Every device in both the lower group and the upper one could send the notice. +When a member wallet certificate completes, every device in `G` files it within +seconds of the others. Each of them that is also in `P` would then post into `P` +at once. A burst like that is the shape [mls-skipped-keys.md](./mls-skipped-keys.md) +warns of: one of two group events arriving back to back can be dropped for good. + +**Recommended: one sender is elected for the immediate send, and every device is a +fallback for the catch-up.** + +- The **elected** device is the one whose profile's key sorts lowest among the + members of *both* rooms, as this device's participant lists have them. It + forwards on arrival. +- Every **other** device forwards only in the catch-up pass (D5). By then the + elected device's notice has usually arrived, and the target counts as told. +- Devices disagreeing about the participant lists can elect two senders. The + cost is one duplicate notice, which D6 keeps out of the transcript. + +The alternative, everybody sending at once, is simpler and correct, since +`guardedWalletsOf` already collapses duplicates. It is rejected for the burst, +not for the duplicates. + +### D5. When the catch-up runs + +**Recommended: when a Marmot room's chat is opened, and when a group's wallet +screen is opened**, for that room. That is `ChatMessageListViewModel.initiate`, +beside `askForGroupHistory`, and `GroupWalletViewModel.initiate`, which already +reads `shareableGuardedWallets`. + +That covers: +- certificates and statements signed before this ships; +- a device that was offline when the elected one should have sent; +- an elected device that never sent. + +A pass over every room at launch would cover more, and would put a notice burst +on every room at once, on every launch. It is rejected for now and named under +*what this does not do*. + +### D6. What the transcript says + +Today each notice writes a *Shared @alice's guarded wallet with this group* +line, attributed to the member who forwarded it. The forwarder never sees its +own line: a sender is not handed its own MLS message back. + +**Recommended:** +- a line only for the **first** notice of a statement in a room. A notice whose + statement this room already holds, in any form, writes none; +- the forwarding device writes the same line into the target room on its own + side as it sends, so it sees what it did, as the button's snackbar did. + +### D7. Which profile sends + +One database holds every profile on the device. A room row's `userPublicKey` is +the profile that is in it. + +**Recommended: the notice is sent as the target room's own profile, and only when +that is the source room's profile too.** The arrival path that files a 30334 or +a 30331 (`ChatMessage.applyInnerEvent`) has no active key to hand. The room row +has it, and a device must never post into a room as a profile that is not the +one in it. + +### D8. A way to turn it off + +**Recommended: `GroupWalletRollout.FORWARDS_GUARDED_WALLETS = true`**, read by the +arrival triggers and the catch-up, not by the button. It is a behaviour that +sends messages without a person, so it gets one switch, in the same place as the +other wallet gates, for the release where it first ships. + +--- + +## Phase 1 — the rules, pure + +New in `GuardianManager` (or a small `GuardianForwarding` beside it, if it reads +better): + +```kotlin +/** [statement] believed on its own merits: everything [verify] checks except the ancestor's own walk. D2. */ +fun believable(statement: Event): Believable? // the guardians, the descendant id, the chain + +/** The guardian rooms [statement] is forwarded to from [chatRoomId]: those after it in the list, nearest first. D3. */ +fun upwardOf(guardians: List, chatRoomId: String): List + +/** Who sends at once, of [candidates] -- the members of both rooms: the lowest key. D4. */ +fun electedSender(candidates: Set): HexKey? +``` + +`verify` is rewritten as `believable(statement)` plus the walk, with its kdoc's +four rules unchanged. + +**Tests**, commonTest: +- `upwardOf` for a grandchild's statement: from the grandchild's own room, both + guardians; from the middle group, the root alone; from the root, nothing; +- `upwardOf` for a member wallet from its guarding group, two levels up: the + parent and the root; +- `believable` accepts what `verify` accepts and refuses each mutation + `verify`'s tests refuse, apart from the walk; +- `electedSender` is the lowest key and is null for an empty set. + +--- + +## Phase 2 — telling, as a function a trigger can call + +```kotlin +/** + * Tells every group above [chatRoomId] that this device's profile is in, and that has + * not been told, about [statement]. [whenElected] restricts it to the targets this + * device is the elected sender for (D4); the catch-up passes false. + * Returns the rooms told. + */ +suspend fun forward(database: BennuDatabase, statement: Event, chatRoomId: String, whenElected: Boolean): List +``` + +1. `believable(statement)`, or nothing; +2. targets: `upwardOf(guardians, chatRoomId)` → rooms on this device that are + Marmot rooms, belong to the source room's profile (D7), and have not been told + in either form (D3); +3. with `whenElected`, keep a target only if this profile is + `electedSender(participants(source) ∩ participants(target))`; +4. `share` into each, as that profile, and write the forwarder's own line (D6). + +`shareableFrom` and `targetsFor` move onto the same upward rule and the same +*told* check, so the button and the automation cannot disagree about what is +left to share. That fixes both bugs above for the button too. + +**Tests**, jvmTest, in the shape of `MemberWalletGuardianJvmTest`: +- a member wallet certificate in `G`, this device in `G` and `P`: `forward` + tells `P` and not `G`; +- the same from `P` holding the forwarded certificate: tells `R`, not `G`; +- a target holding the statement as a `GroupSignedEvent` counts as told; +- a target belonging to another profile on the device is never told; +- `whenElected` with a lower-keyed member in both rooms tells nobody, and + without it tells `P`; +- a statement that is not `believable` is forwarded nowhere. + +--- + +## Phase 3 — the triggers on arrival + +Three places, each after the statement has been believed and filed, so the +row the *told* check reads already exists: + +| arrival | where | forwards | +|---|---|---| +| a member wallet certificate is filed in `G` | `ChatMessage.applyInnerEvent`'s 30334 arm, reached from `FrostSigningManager.applySignedEvent` on every device that followed the session | the certificate, from `G`, `whenElected = true` | +| a guarded wallet statement is filed in a subgroup | the 30331 arm, when `wallet.account.isGuarded` | the statement, from the subgroup's room | +| a notice arrives in a group | the 30333 intercept in `ChatMessage`'s inbound path, after `describeNotice` believes it | the statement inside, from this group, onward | + +Each call is wrapped so a failure to forward is logged and never stops the line +being written. Forwarding is an extra, and the arrival is the thing. + +All three read `GroupWalletRollout.FORWARDS_GUARDED_WALLETS` (D8). + +**Tests**, jvmTest: a three-level hierarchy on one device -- root `R`, middle +`M`, grandchild `C`, this device a member of all three and the elected sender +throughout: +- `C`'s guarded statement filed in `C` ends with notices in `M` and in `R`, with + nobody calling `share`; +- a member wallet certificate filed in `C` reaches `M` and `R` the same way; +- the notice `M` receives does not travel back down into `C`; +- with the switch off, nothing is sent. + +--- + +## Phase 4 — the catch-up + +`GuardianManager.forwardAll(database, chatRoomId)`: every statement +`shareableFrom` would list from the room, on every chain, through `forward` with +`whenElected = false`. Called from: + +- `ChatMessageListViewModel.initiate`, beside `askForGroupHistory`, for a Marmot + room; +- `GroupWalletViewModel.initiate`, before `shareableGuardedWallets` is read, so + the *Tell the groups above* section shows only what is truly left. + +Both go through `ChatRepository.forwardGuardedWallets(chatRoomId)`, so the view +models still talk to repositories. + +**Tests**: a certificate signed before this existed -- filed with no trigger -- +is forwarded the first time its group's room is opened, and not again the second +time. A non-elected device forwards in the catch-up what the elected one never +sent. + +--- + +## Phase 5 — the transcript + +- The 30333 intercept writes its line only when no other stored notice in the + room carries the same statement id, and the room does not hold the statement as + a `GroupSignedEvent`. A duplicate is filed and silent. +- `forward` writes the forwarder's own line into each room it tells, typed + `TYPE_GUARDED_WALLET_SHARED`, `isUserMessage = true`, with the words the + receivers' devices write. + +**Tests**: two notices for one statement from two forwarders give one line; the +forwarder's own device shows its line in the room it told. + +--- + +## Phase 6 — the screen + +The *Tell the groups above* section on `GroupWalletScreen` stays, now as the +fallback, and lists only what the catch-up could not send. In practice that +means a notice lost on the wire, or a group above in which this device holds no +row. Its supporting line becomes *This device shares these on its own when it +can. Share now if a group above has not heard*. The strings go in +`strings.xml`, in sentence case. + +The snackbar the button shows today stays as it is. + +--- + +## Phase 7 — docs, and checking it on the emulators + +- [group-wallet-guardians.md](./group-wallet-guardians.md), *How an ancestor + finds the coins*: forwarding is automatic, one generation per device in both + rooms, with the button as a fallback. +- [member-guarded-wallets.md](./member-guarded-wallets.md), Phase 10: a member's + wallet reaches the groups above without anybody sharing it. +- [README.md](./README.md): this note's row. +- This note: *Built*, and a table of where the build chose differently. + +By hand, signet, three devices. `R` is the root, `M` its guarded subgroup, `G` +`M`'s guarded subgroup, and Alice is in `G`. Device 1 is in `G` and `M`, device +2 in `M` and `R`. + +1. Alice asks `G` to guard a wallet, and `G` signs. With nobody touching + device 1, `M`'s wallet screen lists `@alice` within a minute. +2. With nobody touching device 2, `R`'s does too, and `R`'s transcript has one + *Shared @alice's guarded wallet* line. +3. `G`'s transcript has no line about its own member's wallet coming back down. +4. Device 2 offline while `G` signs a second wallet: it appears in `R` the first + time device 2 opens `M`. +5. `R` makes a guardian spend from Alice's wallet through its leaf. + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +--- + +## Order and size + +| phase | touches | ships | +|---|---|---| +| 1 | `GuardianManager`, pure | dark | +| 2 | `forward`, and the button's rules | **fixes both bugs in the button** | +| 3 | three arrival arms | **the switch**: nothing sends without a person before this | +| 4 | two view models, `ChatRepository` | with 3 | +| 5 | the 30333 intercept, `forward`'s own line | with 3 | +| 6 | `GroupWalletScreen` | any time after 4 | +| 7 | docs and the run | last | + +Phase 2 is worth landing alone. It is a fix to the button that stands without the +automation. + +--- + +## What this does not do + +**It does not reach a group nobody sits in.** Forwarding needs a device in both +rooms, one generation at a time. A group above that shares no member with the +group below still cannot be told, and the remedy is the one the guardians note +gives: a member in common. + +**It does not tell a member welcomed into a group above after the notice.** +Notices are not chroniclable, so a device that joins `R` later holds none of the +notices `R` was sent, and lists none of the wallets. The catch-up does not help +it: the forwarder's device already holds its own copy of the notice and counts +`R` as told. Telling late joiners is the chronicle's job, and this plan does not +take it on. + +**It does not sweep every room at launch.** The catch-up runs per room as the +room or its wallet screen is opened (D5). A device that never opens the lower +group never forwards in the catch-up, though it still forwards on arrival when +it is the elected sender. + +**It does not make a notice reliable on the wire.** A notice lost to the skipped-keys +bug stays lost until a catch-up on another device sends one again, or somebody +taps *Share*. + +**It does not change what a group above can do with what it is told.** It finds +the wallet, watches it and can spend through its leaf after the delay. All of +that is unchanged; only the finding no longer waits on a tap. + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| every device sends at once | correct, since duplicates collapse, but it puts a burst of group events into every group above at the moment a certificate completes, the one shape `mls-skipped-keys.md` says loses messages (D4) | +| the member's own device forwards their wallet | the member is in `G` and seldom in the groups above, and a subgroup's statement has no single owner; the device in both rooms is the one that can | +| a pass over every room at launch | catches the most, and sends the most at once, on every launch (D5) | +| removing the button | a notice lost on the wire has no other way back until somebody opens the right room on the right device | +| a new kind for an automatic notice | the 30333 notice already says everything, and every build that reads it today reads these | diff --git a/docs/guarded-wallet-funding.md b/docs/guarded-wallet-funding.md new file mode 100644 index 00000000..4269b4bb --- /dev/null +++ b/docs/guarded-wallet-funding.md @@ -0,0 +1,534 @@ +# Funding a guarded wallet: a group paying into a descendant's wallet + +An ancestor group can already *take* from a descendant's guarded wallet. This +plan is about the other direction: **the group pays coins from its own wallet +into the descendant's guarded wallet, using an address its own devices derive +and every signer checks.** It is a send from the group's wallet with the +destination filled in, as the request guessed. What the request did not settle +is what that destination should be, how a signer can tell it is really the +descendant's address and not one the proposer typed, and how the guarded +wallet row on the wallet screen fits a second button. This plan answers those +three. + +Read [group-wallet-guardians.md](./group-wallet-guardians.md), +[group-send-an-amount.md](./group-send-an-amount.md) and +[group-wallet-addresses.md](./group-wallet-addresses.md) first. This plan uses +the forwarded statement from the first, the send form and its reservations from +the second, and the "current plus two" rule from the third. It changes no +format, no derivation and no schema. + +**Built**, phases 1-6, one commit each, written against the code as it stood +at `8cb6f04e`, schema v29, with the `lightning-kmp-app` submodule at `e0d2b82`; +the build changes no schema. `GroupWalletState.fundingAddress`, +`GroupSpendBuilder.Destination.Funding`, `GroupSpend.fundingsOf` and +`GroupSendRoute.fundChatRoomId` are the entry points. The phases below are kept +as written; where the build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 1 tests `claimedFundingIndices` | Phase 2 does: until the builder writes a claim there is no PSBT to read one from. Phase 1's watched-window test also counts the slots, eight, so the bound and the look-ahead cannot drift apart unnoticed | +| Phase 2: `send` and `sendAll` take a destination rather than an address string | both, as overloads: the string versions build a `Destination.Address` and call through, so the thirty-odd existing call sites, most of them tests, did not change. The claim always goes on output 0, where both builders put the payment | +| Phase 3: the check runs in `acceptSpendProposal` and `checkedSpend` | and in `proposeSpend` and `proposeGuardianSpend`, so a proposal every other device would refuse is refused before it is sent. It is one extension, `GroupSpend.Result.withFundings`, and a spend none of whose payments claims anything reads no guarded wallets at all | +| nothing about bumping | `GroupSpendBuilder.bump` rebuilt the PSBT without the claim, so a bumped funding would have read as a payment to a bare address and released its index. It carries `Checked.fundings` across | +| Phase 3's test is in the shape of `GuardianSpendRoundTest` | it is three tests in `GuardianSigningJvmTest`, which already holds an ancestor, a guarded child and the forwarding. The refusal test has the lie proposed by a device never told about the wallet -- the realistic way one arrives, since a device that holds the wallet refuses to propose it | +| Phase 4: the card says *To* and then the wallet's name | *To* and then *Savings's guarded wallet*. The title already says *Fund …*, and the card repeating it read twice. The index uses the address list's own *Address %1$s* | +| Phase 4: `MiddleEllipsis` on the address | as written, and on the desktop target it ellipsises at the end, as the address list does there | +| Phase 5: the name stays on one line | two: at 200% text a one-line name was cut to a word, and the name is what says which wallet the buttons act on | +| Phase 5: a `GroupWalletViewModelJvmTest` case for `arriving` | `GuardedWalletRowTest` in commonTest, since `arriving` is a property of the row and needs no view model; and `GuardedWalletCardJvmTest` renders the card, including at twice the text size | + +Still to do by hand: the signet funding between two real devices that the end +of Phase 6 asks for. + +The headline: **the group already watches every guarded wallet below it, so its +devices already know which of that wallet's receive addresses are unused. A +funding spend pays the first unreserved address from `current + 2` upward, and +the PSBT output carries that address's derivation under the descendant's +account, the same field change already uses. Every signer derives that address +again from the forwarded statement it already holds, and then shows the spend as +*Fund Thandi's group's guarded wallet* rather than as a bare address. If the +derivation does not reach the address, the signer refuses the spend.** + +--- + +## What is already there + +Funding needs no new knowledge, because the ancestor already has it: + +| what funding needs | where it already is | +|---|---| +| the descendant's account xpub and script tree | the forwarded guarded statement, checked by `GuardianManager.verify` and listed by `guardedWalletsOf` | +| which of its receive addresses are used | `GroupWalletViewModel` already subscribes to `wallets.walletFor(guarded.account)` for every guarded row; `GroupWalletState.receiveAddresses` reads that state | +| coins to send, change, reservations, the mainnet cap | `GroupSendViewModel` and `GroupSpendBuilder`, unchanged for the room's own wallet | +| a place in the PSBT to say *this output is under that account at that index* | `taprootDerivationPaths` on an output, which `GroupSpend.psbtOf` already writes for change | +| a signer who rebuilds a claim rather than trusting it | `GroupSpend.check`, step 5: change is change only if it derives | + +So the work is: choosing the address, writing the claim, checking it, and +showing it. There is no protocol work. + +--- + +## Phase 0 — decisions, before any code + +Seven, each with a recommendation. The phases assume the recommended answer. + +### D1. Pre-fill the address field, or replace it? + +**Recommended: replace it with a fixed destination card.** The request guessed +"pre-fill the spend screen", and that is close. But an editable field that +starts with the descendant's address and can then be changed makes the title +(*Fund X's guarded wallet*) a claim the form cannot keep. A member who wants to +send somewhere else already has *Send*. In fund mode the form shows: + +``` +┌──────────────────────────────────────────────┐ +│ To Thandi's group's guarded wallet │ +│ bc1p8q…x7kd · address 5 │ +│ │ +│ This group can spend these coins again once │ +│ they have 12 confirmations. │ +└──────────────────────────────────────────────┘ + Send everything ( ) + Amount in sats [ ] sats + Feerate in sats per byte [ ] + Sends 50,000 sats to Thandi's group's + guarded wallet with a fee of 420 sats + [ Ask the group to send ] +``` + +The amount, feerate, send-everything and preview all work as they do now. + +### D2. Which address? + +**Recommended: the lowest index from `current + ADDRESSES_AHEAD` upward that no +open spend in this room already pays, and below `current + RECEIVE_LOOKAHEAD`.** + +- **Not `current`.** The child's own members are handing out `current` to their + own payers right now; that is the reason the address list exists. Every + device computes the same `current`, the ancestor's included, so funding to it + is the address-reuse hazard + [group-wallet-addresses.md](./group-wallet-addresses.md#the-bound) describes, + caused by an ancestor this time. +- **From `current + 2` upward.** The child's members start at `current` and go + up through the next two. Starting the ancestor at the top of that window and + going higher keeps the two sides out of each other's way. Only one index is + shared (`current + 2`), and only when a third child member is handing out + addresses at the same moment. +- **Reserved like change.** Until the funding confirms, its address still reads + as unused, so a second funding proposal would pick the same address. Open + spends' claimed funding indices are held exactly as + `reservedChangeIndices` holds change (Phase 3). +- **Bounded by the look-ahead.** The child watches `current … current + 9`. An + address past that would be paid and the child would not see it until its own + look-ahead caught up. With eight slots (`current + 2 … current + 9`), a + room with that many open fundings into one wallet is told to wait, the way + `TooManyOpen` already handles change. + +### D3. How does the proposal say where the money goes? + +**Recommended: in the PSBT, as the output's `tap_bip32_derivation` under the +descendant's account fingerprint, with no new nostr tag.** That is the field a +change output already carries, read with the same code, and it is where +[the guardian spend chose to put its claim](./group-wallet-guardians.md) +for the same reason: a second place to say it would be a second thing to +disagree. An old client's `check` sees a derivation whose fingerprint is not its +account's, treats the output as a plain payment, and shows the address, which is +the right thing for an old client to do. + +### D4. What does a signer do with the claim? + +**Recommended: one rule for each of three cases.** + +| the output's claim | the signer's device | result | +|---|---|---| +| a fingerprint of a guarded wallet it holds, at an index that derives to this output's script | shows *Fund X's guarded wallet* | signed as usual | +| a fingerprint of a guarded wallet it holds, at an index that does **not** derive to the script | refuses the proposal before it is shown | the same refusal step 5 gives a change claim that does not derive | +| a fingerprint it does not recognise (no forwarded statement on this device, or a wallet it never verified) | ignores the claim and shows the bare address | as today | + +The second row is what makes the label safe: no proposer can put a friendly +name on a payment to an address the descendant does not own. The third row +means a member who never got the forwarded statement still sees the truth, +just less of it. + +### D5. A rollout gate? + +**Recommended: none.** A funding spend is a send from the group's own wallet to +an address, and it is already held to `GroupWalletRollout.MAINNET_CAP`. A +mixed-version group loses nothing: old signers see a payment to an address, +which is exactly what it is. + +### D6. What can be funded, and from what? + +**Recommended: only guarded wallets of groups below this one that this room +holds a verified statement for, and only from the room's own wallet.** + +- Unguarded subgroups: no. Their statements are never forwarded upward, so the + ancestor has no xpub to derive an address from. *What is left* covers this. +- Siblings, ancestors, unrelated groups: no. There is no statement for them in + this room, and *Send* with a pasted address works. +- From a guarded wallet into another guarded wallet (a guardian moving coins + between two descendants): no. `GroupSendRoute` already uses + `guardedChatRoomId` to mean the *source*. A route naming both a source and a + destination is refused (Phase 4). Rebalancing is its own decision. + +### D7. Does the child learn who paid it? + +**Recommended: not in this plan.** The child sees a coin arrive at an address it +did not hand out, on its address list as *Paid · 50,000 sats*. Saying *from the +parent* means sending a notice down the hierarchy, which no flow does today. +Only a member who sits in both rooms could carry it, and the child could verify +only that the transaction pays its own address, not who funded it. *What is +left* has the shape of it. + +--- + +## Phase 1 — choosing the address, pure + +**Half a day, most of it tests.** + +In `wallet/GroupOnchainWallet.kt`, beside `receiveAddresses`: + +```kotlin +/** + * The receive address an ancestor pays when it funds this wallet: the lowest + * unused index from [GroupOnchainWallet.ADDRESSES_AHEAD] past the current one + * that [reserved] does not already hold, and that the wallet still watches -- + * or null before Electrum has answered, and when every such index is held. + * See `docs/guarded-wallet-funding.md`, D2. + */ +fun fundingAddress(reserved: Set): GroupAddress? +``` + +It reads the same `current` as `receiveAddresses`, so the two never disagree, +and it skips any index that is already `alreadyUsed` (the gap rule from the +address note: a watch-only wallet may have been paid above `current`). + +In `wallet/GroupSpend.kt`, beside `claimedChangeIndices`: + +```kotlin +/** The receive indices under [account] that [psbt]'s outputs claim to fund. Claims, not checks, as for change. */ +fun claimedFundingIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set +``` + +**Tests**, in `GroupOnchainWalletJvmTest` against `FakeElectrum`: + +- a fresh wallet funds `/0/2`; +- with `/0/2` reserved it funds `/0/3`; with `/0/2 … /0/9` reserved it returns null; +- paying `/0/0` moves the funding address to `/0/3`; +- a payment to `/0/4` while `/0/0` is current is skipped: `/0/2`, then `/0/3`, then `/0/5`; +- the address is null until Electrum has answered, as `receiveAddress` is; +- every index returned is one `receive.addresses` has generated. This fails if + the bound and the look-ahead ever drift apart. + +--- + +## Phase 2 — the builder writes the claim + +**Half a day.** + +`GroupSpendBuilder.send` and `sendAll` take a destination rather than an +address string: + +```kotlin +sealed interface Destination { + /** What the member typed: whatever it is, it is not the group's to vouch for. */ + data class Address(val address: String) : Destination + /** A descendant's guarded wallet, at the receive address Phase 1 chose. */ + data class Funding(val account: GroupWalletDerivation.Account, val derived: GroupWalletDerivation.Derived) : Destination +} +``` + +`Funding` pays `derived.pubkeyScript`, the guarded address with its tree. There +is no string round trip, so `NotAnAddress` cannot happen for it. +`GroupSpend.psbtOf` gains a `funding: Map>` beside +`change`, and writes each one with `pathOf(derived, descendantAccount)`. This +is the same call change uses, with the descendant's fingerprint instead of the +room's. `Built` gains `funded: Funding?` so the preview can say where it goes. + +**Tests**, in `commonTest` beside the builder's existing ones: + +- a funding output's derivation survives `Psbt.write` / `Psbt.read` with its + fingerprint intact, for a fingerprint whose top bit is set. This is the + unsigned-read bug the guardians note fixed, checked again on a new field; +- `GroupSpend.check` against the room's own account accepts the PSBT and lists + the funding output among `payments`, not as change; +- a `send` to a typed address builds exactly the PSBT it built before. + +--- + +## Phase 3 — every signer checks the claim, and says it + +**A day and a half.** This is the phase that makes the label safe, so it lands +before any button that produces one. + +**The check.** A pure function in `GroupSpend`, separate from `check` so that +`check` stays about the room's own account: + +```kotlin +data class Funding(val outputIndex: Int, val wallet: GuardianManager.GuardedWallet, val derived: GroupWalletDerivation.Derived) + +sealed interface FundingReading { + data class Ok(val fundings: List) : FundingReading + data class Refused(val reason: String) : FundingReading +} + +/** D4's three rows, over [checked]'s payments, against the guarded wallets this room holds. */ +fun fundingsOf(checked: Checked, guarded: List): FundingReading +``` + +Fingerprints are four bytes, so two held wallets can share one. Every wallet +with a matching fingerprint is tried, and the claim is refused only if none of +them derives to the script. + +**Where it runs:** + +- `FrostSigningManager.acceptSpendProposal`, straight after `GroupSpend.check`. + A `Refused` drops the proposal with the reason logged, as a failed `check` + does. Guardian spends (`spender is Guardian`) are checked too, since a + guardian could pay one descendant from another's coins once D6 is revisited. +- `FrostSigningManager.checkedSpend`, so the approval screen and the proposal + list read the same answer. `Checked` gains `fundings: List = + emptyList()`, filled here rather than in `check`. +- `FrostSigningManager.reservedFundingIndices(database, chatRoomId, account)`, + over `openSpends` like `reservedChangeIndices`, with a + `FrostSigningRepository` method for the form. + +**What it says.** `ProposedSpend.summarize` reads `spend.fundings`: + +| spend | label | detail | +|---|---|---| +| one payment, a funding | *Fund Thandi's group's guarded wallet* | *Send 50,000 sats to Thandi's group's guarded wallet, address 5* | +| several payments, one a funding | *Spend from the group's wallet* | *Send 70,000 sats to 2 addresses, 50,000 of them to Thandi's group's guarded wallet* | +| no funding | unchanged | unchanged | + +That one function feeds the signing screen, the room's proposal list +(`ProposalListViewModel`) and the wallet screen's *Spends* rows +(`SpendRowCard`), so all three change together. A name is the descendant's +certified name, `GuardedWallet.name`, falling back to *a subgroup* as the +guardian spend's label does. + +**Tests**, a jvmTest in the shape of `GuardianSpendRoundTest`, with a parent +and child ceremony and the child's statement forwarded: + +- a true claim is accepted and summarised as *Fund … guarded wallet*; +- a claim at the wrong index is refused at `acceptSpendProposal`, and no session + is written; +- the same PSBT read by a member whose device holds no forwarded statement is + accepted and shown as a bare address; +- an open funding's index is reserved, and a failed one's is released. + +--- + +## Phase 4 — the form in fund mode + +**A day.** + +**The route.** `GroupSendRoute` gains `fundChatRoomId: String? = null`: the +descendant whose guarded wallet this send pays. It is a second field, not a +second meaning for `guardedChatRoomId`, which names where coins come *from*. A +route with both set is `GroupSendUIState.Unavailable` (D6). + +**The view model.** `GroupSendViewModel.initiate` finds the guarded wallet the +same way it already does for a guardian spend +(`chatRepository.guardedWallets(chatRoomId)`, matched on room and chain). The +wallet being spent is still the room's own. `Ready` gains: + +```kotlin +/** The descendant's guarded wallet this send pays, with where it is up to -- or null for a send to a typed address. */ +val funding: FundingTarget? = null + +data class FundingTarget( + val wallet: GuardianManager.GuardedWallet, + val walletState: GroupWalletState?, + val reserved: Set, +) { + val address: GroupAddress? get() = walletState?.fundingAddress(reserved) +} +``` + +`follow` combines a third flow, `wallets.walletFor(guarded.account).state`, +with the two it already has, and re-reads `reservedFundingIndices` whenever +the room's transactions change. If somebody pays the chosen address while the +form is open, the next emission moves the destination to the next index, and +the preview follows. That is why the card shows the index: a member who sees it +change knows why. `preview()` builds with `Destination.Funding` when `funding` +is set, and returns null while its address is null. + +**The screen** (`GroupSendScreen`): + +- the title becomes *Fund %1$s's guarded wallet*, beside the existing guardian + title, for the same reason that one is there: the title is where the form says + whose money moves where; +- `OutlinedTextField(addressField)` is replaced by the destination card from + D1: an `OutlinedCard` with *To* in `labelMedium`, the wallet's name in + `titleMedium`, the address in the monospace style with + `TextOverflow.MiddleEllipsis` and *address %1$d*, and under it, in + `bodyMedium`/`onSurfaceVariant`, *This group can spend these coins again once + they have %1$d confirmations.* with `ANCESTOR_DELAY`. That sentence answers + the request's last question: what is worth saying while funding a guarded + wallet is that the money stays within the group's reach; +- while the address is null, a `LoadingDataIndicator(fillScreen = false)` with + *Finding an address in %1$s's wallet…* in the card's place, and a null address + once Electrum has answered (D2's eight slots all held) shows *Wait for this + group's open payments to %1$s to confirm* in `error`; +- `SendPreview` says *Sends %1$s sats to %2$s's guarded wallet with a fee of + %3$s sats* for a funding; +- the propose button is unchanged and calls `proposeSpend`, because this is the + room's own spend. + +**Tests**, in `GroupSendViewModelJvmTest`, with `follow` and the fake chain: + +- the preview builds to `/0/2` of the descendant's account, with the claim; +- an open funding at `/0/2` makes the next one go to `/0/3`; +- paying `/0/2` while the form is open moves it to `/0/3`; +- both `guardedChatRoomId` and `fundChatRoomId` set gives `Unavailable`. + +--- + +## Phase 5 — *Fund* on the wallet screen, without crowding the row + +**A day.** + +**Where the button goes.** On each row of the *Guarded wallets* section +(`guardianItems` in `GroupWalletScreen.kt`), next to *Spend*, as the request +asks. Today the row is a `ListItem` with *Spend* as a `TextButton` in +`trailingContent`. A second button there would squeeze the headline (the +group's name, already ellipsised), and at large text sizes the two buttons +would leave the name a few characters. So the actions move out of the trailing +slot and below the content, in the row's own card: + +``` + today after +┌─────────────────────────────────────┐ ┌─────────────────────────────────────┐ +│ ▣ Thandi's group's… [ Spend ] │ │ ▣ Thandi's group's savings │ +│ 12,000 sats within this group's… │ │ 12,000 sats within this group's │ +└─────────────────────────────────────┘ │ reach · 50,000 sats arriving │ + │ [ Fund ] [ Spend ]│ + └─────────────────────────────────────┘ +``` + +- **An `OutlinedCard` per guarded wallet**, holding the existing `ListItem` + (with no `trailingContent`) and then the actions. A card is how M3 groups + content with the actions that apply to it. With several wallets listed, a bare + row of buttons under each `ListItem` would leave it unclear which wallet a + button belongs to. +- **The actions in a `FlowRow`**, aligned to the end with + `Arrangement.spacedBy(MaterialTheme.spacing.targetGap, Alignment.End)`, so at + 200% text the two buttons wrap onto two lines instead of truncating. This is + `SpendRowCard`'s *Send again* / *Bump the fee* row, with wrapping added. + `FlowRow` is new to this codebase. It is in `foundation.layout`, and the audit + counts it as neither spacing nor a dimension. +- **Both `TextButton`s**, equal weight: neither is the obvious primary action + for every wallet, and a filled *Fund* would read as a recommendation. *Fund* + first and *Spend* second, so money in reads before money out. +- **Each button names its wallet to a screen reader.** Two rows of *Fund* / + *Spend* are four identical labels when read without the layout. Each gets + `Modifier.semantics { contentDescription = … }` with *Fund %1$s's guarded + wallet* / *Spend from %1$s's guarded wallet*. The second string already + exists. This fixes the *Spend* button as it is today too. +- **Each button has its own gate**, so a row can show either one alone. *Fund* + appears only in the `Loaded` state (the room has a wallet of its own to pay + from), behind `canSign && canWatch`, the same gates as the room's *Send*. + The `NotOpened` branch passes `onFund = null`, because a group with no wallet + has nothing to fund with. *Spend* keeps the gates it has. +- **What is arriving.** After a funding, `withinReach` stays the same for two + hours, which looks like the money vanished. `GuardedWalletRow` gains + `arriving: Satoshi?`: coins in the wallet with fewer than `ANCESTOR_DELAY` + confirmations. The supporting line adds *· %1$s sats arriving* when it is + non-zero. It counts every such coin, not only this group's funding. That is + true, and it is all the ancestor can know. + +`toGuardianFund` sits beside `toGuardianSpend` in `GroupWalletScreen` and +navigates to `GroupSendRoute(…, fundChatRoomId = row.wallet.descendantChatRoomId)`. + +**Strings**, sentence case, in the guardian block of `strings.xml`: `fund`, +`fund_s_s_guarded_wallet`, `to`, `address_d`, +`this_group_can_spend_these_coins_again_once_they_have_d_confirmations`, +`finding_an_address_in_s_s_wallet`, `wait_for_this_group_s_open_payments_to_s_to_confirm`, +`sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats`, `s_sats_arriving`. +Apostrophes are written plain, as `spend_from_s_s_guarded_wallet` is, because +Compose Resources does not unescape `\'`. + +**Tests**: a `GroupWalletViewModelJvmTest` case that `arriving` counts an +unconfirmed coin and drops it at 12 confirmations. The layout is checked by +`m3Audit`, which has to stay at 0 on every budget, and by looking at it at +compact width and at 200% text. + +--- + +## Phase 6 — the notes + +**An hour.** + +- This note becomes **Built**, with a table of where the build chose + differently. +- A row in [README.md](./README.md), and a sentence in its reading order after + the guardians and policy notes. +- [group-wallet-guardians.md](./group-wallet-guardians.md)'s *What this does not + do* says guardians cannot constrain where coins go. It gains a line pointing + here for the direction that is supported: coins coming in. +- [group-wallet-addresses.md](./group-wallet-addresses.md)'s *Why `+ 2`* gains a + sentence: an ancestor funding the wallet starts at the top of that window + and goes up. + +Each phase is one commit, checked with +`./gradlew :composeApp:m3Audit` and +`./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest`. Before +Phase 6's status line says built, a funding should be made by hand on signet +between two real devices, one in each room, and the child's address list +checked to show it at `current + 2`. + +--- + +## What this does not do + +**It does not fund an unguarded subgroup.** The parent has no xpub for it. The +child could forward its plain statement upward the way a guarded one is, but +that gives the parent a full view of a wallet whose point is that the parent +has no part in it, so it is a decision of its own. + +**It does not fund a subgroup that has not opened a wallet.** There is no +statement and so no address. The guarded row only exists once one is forwarded. + +**It does not tell the child who paid.** See D7. + +**It does not stop the child spending the coins at once.** Funding is a gift +into a wallet whose own quorum holds the key path. The 12-block delay is on the +ancestor's leaf, not the child's key. The destination card says what the +ancestor keeps (a way back after 12 confirmations), and it says nothing that +suggests the coins are locked for the child. + +**It does not make the address private from the child's members.** It is one of +the child's own addresses. They see the payment and its amount, and anyone in +both rooms can match it to the parent's spend. + +--- + +## What is left, when someone wants it + +- **A notice to the child.** A member in both rooms, on seeing a funding of this + room confirm, posts a transcript line in the child's room: *Parent group sent + 50,000 sats to this wallet*. The child's devices check that the transaction + pays one of their addresses, and attribute it to the member who posted it, + since the child cannot check that the parent sent it. This is the reverse of + the upward forwarding, and it needs the same overlap one level at a time. +- **Funding an unguarded child**, behind the decision in *What this does not do*. +- **Moving coins between two guarded descendants** in one guardian spend: a + source and a destination on one route, D6's third bullet. +- **A guarded wallet's own screen**, reached by tapping its card, with its + coins, its address list and both actions. The card's two buttons are enough + for now. A third action would be the time to build it. + +--- + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| pre-fill the address field and leave it editable | the label would be a claim the form cannot keep; *Send* is already there for any other address (D1) | +| fund `current` | it is the address the child's own members are handing out (D2) | +| a nostr tag `["funds", , ]` on the proposal | the PSBT already has a field for *this output is under that account*, read by code that exists; a second place would be a second thing to disagree (D3) | +| recognise a funding by scanning every payment against the descendant's addresses, with no claim | it costs a derivation per address per output per signer, it misses an address past the window, and it would quietly label a typed address that happens to be the child's. The claim states what the proposer meant, and the signer checks it | +| refuse a claim the signer cannot verify | it would make a funding unsignable by every member who missed the forwarded statement, for no safety gain: the bare address is the truth (D4) | +| *Fund* in an overflow menu on the row | it hides the one action this plan adds, behind an icon whose meaning nobody can guess; there are only two actions | +| *Fund* in the trailing slot beside *Spend* | the name, the only thing that says which wallet a row is, shrinks to a few characters at large text sizes | +| *Fund* as a filled button | neither action is the one every member wants; a filled button would be a recommendation the app cannot make | diff --git a/docs/guardian-delay.md b/docs/guardian-delay.md new file mode 100644 index 00000000..1fe22f82 --- /dev/null +++ b/docs/guardian-delay.md @@ -0,0 +1,650 @@ +# The parent sets the delay: how long a coin waits before a guardian can take it + +Today every leaf in a guarded wallet is ` OP_CHECKSIGVERIFY 12 +OP_CHECKSEQUENCEVERIFY`: any ancestor can take a coin once it has 12 +confirmations, about two hours. Twelve is one constant, +`GuardianDerivation.ANCESTOR_DELAY`, the same for every ancestor at every +distance. This plan lets a group choose that number for its own leaf when it +makes a guarded subgroup. The floor is **6 blocks**. The ceiling is **65,535 +blocks**, the largest relative lock BIP68 can express in blocks. Everywhere the +app shows a delay, it also shows roughly how long that is in minutes, hours, +days, months or years, whichever reads best. + +The headline: **the parent chooses its own leaf's delay on the subgroup picker, +next to the choice of a guarded wallet. The choice rides the ceremony proposal, +the parent's quorum signs it into the birth certificate as the delay on the +parent's guardian tag, and the child's quorum signs it again. An inherited +ancestor's leaf keeps the delay that ancestor chose, so each group's terms +follow its key down the tree.** + +Read [group-wallet-guardians.md](./group-wallet-guardians.md) and +[subgroup-wallet-policy.md](./subgroup-wallet-policy.md) first. This builds on +the guardian tag from the first and the wallet-policy plumbing from the second, +and it changes one section of the first: [*Why 12, and why for +everybody*](./group-wallet-guardians.md#the-leaf). + +**Built**, phases 1-8, one commit each, in the order the plan asked for — +Phase 7 before Phase 5 — written against the code as it stood at `60cb3fa7`, +schema v29; the build is schema v31. `GuardianDerivation.DELAY_RANGE`, +`grant(..., delay)`, `BlockDuration` and `delayText` are the entry points. The +phases below are kept as written, line references included, which have since +moved; where the build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 2: one jvmTest | two. The script edges are in `GuardianSpendRoundTest` (commonTest), beside the 12-block test they generalise; the builder and the check are in `GuardianSigningJvmTest`, where the funded-state fixture is | +| Phase 3: `BlockDuration` in `wallet/` | in `text/`, beside `Sats.kt`, with `groupedBlocks()`. `delayText` and `approximateDuration` are in `ui/composable/widgets/DelayText.kt`. `BlockDuration.describe` says the same in fixed English for `ProposedEvent`, which is not a composable | +| Phase 4: a migration test | none, as for the policy's v29: the nullable auto-migrations have none, and every jvmTest's in-memory database runs at v30 | +| Phase 5: `setGuardianDelay` stores what was typed | two calls: `setGuardianDelay(blocks)` for a preset and `setGuardianDelayInput(text)` for the field, which drops anything but digits and stops at seven, enough to say *at most 65,535* about a number past it. The presets are `SelectSubgroupAdminsViewModel.DELAY_PRESETS`, as `FilterChip`s in a `FlowRow`. A retry comes back on its preset when it was one, and in the field when it was not | +| Phase 5: tests of `confirm` | not written, as for the policy: `confirm` needs an `Identity` with a private key and settled key packages | +| Phase 6: the summary's own-leaf line | a separate element, *this group after 144 blocks, about 1 day*, after the existing reach line | +| Phase 7: the guarded section's title says the shortest delay | not built. Each guardian is listed nearest first with its own delay, named by the room this device holds for it — `GroupWalletUIState.guardianNames` — and otherwise *a group above this one* | +| Phase 7: `withinReach` reads `wallet.account.guardians[position].delay` | `GuardianManager.GuardedWallet.delay`, the same thing named once | +| Phase 4: schema 29 → 30 | **30 → 31.** The default branch took 30 for the member-wallet tables (`docs/member-guarded-wallets.md`) while this was being built, so `DkgSession.guardianDelay` is v31 | +| nothing about member wallets or funding | both landed on the default branch meanwhile, quoting 12. On merging: `GuardedWalletRow.arriving` counts by this group's own leaf like `withinReach`; the funding form says that leaf's delay; a member wallet's screens and its proposal summary say each guardian's delay, through `MemberWalletManager.delaysOf` -- the group's own leaf at the default, every group above at the delay it chose. A group could not then choose the delay on its own leaf in a member's wallet; since [member-wallet-delay.md](./member-wallet-delay.md) it does, in a policy it signs, and a group that signs none does not guard members' wallets at all | + +Still to do by hand: the three-emulator run in Phase 8. + +--- + +## What is already per leaf, and what is not + +Less of this is new than it sounds. The guardians work wrote the delay into +every tag precisely so that a later delay would be "a later account's tags, not +a new format", and most of the code already reads it from there: + +| piece | today | +|---|---| +| `GuardianTag` | `["guardian", , , , ]`. `parse` already accepts 1 to 65,535 | +| `GuardianDerivation.Guardian.delay` | a field, defaulting to `ANCESTOR_DELAY` | +| `GuardianDerivation.leafScript` | already writes 1 to 16 as `OP_1`…`OP_16` and anything above as a minimal number push, and refuses anything outside 1 to 65,535 | +| `grantedTo` | `copy(...)` of the guardian, so an inherited key already keeps its delay one step down | +| `descriptorTree` | `older(${guardian.delay})` | +| `GroupSpend.check` | reads the spender's own leaf's delay and requires every input's sequence to equal it | +| `GroupSpendBuilder.lockOf` | per leaf: offers a guardian only coins at least that deep, and puts that sequence on every input | +| fee sizing, `GroupSpend.kt:390` | built from the real leaf script, so a longer number push is already counted | +| `GuardianManager.takenIn` | rebuilds each leaf from its own delay | + +What still assumes 12: + +| piece | where | +|---|---| +| `grant()` | the parent's own new entry takes the default, `ANCESTOR_DELAY` | +| `refuseCertificate` | compares the proposal to `grant()`, so any own delay other than 12 is refused | +| `GuardedWalletRow.withinReach` | `confirmations >= ANCESTOR_DELAY` (`GroupWalletUIState.kt:89`) | +| every string that quotes a delay | the picker (`SelectSubgroupAdminsScreen.kt:395`), the join gate (`DkgJoinApprovalScreen.kt:78`), the wallet screen (`GroupWalletScreen.kt:386`, `:408`, `:461`, `:672`), and six strings in `strings.xml` that say `%1$d confirmations` as if there were one number | +| the guardians note | *Why 12, and why for everybody* | + +So the work is three things: let the parent choose, carry the choice to +everybody who signs it, and stop every screen from saying "12". + +--- + +## The limits + +### The floor: 6 blocks + +About an hour. It keeps the property the guardians note gives as the reason for +a delay at all: **the child's own spends always go first.** A guardian cannot +race the child for a payment that has only just arrived, nor take the change +from a spend the child made a few minutes ago. Below about six blocks, one block +found quickly or a short reorg can put a fresh coin within a guardian's reach +before the child has had a chance to act on it. + +### The ceiling: 65,535 blocks + +BIP68 gives a relative lock 16 bits of `nSequence`. With the type flag (bit 22) +clear, the value counts blocks: 1 to 65,535, which is about 455 days, or a +little over 15 months. That is the most the protocol can express **for a lock +that counts from the coin's own confirmation**, which is the kind the guardian +leaf has to be. + +Two other locks look longer and are not the same thing: + +- **BIP68 in time units** (bit 22 set) counts 512-second steps, also 16 bits. + Its ceiling is 65,535 × 512 s, about 388 days, so it is *shorter* than the + block form. It also measures median time past rather than blocks. Not used. +- **An absolute lock** (`OP_CHECKLOCKTIMEVERIFY`) can name any height or date, + but it counts from a fixed point rather than from the coin. A leaf with one + would become spendable by the guardian for every coin at once, on one day, + however recently each arrived. That is a different promise, and it is listed + under [what this does not do](#what-this-does-not-do). + +Staying at or below 65,535 also keeps two other things true without extra +checks: + +- **bit 22 is never set**, so the number is always read as blocks; +- **the sequence stays far below `GroupSpend.MAX_SEQUENCE`** (`0xfffffffd`), so + a guardian spend still signals replaceability and *Bump the fee* still works. + +### The encoding, at its edges + +Script numbers are little-endian, sign-and-magnitude, minimally encoded. +`Script.encodeNumber` in bitcoin-kmp already does this, including the zero byte +a positive number needs when its top byte has the high bit set. The cases a test +has to pin, because each is where the encoding changes length: + +| delay | `` in the leaf | leaf script | +|---|---|---| +| 6 | `OP_6` | 36 bytes | +| 16 | `OP_16` | 36 bytes | +| 17 | `0x01 0x11` | 37 bytes | +| 127 | `0x01 0x7f` | 37 bytes | +| 128 | `0x02 0x80 0x00` | 38 bytes | +| 32,767 | `0x02 0xff 0x7f` | 38 bytes | +| 32,768 | `0x03 0x00 0x80 0x00` | 39 bytes | +| 65,535 | `0x03 0xff 0xff 0x00` | 39 bytes | + +A guardian input therefore costs at most three weight units more than it does +today. That is under one vbyte, and it is paid only when a guardian spends. + +--- + +## What a longer delay changes, said plainly + +The guardians note is candid that two hours is not autonomy: "two hours is not +long enough for a child to notice a coin coming within reach and move it." +That stops being true as the delay grows, and the picker has to say so. + +**The clock is per coin, and spending resets it.** A coin moved by the child is +a new coin, confirmed afresh. So a child that spends, or merely moves, each coin +before it is `d` blocks old keeps every coin out of every guardian's reach for +as long as it keeps doing that. With `d = 12` that would mean a transaction +every two hours, which is not practical. With `d = 4,320`, about a month, it +means one consolidation a month, which is cheap. + +So the choice is a real trade, and the picker's description says both halves: + +| delay | the guardian is | the child is | +|---|---|---| +| short (hours) | an override: in practice it can take any coin the child has not just received | under the guardian's control | +| long (months) | a backstop: it reaches coins the child has left alone for that long, such as a dormant wallet or a group that has stopped meeting | able to keep its coins out of reach by moving them before the lock runs out | + +A long delay is the right choice for a parent that wants a recovery path for a +subgroup that falls silent, and the wrong one for a parent that wants to be able +to take funds back from a subgroup that is still active. + +--- + +## Phase 0 — decisions, before any code + +Six, each with a recommendation except D1, which is decided. The phases below +assume the recommended answer. + +### D1. Whose delay does the parent choose? + +**Decided: its own leaf's only. An inherited key keeps the delay its ancestor +chose.** + +With root → middle `M` → grandchild `C`: + +``` +cert(M), signed by root: [ root/i(M) delay d₁ ] root chose d₁ +cert(C), signed by M: [ M/i(C) delay d₂, M chooses d₂ + root/i(M)/i(C) delay d₁ ] passed down unchanged +``` + +`grantedTo` already copies the delay, so this is what the code does today, with +every `d` equal to 12. It keeps each delay the decision of the group whose leaf +it is: the root decided how long a coin in `M`'s subtree waits for the root, and +`M` cannot shorten or lengthen that. Under the wallet-policy plan's D4 a guarded +group can only make guarded subgroups, so the root's terms reach every guarded +descendant of `M` unchanged. + +The alternative is one delay per certificate, chosen by the parent, applying to +every leaf. It is simpler to show, since a wallet then has one number. But it +lets `M` rewrite the root's terms in `C`'s wallet. A short `d₂` would bring the +root's reach closer than the root chose for `M`, and a long `d₂` would push it +further away. Neither was the root's decision. Rejected. + +### D2. The range + +**Recommended: 6 to 65,535, as `GuardianDerivation.MIN_DELAY` and `MAX_DELAY`, +enforced by the parser as well as the picker.** `GuardianTag.parse` and +`leafScript` move from `1..0xFFFF` to `MIN_DELAY..MAX_DELAY`. Every guardian tag +in existence says 12, so tightening the parser breaks nothing that was ever +written. A tag under 6 from a modified client then fails to read, and the +existing rule handles it: the certificate's guardian list reads as null, so the +wallet-policy read is null and `GroupKeyStateManager.parentageOf` drops the key +state. + +### D3. The default + +**Recommended: 12, unchanged.** It is what every existing guarded wallet uses, +and the guardians note gives the reasons for it. `ANCESTOR_DELAY` is renamed +`DEFAULT_DELAY`, because it is no longer the delay, only the one offered first. + +### D4. How the picker asks + +**Recommended: presets plus a custom number of blocks.** + +| preset | blocks | shown as | +|---|---|---| +| 1 hour | 6 | about 1 hour | +| 2 hours (default) | 12 | about 2 hours | +| 1 day | 144 | about 1 day | +| 1 week | 1,008 | about 7 days | +| 1 month | 4,320 | about 1 month | +| 6 months | 26,280 | about 6 months | +| longest | 65,535 | about 15 months | +| custom | 6–65,535 | the field's supporting text, live | + +A slider over 6 to 65,535 is unusable at the short end, where most choices are, +and a logarithmic one shows the user numbers they did not pick. Presets cover +what people mean. The custom field is for the exact number, and says what it +works out to while it is being typed. + +### D5. How a delay is said in time + +**Recommended: "about", the largest unit that makes the number at least 2, and +exactly one of a unit when the delay is within 5% of it.** The rule, at 10 +minutes per block, with a month of 30.44 days and a year of 365.25: + +1. If the delay is within ±5% of exactly one hour, day, month or year, use that + unit, singular: *about 1 day*. +2. Otherwise use the largest of years, months, days, hours and minutes in which + the delay comes to at least 2, rounded to the nearest whole: *about 36 hours*, + *about 3 months*. + +Worked through: + +| blocks | exact | shown | +|---|---|---| +| 6 | 60 min | about 1 hour | +| 12 | 2 h | about 2 hours | +| 100 | 16.7 h | about 17 hours | +| 144 | 1 day | about 1 day | +| 216 | 1.5 days | about 36 hours | +| 1,008 | 7 days | about 7 days | +| 4,320 | 30 days | about 1 month | +| 13,140 | 91 days | about 3 months | +| 26,280 | 182.5 days | about 6 months | +| 52,560 | 365 days | about 1 year | +| 65,535 | 455 days | about 15 months | + +Years appear only near exactly one year, because the ceiling is 1.25 years, and +"about 15 months" says more than "about 1 year". Weeks are left out: the units +asked for were minutes, hours, days, months and years. Adding weeks later is one +more row in the rule, for example "about 2 weeks" instead of "about 14 days". + +**Always beside the block count, never instead of it.** Blocks are what the +script enforces. Ten minutes is the average, not a promise, so a delay of 144 +blocks can take 20 hours or 30. The text reads *144 blocks, about 1 day*. + +**Regtest shows blocks only.** Its blocks arrive when somebody mines them, so a +time estimate there would be wrong. Signet and the testnets use the same +10-minute target as mainnet and get the estimate. The picker always uses +mainnet's estimate, because a certificate is not for any one network. + +### D6. Fixed at birth + +**Recommended: yes, like the wallet policy.** The delay is part of the guardian +tag, the guardian tag is part of the certificate the child's key state carries, +and the guardians note's rule 2 fixes an account's guardian set, delays +included, at its first statement. Changing a delay means a new subgroup. + +--- + +## Phase 1 — the range, and the parent's own delay, pure + +In `GuardianDerivation`: + +```kotlin +const val MIN_DELAY: Long = 6L +/** BIP68's block-based relative lock is the low 16 bits of nSequence. */ +const val MAX_DELAY: Long = 0xFFFFL +const val DEFAULT_DELAY: Long = 12L // was ANCESTOR_DELAY +val DELAY_RANGE: LongRange = MIN_DELAY..MAX_DELAY + +fun grant( + thresholdPublicKey: HexKey, + ownChatRoomId: String, + inherited: List, + childChatRoomId: String, + delay: Long = DEFAULT_DELAY, // the parent's own leaf, D1 +): List +``` + +- `grant` requires `delay in DELAY_RANGE` and puts it on the first entry only. + The inherited entries go through `grantedTo`, unchanged, and keep theirs. +- `leafScript` requires `DELAY_RANGE` instead of `1..0xFFFF`. +- `GuardianTag.parse` reads only delays in `DELAY_RANGE` (D2). +- `Guardian.delay` keeps its default, renamed to `DEFAULT_DELAY`, so no caller + that builds a guardian by hand changes. +- The class comment and the KDoc on the old constant are rewritten. "One value + for every ancestor at every distance" stops being true. + +**Tests**, `GuardianDerivationTest`: +- the encoding table above, byte for byte, through `Script.write(leafScript(...))`; +- `grant(..., delay = 4_320)` puts 4,320 on the parent's entry and leaves an + inherited entry at the delay it arrived with; +- `descriptorTree` writes `older(65535)` and passes bitcoin-kmp's descriptor + checksum; +- 5 and 65,536 are refused by `grant`, `leafScript` and `GuardianTag.parse`. + +One commit. Nothing chooses a delay yet. + +--- + +## Phase 2 — the script enforces it, at every edge + +A jvmTest in the shape of `GuardianSpendRoundTest`. For each delay in `[6, 16, +17, 127, 128, 32_767, 32_768, 65_535]`, a parent quorum's shares sign a +script-path spend of a child's coin. Then: + +- `Transaction.correctlySpends` accepts the spend at `nSequence = delay` and + refuses it at `delay - 1`; +- `GroupSpend.check` refuses an input whose sequence is not the leaf's delay; +- `GroupSpendBuilder.spendable` offers a coin with `delay - 1` confirmations to + nobody but the owner, and offers it to the guardian at `delay`. + +This is the phase that would catch an encoding mistake before a coin could. A +leaf whose lock is pushed non-minimally is a coin nobody can spend through that +leaf. + +--- + +## Phase 3 — saying a delay in time + +New, pure, in `wallet/`: + +```kotlin +object BlockDuration { + const val MINUTES_PER_BLOCK = 10 + + enum class Unit { MINUTES, HOURS, DAYS, MONTHS, YEARS } + data class Approximate(val count: Int, val unit: Unit) + + /** D5's rule. */ + fun approximate(blocks: Long): Approximate +} +``` + +And one composable beside the other text helpers: + +```kotlin +@Composable +fun delayText(blocks: Long, chain: Chain?): String // "144 blocks, about 1 day"; regtest: "144 blocks" +``` + +The units are **plurals**, the catalogue's first: `` and the rest, with `one` and `other`, read through +`pluralStringResource`. A plain `%1$d hours` string reads *about 1 hours*, and +the sentence-case audit cannot catch that. `StringCatalogueJvmTest` gains a +case asserting that plurals resolve on the JVM, as CLAUDE.md asks. + +**Tests**, `BlockDurationTest`: every row of D5's table, both edges of each ±5% +window (for example 137 and 151 blocks for *one day*), and the full range from 6 +to 65,535 never returning a count of 0 or a unit above years. + +--- + +## Phase 4 — the ceremony carries the delay + +The same path the wallet policy took in the policy plan's Phase 2, one field +further: + +- `DkgRitualEvents`: a `["guardian_delay", ""]` tag on a subgroup's + ceremony proposal, written only beside `["wallet", "guarded"]`; +- `ChillDkgRitualManager.proposeRitual(guardianDelay: Long?)`. It requires null + unless the policy is `GUARDED`, and a delay in `DELAY_RANGE` when it is set, + checked before the running-ceremony lookup as the policy is; +- `acceptProposal` files it, and drops a proposal whose delay does not read, + falls outside the range, or comes without a guarded policy; +- **Schema 29 → 30**: the nullable `DkgSession.guardianDelay`. Null for every + ceremony before this and for every unguarded one, an auto-migration like the + policy's. + +A guarded ceremony from a build that has the policy and not the delay carries no +delay. It is certified at `DEFAULT_DELAY`, which is what that build would have +written. + +**Tests**, in `SubgroupCeremonyInParentRoomTest`: the delay travels on the +proposal and nowhere else, and lands on every admin's session; a delay with an +unguarded policy, a delay of 5, and `"twelve"` are each dropped; a guarded +proposal with no delay files null. + +--- + +## Phase 5 — the picker, and the join gate + +### `SelectSubgroupAdminsScreen` + +Under the *Guarded wallet* row, shown only while it is selected, a *How long +before the groups above can spend a coin* section: + +- D4's presets as a row of `FilterChip`s, wrapping, the default selected; +- *Custom* opens an `OutlinedTextField` with a number keyboard. Its supporting + text is the live `delayText` while the value is in range, and the reason + (*at least 6 blocks*, *at most 65,535 blocks*) while it is not; +- under both, one line of D1's consequence for the parent's own leaf, and + [the trade above](#what-a-longer-delay-changes-said-plainly) in a sentence: + *A coin the subgroup moves starts waiting again, so a long delay lets it keep + its coins out of reach by moving them.* + +The description on the guarded row stops quoting one number. It lists the +parent's own delay, plus *and the N groups above it, on the terms they set* +when the parent's own certificate carries guardians. The picker reads those +terms from `ChatRepository.guardiansOf`, which it already calls. + +In `SelectSubgroupAdminsViewModel`: + +- `guardianDelay: MutableState`, starting at `DEFAULT_DELAY`; +- `setGuardianDelay` clamps nothing and stores what was typed, because the field + has to be able to show *at most 65,535* about the number the user actually + entered; +- `refusal()` refuses an out-of-range delay under a guarded policy, before the + key-package wait, as the policy refusals are; +- `prefillFromRetry` restores the delay from the failed ceremony; +- `confirm` passes it, and passes null for an unguarded subgroup. + +CLAUDE.md applies in full: chips and the field from `material3`, spacing from +`MaterialTheme.spacing`, strings and plurals in the catalogue in sentence case, +and the custom field with a real label and supporting text, not a placeholder. + +### `DkgJoinApprovalScreen` + +The guarded line gains the delay: *The subgroup's wallet will be guarded: this +group can spend a coin in it once it has 144 confirmations, about 1 day.* An +inherited ancestor's terms are not on this screen, because a member deciding +whether to join cannot check them. They are on the wallet screen, from the +verified certificate, in Phase 7. + +**Tests**, `SelectSubgroupAdminsViewModelJvmTest`: the default is 12; a preset +and a typed delay are what `refusal()` judges; 5 and 65,536 are refused with +their reasons; a retry restores the delay; an unguarded subgroup confirms with +no delay. + +--- + +## Phase 6 — the certificate carries it, and both quorums check it + +### Proposing + +`SubgroupManager.proposeBirthCertificate` reads `key.guardianDelay` off the +child's ceremony, as it reads the policy, and passes it to `grant`: + +| ceremony | certificate's own entry | +|---|---| +| guarded, delay `d` | `d` | +| guarded, no delay (older build) | `DEFAULT_DELAY` | +| unguarded | no guardian tags at all, as today | + +### Every parent signer + +`refuseCertificate` stops comparing the whole proposal to `grant()` with the +default. Instead: + +- the first entry's delay is in `DELAY_RANGE`, which reading the tag already + guarantees under D2; +- the proposal equals `grant(..., delay = proposed.first().delay)`. The key, the + chain code and the order are checked exactly as before. The **inherited** + entries' delays must be exactly the ones on the group's own certificate, + because `grant` copies them, so a proposer cannot shorten the root's wait in + the grandchild's wallet (D1). + +The existing test case *a shorter delay*, `copy(delay = 1)`, keeps refusing, +now because 1 is out of range. Two cases are added: +- an inherited entry with its delay changed is refused; +- an own delay of 4,320 is accepted. + +### What the parent's admins read + +`ProposedEvent`'s certificate summary says the delay on the parent's own leaf: +*this group can spend from its wallet once a coin has 144 confirmations, about +1 day*. `ProposedEvent` is not a composable, so it uses +`BlockDuration.approximate` with fixed English words, as the rest of that file +does. + +### Every child signer + +`SubgroupManager.refusePolicy`, behind `refuseKeyState`, also requires the +certificate's first guardian delay to equal the ceremony's announced +`guardianDelay`, when there is one. This is the same consent rule as the policy: +the admins were shown the number at the join gate, and joining was agreeing to +it. + +**Tests**, in `SubgroupManagerJvmTest`: each row of the proposing table; +`refuseCertificate`'s new cases; a key state whose certificate carries 12 under +a ceremony that announced 4,320 is refused by `refuseKeyState`. + +--- + +## Phase 7 — every screen says each leaf's own delay + +Once a wallet can hold leaves with different delays, no sentence with one +`%1$d` in it is true any more. + +**The child's wallet screen** (`GroupWalletScreen`, `OpenWalletAction` and the +guarded wallet's header). The sentence that quotes one number becomes a list +under it, nearest ancestor first, one row per guardian: + +``` +Guarded + #Council after 144 blocks, about 1 day + #Ekklesia after 4,320 blocks, about 1 month +``` + +The names come from the rooms the device has, falling back to *a group above +this one*. The shortest delay is the one that matters most to the child, so the +section title says it: *The groups above can spend a coin from 144 +confirmations, about 1 day*. + +**An ancestor's *Guarded wallets* list** (`:672`). `GuardedWalletRow.withinReach` +uses this group's own leaf's delay, `wallet.account.guardians[position].delay`, +instead of the constant. Each row's supporting line says that delay, because +two of a group's descendants can have made it different promises. + +**The detail screens.** The subgroup rows that say *Guarded wallet* since the +policy plan's Phase 8 become *Guarded wallet, 144 blocks, about 1 day*, read off +the certificate's first guardian. + +**The send screen**, for a guardian spending from a descendant. Its +"spendable" line already counts only coins past this leaf's lock, through +`GroupSpendBuilder.lockOf`. It gains the delay in words, so a guardian looking +at a balance of zero learns why. + +The six strings that say `%1$d confirmations` are replaced, not edited: each +takes the `delayText` as a `%1$s`, or is split into a title and the per-guardian +rows. + +**Tests**: `GroupWalletViewModelJvmTest` and a `GuardedWalletRow` test with two +guardians at 12 and 4,320, where a coin with 100 confirmations is within the +first's reach and not the second's. + +--- + +## Phase 8 — docs, and checking it on the emulators + +- [group-wallet-guardians.md](./group-wallet-guardians.md): *Why 12, and why for + everybody* becomes *Why a delay, and who sets it*. It keeps the reasoning for + a floor, adds the autonomy trade, and links here. The headline's `12` becomes + ``. +- [subgroup-wallet-policy.md](./subgroup-wallet-policy.md): the guarded row on + the picker gains the delay, one sentence. +- [README.md](./README.md): this note's row and a sentence on reading order. +- This note: *Built*, and the table of where the build chose differently. + +By hand, regtest, three emulators: + +1. The root makes a guarded subgroup `M` at 6 blocks, and `M` makes a guarded + subgroup `C` at 20 blocks. +2. `C`'s wallet screen lists `M` at 20 blocks and the root at 6. +3. With a coin in `C` mined 10 blocks deep, the root can spend it and `M` + cannot. At 20 blocks deep, both can. +4. A guardian spend from the root goes through at `nSequence = 6`, and a + hand-built one at 5 is rejected by the regtest node as non-final. + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +--- + +## Order and size + +| phase | touches | ships | +|---|---|---| +| 1 | `GuardianDerivation`, `GuardianTag` | dark: the default is still 12 everywhere | +| 2 | tests only | — | +| 3 | `BlockDuration`, the first plurals | dark: nothing shows it yet | +| 4 | DKG proposal tags, `DkgSession`, schema 30 | dark: nothing sets a delay | +| 5 | picker, join gate | **the switch** | +| 6 | certificate, both signers' checks | with 5 | +| 7 | wallet, detail and send screens | before 5 | +| 8 | docs, emulator run | last | + +**Phase 7 should land before Phase 5.** A build that can make a wallet with a +6-block leaf, while its own wallet screen says 12, would be telling a group the +wrong number about its own money. Phases 1-4 and 7 change nothing a user can +choose, so they can go out first. Phases 5 and 6 go together, because a picker +whose number the certificate did not carry would be a number that meant +nothing. + +**Mixed versions.** A parent signer on a build from before Phase 6 compares the +proposal to `grant()` with 12, so it **refuses** any other delay. That is the +safe failure: it never signs a delay it did not check. A group whose signers +are not all updated can still make subgroups at 12, but not at any other delay. +Readers on older builds already build each leaf from its own tag, so they derive +the right addresses and enforce the right sequence. They only show the wrong +number on screen. + +--- + +## What this does not do + +**It does not let the parent change a delay after birth** (D6). A different +delay is a different subgroup. + +**It does not let a middle group change an ancestor's delay** (D1). The root's +terms reach every guarded descendant as the root set them. + +**It does not give an ancestor two delays in one wallet.** One leaf per ancestor, +as before. "This group can take any coin after a week, and everything after a +year" would be two leaves per ancestor and a different tree. + +**It does not offer an absolute lock.** "On 1 January 2027, every coin in this +wallet becomes the root's" is a `OP_CHECKLOCKTIMEVERIFY` leaf. It is not a delay +counted from each coin, and it is a different promise about time, with a +different ceiling and different consequences for a child that keeps moving its +coins. + +**It does not make a long delay safe against an active child.** A child that +moves its coins before the lock runs out keeps them out of reach, and the +picker says so. Nothing on mainnet can force coins to stay put without a +covenant, which the guardians note has already said there is none to write. + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| one delay per certificate, for every leaf | lets a middle group rewrite its ancestors' terms (D1) | +| time-based BIP68 locks | a lower ceiling (about 388 days), coarser 512-second steps, and median time past rather than blocks, for no gain | +| a slider over 6 to 65,535 | unusable at the short end, where most choices are | +| a floor of 1 | lets a guardian race the child for a payment one block after it arrives, the thing a delay exists to prevent | +| showing time without blocks | blocks are what the script counts; ten minutes is an average | +| a time estimate on regtest | its blocks come when somebody mines one | diff --git a/docs/material-design-conformance.md b/docs/material-design-conformance.md index 2b0f3de5..695bfcf6 100644 --- a/docs/material-design-conformance.md +++ b/docs/material-design-conformance.md @@ -4,6 +4,10 @@ What the M3 foundations actually require, where this app's 43 screens stand against them today, and a phased order of work that makes each phase mechanical by the time it starts. +*Nine of those 43 -- the artifact, chapter, dialect and translation screens -- +have since been removed as unreachable ([ceremony-creation.md](./ceremony-creation.md)), +and one, `CreateSharedKeyScreen`, added. The counts below are as measured.* + The app already builds on Material 3 — `compose-material3:1.10.0-alpha05`, a generated `ColorScheme`, `Scaffold`/`TopAppBar`/`ListItem` throughout. What is missing is not the library. It is that **the design decisions live at the call @@ -882,7 +886,8 @@ navigation component counts drop *below* their floors. **Left for a person, and for a later commit.** Proposals → signing and artifacts → chapters are the two remaining list-detail -families the plan names. Chat was done first and alone, deliberately: it is the +families the plan names (artifacts → chapters has since been removed with the +documents). Chat was done first and alone, deliberately: it is the one the spec is most careful about, and it is the one whose eleven entry points made the shape of the answer clear. The other two are the same shape with different content. diff --git a/docs/member-chronicle.md b/docs/member-chronicle.md index 62c31493..c4484122 100644 --- a/docs/member-chronicle.md +++ b/docs/member-chronicle.md @@ -9,7 +9,17 @@ Read [shared-key-derivation.md](./shared-key-derivation.md) first. The property this whole design rests on -- that a room's id *is* the key it signs with -- is stated there, and everything cheap about what follows is downstream of it. -**Built**, phases 1-9, one commit each, with two exceptions named in Phase 7. The +**Built, and carrying nothing at the moment.** The document kinds it was built +for were removed with their screens ([ceremony-creation.md](./ceremony-creation.md), +Phase 7), and nothing else the group signs is safe or useful to replay. What a +chronicle may carry is now a `ChronicleKinds` value, `ChronicleEvent.KINDS`, and +it is empty: a device asks for no chronicle, sends none, and applies nothing from +a page an older build sends. The machinery below is kept and tested with a kind +set of the tests' own. Adding a kind back means editing `ChronicleEvent.KINDS` on +purpose, with the reason it is safe to replay. The row rebuild and translation +supersession described below went with the documents. + +Built, phases 1-9, one commit each, with two exceptions named in Phase 7. The phases are kept as written because they are the reasoning, and the code reads better against the argument it came from than against a summary of itself. Where the implementation chose differently the section says so, and it did so five diff --git a/docs/member-guarded-wallets.md b/docs/member-guarded-wallets.md new file mode 100644 index 00000000..d240a0d6 --- /dev/null +++ b/docs/member-guarded-wallets.md @@ -0,0 +1,996 @@ +# Member wallets: a guarded wallet a group keeps for one person + +Today a guarded wallet belongs to a group. A subgroup's quorum holds the key +path, and every ancestor holds a leaf that can take any coin 12 blocks after it +confirmed. This plan gives the same shape to **one member**. The key path is a +key only that member holds, and the leaves are the group's and the group's own +guardians', exactly as they would be for a guarded subgroup of that group. The +member spends alone, at any time, with one Schnorr signature. The group can step +in, and so can every group above it. + +**The member proposes it.** Their device generates a random private key, works +out every ancestor leaf, builds the descriptors, stores the key, and only then +puts a request into the group's room. The group's quorum checks all of it and +signs a **member wallet certificate**: the group's signature saying it guards +this key for this person. That certificate is what the member's device opens the +wallet on, what every guardian watches, and what is forwarded upward so the +groups above can find the coins. + +Read [subgroups.md](./subgroups.md), +[group-wallet-guardians.md](./group-wallet-guardians.md) and +[subgroup-wallet-policy.md](./subgroup-wallet-policy.md) first. This plan reuses +the guardian derivation from the second without changing it. It reuses the +grant, the leaf, the tree, the signing cache, the forwarding notice and the +guardian spend. What is new is who holds the key path, and the artefact the group +signs to agree to it. + +**Built**, phases 1-12, one commit each (Phase 9 in two), written against the +code as it stood at `8cb6f04e`, schema v29; the build is schema v30. +`MemberWalletDerivation`, `MemberWalletRequestEvent`, `MemberWalletCertificateEvent`, +`MemberWalletManager` and `GuardianManager.GuardedSubject` are the entry points, +and `GroupWalletRollout.MEMBER_WALLETS_ON_MAINNET` is the gate. The phases +below are kept as written; where the build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 2: the answer carries the signed `GroupKeyStateEvent`, whole | it carries the threshold key, its path and the group's certificate. A `GroupKeyState` row keeps what the state said and not the event, and nothing in the event is needed beyond what checks itself: the key at the path rederives the room, and the certificate certifies it and names that key | +| Phase 2: the first share-holder by npub answers at once, the rest after a minute | every device holding the verified state answers a request no answer names yet, as the chronicle's request is answered. Duplicates cost bandwidth and nothing else | +| Phase 3: the request is an inner event signed by the member | an inner event is an unsigned rumor, and the row it travels in keeps no `sig`. The signed request travels whole as the content of an inner event of the same kind -- `MemberWalletRequestEvent.carried` -- the way a 30333 notice carries a statement, and only from the member who signed it | +| Phase 5: `MemberWalletSpend` in a later bump | the same bump, v30, beside `MemberWallet` | +| Phase 6: the screens talk to `ChatRepository` | a `MemberWalletRepository` of their own, which holds the active identity: nothing above it touches a key | +| Phase 6: the gate arrives in Phase 12 | with Phase 6, where an entrance is first offered, as the guardians note's gate came with its Phase 5 | +| Phase 7: requests join `observeProposalsAwaitingYou` | *Put to the group* is on the request's row in the group page's *Members' guarded wallets* (Phase 11). The transcript says a request arrived; the proposal list still lists only sessions | +| Phase 7: the summary names the member | `ProposedEvent.summarize` takes a `nameOf`, and the callers that have no profiles to hand pass none, so the proposal list and signing screen say *Guard a member's wallet* without the name. The certificate's `p` tag is the member either way | +| Phase 8: the wipe callers warn first | `wipeDatabase` has no callers and `BennuDatabase.wipeData` deletes nothing. There is nothing to guard yet; a note on `wipeData` says what a caller must do once it does | +| Phase 9: `GroupTransactionWatcher` generalised | a member's spend has no session, so `MemberWalletViewModel` follows the member's spends while the wallet screen is open, sending again any Electrum has not heard of -- the economy the guardian-spend notice makes. *Bump the fee* is not built for a member's spend | +| Phase 10: `descendantChatRoomId` becomes `subject.id`, `statement` becomes `signedEvent` | both keep their names -- `descendantChatRoomId` is `subject.id`, and `statement` is the 30334 for a member -- so the guardian spend path did not change a line. `Spender.Guardian.name` is `@name` for a member | +| Phase 11: the person's page shows the amount within each group's reach | it does not watch the chain, so it shows the guarding group and *Spend*; the group's wallet screen has the amount. On one's own profile the section is not drawn: the profile's own list is the answer there | +| Phase 12: the three-emulator run lifts the gate | the gate was lifted by decision before the run; see below | +| D8: the member's own spend is capped until the gate lifts | capped on mainnet by `MAINNET_CAP` regardless, since the gate lifted without the run that was to justify lifting both | + +**The mainnet gate is open.** It was to lift on Phase 12's run -- a three-level +hierarchy on signet watching one member's wallet, the root making a guardian +spend from it -- and was lifted by decision before that run, as the guardians +note's gate was. The run is still worth making. Until it has been, a member's +own spend on mainnet is held to `GroupWalletRollout.MAINNET_CAP`, as every +group spend and every guardian spend is; `memberCapFor` is where that lifts. +The mixed-version risk below is unchanged: a group whose signers are not all on +a build from Phase 7 onward should not be asked to guard a member's wallet. + +Still to do by hand: Phase 12's run on signet. + +--- + +## Should it be a birth certificate? + +The question this plan has to settle first. The answer is in two parts. + +**It needs a group-signed artefact, yes.** An ancestor believes a guarded wallet +only on signatures it can check itself. For a subgroup those are the parent's +signature on the certificate and the child's on the statement. A member wallet +needs the group's signature for the same reason: without it, the groups above +have only the forwarder's word that the group agreed to guard this key. + +**It must not be a 30329.** A `SubgroupBirthCertificateEvent` says *this room is +my child*, and every reader of that kind assumes there is a room: + +| reader | what it would do with a member's wallet in a 30329 | +|---|---| +| `SubgroupBirthCertificateEvent.certifies`, check 4 | requires `marmotGroupId(subgroup_key, frost_path) == content`. A wallet key is not a room, so the certificate either never verifies, or its content is set to the id that key *would* make, and then it is a room to everything below | +| `SubgroupManager.subgroupsOf`, `DatabaseDkgRepository`'s observer | lists every 30329 as a subgroup. The member's wallet would show in the parent's *Subgroups* section as *certified, not yet created*, forever, on every build, old ones included | +| `ChatMessage.applyInnerEvent`'s 30329 arm | writes a "subgroup was born" line in the transcript | +| `ProposedEvent.summaryOf`'s 30329 arm | asks the signers to approve "a subgroup, for Alice" | +| `SubgroupManager.refuseCertificate` | applies D4 of the policy note: a guarded group may only make guarded *subgroups*. That rule is about rooms, and its `name` and `p` tags are a founding roster that a wallet does not have | +| `GroupWalletStatementEvent.Reading.guardiansCheckOut` | expects the certificate to certify the room whose key signed the statement | +| `DkgRitualViewModel`'s `firstCarrying(30329)` | resumes a subgroup ceremony from the certificate it finds | + +So the member wallet certificate is **its own kind, 30334**. It shares the +guardian tags, the grant function and the forwarding notice with the subgroup +path, and none of the lineage meaning. Nothing that reads 30329 ever sees it. + +**How it shows on the group's pages**, as the question guessed: + +- On `ChatRoomDetailScreen` it is **not** a subgroup row. It gets a section of its + own, *Members' guarded wallets*, under *Subgroups*. A row there is a person, and + tapping it opens that person's profile (`ProfilePreviewRoute`), the same place + a tap on a member row already goes. It does not open a chat room, because there + is none. +- In the *Guarded wallets* list on an ancestor's wallet screen, a subgroup's + wallet stays `#groupName`. A member's wallet is `@username`. +- On the member's own profile, each wallet is named for the group that guards + it: *Guarded by #Ekklesia*. + +--- + +## The shape + +``` +k random 32 bytes, generated on the member's device never leaves it +P_W = k·G the wallet key +W = taggedHash("bennu/member-wallet/id/v1", serP(P_W)) the wallet's id: 32 bytes, nobody's key + +account = GroupWalletDerivation.account(P_W, chain, 0, grant) unchanged, P_W in place of a threshold key +grant = GuardianDerivation.grant(K_G, G, guardians(G), W) unchanged, W in place of a child room id +``` + +An address of the member's wallet, beside a guarded subgroup's: + +``` + guarded subgroup C of G member wallet W under G +key path account(K_C)/change/index account(P_W)/change/index +leaf 1 R_G / i(C) / n/a/change/index R_G / i(W) / n/a/change/index +leaf 2… g / i(C) / … for g in guardians(G), nearest first -- the same list, one step further for W +``` + +So a member's wallet under `G` is guarded **exactly as a guarded subgroup of `G` +would be**: the same ancestors, the same 12-block lock, the same caterpillar, and +the same descriptor shape, which Bitcoin Core imports. Every ancestor signs for +its leaf with the `GuardianDerivation.signingCache` it already uses, walking the +line of descent down to `W` instead of down to a room. + +### Why `W` is a hash and not the key + +A room id here *is* a public key, and `GroupKeyStateEvent.isSignedByRoom` asks +whether that key signed something. If `W` were `xonly(P_W)`, the member could +sign events that read as *signed by room W*. A `W` that nobody holds a key for +cannot be mistaken for a room by anything that checks signatures. The tag keeps it +apart from every other hash in the app. It is 32 bytes, so `childIndex` takes it +as it stands. + +### Why a random key, and only one wallet per key + +The member asked for this, and the derivation gives a second reason. Every step +below `P_W` is an unhardened public tweak, and every guardian holds the account +xpub, with its chain code. So a guardian who learns the private key of **one** +address can recover `k`. That is ordinary BIP32, and it is the same rule the +wallet note states for a group's threshold key. It means `k` has to be a key that +is good for nothing else: + +- **not the nostr key.** A leak would hand over the member's identity. A signer + behind NIP-55 cannot apply taproot tweaks in any case. And a wallet key equal to + an npub would tie the chain to the relay graph; +- **not a key from the profile's seed.** An nsec or npub profile has no seed + ([nsec-sign-in.md](./nsec-sign-in.md)). This is the first wallet such a profile + could hold. + +One key gives one wallet, on one network, at account 0. A second wallet is a +second key. + +### The member's own spend + +Key path, one signature, nothing to coordinate: + +``` +d = k + I[0:32] the account step, as a private key +d' = CKDpriv(CKDpriv(d, change), index) unhardened, matching CKDpub on the other side +sig = signSchnorr(sighash, d', TaprootTweak.ScriptTweak(merkleRoot(tree))) +``` + +`k` itself signs exactly one thing: the proof of possession in the request, +under its own tagged hash (Phase 3). It is never an output key, because the +account step always tweaks it first. + +--- + +## Who agrees to what + +Three parties, and each one signs what it is agreeing to: + +1. **The member agrees to be guarded.** The request is an inner event signed with + their nostr key, so it is bound to their identity. It is also signed with `k`, + which proves they hold the wallet key. It names the group, the wallet key, the + guardians and the descriptors their own device worked out. Consent comes first + here, which is the reverse of a subgroup, because the member already exists and + holds their key before anyone grants anything. +2. **The group's quorum agrees to guard it.** Each signer's device recomputes + the grant from the group's own key and certificate, checks the request against + it byte for byte, and checks that the person asking is a member. The + certificate embeds the request whole, so anyone who reads the certificate can + see that the member asked. +3. **The ancestors are not asked**, in the same way they are not asked when a + guarded subgroup is born. Each inherited key is the group's own grant passed one + step further. The group's quorum already holds the power to pass it to a + subgroup, and nothing here gives the ancestors any power they did not already + have. + +### What "full control" means, and what the member gives up + +The member can spend every coin, at any time, alone. No script stops a key-path +spend. The group, and every group above it, can also take any coin that has sat +confirmed long enough, without asking and without warning. How long is each +guardian's own delay: the group's own leaf at the delay its member-wallet +policy sets, and every group above at the delay it chose for the group below it +-- see [member-wallet-delay.md](./member-wallet-delay.md) and +[guardian-delay.md](./guardian-delay.md). It was 12 blocks for every leaf when +this note was written. That is the +guardians note's *the child gives up a real thing*, said about one person. The +consent screen says it in these words before a key is made (Phase 6). + +The groups above see the wallet too. The certificate carries the member's npub +and the account xpub, so every member of every guarding group can see its whole +balance and know whose it is. That also goes on the consent screen. + +--- + +## The order, and why it is forced + +``` + 1. the member's device reads K_G and guardians(G); generates k; derives W, the grant, the account + and both descriptors; stores k nothing has left the device + 2. the member publishes the request into G's room the proposal + 3. any signer of G opens a FROST session over the certificate the request determines + 4. G's quorum signs it; every device in G files the certificate the wallet exists + 5. a member in G and P forwards it into P as a 30333 notice, and so on up the ancestors find it +``` + +Step 2 comes after step 1 because the member asked for it to. It also has to: the +request carries the leaves, and the leaves are a function of `W`, so of `k`. Step +3 needs a signer, because a FROST session can only be opened by a device holding a +share (`proposeSigningBatch` throws without a `signerIdOf`). Step 4 is when +addresses are first offered. A wallet that the guardians have not agreed to guard +should not be handed out to be paid. + +--- + +## Phase 0 — decisions, before any code + +### D1. A new kind, not a birth certificate + +**Decided by the table above.** The certificate is 30334 and the request is +30335, the next free numbers after the notice at 30333. Phase 2's key notice +takes 30336. + +### D2. Who puts the request to the group? + +**Recommended: any signer, by tapping *Put to the group*.** The member's request +appears on every share-holder's device beside the proposals already waiting for +them. The first to tap it opens the FROST session, and proposing counts as their +own approval, as it does for every session. If the member is a signer, their +device opens the session directly and needs no sponsor. + +The certificate is a pure function of the request, and its `created_at` is the +request's. So two signers who tap at the same moment open two sessions over **one +event id**, and `GroupSignedEvent` keeps one row. A sponsor cannot change +anything, because every other signer rebuilds the certificate from the request +and drops a proposal that differs by a byte. + +The alternative is to let the member coordinate the FROST session without +holding a share. It is a better fit to the words "the individual proposes", and +FROST allows a coordinator who is not a signer. But `FrostSigningManager.advance` +returns at its first line without a `secretShare`, `proposeSigningBatch` +requires a `signerIdOf`, and the session row's `signApprovedAt` assumes the +proposer signs. Changing all three means touching the one manager every signature +in the app goes through, to save one tap. That is rejected for now, and written +up under the appendix. + +### D3. Which members may ask? + +**Recommended: any member of the group whose profile can sign and can watch the +chain.** Not only admins. The group has to be a Marmot room with a threshold key, +and, since [member-wallet-delay.md](./member-wallet-delay.md), one that has +opened to its members' wallets: a group that has signed no member-wallet policy, +or whose newest one is closed, takes no request. +A read-only profile cannot sign the request. A profile with no Electrum client +(`GroupOnchainWallets` is null for it) could not see its own coins, so it is not +offered a wallet it cannot see. + +### D4. What the member's device has to know, and the member who joined late + +The grant needs `K_G` and the guardian keys in `G`'s own certificate. Today both +are read off `G`'s verified key state, and only ceremony participants hold one. A +member welcomed after the founding has neither. That is +[subgroups.md](./subgroups.md#what-this-does-not-do)'s gap, and it would leave +most ordinary members unable to ask. + +**Recommended: Phase 2, a key notice.** A member's device that holds no key state +for `G` posts a request for one. Any device that does hold one answers with the +signed `GroupKeyStateEvent`, whole, in a 30336. The asking device does **not** +file it as key state: the chronicle note's reason for keeping key states out of +the chronicle still holds. It reads `K_G` and the certificate out of the notice on +every use, after `GroupKeyStateManager.stateFrom`'s checks. This is safe for one +reason: `G` is `marmotGroupId(K_G)`, so no validly signed state, however old, can +name a different key. + +An answer is not needed when `G` has a guarded wallet: its statement carries +`G`'s certificate, and so `K_G` too. That is a fallback, not the route, because a +root group has neither. + +If D4 is deferred, Phases 1 and 3 to 12 still stand. The entrance is then hidden +for a member with no key state, and the screen says why. + +### D5. How many wallets, and what are they called? + +**Recommended: as many as the member likes, one key each, one network each, +account 0, with an optional label** (*Savings*). The label goes in the request, +and so into the certificate. The person's name does **not**. Rows show `@` plus +the member's live profile name (`Profile.humanReadableNameOrPubkey()`). The +certificate fixes the npub. A person renaming themselves is not drift in a +historical record, because there is no founding name to drift from. + +### D6. Where the key lives, and how it is backed up + +**Recommended: in the database, scoped to the profile, as `DkgSession.secretShare` +already is**: a `MemberWallet` row keyed by `W`, with the owner's npub. It is +**never** a foreign key to `ChatRoom`. Deleting the group's room on this device +must not delete a private key that coins may sit behind. That is the same +argument `parentChatRoomId` makes against a cascade, with money at the end of it. + +Backups: + +- the member wallet screen offers **Export key**, behind a confirmation, as a + `tr(xprv…/0/*,{…})` descriptor any wallet that imports taproot descriptors can + sweep from; +- **the group is the recovery path.** A member who loses the device loses `k`, + and their guardians can still take every coin after 12 blocks and pay it to the + member's new wallet. The screen says so, because it is the honest upside of being + guarded; +- `wipeDatabase()` ("end this", and signing out) has to warn when a member wallet + holds coins and its key is on this device only (Phase 8). + +### D7. Which guardians, and can the member leave some out? + +**Decided: exactly `SubgroupManager.grantFor(G, W)`**, the list a guarded subgroup +of `G` would get. A member cannot drop an ancestor or choose their own: signers +compare the whole list. Under a root group, or one whose certificate is +*unguarded*, that is `G` alone, by D2 of the policy note. Under a *guarded* `G` it +is `G` and every group above it. A member who wants no guardians has a plain +wallet already. That is the profile's own wallet, and it is outside this plan. + +### D8. Rollout + +**Recommended: `GroupWalletRollout.MEMBER_WALLETS_ON_MAINNET = false`**, lifted +after a signet run (Phase 12) in which a three-level hierarchy watches one +member's wallet and the root makes a guardian spend from it. The member's own +spends go through a single-signer path the app has never had. So until the gate +lifts, a member's own spend from this device on mainnet is held to `MAINNET_CAP`. +Guardian spends from a member wallet are already held to it. + +--- + +## Phase 1 — the derivation and the member's signature, pure + +New `managers/MemberWalletDerivation.kt`, beside `GuardianDerivation`: + +```kotlin +object MemberWalletDerivation { + /** `taggedHash("bennu/member-wallet/id/v1", serP(walletKey))`, hex. Frozen once a certificate carries one. */ + fun walletId(walletKey: PublicKey): String + + /** The account the member's key opens under [guardians]: `GroupWalletDerivation.account` over [walletKey]. */ + fun account(walletKey: PublicKey, chain: Chain, guardians: List): GroupWalletDerivation.Account + + /** The private key of the address at `change/index`: the account step, then CKDpriv twice. */ + fun privateKeyAt(walletPrivateKey: PrivateKey, chain: Chain, change: Long, index: Long): PrivateKey + + /** The signature an input of a checked spend needs: [privateKeyAt] under the address's script-path tweak. */ + fun sign(walletPrivateKey: PrivateKey, input: GroupSpend.SpentInput, account: GroupWalletDerivation.Account): ByteVector64 +} +``` + +`GroupWalletDerivation.account` already takes any public key. The only change +there is its parameter's name and kdoc. It says *threshold key*, and from now on +it is "the key the key path belongs to". + +**Tests**, commonTest: + +- `privateKeyAt(k)`'s public key is `derive(account, change, index).internalKey` + at ten indices on both branches; +- a signature from `sign` verifies against the address's output key, and + `correctlySpends` accepts a key-path spend of a guarded address built by + `GroupSpendBuilder`; +- `GuardianDerivation.grant(K_G, G, inherited, W)` reaches the keys a guardian's + `signingCache` reaches for `lineage = [… , W]`, so an ancestor can sign every + leaf of a member wallet; +- `walletId` vectors, and a check that `W` is not `xonly(P_W)`; +- the descriptor passes bitcoin-kmp's checksum and matches + `GroupWalletDerivation.Account.receiveDescriptor`. + +Nothing calls it yet. + +--- + +## Phase 2 — every member can know the group's key (D4) + +New `nostr/wallet/GroupKeyNoticeEvent.kt`, kind **30336**, in two shapes: + +``` +asking: kind 30336, content "", ["h", G] +answering: kind 30336, content , ["h", G], ["e", ] +``` + +- `MemberWalletManager.groupKeyFor(database, G)` returns `K_G` and the + certificate, read off this device's verified key state, then off `G`'s guarded + wallet statement, then off the newest answer in `G`'s room that passes + `stateFrom`. It is never written into `GroupKeyState`. +- **Answering.** A device that holds a verified state answers an asking notice + that has no answer yet. To keep a room of signers from all answering at once, + only the share-holder whose npub sorts first among those the device knows about + answers straight away. The rest answer if nothing has arrived after a minute. + Duplicates are harmless. +- `ChatMessage.applyInnerEvent` gets a 30336 arm that writes **no** line. It is + plumbing, and without the arm an older build would show a raw-JSON bubble, which + is reason enough to ship it early. + +**Tests**: an answer carrying a state for another room is ignored; an answer +whose certificate does not read is ignored; an old state for the same room still +gives the right `K_G`; nothing is filed into `GroupKeyState`. + +--- + +## Phase 3 — the request, pure + +New `nostr/wallet/MemberWalletRequestEvent.kt`, kind **30335**, an inner event +in `G`'s MLS room and signed by the member's nostr key. It never goes to a relay, +for the reason the statement never does: it carries an xpub. + +``` +kind: 30335 +pubkey: +content: +tags: + ["h", G] the group asked; a request is not replayable into another room + ["wallet", W] + ["wallet_key", ] + ["chain", "mainnet" | "signet" | …] GroupWalletStatementEvent.chainName + ["guardian", , , , "12"] one per guardian, nearest first -- GuardianTag reused + ["descriptor", tr(…,{…}), "receive"] + ["descriptor", tr(…,{…}), "change"] + ["label", "Savings"] optional + ["member_wallet_policy", ] since member-wallet-delay.md: what the request was built under + ["possession", ] +``` + +The possession signature is over +`taggedHash("bennu/member-wallet/possession/v1", xonly(npub) ‖ G ‖ serP(P_W) ‖ chainHash)`. +That message includes everything that has to bind the key to one person in one +group on one network. Without it, Bob could ask for a certificate on Alice's +wallet key under his own name, and every list above would show her coins as +`@bob`'s. + +`read(event): Reading?` and `Reading.verified(): MemberWalletDerivation.Account?` +check: + +1. the nostr signature, and that the event is 30335; +2. `W == walletId(P_W)`; +3. the possession signature under `P_W`; +4. the first guardian is `G` itself, so a request cannot leave out the group it + asks; +5. `account(P_W, chain, guardians)` rederives the xpub and both descriptors byte + for byte. + +This is everything a reader can check without `G`'s key. The grant is Phase 7's, +because only a device that holds `K_G` can check it. + +**Tests**: a request round-trips; each of the five checks fails on its own +mutation; a request with no label reads; two `wallet` tags do not read. + +--- + +## Phase 4 — the certificate, pure + +New `nostr/wallet/MemberWalletCertificateEvent.kt`, kind **30334**, signed by +`G`'s room through FROST: + +``` +kind: 30334 +pubkey: G set by the signing session +created_at: the request's created_at so every sponsor proposes one event id +content: W +tags: + ["d", W] addressable: newest per wallet wins, all of them identical + ["p", ] + ["wallet_key", ] + ["chain", …] + ["guardian", …] as in the request + ["descriptor", …, "receive"] + ["descriptor", …, "change"] + ["label", …] if the request had one + ["request", ] +``` + +- `template(request: Event): EventTemplate`. The **only** way a certificate is + built. A sponsor passes the request and nothing else. +- `verify(certificate, groupChatRoomId): Verified?`, standalone and with no + database: + 1. 30334, and `isSignedByRoom(certificate, G)`; + 2. the embedded request passes Phase 3's `verified()`, and its `h` is `G`; + 3. the certificate is exactly `template(request)` with `G` as author. One + comparison covers every tag, so no tag can say one thing in the request and + another in the certificate; + 4. the `p` tag is the request's author. + + `Verified` carries the npub, `W`, the label and the account. It is what the + member's device, every guardian and every forwarded notice open the wallet on. + +The request is embedded rather than looked up, as the certificate is embedded in a +guarded statement. That makes the certificate self-contained for an ancestor who +was never in `G`'s room, and it means *the member asked* is checked from the +group's signature rather than taken on trust. + +**Tests**: a certificate verifies; one signed by another room, one whose request +is from another group, one whose `p` is not the request's author, and one with a +guardian swapped relative to its request each fail. +`SubgroupBirthCertificateEvent.certifies` is false for a 30334, and +`SubgroupManager.subgroupsOf` ignores one stored in the parent. That last test +exists to fail the day somebody reads both kinds in one query. + +--- + +## Phase 5 — schema 29 → 30 + +One new table. Room auto-migrates a new table, so the entry joins the list in +`BennuDatabase`. + +```kotlin +@Entity(indices = [Index("ownerPublicKey"), Index("guardingChatRoomId")]) +data class MemberWallet( + @PrimaryKey val walletId: String, // W + val ownerPublicKey: HexKey, // the profile it belongs to: one database holds every profile + val guardingChatRoomId: String, // G -- a plain column, never a foreign key (D6) + val chain: String, + val walletPrivateKey: HexKey, // k + val label: String?, + val requestJson: String, // the signed 30335, kept so a declined request can be asked again + val createdAt: Instant, +) +``` + +No *certified* column. A wallet is certified when `G`'s `GroupSignedEvent` rows +hold a 30334 for `W` that passes `verify`. That is read again each time, as +`GroupWallet` reads statements. A column would be a second copy that could +disagree with the signature. + +`MemberWalletDao`: `getByOwner`, `observeByOwner`, `getById`, `upsert`, and a +`delete` the manager calls only for a wallet that was never certified (Phase 8). + +Spends get a second table, `MemberWalletSpend`, in Phase 9, where they are first +needed. + +--- + +## Phase 6 — the member asks + +New `managers/MemberWalletManager.kt`: + +```kotlin +object MemberWalletManager { + /** Steps 1 and 2: makes the key, works out the leaves, stores the key, and only then publishes the request. */ + suspend fun request(database: BennuDatabase, groupRoom: LocalChatRoom, identity: Identity, chain: Chain, label: String?): MemberWallet + + /** Every wallet [ownerPublicKey] holds a key for here, or that a group this device is in has certified for them. */ + suspend fun walletsOf(database: BennuDatabase, ownerPublicKey: HexKey): List +} +``` + +`request` checks the request it built with Phase 3's `verified()`, and checks the +grant against `groupKeyFor`, **before** it publishes. A request this device would +refuse should never be shown to a quorum. It stores the row before it publishes, +so a crash between the two leaves a key and no request rather than a request and +no key. + +### The entrances + +- **The member's own profile** (`ActiveProfileScreen`): a *Guarded wallets* + section (Phase 8) with *New guarded wallet*, which opens a picker of the groups + this profile is in that have a key. +- **The group's detail screen**: *Ask this group to guard a wallet for you*, in + the new *Members' guarded wallets* section (Phase 11). It opens the same screen + with the group already chosen. + +Both lead to `NewMemberWalletScreen` (route `NewMemberWalletRoute(activeUserPublicKey, chatRoomId?)`, +with a `NavigateBackButton`). It is a consent screen first and a form second: + +| line | says | +|---|---| +| headline | *A wallet only you can spend from, guarded by #Ekklesia* | +| who can step in | *#Ekklesia and the N groups above it can take any coin that has been confirmed for 12 blocks, without asking you* | +| who can see it | *Members of those groups will see this wallet's balance, and that it is yours* | +| recovery | *If you lose this device, those groups can still move your coins for you* | +| label | an optional text field | +| action | *Ask #Ekklesia* | + +`N` is `grant.size - 1`. Strings go in `strings.xml`, in sentence case, with +`%1$s` and `%2$d`. CLAUDE.md applies in full. + +### Refusals, at the screen and again in `request` + +| refused | because | +|---|---| +| a read-only profile | it cannot sign the request (`LocalCanSign`) | +| no Electrum client for the profile | it could not see its own coins (D3) | +| the group has no key, or is not a Marmot room | there is nobody to sign the certificate, and no room to carry it | +| `groupKeyFor` is null | the grant cannot be worked out. Offer *Ask the group for its key* (Phase 2) | +| `grantFor` is null | `G`'s certificate carries guardian keys this build cannot read. Today that surfaces at the end of a ceremony, and here it is refused up front | +| `MEMBER_WALLETS_ON_MAINNET` is shut and the chain is mainnet | D8 | + +**Tests**, jvmTest: `request` stores before it publishes; the published request +passes `verified()` and its guardians equal `grantFor`; each refusal above holds; +a member with no key state succeeds once an answer from Phase 2 is in the room. + +--- + +## Phase 7 — the group signs, and every signer checks + +### Every signer refuses a certificate the group did not agree to + +`FrostSigningManager.acceptProposal` gets a third check beside the certificate +and statement checks it already has (`:569`, `:591`). It is +`MemberWalletManager.refuseCertificate(database, chatRoomId, thresholdPublicKey, rebuilt)`, +for every rebuilt 30334, and it runs before anything is shown: + +- `MemberWalletCertificateEvent.verify` fails → *is not a certificate this group + could have been asked for*; +- the request's `h` is not this room → *was asked of another group*; +- the request's author is not a participant of this room (a `Participant` row + with `deletedAt == null`) → *was asked by somebody who is not a member*; +- the guardians are not `SubgroupManager.grantFor(chatRoomId, thresholdPublicKey, W)` + → *grants guardian keys this group does not*. This is `refuseCertificate`'s key + check with `W` in place of the subgroup's room id, and it reuses the same + function. + +The group's policy, read off its own certificate, decides only *which* keys the +grant carries (D7). It never refuses a member wallet. Even an unguarded group +can guard its members. + +### Sponsoring + +- `MemberWalletManager.putToGroup(database, groupRoom, userPublicKey, request)` + is `FrostSigningManager.proposeSigning(kind = 30334, template(request))`. It + returns the open session instead when one already carries that event id. +- `ChatMessageListViewModel.observeProposalsAwaitingYou` also lists requests that + have no certificate and no open session, on share-holders' devices. Each gets a + *Put to the group* action, which counts as the sponsor's approval, and the + dialog says so. + +### What the group reads + +- `ProposedEvent.summaryOf` gets a 30334 arm: *Guard a wallet for @alice + (Savings). This group and the N above it will be able to take its coins once + they are 12 blocks old. Only @alice can spend from it before then.* +- `ChatMessage.applyInnerEvent` arms: + - 30335 writes *@alice asked this group to guard a wallet for her*, and nothing + else happens. It is a request, not a decision; + - 30334, when it comes through `applySignedEvent`, writes *This group now + guards a wallet for @alice*. + + Without these arms, both kinds fall to `else ->` and show raw JSON. That is the + failure mode [member-chronicle.md](./member-chronicle.md) names, and it is + avoidable here. + +**Tests**, jvmTest, in the shape of `SubgroupManagerJvmTest`: a certificate whose +guardians omit an ancestor, swap one or reorder them is refused; a request from a +removed member is refused; a request replayed from another group is refused; two +sponsors produce one `GroupSignedEvent`; an unguarded group's certificate carries +only its own key and is accepted. + +--- + +## Phase 8 — the member's wallet + +### Opening + +`MemberWalletManager.walletsOf` joins two sources: + +1. `MemberWallet` rows for this profile, the wallets whose key is on this device; +2. 30334s in the signed events of every room this device is in whose `p` is this + profile's npub, which includes wallets this profile made on **another device**. + +Each source gives a `MemberWalletRow`: + +| state | when | the profile row's supporting line | +|---|---|---| +| `Asked` | a key and request here, no session, no certificate | *Waiting for someone in #Ekklesia to put it to the group* | +| `Signing` | an open session over the certificate | *#Ekklesia is signing* | +| `NotSigned` | the session failed or was declined, and there is no certificate | *#Ekklesia did not sign. Ask again, or discard* | +| `Open` | a certificate, and the key is here | the balance | +| `WatchOnly` | a certificate, and the key is not here | the balance, *key on another device* | + +*Ask again* republishes the stored request, unchanged. *Discard* deletes the row, +and is offered only before a certificate exists. No address has been offered by +then, so no coin can be behind the key. + +### The profile section + +`ActiveProfileScreen` gets *Guarded wallets* between the profile's own rows and +*Switch profile*. There is one `ListItem` per `MemberWalletRow`, with the headline +*#Ekklesia*, or *#Ekklesia · Savings*, and the supporting line from the table. A +`ListItem` is clickable, so it gets `minimumInteractiveComponentSize()`. *New +guarded wallet* sits under the list. An empty list shows `EmptyState` with its own +message, *You have no guarded wallets*. + +The list is never published. A kind 0 is public, and the xpub must never leave an +encryption. + +### `MemberWalletScreen` + +Route `MemberWalletRoute(activeUserPublicKey, walletId)`, a pushed screen with a +`NavigateBackButton`. It reuses `GroupWalletScreen`'s composables wherever they +are already separate: `BalanceCard`, `CoinRow`, and the address list as +`GroupWalletAddressesScreen` draws it (current address plus two, so a guardian's +watch never falls behind the addresses handed out). It adds: + +- *Guarded by #Ekklesia and N more*, with the 12-block line; +- **guardian spends**: `GuardianManager.takenIn` over the wallet's history, + rendered *#Ekklesia took 50,000 sats in …*. They are read off the chain on each + pass, as a subgroup's are, and stored nowhere; +- *Send* (Phase 9), and for an `Open` wallet *Export key* (D6); +- the four states, wrapped in `ScreenStateTransition`. + +### Losing the key by accident + +`wipeDatabase()`'s callers ("end this" on `CreateProfileScreen`, and the sign-out +dialogs) check for an `Open` member wallet with a balance whose key exists only +here. If there is one, they say so and offer *Export key* before going on. + +**Tests**, `MemberWalletViewModelJvmTest`: each row of the state table; a +certificate for this npub with no key here reads `WatchOnly`; *Discard* is not +offered once a certificate exists. + +--- + +## Phase 9 — the member spends + +- `MemberWalletSpendViewModel` builds with `GroupSpendBuilder`, checks with + `GroupSpend.check(psbt, account, Spender.Owner)`, which is unchanged, signs each + `SpentInput` with `MemberWalletDerivation.sign`, witnesses with + `Checked.witnessed`, and asserts `correctlySpends` before it broadcasts. +- The form is `GroupSendScreen`'s. If its fields are not already a separate + composable, extracting them is this phase's first commit, so the member's form + cannot drift from the group's (the decimal-point bug in + [group-send-an-amount.md](./group-send-an-amount.md) is the reason). +- `MemberWalletSpend` table (schema 30 → 31, or folded into Phase 5's bump if + both land in one release): `txid` PK, `walletId`, `psbt`, `signedTransaction`, + `broadcastAt`, `seenAt`, `confirmedAt`, `replacedByTxid`. It is the subset of + `GroupTransaction` a spend with no session needs. `GroupTransaction` cannot hold + it, because its foreign keys are to a session and a room. +- `GroupTransactionWatcher`'s follow and conflict logic, generalised over the + row's type, or copied once with a comment pointing at the original if the + generic version reads worse. *Bump the fee* signs a replacement locally. +- Change goes to the wallet's own change branch, reserved as + `reservedChangeIndices` does for a group. +- `capFor(chain)` applies while D8's gate is shut. + +**Tests**: a spend of two coins and change passes `correctlySpends`; a spend to +a foreign change output is refused by `check`, as it is for a group; a bump +replaces and settles. + +--- + +## Phase 10 — the guardians see `@alice` + +> Since [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md) a member's +> wallet reaches the groups above with nobody tapping *Share*: the group's devices +> that are also in a group above tell it as the certificate is filed. + +The guardian side is built. What changes is what a guarded wallet can be. + +[member-wallet-guarding-group.md](./member-wallet-guarding-group.md) later +gathered these rows by person and named, on each, the group that directly +guards the wallet. + +### `GuardianManager.GuardedWallet` learns its subject + +```kotlin +sealed interface GuardedSubject { + /** The id the line of descent ends in: a room id, or a member wallet's W. */ + val id: String + data class Subgroup(override val id: String, val name: String?) : GuardedSubject + data class Member(override val id: String, val ownerPublicKey: HexKey, val label: String?) : GuardedSubject +} +``` + +`descendantChatRoomId` becomes `subject.id`. `statement` becomes `signedEvent`, +which is the 30331 for a subgroup and the 30334 for a member. `certificate` stays +the subgroup's alone. `spender()`, `position` and `lineage` do not change, because +`GuardianDerivation.lineage(guardians, W, ancestor)` already works for any +32-byte id. + +### Reading + +- `verify` dispatches on kind: 30331 takes today's path, and 30334 takes + `MemberWalletCertificateEvent.verify` plus the same ancestor walk (rule 4 of + `verify`'s kdoc). +- `guardedWalletsOf(G)` reads `G`'s **own** 30334 `GroupSignedEvent`s beside the + 30333 notices it was forwarded. The direct guardian holds the certificate it + signed, so it needs no notice to learn of it. +- `shareableFrom(G)` includes `G`'s member certificates, so a member of `G` who + sits in `P` sees them under *Tell the groups above*, and one tap forwards them. + The 30333 notice carries a 30334 as its content. An older build's `verify` + returns null for that kind, so it shows no line and lists nothing. +- `describeNotice` gets *Shared @alice's guarded wallet with this group*. + +### Spending + +`proposeGuardianSpend` and its `["guarded", ]` tag already take an id, and +`guardedWalletFor` looks it up. With `W` in that slot, nothing in `GroupSpend`'s +guardian arm changes. `GroupTransaction.guardedChatRoomId` holds `W` for a member +wallet. The column keeps its name, because a rename is a migration for a word, and +its kdoc says *the room or member wallet*. + +### Showing it + +`GroupWalletScreen.guardianItems` gives the headline by subject: + +```kotlin +when (val subject = row.wallet.subject) { + is GuardedSubject.Subgroup -> subject.name ?: stringResource(Res.string.a_subgroup) // "#Translation" + is GuardedSubject.Member -> stringResource(Res.string.at_s, profileName(subject.ownerPublicKey)) // "@alice" +} +``` + +The profile name comes from `ProfileDao`, falling back to a shortened npub. +`GuardedWalletRow` carries the profile, so the composable does no lookups. A +member wallet with a label shows it in the supporting line, before the *within +reach* amount. + +**Tests**, `GuardianSigningJvmTest`-shaped: a parent's shares sign a leaf of a +member wallet, and `correctlySpends` accepts it at sequence 12 and refuses it at +11; a root two levels up does the same through a forwarded notice; a notice +carrying a 30334 whose guardian entry for this group is not the key its walk +reaches is ignored; `guardedWalletsOf` returns both kinds, sorted by display name. + +--- + +## Phase 11 — the group's page and the person's page + +### `ChatRoomDetailScreen` + +There is a new section, **Members' guarded wallets**, under *Subgroups*. Its rows +are `MemberWalletRow`s read from the room's 30334s: + +- leading: the member's avatar; +- headline: `@alice`, and `@alice · Savings` when there is a label; +- supporting: *Asked by @alice, not yet signed* for a request with no certificate, + and otherwise nothing more. The balance belongs to the wallet screen; +- tap: `ProfilePreviewRoute(activeUserPublicKey, ownerPublicKey)`, as member + rows already do (`:575`). + +Below the rows, for a member who may ask (D3), is *Ask this group to guard a +wallet for you*. An empty section with the button hidden is not shown at all. + +### `ProfilePreviewScreen` + +There is a new section, **Wallets your groups guard**, listing every guarded +wallet this device knows of whose subject is that npub. These come from each +group's own certificates and from forwarded notices, so a root sees a +grandchild's member. (Since [member-wallet-guarding-group.md](./member-wallet-guarding-group.md), +D7, there is one entry per wallet: *Guarded by* names the group that signed its +certificate, and each group here holding a leaf has a line of its own beneath.) +Each row reads *Guarded by #Ekklesia*, with the amount within +this group's reach, and *Spend* for a share-holder, which opens +`GroupSendRoute(chatRoomId = , guardedChatRoomId = W)`, the +guardian spend that exists today. When the profile shown is the active one, the +section is the Phase 8 list instead. + +This is where the question's "navigate to the individual user profile instead of +the group chat" ends up. A subgroup is somewhere you go into. A person is someone +you look at. + +**Tests**: the detail screen's state lists a certified wallet and a pending +request separately from the subgroups; the preview's state lists wallets from two +guardian rooms for one npub. + +--- + +## Phase 12 — the gate, docs, and the emulators + +- `GroupWalletRollout.MEMBER_WALLETS_ON_MAINNET` and `offersMemberWalletsOn(chain)`, + with the condition that lifts them (D8). They gate the entrances in Phase 6 and + Phase 11's button only. A device with the gate shut still accepts, shows and + signs a certificate somebody else asked for. A gate decides what this device + offers, never what a quorum may decide. +- [group-wallet-guardians.md](./group-wallet-guardians.md): *What this does not + do* gets a pointer here. *How an ancestor finds the coins* says the forwarded + thing may be a member certificate. +- [subgroups.md](./subgroups.md): one line under the certificate's tag table + saying a member wallet is not a subgroup and has its own kind. +- [README.md](./README.md): the row, and a sentence on reading order. +- This note: *Built*, and a table of where the build chose differently. + +By hand, signet, three emulators, a root `R`, its guarded subgroup `M`, and Alice +in `M` but not in `R`: + +1. Alice, holding no key state for `M`, asks for `M`'s key. An `M` signer's device + answers it, and her *New guarded wallet* opens. +2. The consent screen names `#M` and one group above it. She asks, and `M`'s + transcript says so. +3. An `M` signer taps *Put to the group*, and a second approves. Alice's profile + row goes from *waiting* to *signing* to a balance of 0. +4. `M`'s detail screen lists `@alice` under *Members' guarded wallets*, and the + row opens her profile. +5. Pay her receive address. A member in both `M` and `R` taps *Share*. `R`'s + wallet screen lists `@alice` beside `#M`. +6. Alice spends part of it alone. `correctlySpends` holds, and her change is + watched by `M` and `R`. +7. After 12 blocks, `R` takes the rest through its leaf. Alice's wallet screen + says *#R took …*. +8. Alice's second phone, on the same profile, lists the wallet as *key on another + device*. +9. A request edited to drop `R`'s key, sent from a debug build, is dropped by + every `M` signer, and the reason is in the log. + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +--- + +## Order and size + +| phase | touches | ships | +|---|---|---| +| 1 | `MemberWalletDerivation` and its tests | dark | +| 2 | key notice, its dispatch arm | dark, but useful on its own | +| 3 | the request, pure | dark | +| 4 | the certificate, pure | dark | +| 5 | schema 30 | dark | +| 7 | signer checks, sponsoring, transcript arms | **before 6**: binding on every device that did not draw the screen | +| 6 | the member asks | **the switch** | +| 8 | the member's wallet and profile section | with 6 | +| 9 | the member spends | with 6. A wallet that can receive and not send is a trap | +| 10 | guardians list and spend from it | with 6 | +| 11 | detail and profile pages | any time after 7 | +| 12 | gate, docs, emulator run | last | + +Phases 1 to 5 and 7 can land before anyone can ask for anything, and 7 should. +It is what makes every signer check the grant and every older-build bubble go +away, so it wants to be on every member's phone before the first request exists. +That is the policy note's reasoning about its own Phase 7, applied again. + +**The mixed-version risk, placed once more.** A signer on a build before Phase 7 +sees *Event of kind 30334* with nothing checked, and could sign a certificate with +a guardian missing. That does not cost the member coins, because they still hold +the key path. But it can drop a group above from a wallet it is meant to guard. +The remedy is the familiar one: everybody in a group that guards members should be +on a build from Phase 7 onward before the gate opens. + +--- + +## What this does not do + +**It does not make the guard cryptographic beyond the leaf.** The member's key is +the member's, and they can move every coin to a plain wallet at any time. What +the group gets is the right to take coins that have sat for 12 blocks, which is +the same thing a guarded subgroup's ancestors get, and nothing more. + +**It does not guard a wallet that already exists.** The profile's own wallet, +and any wallet made elsewhere, stay as they are. Being guarded means a new key. + +**It does not end when the member leaves the group.** The leaf is in every +address. A member who leaves keeps a wallet the group can still take from, and the +way out is to spend everything to a new wallet. The profile row says *You are no +longer in #Ekklesia* when that is so. + +**It does not let the group revoke.** There is nothing to revoke. The +certificate is a signature that exists forever, and the group can only stop +watching. + +**It does not reach a member who cannot watch the chain** (D3), and it does not +reach a read-only profile at all. + +**It does not survive a re-keyed group**, for the reason the guardians note +gives. The leaf is bound to `K_G`. + +**It does not spend from several member wallets at once.** Each wallet is one +key, and a spend is from one wallet. + +--- + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| a 30329 birth certificate for the person | every reader of 30329 assumes a room. See the table at the top | +| the member coordinating the FROST session without a share | the closest fit to "the individual proposes", and FROST allows it. But `advance`, `proposeSigningBatch` and `signApprovedAt` all assume the coordinator signs, and this is the one manager every signature goes through. Worth revisiting if a second feature wants a non-signing coordinator | +| the group's signers computing the leaves | the member asked to incorporate them before sharing, and a member who checks nothing is agreeing to a tree they never saw | +| the member's nostr key as the wallet key | leaks the identity through any one address's key, does not work for a NIP-55 signer, and links the npub to the chain | +| a key from the profile's seed, hardened | backed up by the mnemonic for free, but an nsec or npub profile has none. The group is the recovery path anyway (D6) | +| `W = xonly(P_W)` | `W` would then be a key, and an event "signed by W" would read as signed by a room | +| a member's wallet as a 1-member subgroup | a ceremony, a key state, a Marmot room and a three-admin floor, to hold one person's key. The point of a member wallet is that it is *not* a group | +| filing the key notice into `GroupKeyState` | it would give every late member a key state and quietly change what `thresholdKeyFor` answers for them across the app. Reading it in one place, for one purpose, keeps the change where it is needed | +| choosing which ancestors guard it | the grant is a function, and a choice is a second thing signers would have to agree on. A guarded subgroup of `G` has no choice either | +| listing member wallets in the subgroups section | a row there navigates into a room, and its title is a founding name. A person is neither | diff --git a/docs/member-wallet-delay.md b/docs/member-wallet-delay.md new file mode 100644 index 00000000..3a5bc9b2 --- /dev/null +++ b/docs/member-wallet-delay.md @@ -0,0 +1,583 @@ +# The group decides whether it guards members' wallets, and at what delay + +A member's guarded wallet carries one leaf for the group that guards it and one +for every group above it. Since [guardian-delay.md](./guardian-delay.md), each +ancestor's leaf keeps the delay that ancestor chose when it made the group below +it. The group's **own** leaf, though, is always `GuardianDerivation.DEFAULT_DELAY`, +12 blocks. The member's device builds the grant without a delay +(`MemberWalletManager.kt:193`), and every signer recomputes it the same way and +refuses anything else (`refuseCertificate`, line 518). Nobody chooses the number. + +This plan lets the group choose it. **The group's quorum signs one standing +statement in its own room: wallets members ask this group to guard carry this +group's leaf at `d` blocks. A member's device builds its request under the +newest such statement and carries that statement in the request. Every signer +checks that the request's own leaf has exactly that delay, and that the +statement it was built under is the group's newest.** Each wallet's delay is +then fixed in its certificate, as every guardian tag already is. A later +statement changes the wallets members ask for after it, and never one already +guarded. + +**The statement is also the group's opt-in.** A group that has never signed one +does not guard members' wallets: the member's group picker says so, and every +signer refuses a request to it. **A later statement can close it again** with a +`closed` tag, and from then on the group takes no new member wallets until a +newer statement opens it. Closing never releases a wallet already guarded, since +the group's leaf is in every one of its addresses. + +Read [member-guarded-wallets.md](./member-guarded-wallets.md) and +[guardian-delay.md](./guardian-delay.md) first. This plan reuses the request, +the certificate, the key notice and the signer check from the first, and the +delay range, the formatter and the delay chooser from the second. + +**Built**, phases 1-7, one commit each, written against the code as it stood at +`05bd6ed6`, schema v31, with no schema change. D1 (a group-signed event, not the +birth certificate) was decided before the build; the opt-in (D8) and the +`closed` tag (D9) were added on review. `MemberWalletPolicyEvent`, +`MemberWalletManager.policyFor` and `judgePolicy`, and `MemberWalletPolicyScreen` +are the entry points. The phases below are kept as written; where the build +chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 1: `verify` only | also `read`, the shape without the signature, for `ProposedEvent`: a signer reads a policy before the group has signed it. `ORDER` is public, for the signers' staleness check | +| Phase 4: a `POLICY_UNKNOWN` refusal | not built. `KEY_UNKNOWN` already covers a member who has had no key answer, with its button to ask, and the answer carries the policy. A member whose answer came from a device that held no policy reads `NOT_OFFERED` until an answer that does arrives | +| Phase 4: `verified()` refuses a request carrying no policy | it accepts one. Certificates signed before policies embed a request with none, and refusing it would stop every wallet already guarded from verifying. That a *new* request must carry an open policy is the signers' rule, in `judgePolicy` | +| Phase 4: *set by #Council* beside the group's line | not added: the reach sentence already names the group whose delay it is | +| Phase 5: the group page's request row says why | the member's wallet screen does, through `MemberWalletRow.refusedBecause` and `MemberWalletManager.Why`. *Ask again* on a refused request makes a new one under the newest policy with a new key and discards the old -- `askAgain` takes the member's key and returns the wallet now asked for, and the wallet screen follows it. For a closed group only *Discard* is offered | +| Phase 6: `MemberWalletPolicyViewModel` holds the input as typed | in `GuardianDelayInput`, shared with the subgroup picker, as `GuardianDelayChooser` is | +| Phase 6: the row shows for every member | for every member of a Marmot group that is not disbanded (`showsMemberWalletPolicy`); a device that cannot sign sees the state and no button | +| nothing about test fixtures | `GroupFixtures.openToMembers`: every member-wallet test now opens its group first, since D8 closes a group with no policy | + +Still to do by hand: the three-emulator run in Phase 7. + +--- + +## Where the delay should live + +The question this plan has to settle first. There are four places a group-level +number could be signed, and only one of them is the group's own decision about +the group's own leaf. + +| place | who signs it | why not | +|---|---|---| +| the group's **birth certificate** (30329) | the **parent's** quorum, once, at the group's birth | it is the parent's statement about the child, and the member-wallet delay is the group's decision about its own leaf. The group did not sign it and cannot change it, because a certificate is replaceable only by the parent, and the group's key state carries the one it was born with. A **root group has no certificate at all**, so the most common group could never set a delay | +| the group's **key state** (30326) | the group's own quorum | it answers one question, *what does this room sign with*, and `GroupKeyStateManager.stateFrom` drops a state that says anything it cannot check. Changing a wallet policy would mean re-signing the room's key state, which every device then re-adopts. The key notice already carries the key, so the delivery advantage is small | +| the group's **wallet statement** (30331) | the group's own quorum | it opens one account on one network, and only once. A group with no wallet of its own, or a group that guards members on signet and mainnet, has nowhere to put it. It is also immutable for its account by the guardians note's rule 2 | +| **a new group-signed event**, 30337 | the group's own quorum | **recommended.** Signed by the group about the group, changeable by the group, and verifiable by anyone holding the room's id, through the same `GroupKeyStateEvent.isSignedByRoom` check the chronicle and the certificates use | + +So the answer to "birth certificate or group signed event" is **a group-signed +event of its own kind**. The birth certificate stays the parent's, and keeps +deciding only what the parent decides: whether the group is guarded, and the +parent's own leaf's delay in the group's wallet. + +--- + +## The policy event + +Two shapes, one kind: + +``` +open: kind 30337, pubkey G, content "" + ["d", "member-wallets"] addressable: the newest wins + ["guardian_delay", ""] 6..65,535, GuardianDerivation.DELAY_RANGE + +closed: kind 30337, pubkey G, content "" + ["d", "member-wallets"] + ["closed"] +``` + +Exactly one of `guardian_delay` and `closed`. An event with both, or neither, +does not read: a group that has said two things about its members' wallets has +said nothing a device can act on, and guessing which it meant would be the device +deciding for the group. + +- **Signed by `G`'s quorum** through the existing FROST proposal path, like the + wallet statement. No new signing machinery. +- **Newest wins**, by the group's own `created_at` with the id breaking a tie, + for the reason `GroupWallet.newestAmong` gives: two devices that read the same + events in different orders have to agree. +- **No policy means not offered** (D8). A group guards members' wallets only + once its quorum has said so, and at the delay it said. +- **The newest decides, open or closed** (D9). Closing and opening again are each + one more statement; nothing is ever deleted, and every device agrees on which + is newest. +- **The `d` tag names *member wallets*, not *delay***, so a later rule about + members' wallets is another tag on the same event rather than another kind. + +### Why the request carries it + +A member's device needs the delay before it builds anything, because the leaf, +the tree and both descriptors depend on it. Two kinds of device may not hold the +newest policy: + +- **A member who joined after it was signed.** MLS cannot decrypt messages from + before a member's welcome, which is the reason the key notice (30336) exists. +- **A signer who missed it.** `docs/mls-skipped-keys.md` describes how a group + event that arrives a moment late is dropped for good on one device. + +So the request carries, whole, the policy event it was built under. Any reader +can check it with `G` alone. A signer that missed the newest policy then still +judges the request against what the group actually signed. A signer whose newest +is newer than the one carried refuses the request as stale, and the member asks +again. Because the certificate embeds the request, the ancestors can also see +why the leaf has the delay it has. + +--- + +## Phase 0 — decisions, before any code + +### D1. A group-signed event, not the birth certificate + +**Decided.** Kind 30337, the next free number after the key +notice at 30336. + +### D2. Can the group change it? + +**Recommended: yes, for wallets asked for afterwards; never for one already +guarded.** A wallet's delay is in its certificate's guardian tags, and the +guardians note's rule 2 fixes an account's guardians, delays included. So a new +policy reaches only requests built under it. The screen that changes it says so: +*Wallets already guarded keep the delay they were guarded at.* + +### D3. What the delay covers + +**Recommended: the group's own leaf only.** Each group above keeps the delay it +chose for the group (guardian-delay D1), so a member's wallet under `M`, under +the root, reads: + +``` +leaf 1 M's own delay from M's newest 30337, or 12 +leaf 2 the root's the delay the root chose for M, unchanged +``` + +A group cannot shorten the root's wait in its members' wallets any more than in +its subgroups'. + +### D4. One delay per group, not per member + +**Recommended: one.** A group that wants to treat one member differently is +asking for a different rule, and a per-member table would be a roster the group +signs over and keeps current. The member still chooses *whether* to ask. If they +do not like the group's delay, they do not have to ask that group. + +### D5. Who may set it + +**Recommended: any member holding a share proposes, and the group's quorum +decides,** like every other event the group signs. The entrance is shown only to +a device that can sign (`FrostSigningManager.canSign`), as the wallet's *Open* +button is. + +### D6. Which request a signer accepts + +A signer holds `held`, the newest verified 30337 it has, or none. The request +carries `carried`, or none. **Recommended:** + +| carried | held | judged at | otherwise | +|---|---|---|---| +| an open 30337 `G` signed | none, or one -- open or closed -- not newer than it | `carried`'s delay | — | +| an open 30337 `G` signed | a newer open one | — | refused: *was asked under a delay the group has since changed* | +| an open 30337 `G` signed | a newer closed one | — | refused: *the group has stopped guarding members' wallets* | +| a closed 30337, or one not signed by `G`, or unreadable | any | — | refused: *carries a policy this group did not sign open* | +| none | any | — | refused: *does not say the group guards members' wallets* | + +The first row covers the signer that missed the group's opening statement, and +the one whose newest is a closing the group has since reversed: the request +carries an open policy `G` signed, and nothing newer says otherwise, so the +signer is told what it missed rather than refusing it. + +The last row is how a request from a build before this plan fails: it carries no +policy, so it never asked for the delay the group chose, or for a group that +chose to guard members at all. That is the right failure. + +### D7. Mixed versions + +**A signer on a build before this plan compares to `grantFor` at the default**, +so it refuses any request whose own leaf is not at 12. That is the safe way to +fail. It is also blind to D8 and D9: it would still sign a request at 12 to a +group that never opened, or has closed, if a member on an older build asked. A +group should open at a delay other than 12, or close, only once every member who +can sign is on a build from Phase 5 onward. The screen says this, because a +device cannot see other devices' versions. + +### D8. No policy, no member wallets: the statement is the group's opt-in + +**Recommended.** Today any member can ask any group, and the group only agrees +when its quorum signs that member's certificate. With D8 the group agrees up +front, once, for everybody, and every new member wallet's delay is one its group +chose. There is no default any more. + +What this changes for groups that exist: + +- **A group that wants to keep guarding members' wallets signs an open policy + once**, even to stay at 12. Phase 6's screen offers *Guard members' wallets* + with 12 selected, so that is one tap and a quorum. +- **Wallets already guarded are not touched.** Their certificates stand; the + member still spends, and every guardian still watches. D8 is about new + requests. +- **A request already asked and not yet signed** is refused by D6's last row + once the signers update. The member's row says why and offers *Ask again*, + which works once the group opens. + +### D9. Closing, and opening again + +**Recommended: `["closed"]` on a newer policy.** + +- **Closed means no new member wallets.** The member's picker says *this group + has stopped guarding members' wallets*; every signer refuses a request built + under an older open policy (D6's fourth row) and puts nothing to the quorum. +- **Closed does not release a wallet already guarded.** The group's leaf is in + every address of every wallet it guards, and no statement can take it out. The + group can still take any coin there after its delay, and the screen that + closes says so: *Wallets already guarded stay guarded.* A member who wants out + moves their coins to a wallet of their own, which needs nobody's agreement. +- **Opening again is a newer open policy**, at any delay. It reaches only + requests built after it, as every policy does. +- **Closing is not a refusal of a person.** It is the group's statement about + every member at once, and D4 rules out a per-member list for the same reason. + + +--- + +## Phase 1 — the policy event, pure + +New `nostr/wallet/MemberWalletPolicyEvent.kt`: + +```kotlin +object MemberWalletPolicyEvent { + val KIND: Kind = 30337 + const val IDENTIFIER = "member-wallets" + + fun open(delay: Long, createdAt: Long = now): EventTemplate // requires DELAY_RANGE + fun closed(createdAt: Long = now): EventTemplate + + /** What [event] says, as [chatRoomId] signed it. */ + sealed interface Policy { + val event: Event + val createdAt: Long get() = event.createdAt + + data class Open(val delay: Long, override val event: Event) : Policy + data class Closed(override val event: Event) : Policy + } + + /** [event] as [chatRoomId]'s policy: the kind, the `d`, exactly one of a readable delay or `closed`, signed by the room. */ + fun verify(event: Event, chatRoomId: String): Policy? + + /** The newest among [events] that verifies, by created_at then id -- open or closed. */ + fun newestAmong(events: List, chatRoomId: String): Policy? +} +``` + +`verify` checks the kind, the `d` tag, exactly one of a `guardian_delay` tag that +reads and is in `GuardianDerivation.DELAY_RANGE` or a bare `closed` tag, and +`GroupKeyStateEvent.isSignedByRoom(event, chatRoomId)`, all inside `runCatching`. + +**Tests**, `MemberWalletPolicyEventTest`, pure: +- an open policy and a closed one each round-trip; +- each of these fails on its own: another kind, a missing `d`, two delays, + `"5"`, `"65536"`, `"twelve"`, both a delay and `closed`, neither, signed by + another room; +- of an open, a closed and a second open policy, the newest wins whatever order + they arrive in, and a tie on `created_at` goes to the larger id on every device. + +--- + +## Phase 2 — the group files it, and the transcript says it + +The FROST completion path already files every signed event in +`GroupSignedEvent` (`FrostSigningManager.recordSignedEvents`), whatever its kind. +This phase reads them: + +- `MemberWalletManager.policyFor(database, G): MemberWalletPolicyEvent.Policy?` + is the newest verified among `G`'s stored 30337s and any carried in key-notice + answers (Phase 3). It is the one reader, used by the member's device in Phase 4 + and by every signer in Phase 5. Null means the group has not opened (D8). +- `ChatMessage.applyInnerEvent` and `applySignedEvent` get a 30337 arm that + writes one transcript line: *The group guards members' wallets, after 144 + blocks, about 1 day*, or *The group has stopped guarding new members' wallets*. + Without the arm an older build shows a raw-JSON bubble, which is reason to ship + this phase before Phase 6's entrance. +- `ProposedEvent.summarize` gets a 30337 arm: *Members' guarded wallets · this + group after 144 blocks, about 1 day · for wallets asked for from now on*, or + *Members' guarded wallets · no new ones · wallets already guarded stay + guarded*. + +**Tests**: `policyFor` prefers the newest of an open and a closed policy, either +way round; ignores one signed by another room; returns null for a group that +never signed one. The summary says the delay in both blocks and time, and says +what closing leaves alone. + +--- + +## Phase 3 — the key notice carries it + +A member who joined after the policy was signed cannot decrypt it. The key +notice already answers that member's other question, *what does this group sign +with*, so it answers this one too: + +- `GroupKeyNoticeEvent.answeringTags` gains + `["member_wallet_policy", ]` when the answering device + holds one, open or closed. +- `read` returns it in `GroupKey.policy`, verified by + `MemberWalletPolicyEvent.verify(it, G)`. A policy present and unreadable makes + the whole answer unreadable, as an unreadable certificate already does. It is + never read as "no policy". +- `MemberWalletManager.groupKeyFor` gains the policy, and `policyFor` considers + it beside the stored ones. + +Until an answer brings one, a late member's device holds no policy for a group +that may well be open. Phase 4's picker therefore tells *not known yet* apart +from *not offered*: a device that holds no key state and no answer says the +first, and offers the existing *Ask the group for its key*. + +**Tests**: an answer carrying an open policy gives it, and so does one carrying +a closed one; one carrying a policy signed by another room does not read; an +answer without one reads, with no policy. + +--- + +## Phase 4 — the member builds under it + +`MemberWalletManager.refusal(database, G, chain)` gains three reasons, checked +after the ones it has: + +| `MemberWalletManager.Refusal` | when | what the picker says | +|---|---|---| +| `POLICY_UNKNOWN` | no key state and no key answer yet, so no policy could be known | *Ask the group for its key* (the existing button) | +| `NOT_OFFERED` | the key is known and no policy is | *This group doesn't guard members' wallets* | +| `CLOSED` | the newest policy is closed | *This group has stopped guarding members' wallets* | + +So the picker still lists every group, each with why it cannot be chosen, as it +does today. A group without an open policy is never offered silently. + +In `MemberWalletManager.request`, which already refuses on any refusal: + +```kotlin +val policy = policyFor(database, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open + ?: throw IllegalStateException("$chatRoomId does not guard members' wallets") +val grant = GuardianDerivation.grant( + groupKey.thresholdPublicKey, chatRoomId.lowercase(), groupKey.guardians, walletId, + delay = policy.delay, +) +``` + +- `MemberWalletRequestEvent` gains `["member_wallet_policy", ]`, always. The member's nostr signature covers it, as it covers + everything in the request. +- `Reading.verified()` gains a sixth check: the carried policy is open, verifies + against the request's `h`, and the first guardian's delay equals its delay. + This is everything a reader can check without knowing the group's newest. The + newest is Phase 5's job. +- `MemberWalletManager.delaysOf` reads the open policy for the first delay, and + is null for a group that is not open. The new-wallet screen already lists each + guardian's delay from it (since `3b2d9bd8`), and gains *set by #Council* beside + the group's own line. + +**Tests**: a request under an open policy at 4,320 has its first guardian at +4,320 and carries the policy; `request` refuses a group with no policy and one +whose newest is closed; a request whose first delay disagrees with its carried +policy fails `verified()`, and so does one carrying a closed policy or none. + +--- + +## Phase 5 — every signer checks it + +`MemberWalletManager.refuseCertificate` stops computing the expected grant at +the default. Instead it: + +1. reads the request out of the certificate, as it already does; +2. applies D6's table, with `held = policyFor(database, G)` and `carried` from + the request, to get the delay or a reason to refuse; +3. compares the certificate's guardians to + `SubgroupManager.grantFor(database, G, K_G, W, delay)`, which since + guardian-delay Phase 6 takes the own leaf's delay. The keys, their order and + every inherited delay are checked exactly as before. + +`MemberWalletManager.putToGroup` runs the same check before it proposes, as it +already runs `refuseCertificate`. A sponsor is then never asked to put to the +quorum a request their own device knows is stale, or asks a closed group. + +The member's request row on the group page (*Asked by @alice, not yet signed*) +reads the same reasons: + +- **asked under an older delay**: offers the member *Ask again*, which builds a + new request under the newest open policy, with a new key; +- **the group has stopped guarding members' wallets**: offers *Discard*, and + says *Ask again* will be possible if the group opens again; +- **does not say the group guards members' wallets**, a request from before this + plan: offers *Ask again* once the group has opened. + +Either way the old request's key is discarded, because no address was ever +offered. + +**Tests**, `MemberWalletSigningJvmTest`: every row of D6's table, through +`refuseCertificate`; a signer that missed the opening policy accepts a request +carrying it; a signer holding a newer closed policy refuses a request carrying an +older open one; two signers with different held policies agree once the request +carries the newer one. + +--- + +## Phase 6 — the group opens it, sets it, and closes it + +Phases 5 and 6 ship together (see the order table): once signers refuse a +request with no policy, a group needs this screen to open. + +**The entrance.** On `ChatRoomDetailScreen`, in *Members' guarded wallets*, a +first row for every member, in one of three states: + +``` +Guards members' wallets after 144 blocks, about 1 day [Change] +Doesn't guard members' wallets [Guard members' wallets] +Stopped guarding new members' wallets [Guard members' wallets] +``` + +The buttons are shown only where the device can sign (D5); everybody sees the +state. Every button opens `MemberWalletPolicyScreen`, a pushed screen with a +`NavigateBackButton`, which holds: + +- `GuardianDelayChooser`, **moved out of** `SelectSubgroupAdminsScreen` into + `ui/composable/widgets/GuardianDelayChooser.kt`, with its presets, its custom + field and its live `delayText`, starting at the group's current delay, or 12 + for a group opening for the first time. Its words are passed in, because *the + subgroup* and *the member* differ; +- D2's line: *Wallets already guarded keep the delay they were guarded at*; +- D7's line: *Members whose app is older than this one can only be guarded at + 12 blocks, and don't know this group can close*; +- **Ask the group**, which proposes an open 30337 at the chosen delay through + `FrostSigningRepository.proposeSigning` and goes to `FrostSigningRoute`, as + opening a wallet does; +- on an open group only, **Stop guarding new wallets**, an `OutlinedButton` + under it, which first asks in a dialog -- *Stop guarding new members' wallets? + Wallets already guarded stay guarded, and this group can still take their + coins after the delay.* -- and then proposes a closed 30337 the same way. + +A view model, `MemberWalletPolicyViewModel`, holds the input as typed, refuses a +delay below 6 or above 65,535 blocks with the reasons the subgroup picker +already uses, does not propose the delay an open group already has, and does not +propose closing a group that is not open. + +The member's own leaf is the group's, and the trade the subgroup picker states +applies here too, said for a person: *A coin the member moves starts waiting +again, so a long delay lets them keep their coins out of reach by moving them.* + +CLAUDE.md applies in full: strings in the catalogue in sentence case, spacing +from `MaterialTheme.spacing`, the screen's four states, and the outcome reported +through `rememberNotifier`. + +**Tests**, `MemberWalletPolicyViewModelJvmTest`: a group opening for the first +time starts at 12; an open group starts at its delay; a preset and a typed delay +are what it proposes; out-of-range delays are refused with their reasons; +proposing the current delay is refused; closing is offered only to an open +group, and proposes a closed policy. + +--- + +## Phase 7 — docs, and checking it on the emulators + +- [member-guarded-wallets.md](./member-guarded-wallets.md): *What "full control" + means* stops saying 12 and links here; D3 (*which members may ask*) gains + *and only of a group that has opened*. The request's tag list gains the policy. +- [guardian-delay.md](./guardian-delay.md): its build table's member-wallet row + ("a group still cannot choose…") points here. +- [README.md](./README.md): this note's row. +- This note: *Built*, and a table of where the build chose differently. + +By hand, regtest, three emulators: Alice (a signer), Bob (a signer), and Carol, +who joined the group after step 2. + +1. Carol's picker, before anything, says *This group doesn't guard members' + wallets*. +2. Alice and Bob open the group at 144 blocks. The transcript says so on the + devices that were in the room. +3. Carol joins. Her picker says the group's key is not known yet; she asks; the + answer carries the policy; her screen says *after 144 blocks, about 1 day*. +4. Bob puts Carol's request to the group. Both signers accept it, and the + certificate's first guardian tag says 144. +5. Alice and Bob change the delay to 1,008. Carol's wallet still says 144. A new + request from Carol is built at 1,008. +6. Alice and Bob close the group. Carol's picker says *stopped guarding*; a + request she built before the close is refused by both signers; her wallet at + 144 is still guarded, and Alice can still take a coin from it after 144 blocks. +7. Alice and Bob open it again at 6. Carol can ask again, at 6. +8. A request built on an older build (12, no policy) is refused by both signers, + with *does not say the group guards members' wallets*. + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +--- + +## Order and size + +| phase | touches | ships | +|---|---|---| +| 1 | `MemberWalletPolicyEvent` and its test | dark: a kind nothing produces | +| 2 | `policyFor`, the transcript and summary arms | dark, and should ship early: an older build shows a raw-JSON bubble for a 30337 it has no arm for | +| 3 | the key notice | dark | +| 4 | the request, the picker's refusals | **with 5 and 6**: from here a member can ask only an open group | +| 5 | the signers' check | **with 4 and 6**: from here signers refuse a request to a group that has not opened | +| 6 | the entrance and the screen | **with 4 and 5**: the only way a group opens | +| 7 | docs and the emulator run | last | + +**Phases 4, 5 and 6 are one release.** Under D8, Phases 4 and 5 stop every group +taking new member wallets until it opens, and Phase 6 is how it opens. Shipped +apart, the member's picker would say *doesn't guard members' wallets* about every +group, with no way for any group to say otherwise. Shipped together, an existing +group loses nothing but one quorum: the first time anybody wants a new member +wallet from it, a signer opens it at 12. The release note should say so, since +for a few days every group will read *doesn't guard members' wallets* until +somebody opens it. + +No schema change. Policies are `GroupSignedEvent` rows like every other event +the group signs, and the request already keeps its event whole. + +--- + +## What this does not do + +**It does not change a wallet already guarded** (D2). A different delay is a new +request, with a new key. + +**Closing does not release a wallet** (D9). The group's leaf is in every address +of every wallet it already guards, and the group can still take a coin from one +after its delay. Closing stops new wallets, and nothing else. Releasing a +member's wallet would need the member to move their coins somewhere the group +holds no leaf, which they can do alone at any time. + +**It does not open groups that existed before it** (D8). Each group's quorum +opens it, once. Nothing opens a group on its behalf, because the point of D8 is +that a group guards members' wallets only once it has said so. + +**It does not let the member choose.** The member chooses whether to ask, and +sees the delay before they do. A member who wants a longer delay than the group +offers asks a different group, or asks this one to change it. + +**It does not set the subgroup picker's default.** A group making a guarded +subgroup still chooses that subgroup's delay on the picker, starting from 12. +Using the member-wallet policy as the picker's starting point is a one-line +follow-up, and it is left out so that the policy means one thing. + +**It does not reach a group's ancestors.** The root's delay in a member's wallet +under `M` is the delay the root chose for `M` (D3). A root that wants a +different wait in its descendants' members' wallets sets it when it makes the +group below it. + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| a tag on the group's birth certificate | the parent's statement, not the group's; fixed at birth; absent for a root group (see *Where the delay should live*) | +| a tag on the group's key state | re-signing what the room signs with to change a wallet rule, and every device re-adopting it | +| a tag on the group's wallet statement | one per network and account, immutable, and absent for a group with no wallet of its own | +| the member chooses, within a range the group sets | asked for as *the group sets the delay*; a range is a second number to sign and explain, and can be added later as a second tag on the same event | +| signers judge only by the policy they hold | a signer that missed the newest policy would refuse a correct request, and two signers holding different ones would never agree on the same request | +| a per-member delay | a roster the group signs and keeps current (D4) | +| no policy means guard at the default, 12 | the first draft of this plan. It made every group a guardian of any member who asked until its quorum refused, and made the closed tag an opt-out from something no group had opted into (D8) | +| a separate kind to close | two kinds to order against each other; one addressable kind whose newest says open or closed has one answer on every device (D9) | +| deleting the policy to close | a signed event is never deleted on other devices, and an absence cannot be told apart from a member who never received it | diff --git a/docs/member-wallet-guarding-group.md b/docs/member-wallet-guarding-group.md new file mode 100644 index 00000000..7c60f8b4 --- /dev/null +++ b/docs/member-wallet-guarding-group.md @@ -0,0 +1,519 @@ +# Which group guards a member's wallet, as the groups above see it + +An ancestor's *Guarded wallets* list shows `@alice` with no word about where her +wallet sits. Suppose Alice is in two groups of one tree and each guards a wallet +for her. The root then sees two rows that read the same, and nothing on the screen +says they came from different branches. This plan names the group that **directly** +guards each member wallet, which is the group that signed its certificate. It +gathers a person's wallets under that person, so an ancestor can see at a glance +that one member has three wallets guarded by two groups. + +Read [member-guarded-wallets.md](./member-guarded-wallets.md) first, Phases 10 +and 11 especially. This plan changes what those phases draw. It does not change +what they verify. + +**Built**, phases 1-6, one commit each, written against `263a25a7`, schema v31; +no phase changed the schema. `GuardedWallet.directGuardianChatRoomId`, +`GuardianManager.foundingNameOf`, `GuardedWalletNoticeEvent.certificateIn`, +`byPerson` and `MemberWalletManager.byWallet` are the entry points. The phases +below are kept as written; where the build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| D3, third source: 30331 notices told to *any* room here | only those told to the holding room, which `guardedWalletsOf` already reads. Reaching every room would have been a query by kind across rooms, the one new query the plan said it did not need | +| Phase 2: `foundingNameOf` | and `foundingCertificateOf` beside it, which returns the checked event: Phase 3 forwards the certificate, not the name | +| Phase 3, step 4: each told row paired with its own carried certificate, and the copy with one wins a fold | every certificate the room's notices carry is pooled, with the ones its 30331 statements embed, and offered to every wallet. Each is checked against the room and parent it would name, so one that certifies neither is never used, and the fold needs no tiebreak | +| Phase 3, not in the plan | *Tell the groups above* offers only guardians above the room it is shown from. It offered every guardian but that room, so a device in P and M was asked to tell M about M's own member's wallet -- found writing the two-hop test | +| Phase 5, step 2: `guarded_by_this_group`, `n_guarded_wallets` | noun phrases inside `guarded_by_s` -- `this_group`, `a_group_below_s`, `a_group_below_this_one` -- so the button descriptions can use the same phrase mid-sentence; `n_wallets`, since *2 guarded wallets, guarded by 2 groups* says it twice; and `s_comma_s` to join the two plurals | +| Phase 5, step 3: `guardedWalletName` gives `@alice · Savings` | every such sentence is *X's guarded wallet*, and *@alice · Savings's* does not read. A labelled wallet is *@alice's guarded wallet “Savings”*, an unlabelled one *@alice's wallet guarded by #M* | +| Phase 5, step 4: `displayName` becomes `@alice · Savings` | `displayName` is unchanged; `Spender.Guardian` gains `label`, and `ProposedSpend.guardedWallet` appends it the same way. The transcript's *The group signed …* line and the send form's title use it too | +| Phase 4: cards nearest first, then by guardian name | then by label as well, so two wallets under one group keep an order | +| Merged with [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md), which landed alongside | that note made forwarding automatic, so `GuardianManager.forward` -- on arrival and in the catch-up -- carries the certificate too, read by `guardianCertificateFor`. D5's rule lives in its `told`, which also counts a statement the room signed itself, and `alreadyTold` is gone. D5's extra transcript line never appears: that note's one line per wallet per group keeps the second notice silent. Both branches made the upward-only fix; its `upwardOf` is the one kept | +| Phase 6: `GuardedHereWallet(walletId, label, guardianName, holders)` | and `below`, the group it is known to sit below, for the line when no holder can name the guardian; with neither it is *another group*. `GuardedHere.guardianName`, which was the holder's room name, is now `holderName` | + +Still to do by hand: Phase 7's run on signet. + +--- + +## The example used throughout + +``` +R root +├── P R's guarded subgroup +│ └── M P's guarded subgroup — guards Alice's "Savings" +└── N R's guarded subgroup — guards Alice's "Rent" +``` + +| wallet | guardians, nearest first | R's `position` | R's `lineage` | +|---------|--------------------------|----------------|-------------------| +| Savings | `[M, P, R]` | 2 | `[P, M, W_savings]` | +| Rent | `[N, R]` | 1 | `[N, W_rent]` | + +What R's wallet screen draws today: + +``` +Guarded wallets + @alice · Savings 12,000 sats within this group's reach + @alice · Rent 4,000 sats within this group's reach +``` + +And with no labels, two identical `@alice` rows. The *Fund* and *Spend* buttons +on both are described to a screen reader as *Fund @alice's guarded wallet*, so +nothing tells the two apart. + +--- + +## What the code already knows + +Most of the answer is already in memory, unused. + +- **The direct guardian is `account.guardians.first()`.** + `MemberWalletRequestEvent.verified` refuses a request whose nearest guardian is + not the group it asks (`MemberWalletRequestEvent.kt:237`). `MemberWalletCertificateEvent.verify` + also requires that same group to have signed the certificate. So + `guardians[0].chatRoomId == certificate.pubKey == Verified.groupChatRoomId`, + and an ancestor that has believed the certificate has believed this too. +- **The branch is `lineage.first()`.** `GuardianDerivation.lineage` gives the + rooms from the ancestor's own child down to the wallet. Its first element is + the child of *this* group that the wallet sits under. This group signed that + child's birth certificate, so it can always name it. +- **The distance is `position`.** 0 means this group is the direct guardian. 1 + means a child is, and so on. +- **What the code cannot always do is put a name to `guardians[0]`.** Names come + from `ChatRoom.subject`, and only for rooms this device is in + (`GroupWalletViewModel.namesOf`, `guardedByGroupsHere`). Take a device in R but + not in M. It has M's room id and nothing else. + +Room ids are signing keys (`GroupKeyStateEvent.isSignedByRoom` checks +`pubKey == chatRoomId`). So any device can check M's birth certificate on its own. +It is a 30329 that P signed, and `SubgroupBirthCertificateEvent.certifies(cert, M, P)` +needs nothing but the event. The certificate is the thing an ancestor is missing, +and it does not have to trust whoever hands it over. + +--- + +## Phase 0 — decisions, before any code + +### D1. "Directly guarded by" means the certificate's signer + +That is `guardians[0]`. It is not the room the notice was forwarded into, and not +the member who forwarded it. One wallet has exactly one direct guardian, however +many ancestors hold a leaf in it. + +### D2. The founding name, then the live one, then where it sits + +Order of preference for the direct guardian's name: + +1. its **founding name**, from a 30329 this device has checked (D3); +2. its live `ChatRoom.subject`, where this device is in that room; +3. a phrase saying where it sits: *a group below #P*, using the branch, which is + always known. + +The founding name comes first because the same list already names subgroup rows +by founding name (`GuardedSubject.Subgroup.name`, "a rename does not reach it"). +A card that said *#Translators* for the guardian of `@alice`'s wallet, two cards +below a subgroup row reading *#Translation* for the same room, would contradict +itself. It also means two members of R see the same words when they talk about +the row. + +### D3. Where a founding name can come from + +For a room `X` with parent `Y` (`guardians[i]` and `guardians[i + 1]`), every +source is checked with `certifies(cert, X, Y)`, never taken on trust: + +| source | present on | +|---|---| +| the 30329 `Y` signed, in `groupSignedEventDao` under `Y` | every device in `Y` | +| `GroupKeyState.birthCertificateJson` for `X` | every device in `X` that holds its key state | +| a 30331 notice told to any room here, authored by `X`, which embeds `X`'s certificate | ancestors that were told of `X`'s own wallet | +| **the certificate carried on the 30333 notice itself** (Phase 3) | every device in every room the notice reached | + +The first three already exist. On their own, they name M for R only when this +device is also in P or M, or was told of M's own wallet. The fourth source is the +reason for Phase 3. + +### D4. The notice carries the direct guardian's certificate, as a tag + +A 30333 carrying a 30334 gains one tag: + +``` +["certificate", ] +``` + +- **It is a tag, not a second content.** An older build reads `content` and + nothing else, so it still believes the wallet and ignores the tag. +- **It is checked, not trusted.** A wrong certificate, or one that certifies a + different room, is dropped, and the row falls back to D2's next step. It never + stops the wallet itself from being believed, because the name is not what the + leaf's signing depends on. +- **There is none for a root guardian.** If `guardians.size == 1`, no group is + above to be told, so the case never arises. +- **A 30331 notice is unchanged.** The statement already embeds the subgroup's + own certificate. Its direct guardian is its parent, which is not this plan's + question (see *What this does not do*). + +### D5. A wallet told without a certificate may be told again + +`alreadyTold` matches on the statement's id. Notices sent before Phase 3 carry no +tag, and so as things stand they would block a better one forever. From Phase 3, +a room counts as told only if it holds a notice for that statement **with** a +certificate, or if this device has no certificate to add. The cost is one more +transcript line, *Shared @alice's guarded wallet with this group*, on rooms told +before. `guardedWalletsOf` already folds duplicates by `(id, chain, account)`. + +### D6. An ancestor's list groups member wallets by person + +The *Guarded wallets* section keeps subgroup rows as they are. Member wallets +move under a header for each person: + +``` +Guarded wallets +Wallets of groups below this one. … + + #Translation subgroup cards, unchanged + ... + +Members' wallets + (avatar) @alice person header — opens her profile + 2 wallets, guarded by 2 groups + ┌──────────────────────────────────────┐ + │ Savings │ + │ Guarded by #M, below #P │ + │ 12,000 sats within this group's reach│ + │ This group's delay: … │ + │ Fund Spend │ + └──────────────────────────────────────┘ + ┌──────────────────────────────────────┐ + │ Rent │ + │ Guarded by #N │ + │ … │ + └──────────────────────────────────────┘ +``` + +- **Every member gets a header, even with one wallet.** The layout keeps one + shape, and the header's count is the summary the question asks for. +- **The header counts and the cards name.** *2 wallets, guarded by 2 groups* is + two plurals. Writing the names into the header would need a list join, which + Compose Resources does not localise. The names are one line below, on each + card. +- **Cards are ordered by distance, then by guardian name.** Wallets from one + branch sit together. +- **The card's guardian line by `position`:** + - 0: *Guarded by this group* + - 1: *Guarded by #N* + - 2 and more: *Guarded by #M, below #P*, where `#P` is the branch. +- **The headline is the label. With no label, the guardian line moves up to the + headline.** Two unlabelled wallets of Alice's are then still told apart. + +### D7. The person's page shows one row per wallet, not one per holder + +`guardedByGroupsHere` returns one `GuardedHere` per *holding* group. When P and R +are both here, Savings appears twice, and each row reads *Guarded by #P* or +*Guarded by #R*. That uses "guarded by" for the holder, which this plan reserves +for the direct guardian. Instead: + +``` +Wallets your groups guard + Savings + Guarded by #M + #P: after 144 blocks, about 1 day Spend + #R: after 288 blocks, about 2 days Spend + Rent + Guarded by #N + #R: after 144 blocks, about 1 day Spend +``` + +The holder lines reuse `guardian_after`, which the wallet screen already uses for +delays. + +### D8. Rollout: no gate + +All of this is display, apart from one backward-compatible tag. It needs no +`GroupWalletRollout` gate. Phase 3 is the only part another device reads, and an +older device ignores it. + +--- + +## Phase 1 — the direct guardian, pure + +`GuardianManager.GuardedWallet` gains three derived properties. They are not +fields, so no constructor or test fixture changes: + +```kotlin +/** The group that signed the certificate: the wallet's nearest guardian. `docs/member-wallet-guarding-group.md`, D1. */ +val directGuardianChatRoomId: String get() = account.guardians.first().chatRoomId + +/** True when this group is the direct guardian. */ +val isGuardedHere: Boolean get() = position == 0 + +/** This group's child the wallet sits under, or null when this group guards it directly. */ +val branchChatRoomId: String? get() = lineage.takeIf { position > 0 }?.first() +``` + +The properties are defined for a subgroup's wallet too. Only a member's wallet +is drawn with them (D4, last point). + +**Tests**, in `commonTest`, beside `GuardianDerivationTest`, building the +example's two accounts with `GuardianDerivation`: +- R's Savings has direct guardian M, branch P and position 2; +- R's Rent has direct guardian N, branch N and position 1; +- M's own copy of Savings is `isGuardedHere`, with a null branch. + +--- + +## Phase 2 — naming from what is already here + +1. **`GuardianManager.foundingNameOf(database, roomId, parentRoomId, carried: Event? = null): String?`** + tries D3's sources in order. These are `carried`, then the 30329s + `groupSignedEventDao.getByChatRoomIdAndKind(parentRoomId, SubgroupBirthCertificateEvent.KIND)` + returns, then `roomId`'s `GroupKeyState.birthCertificateJson`, then the + certificates embedded in 30331 notices authored by `roomId`. It returns the + first `parseName` of a certificate that passes `certifies(cert, roomId, parentRoomId)`. +2. **`GuardedSubject.Member` gains `guardianName: String?` and `branchName: String?`**, + filled in `GuardianManager.named` beside `ownerName`. The name follows D2: + founding name, then `chatRoomDao().findChatRoomById(id)?.chatRoom?.subject`, + then null. Every caller of `guardedWalletsOf` gets the names for free, and no + composable does a lookup. That matches what the member-wallets note set out + for `ownerName`. +3. The branch is named the same way. Its parent is this group, so the first + source always answers. + +No query is new. `GroupSignedEvent` is indexed on `chatRoomId`, and one parent's +30329s are a handful of rows. + +**Tests**, in `jvmTest`, `MemberWalletGuardianJvmTest`-shaped, with an +in-memory database: +- a device in R and P names M from P's signed 30329; +- a device in R only, with no notice for M's own wallet, gets `guardianName == null` + and `branchName == "P"`; +- a 30329 for M signed by a room other than P is ignored; +- a renamed M (a new `subject` on a device in M) still shows the founding name. + +--- + +## Phase 3 — the notice carries the certificate (D4, D5) + +1. **`GuardedWalletNoticeEvent`** gains `certificateOf(notice): Event?`, which + reads the tag and verifies nothing, matching `statementOf`. Its kdoc diagram + gets the tag. +2. **`GuardianManager.share`** takes `certificate: Event?` and writes + `["certificate", json]` after the `h` tag when one is given. +3. **`Shareable` gains `certificate: Event?`.** `shareableFrom(G)` fills it: + - for G's own member certificates, from `GroupKeyState.birthCertificateJson` + for G, which every device in G holds; + - for wallets passed on a generation further, from the notice they came in + on, so an R-and-P device forwarding to a great-grandparent hands it on. +4. **`guardedWalletsOf`** keeps each told row's tags, so the read becomes a pair + of statement and carried certificate. When duplicates are folded, the copy with + a certificate that checks out wins. That certificate goes to + `foundingNameOf` as `carried`. +5. **`alreadyTold`** follows D5. +6. **`GuardianManager.describeNotice`** is unchanged. The line names the member, and + the guardian is on the wallet screen. + +**Mixed versions.** An older forwarder copies `content` only, so the tag is lost +at that hop. The next hop up then falls back to Phase 2's sources. Nothing is +believed less than before. + +**Tests**, in `jvmTest`: +- a notice carrying M's 30329 lets a device in R only name M; +- a notice carrying a 30329 that certifies a different room, or one signed by a + room other than `guardians[1]`, is ignored for the name, and the wallet is still + listed; +- a notice with no tag, from today's build, is still believed; +- `shareableFrom` offers a room told before Phase 3 again when this device has a + certificate, and does not when it has none; +- forwarding R ← P ← M keeps the tag at both hops. + +--- + +## Phase 4 — the state: wallets by person + +In `GroupWalletUIState.kt`, beside `GuardedWalletRow`: + +```kotlin +/** One member's wallets as an ancestor's list gathers them -- D6. */ +data class PersonGuardedWallets( + val ownerPublicKey: HexKey, + val ownerName: String?, + /** Nearest first, then by guardian name. */ + val rows: List, +) { + val guardianCount: Int get() = rows.map { it.wallet.directGuardianChatRoomId.lowercase() }.distinct().size +} + +/** [rows]' member wallets by person, people by name; subgroup rows are left out. */ +fun List.byPerson(): List +``` + +The `Loaded` and `NotOpened` states keep `guardedWallets` as they are, because +spend and fund still look rows up by it. The screen calls `byPerson()` on them. +There is no second field to keep in step while the chain flow redraws. + +**Tests**, extending `GuardedWalletRowTest`: +- the example's two rows give one person with `guardianCount == 2`, Rent before + Savings; +- two wallets under one guardian give `guardianCount == 1`; +- subgroup rows are not in the result; +- people sort by name, falling back to key. + +--- + +## Phase 5 — the group's wallet screen + +In `GroupWalletScreen.guardianItems`: + +1. Subgroup rows render as they do now. Member rows are replaced by a + *Members' wallets* sub-heading (`titleSmall`) and, for each + `PersonGuardedWallets`: + - **a header `ListItem`**: `ProfileAvatar` leading, `@alice` headline, and a + supporting line from two new plurals, + `n_guarded_wallets` and `guarded_by_n_groups`, joined with `s_dot_s` or a + comma string. Tapping it opens `ProfilePreviewRoute`, as rows in the group + page's *Members' guarded wallets* already do. It uses + `Modifier.clickable { … }.minimumInteractiveComponentSize()`. + - **one `GuardedWalletCard` per wallet**, indented under the header by + `MaterialTheme.spacing.containerPadding`. Its headline and guardian line + follow D6. +2. **New strings**, in sentence case, in `strings.xml`: + `guarded_by_this_group`, `guarded_by_s_below_s` ("Guarded by %1$s, below %2$s"), + `a_group_below_s` ("A group below %1$s"), `members_wallets`, and the two + plurals. `guarded_by_s` already exists. +3. **The buttons' descriptions name the wallet, not the person.** + `fund_s_s_guarded_wallet` and `spend_from_s_s_guarded_wallet` today take + `guardedName`, which is `@alice` for all of Alice's wallets. A new + `guardedWalletName(row)` gives `@alice · Savings`, or `@alice · guarded by #M` + for an unlabelled wallet. The descriptions use it, so each of a person's + buttons is heard differently. +4. **The spend and fund screens name it the same way.** `GuardedWallet.displayName` + feeds `Spender.Guardian.name` and `ProposedSpend.nameOf`. For a member's + wallet with a label, it becomes `@alice · Savings`, so the proposal a signer + approves says which of Alice's wallets is being spent from. This is display + text only. The signed proposal identifies the wallet by its guarded tag + (`FrostSigningEvents.parseGuarded`), as it does today. + +M3: spacing from `MaterialTheme.spacing`, colour from roles, the avatar's size as +a dimension. `readableContent()` is already on the list's root. + +**Tests**, extending `GuardedWalletCardJvmTest`: +- the example draws one `@alice` header reading *2 wallets, guarded by 2 groups*, + with *Guarded by #N* and *Guarded by #M, below #P* beneath it; +- an unlabelled wallet's headline is its guardian line; +- the four buttons have four different content descriptions; +- a wallet R guards directly reads *Guarded by this group*. + +--- + +## Phase 6 — the person's page (D7) + +1. `MemberWalletManager.guardedByGroupsHere` keeps its signature. A pure + `byWallet()` over its result groups rows by `wallet.descendantChatRoomId` + (that is, `W`) into: + ```kotlin + data class GuardedHereWallet(val walletId: String, val label: String?, val guardianName: String?, val holders: List) + ``` + Holders are ordered nearest first, by `position`. +2. `PersonGuardedWalletsViewModel.rows` becomes `List`. +3. `ProfilePreviewScreen.GuardedByYourGroups` draws one block per wallet: + - the headline is the label, or the guardian line; + - the supporting line is *Guarded by #M*; + - one line per holder: *#P: after 144 blocks, about 1 day* (`guardian_after`, + `delayText`), with *Spend* trailing where `canSpend`; + - each *Spend* is described as *Spend from Savings as #P*, which is a new + string. +4. `guarded_by_s` keeps its meaning. It now names the direct guardian, which is + what its words always said. + +**Tests**, extending `MemberWalletPagesJvmTest`: +- a device in P and R shows Savings once, guarded by M, with two holders; +- Rent shows once, guarded by N, with R as its only holder; +- a holder without a share has no *Spend*. + +--- + +## Phase 7 — docs, the audit, and by hand + +- **This note**: *Built*, plus a table of where the build chose differently. + Done. +- [member-guarded-wallets.md](./member-guarded-wallets.md): Phases 10 and 11 get + a pointer here. Phase 11's *Guarded by #Ekklesia* is changed to say that the + holder now appears on the holder's own line. +- [group-wallet-guardians.md](./group-wallet-guardians.md): under *How an + ancestor finds the coins*, a sentence on the notice's `certificate` tag. +- [README.md](./README.md): the row. + +```bash +./gradlew :composeApp:m3Audit +``` + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +By hand, on signet, with the example's tree and three emulators: + +1. Alice asks M for Savings and N for Rent. Both are certified. +2. A member in M and P shares Savings into P, and a member in P and R shares it + into R. A member in N and R shares Rent into R. +3. On a device in R **only**, R's wallet screen shows one `@alice` header, + *2 wallets, guarded by 2 groups*, with *Guarded by #N* and *Guarded by #M, + below #P*. The names come from the carried certificates, since this device is + in neither M nor N. +4. Repeat step 2's forward into R from a build before Phase 3. The card reads + *Guarded by a group below #P*. +5. On a device in P and R, Alice's profile shows Savings once, with #P and #R as + holders, and Rent once, with #R. +6. TalkBack on step 3: each *Fund* and *Spend* names its wallet. + +--- + +## Order and size + +| phase | touches | ships | +|---|---|---| +| 1 | three properties on `GuardedWallet` | dark | +| 2 | `foundingNameOf`, `GuardedSubject.Member` names | dark | +| 3 | the notice's tag, `share`, `shareableFrom`, `alreadyTold` | **early**: the sooner notices carry it, the fewer rows fall back | +| 4 | `byPerson`, pure | dark | +| 5 | the group's wallet screen | **the visible change** | +| 6 | the person's page | any time after 2 | +| 7 | docs, audit, run | last | + +Phases 1 to 3 change nothing a person sees. Phase 3 is worth landing before 5, so +that by the time the names are drawn, the notices sent in between already carry +them. Phases 5 and 6 are independent of each other. + +--- + +## What this does not do + +**It does not name a subgroup's wallet's parent.** A `#Translation` row could +read *below #P* by the same rule, using `branchChatRoomId`. That is a one-line +follow-up once Phase 5's strings exist, and is left out to keep this plan to the +question it answers. + +**It does not draw the tree.** Distance and branch are enough to tell the cards +apart. A diagram of R's descendants would need every intermediate room's name, +and D3 gives no guarantee of those below the branch. + +**It does not show a member wallet the ancestor was never told of.** An ancestor +sees what was forwarded to it. If Alice has a third wallet under a group whose +members never shared it upward, it is not in R's list and the count is two. The +header counts *wallets this group guards*, not *wallets Alice has*. Its wording +says so. + +**It does not make the name part of what is signed.** The founding name helps a +person read the row. A wrong one, or a missing one, never changes which leaf this +group signs, or whether it can. + +--- + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| the live room name first | two members of R would see different words for one row, and subgroup rows in the same list already use founding names | +| the guardian's name in the 30334 | it is fixed when the member asks, and an ancestor would trust M's word about M's own name. The birth certificate is the parent's word, which is the one the list already relies on | +| putting the whole chain of 30329s on the notice | it names every room between this group and the guardian, but costs one certificate per generation on every hop. This group always knows the branch, and the branch plus the guardian is enough to tell cards apart | +| a separate *Members* tab on the wallet screen | it splits one question, "what can this group reach", across two places. The sub-heading keeps it on one list | +| one card per person, wallets as rows inside it | each wallet has its own *Fund* and *Spend*, and four buttons in one card is the crowding `guarded-wallet-funding.md` Phase 5 moved them out of the trailing slot to avoid | diff --git a/docs/mls-skipped-keys.md b/docs/mls-skipped-keys.md index ca7a533f..e59c3741 100644 --- a/docs/mls-skipped-keys.md +++ b/docs/mls-skipped-keys.md @@ -112,6 +112,9 @@ Several flows publish in bursts, and each of them is a reliable trigger: | `MantraDao.addArtifact` | the artifact, then its first version | | `MantraDao.addChapter` | the chapter, then one per paragraph chunk | +*The two `MantraDao` rows are history: the documents were removed +([ceremony-creation.md](./ceremony-creation.md)).* + `addChapter` is the worst of these: a chapter with twenty paragraphs publishes twenty-one events at once, and only the ones that happen to arrive in ascending generation order survive. diff --git a/docs/npub-profile-preview.md b/docs/npub-profile-preview.md index a7ba285f..4bbe26f1 100644 --- a/docs/npub-profile-preview.md +++ b/docs/npub-profile-preview.md @@ -96,7 +96,7 @@ Almost all of it. The preview is a new screen over pieces that exist. | a kind 0 arriving overwrites the placeholder row | [NostrDao.kt:424](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt) | the observed flow emits it | | the stack shape for "a profile becomes a chat": push the room, pop the profile | [BennuNavHost.kt:1706](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt), `NostrEventDetailRoute`'s DM exit | copied | | `ProfileAvatar`, `humanReadableNameOrPubkey()`, `staticIdentifier()`, `hexToNpubHrp()` | `Profile.kt`, `Credentials.kt` | built | -| a constant app bar with the state transition inside it | [GroupNostrProfileScreen.kt:106](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt) | the layout to copy | +| a constant app bar with the state transition inside it | `GroupNostrProfileScreen`, since removed with the group's nostr profile | the layout to copy | | `LoadingDataIndicator(text = …)`, `EmptyState(message, icon, action)`, `ErrorState(onRetry)`, `NavigateBackButton`, `LocalCanSign` | `widgets/` | built | | strings: `profile`, `try_again`, `start_chat`, `send_message` | `strings.xml` | present; the new ones are listed per phase | diff --git a/docs/shared-key-ceremony.md b/docs/shared-key-ceremony.md index bb1b79a2..8b806220 100644 --- a/docs/shared-key-ceremony.md +++ b/docs/shared-key-ceremony.md @@ -135,6 +135,35 @@ and orders each round's messages by their sender's host key to match. Sorting is the only ordering every device can arrive at without being told. Nothing in the protocol checks this, so `ChillDkgRitualOrderingTest` does. +## Where a ceremony starts, and how one ends early + +A ceremony is started in exactly three places, each of which knows what it is +for: group creation (`SelectChatRoomTypeViewModel`) for a new group's own key, +the subgroup picker (`SelectSubgroupAdminsViewModel`) for a subgroup's, and +`CreateSharedKeyScreen` for an existing NIP-17 group that has no key yet. +`CeremonyEntryPointsJvmTest` counts them. `DkgRitualScreen` shows one ceremony, +named by its route, and never starts one: it used to, from the same button slot +its approvals used, and a member coming back from approving a subgroup's +ceremony opened a second, whole-room one in the parent's room. A Marmot room +cannot hold a ceremony of its own at all -- `proposeRitual` refuses and +`acceptProposal` drops one -- since its id is derived from the key it already +has. See [ceremony-creation.md](./ceremony-creation.md). + +A failed ceremony is tried again from the screen that starts its kind: the +creation screen for a group's own, the subgroup picker, filled in from the one +that failed, for a subgroup's. + +Any participant can **abandon** a running ceremony from its screen, which +broadcasts the same 30316 a fault does and ends it for everyone; nobody outside +the ceremony can, and a 30316 from a non-participant is ignored. ChillDKG has no +"no" short of this, and without it a ceremony opened by mistake could only be +left running. + +The kinds above travel in both transports: gift wraps for a group's own +ceremony, Marmot inner events in the parent's room for a subgroup's. In the +second, 30310-30312 once collided with document kinds that shared the numbers, +and `ChatMessage` now recognises a ceremony's kinds before any content kind. + ## After it completes The group has a threshold public key; each device keeps its own share, restorable diff --git a/docs/subgroup-wallet-policy.md b/docs/subgroup-wallet-policy.md new file mode 100644 index 00000000..0a722414 --- /dev/null +++ b/docs/subgroup-wallet-policy.md @@ -0,0 +1,695 @@ +# The parent decides: a subgroup's wallet policy, fixed at birth + +Today a subgroup's parent agrees to *guard* it — it signs guardian keys into the +child's birth certificate — and the child decides whether to use them: its wallet +screen offers a guarded wallet and a plain one beside it, and whichever statement +its quorum signs is the wallet. This plan moves that decision up one level and +forward to the moment the child is made. **The parent's coordinator chooses +*guarded* or *unguarded* on the subgroup picker, the parent's quorum signs the +choice into the birth certificate, the child's admins agree to it by joining, and +every honest device thereafter offers, signs, derives and watches only the wallet +the certificate allows.** + +Read [subgroups.md](./subgroups.md) and +[group-wallet-guardians.md](./group-wallet-guardians.md) first. This builds on the +certificate from the first and the guardian keys from the second, and it reverses +one section of the second — [*whose choice it is*](./group-wallet-guardians.md#what-this-reverses-and-whose-choice-it-is). + +**Built**, phases 1-9, one commit each, written against the code as it stood at +`b4002804`, schema v28; the build is schema v29. `SubgroupWalletPolicy`, +`SubgroupBirthCertificateEvent.parseWalletPolicy`, `SubgroupManager.walletPolicyOf`, +`refuseCertificate` and `refuseKeyState` are the entry points. The phases below +are kept as written, line references included, which have since moved; where the +build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 2: a migration test like the other bumps have | none. The manual migrations have tests; the nullable auto-migrations, 24→25, 25→26 and 27→28, have none, and 28→29 is one of them. The in-memory databases every jvmTest opens run at v29 | +| Phase 2: `proposeRitual` takes the policy | it also checks it first. A policy on a ceremony with no parent is refused before the running-ceremony lookup, which would otherwise hand back an existing ceremony for a question that should never have been asked | +| Phase 3: the picker reads the parent's policy | through `ChatRepository.walletPolicyOf` and `guardiansOf`, both new; the picker's view models talk to repositories, not managers. The policy refusals come before the key-package wait in `refusal()`, since they do not depend on it | +| Phase 3: a test that `confirm` passes the policy to `proposeRitual` | not written. `confirm` needs an `Identity` with a private key and settled key packages, and the tests cover the state it passes instead | +| Phase 4: `DkgRitualViewModel` passes `session.walletPolicy` | `proposeBirthCertificate` reads it off the ceremony it is already handed. A caller naming the policy would be a caller choosing what the parent signs, for the reason the key is read off the ceremony too | +| Phase 5: the child-signer check sits beside the certificate check | it is `SubgroupManager.refuseKeyState`, called from there and from `proposeSubgroupKeyState`, so the proposer refuses what every other child signer would | +| Phase 6: `account` is null under a guarded policy | `NotOpened.offersPlain`. A null `account` already meant "a room with no key" and hides the way in altogether, so the guarded button would have gone with it | +| Phase 6: `GroupWalletManager.walletPolicyFor` | arrived in Phase 7, where `walletFor` needed it. The wallet screen reads `ChatRepository.walletPolicyOf`, the same `SubgroupManager.walletPolicyOf` underneath | +| Phase 7: `GuardianManager.guardedFrom` | `GuardianManager.verify`, the function that believes a forwarded statement | +| Phase 8: *guarded* or *unguarded* added to the supporting line | a second line under it, on the subgroup rows and on the parent row. An undecided certificate shows nothing | + +Still to do by hand: the three-emulator run in Phase 9. + +--- + +## What the parent can and cannot decide + +The guardians note says it plainly and it stays true: + +> The child's threshold key is the child's. Its quorum can always pay to a plain +> BIP86 address under its own key, and no script in any address can stop it. + +So "the parent decides" cannot mean a cryptographic rule. What it can mean, and +what this plan builds, is a **signed rule every honest client enforces at every +point it touches a wallet**: + +| point | what enforcing the policy means there | +|---|---| +| offering | the child's wallet screen shows only the opening the certificate allows | +| proposing | `GroupWalletViewModel.openWallet` cannot build the other template | +| signing | every member's device refuses a wallet statement proposal that contradicts the policy, before it is shown — the same place a mismatched certificate grant is refused today | +| reading | `GroupWallet.newestAmong` ignores a statement that contradicts the policy, so no honest device derives, watches, or proposes a spend from it | + +A quorum of modified clients can still sign whatever it likes with the child's +key. Nothing short of a covenant changes that, and the UI must never describe the +policy as more than it is. What changes is that the child's *members*, running +this app, can no longer open the wallet the parent ruled out — and that a +coordinator cannot quietly swap the choice, because three parties sign over it. + +### Who agrees to what + +The subgroups note settled a pattern for the threshold — "the one value the +coordinator picks *for other people*" — and this follows it exactly: + +1. **the coordinator picks** the policy on `SelectSubgroupAdminsScreen`, beside + the threshold; +2. **the child's admins agree** by joining: the policy rides on the ceremony + proposal and is shown at the `HOST_KEY` gate (`DkgJoinApprovalScreen`), so + nobody joins a group whose wallet the ancestors can take from without having + been told; +3. **the parent's quorum signs it** into the birth certificate, and the proposal + screen says it in words; +4. **the child's quorum signs it again** when it signs a key state carrying that + certificate, and each child signer's device refuses a certificate whose policy + differs from the one its ceremony announced. + +Step 4 is what stops a second parent admin, resuming the flow after the +coordinator's phone died, from certifying the child under a policy its admins +never agreed to. + +--- + +## Phase 0 — decisions, before any code + +Five, each with a recommendation except D4, which is decided. The phases below +assume the recommended answer; where another answer changes a phase the decision +says which. + +### D1. Which choices does the picker offer? + +**Recommended: two — *guarded* (the default) and *unguarded*.** The certificate's +reading has a third state anyway, *undecided*, for every certificate signed +before this ships; that state keeps today's behaviour, both buttons. Offering +*undecided* in the picker as well ("let the subgroup decide") is a one-line +change once Phase 1 exists, and is worth adding only if somebody asks for it: the +point of the feature is that the parent stops delegating this. + +### D2. What does *unguarded* put in the certificate? + +**Recommended: no guardian keys at all**, plus the policy tag saying so. + +- It is enforced by code that already exists. `verifiedAgainst` refuses a guarded + statement whose guardians are not the certificate's, and a certificate with + none makes every guarded statement fail. Old clients enforce it too, which no + other choice here can say. +- Its cost is that the line of guardians **stops at the unguarded child**. + `SubgroupManager.grantFor` reads the parent's own certificate for the keys to + pass down; an unguarded child has none, so its own children receive only its + key. The root reaches nothing below an unguarded branch. Under D4 such a branch + can only start below a group that is not itself guarded, so a root that makes + its children guarded keeps its reach into the whole tree. + +The alternative is to keep the keys in the certificate and have the tag say +*unguarded*. That keeps the root's reach into the grandchildren while ruling out +the child's own guarded wallet. It costs a new rule in `verifiedAgainst`, and old +clients would offer a guarded wallet the parent forbade, because they see keys +and no tag they read. D4 takes away most of the reason to choose it: a root that +wants to reach everything makes its children guarded, and D4 then carries that to +every group beneath them. + +### D3. Can the parent change its mind? + +**Recommended: no — the policy is fixed at birth.** A certificate is replaceable +by `d` tag, but the child's key state carries the certificate it was born with, +and the guardians note's rule 2 already fixes an account's guardian set at its +first statement. Changing policy is therefore a new subgroup. This matches the +request ("at the time the child group is being created") and is named again +under [what this does not do](#what-this-does-not-do). + +### D4. Does a guarded group have to make guarded children? + +**Decided: yes.** A group whose own certificate reads `Decided(GUARDED)` can +only make guarded subgroups. Guarded is therefore inherited all the way down: +once a group is guarded, every group beneath it is guarded too, and every +ancestor above the first guarded group keeps its leaf in every wallet in that +subtree. A middle group cannot take a branch out of the root's reach by making +an unguarded child. + +The rule needs no new tag and no inheritance machinery. The constraint is read +off the parent's own verified certificate, which every parent signer already +holds because `grantFor` reads it. It is enforced in two places: + +- **the picker** (Phase 3) does not let a guarded parent's coordinator choose + *unguarded*; +- **every parent signer** (Phase 4) refuses a certificate from a guarded group + whose policy is not *guarded*. The picker can be skipped by a coordinator; the + signers cannot. + +What the rule reads, exactly: + +| the parent's own certificate | the child may be | +|---|---| +| `Decided(GUARDED)` | guarded only | +| `Decided(UNGUARDED)` | guarded or unguarded | +| `Undecided`, from before this | guarded or unguarded | +| none — a root group | guarded or unguarded | + +**An undecided parent is not constrained**, even when its certificate carries +guardian keys. Nobody decided anything for it: its own parent offered to guard +it and left the choice to it, and it may have opened a plain wallet. Treating +"keys present" as "guarded" would decide on the parent's behalf something its +own ancestors never signed. A group that wants its whole subtree guarded starts +that subtree with a decided certificate. + +An unguarded group may make a guarded child. That child is guarded by its +unguarded parent, and by nothing above it, because D2's unguarded certificate +carries no keys to pass on. Guarded subtrees therefore start at a root, at an +undecided group or at an unguarded group, and run to the leaves. + +### D5. What does a root group's wallet screen do? + +**Unchanged: a plain wallet.** A group with no parent has no certificate and +nobody to guard it. The policy is only ever read off a verified birth +certificate. + +--- + +## Phase 1 — the policy, pure + +New, in `nostr/subgroup/`: + +```kotlin +enum class SubgroupWalletPolicy { GUARDED, UNGUARDED } + +/** What a certificate says about the child's wallet. */ +sealed interface WalletPolicyReading { + data class Decided(val policy: SubgroupWalletPolicy) : WalletPolicyReading + /** No policy tag: a certificate from before this, which leaves it to the child. */ + data object Undecided : WalletPolicyReading +} +``` + +**`WalletPolicyTag`** in `nostr/subgroup/tags/`, in `GuardianTag`'s shape: + +``` +["wallet", "guarded" | "unguarded"] +``` + +`SubgroupBirthCertificateEvent` grows: + +- `assembleTags(..., walletPolicy: SubgroupWalletPolicy?)` — written after the + guardian tags; null writes none, which only an older build's path should take; +- `parseWalletPolicy(tags): WalletPolicyReading?` — null when the reading is + unusable: a `wallet` tag that does not read, two of them, or a policy that + contradicts the guardian tags beside it. **`GUARDED` requires a non-empty, + readable guardian list; `UNGUARDED` requires none** (under D2). A certificate + that says one thing in its policy and another in its keys is not a thing to + guess the meaning of. + +**`certifies` does not change.** It is about lineage, and its six questions stay +six. The policy is read where it is used, like the guardian keys are. + +**Tests**, `SubgroupBirthCertificateEventTest`: a guarded certificate round-trips; +an unguarded one round-trips with no guardian tags; a certificate with no `wallet` +tag reads `Undecided`; `guarded` with no keys, `unguarded` with keys, two +`wallet` tags, and `["wallet", "maybe"]` each read null; and a certificate with a +policy still `certifies`, so the policy cannot break lineage. + +One commit. Nothing produces the tag yet. + +--- + +## Phase 2 — the ceremony carries the choice + +The coordinator chooses before the ceremony, but the certificate is proposed +after it, possibly by somebody else — any parent admin holding a share can resume +the flow, which is why every step reads stored rows. So the choice travels the +way the subgroup's name already does: on the ceremony proposal, onto +`DkgSession`. + +- `DkgRitualEvents`: write and parse a `wallet` tag on a ceremony proposal + (`WalletPolicyTag` reused), beside `parseSubject` and `parseParentChatRoomId`. +- `ChillDkgRitualManager.proposeRitual` — both overloads, at `:197` and `:1445` — + take `walletPolicy: SubgroupWalletPolicy?`, required non-null when + `parentChatRoomId` is set. +- `acceptProposal` (`:412`) files it on the session, and drops a proposal that + carries a policy but no parent: a policy for a group nobody is the parent of is + a bug, and the ceremony is the cheapest place to refuse it. +- **Schema 28 → 29**: `DkgSession.walletPolicy: String?`. Null for every + ceremony before this and for every non-subgroup ceremony; nothing reads it but + the certificate rung. A migration adding a nullable column, with the migration + test the other bumps have. + +**Tests**: a proposal round-trips its policy onto the session; a subgroup +proposal from an older build (no tag) files null; a parentless proposal carrying +a policy is dropped. + +--- + +## Phase 3 — the picker, and the join gate + +### `SelectSubgroupAdminsScreen` + +A *Wallet* section under the threshold stepper, two radio rows in one +`selectableGroup`, *guarded* selected by default: + +| choice | headline | supporting line | +|---|---|---| +| guarded | Guarded wallet | This group and the `N` above it can spend its coins once they are 12 blocks old | +| unguarded | Unguarded wallet | Only the subgroup can spend from its wallet. Groups above it cannot reach it or anything beneath it | + +Since [guardian-delay.md](./guardian-delay.md), the guarded row no longer quotes +12: under it the coordinator chooses the delay on this group's own leaf, from 6 to +65,535 blocks, and each group above keeps the delay it chose. + +`N` is the count of the parent's own guardians (`SubgroupManager.guardiansOf`), +so the line names the reach the parent is actually granting rather than "the +groups above". The second sentence of the unguarded line is D2's cost; drop it if +D2 goes the other way. + +### The parent's own policy, read once + +The picker is the first thing that needs to know the parent's policy, so this +phase adds the one reader the later phases reuse: + +```kotlin +/** What [chatRoomId]'s own verified certificate says of its wallet; null for a room with none. */ +suspend fun walletPolicyOf(database: BennuDatabase, chatRoomId: String): WalletPolicyReading? +``` + +It goes on `SubgroupManager` beside `guardiansOf`, and like it reads the +certificate off the verified key state. Phase 4's signer check and Phase 6's +`GroupWalletManager.walletPolicyFor` both call it, so the picker, the signers and +the wallet screen cannot disagree about what a group is. + +`SelectSubgroupAdminsUIState.Loaded` carries the result as +`parentPolicy: WalletPolicyReading?`, read once in `initiate()` beside the +parent room. + +### A guarded parent's picker + +When `parentPolicy` is `Decided(GUARDED)`, D4 leaves one choice. The section +still shows both rows rather than hiding the one that cannot be picked, because +the reason is something the coordinator needs to know about their own group: + +- *guarded* is selected and cannot be changed; +- *unguarded* is shown disabled, with its supporting line replaced by the reason: + *This group is guarded, so its subgroups are too*. + +Hiding the row would make the picker look the same as an older build's, where +nobody chose anything. Showing it disabled, with the reason, says that a decision +was made and who made it. + +Rules, each one the picker's because the ceremony fixes everything after it: + +- the choice goes into `SelectSubgroupAdminsViewModel` as + `walletPolicy: MutableState`, and `confirm` passes it to + `proposeRitual`; +- `setWalletPolicy(UNGUARDED)` does nothing under a guarded parent. The state is + never able to hold a choice the screen would show as disabled; +- `prefillFromRetry` (`:123`) restores it from the failed session, as it already + restores the name and threshold. It is coerced to *guarded* under a guarded + parent, the way the threshold is coerced into `quorumRange()`. The failed + session can predate the parent's own certificate, so the restored value can + disagree with what the parent now is; +- `refusal()` refuses *unguarded* under a guarded parent, with the same reason the + row shows. `confirm` runs `refusal()` again, so a state that got past the + screen is still stopped before a ceremony is proposed; +- **guarded is refused when the parent cannot grant**: `grantFor` returns null + when the parent's own certificate carries keys this build cannot read, and + today that is discovered at the certificate step, after a full ceremony. Add it + to `refusal()` and disable the row with the reason. It cannot coincide with a + guarded parent: Phase 1 reads a `guarded` policy with unreadable keys as null, + and Phase 5 drops the key state that would carry it, so a parent whose policy + reads `Decided(GUARDED)` always has keys this build can read; +- guarded is offered while `GroupWalletRollout.offersGuardiansOn` is true for + some network, which it is for all of them today. If the mainnet gate is ever + shut again, say on the row that a guarded subgroup will have no wallet on + mainnet until it opens — the policy is network-agnostic and the gate is not. + +CLAUDE.md applies in full: strings in `strings.xml` in sentence case with `%1$d` +for `N`, spacing from `MaterialTheme.spacing`, colour from roles, the rows +`minimumInteractiveComponentSize`, `Decorative` on any icon beside a label. + +### `DkgJoinApprovalScreen` + +One line under the threshold line the screen already shows: *Its wallet will be +guarded by the group above it and N more* or *Its wallet will not be guarded*. +Read off the session's `walletPolicy`; a ceremony with none shows nothing. This +is the child admins' consent, and it is the only place they see the choice +before their device is committed to a ceremony with it. + +**Tests**: +- `SelectSubgroupAdminsViewModel` passes the chosen policy to `proposeRitual`; +- a retry restores the policy; +- guarded is refused with a reason for a parent whose certificate carries + unreadable keys; +- under a guarded parent: + - the state starts at *guarded* and `setWalletPolicy(UNGUARDED)` leaves it + there; + - a retry of an unguarded session restores as *guarded*; + - `refusal()` names the reason if the state is forced to *unguarded*; +- under an unguarded parent, an undecided parent and a root group, both choices + are open. + +--- + +## Phase 4 — the certificate carries the policy + +### Proposing + +`SubgroupManager.proposeBirthCertificate` takes `walletPolicy: +SubgroupWalletPolicy?`, and `DkgRitualViewModel.proposeBirthCertificate` (`:370`) +passes `session.walletPolicy` — off the session, not a route, for the reason the +name is: whoever resumes has no route. + +| session's policy | parent's own policy | guardian tags | `wallet` tag | +|---|---|---|---| +| `GUARDED` | any | `grantFor(...)`, as today | `guarded` | +| `UNGUARDED` | not guarded | none | `unguarded` | +| `UNGUARDED` | `Decided(GUARDED)` | refused, nothing proposed | — | +| null (an older build's ceremony) | not guarded | `grantFor(...)`, as today | none — the child decides, as today | +| null (an older build's ceremony) | `Decided(GUARDED)` | `grantFor(...)` | `guarded` | + +The two rows with a guarded parent are D4 at the proposer. + +**An unguarded session under a guarded parent is refused with a reason.** +`proposeBirthCertificate` reads `SubgroupManager.walletPolicyOf` for the parent +and throws *this group is guarded, so its subgroups are too*. Every signer would +refuse the certificate anyway, so proposing it would only cost a quorum's +attention. The picker stops this in Phase 3, so it is reached only by: +- a picker that was skipped or had a bug; +- a coordinator whose device held no verified key state for the parent when the + picker opened. `walletPolicyOf` then read null, and the picker treated the + parent as a root group. The certificate is proposed later, possibly from + another device that does hold the parent's key state. + +The subgroup is stranded either way: its ceremony has fixed `unguarded`, and +Phase 5's child signers will refuse any certificate that says otherwise. The +error message tells the coordinator to start the subgroup again. It does not +offer to certify the subgroup as guarded instead, because the subgroup's admins +joined on the understanding that it would be unguarded. + +**An older build's ceremony under a guarded parent is certified as guarded.** +That ceremony carried no policy, so none of its admins was shown one. *Guarded* +is the only certificate the parent's signers will accept. Certifying it as +undecided would hand the child the plain button that D4 exists to remove, and +Phase 5's child check does not apply to a session with no policy, so nothing +downstream would stop it. + +### Every parent signer checks it + +`SubgroupManager.refuseGrant` becomes `refuseCertificate` and grows the policy, +called where it is today (`FrostSigningManager.kt:567`), before anything is +shown. The signing group is `rebuilt.pubKey`, the parent, and its own policy +comes from `walletPolicyOf` on this device's own verified key state, never from +the proposal: + +- the policy reading is null → *carries a wallet policy that does not read*; +- the signing group's own policy is `Decided(GUARDED)` and the certificate's + reading is anything but `Decided(GUARDED)` → *would make an unguarded + subgroup of a guarded group*. This includes `Undecided`, so an older + proposer's certificate with no `wallet` tag is refused under a guarded parent. + That is deliberate: an undecided child gets the plain button, which is the + thing D4 forbids. This check runs first, before the key check below; +- `GUARDED` → the keys must equal `grantFor`, exactly today's check; +- `UNGUARDED` → no keys (Phase 1's parse already says so; restated here so the + refusal names it); +- `Undecided`, under a parent that is not guarded → today's check, unchanged, so + certificates from older proposers are still signable. + +**Where this check reaches, and where it does not.** It is binding on every +signer running a build that has it. A parent signer on an older build does not +read the tag and signs whatever its key check allows. A guarded group should +therefore not make subgroups until every member of it who can sign is on a build +from Phase 4 onward. It is the mixed-version risk again, placed one level up. + +### What the parent's admins read + +`ProposedEvent`'s certificate summary (`text/ProposedEvent.kt:50`) states the +policy in both directions. The guarded line exists — *this group and the one +above it can spend from its wallet* — and gains *, and it cannot open a wallet +without that*; the unguarded case gains its own line, *its wallet will not be +guarded*. An absent line is not a decision anybody can be said to have read, so +the unguarded certificate must say so rather than say nothing. + +**Tests**: +- each row of the proposing table, including the throw for an unguarded session + under a guarded parent; +- a guarded certificate with a swapped key, an unguarded certificate with a key, + and an unreadable policy are each refused; +- an undecided certificate from an older proposer is still accepted under an + undecided, unguarded or root parent; +- under a guarded parent, signers refuse: + - an unguarded certificate; + - an undecided one. + + The second case is the one a reviewer will want to loosen, and the test is + there to fail if anyone does; +- the parent's own policy is read from the signer's key state. A proposal from a + coordinator whose device saw no parent certificate is still refused by a + signer whose device has one. + +--- + +## Phase 5 — the child agrees, and the key state keeps it + +### Child signers refuse a swapped policy + +The child's key state is signed in the parent's room by the child's quorum, and +it carries the certificate. Beside the certificate check in +`FrostSigningManager`'s proposal path, add one for a `GroupKeyStateEvent` +proposal: when this device's `DkgSession` for the ceremony has a `walletPolicy`, +the carried certificate's policy must be `Decided` with the same value. A +mismatch drops the proposal with *carries a certificate whose wallet policy is +not the one this group was made under*. + +This is the step-4 consent from [who agrees to what](#who-agrees-to-what), and +it is what makes the picker's choice binding on whoever proposes the certificate. + +### The verified key state + +`GroupKeyStateManager.parentageOf` drops a state whose certificate's policy +reads null, in the same way it drops one whose parent tags disagree. The +subgroups note learned this the hard way with `claimsParentage`: a tag present +and unreadable must never look like a tag absent, or a corrupt policy reads as +*undecided* and hands the child both buttons. + +**Tests**: a key state whose certificate says `unguarded` under a ceremony that +announced `guarded` is refused by a child signer; a key state carrying an +unreadable policy is dropped by `stateFrom`; one carrying a certificate with no +policy is still adopted. + +--- + +## Phase 6 — the child's wallet screen follows it + +`GroupWalletManager` grows the one place a room's policy is read: + +```kotlin +/** What [chatRoomId]'s verified certificate allows it to open. */ +suspend fun walletPolicyFor(database: BennuDatabase, chatRoomId: String): WalletPolicyReading? +``` + +This delegates to Phase 3's `SubgroupManager.walletPolicyOf`, which reads the +same verified key state `guardedAccountFor` reads. It is null for a room with no +certificate, a root group (D5), which opens plain as today. + +`GroupWalletUIState.NotOpened` gains the reading, and +`GroupWalletViewModel.initiate` (`:87`) fills `account` and `guarded` from it: + +| policy | `account` (plain) | `guarded` | +|---|---|---| +| `GUARDED` | null | the guarded opening | +| `UNGUARDED` | the plain account | null | +| `Undecided` | the plain account | the guarded opening — today | +| none (root) | the plain account | null | + +`OpenWalletAction` (`GroupWalletScreen.kt:340`) then needs only one new branch: +with a decided policy it shows one button and a line naming who decided — +*The group above this one decided its wallet is guarded*, or *…is not guarded*. +The comment at `:355` that calls being guarded "the group's own choice" is +rewritten for the undecided case only, which is now the only case it describes. + +`openWallet(guarded = false)` returns early when `account` is null, as +`openWallet(guarded = true)` already does when `guarded` is — no new guard, only +the state no longer offering what the policy forbids. + +**Tests**, `GroupWalletViewModelJvmTest`: each row of the table above, the +existing `guardedRepository` fixture extended with a policy tag. + +--- + +## Phase 7 — every member enforces it + +The screen only stops this device from proposing. This phase stops the room +accepting. + +### Signing + +`FrostSigningManager`'s proposal path, beside the certificate check: a +`GroupWalletStatementEvent` proposal in a room whose policy is decided is refused +when its guardedness contradicts it — *opens an unguarded wallet, and this +group's parent decided it is guarded*, and the converse. Refused before it is +shown, for the reason a mismatched id is: a member should not be asked to approve +something their device already knows the room has ruled out. + +### Reading + +`GroupWallet.newestAmong` takes the policy, and before its two existing rules +drops every statement that contradicts it. `GroupWalletManager.walletFor` and +the other callers of `newestAmong` pass `walletPolicyFor(...)`. + +Under `GUARDED` this is stronger than today's rule 1. Rule 1 only lets a guarded +statement outrank a plain one; this makes a plain statement nothing at all, even +when no guarded one exists. So a plain statement signed by older clients in a +guarded-only child opens no wallet on any new device — no addresses derived, no +coins watched, and every spend from it refused at `GroupSpend.check`'s caller +because `walletFor` returns null. Under `UNGUARDED` (with D2) nothing new is +needed: a guarded statement cannot verify against a certificate with no keys. + +### Ancestors + +`GuardianManager.guardedFrom` already refuses a statement whose certificate does +not grant its guardians. Add the policy: an ancestor ignores a forwarded +statement whose own certificate contradicts it. It cannot arise from an honest +child, and it costs one line to stop a modified one from showing up in the +ancestor's *Guarded wallets* list. + +**Tests**, jvmTest in the shape of `GroupWalletViewModelJvmTest` and +`GuardianSigningJvmTest`: a plain statement proposed in a guarded-only room is +refused by every signer; a plain statement already stored in a guarded-only room +opens no wallet and a spend proposed against it is refused; an undecided room +behaves exactly as today, both rules included. + +--- + +## Phase 8 — showing the decision from above + +Small, and the reason the parent's members can see what they decided: + +- `ChatRoomDetailScreen`'s subgroup rows (`:260`, `:317`) add *guarded* or + *unguarded* to their supporting line, read off the certificate. It is a fact + about the founding, like the name and roster, and is rendered as one. +- The child's parent row says the same, read off the verified key state. + +--- + +## Phase 9 — docs, and checking it on the emulators + +- [group-wallet-guardians.md](./group-wallet-guardians.md): rewrite *What this + reverses, and why it is still the child's choice*, now *whose choice it is* — the parent now decides, the + child agrees by joining, and the paragraph saying "the parent cannot impose + this" keeps its cryptographic half and loses its policy half. Its *What this + does not do* gains a pointer here. +- [subgroups.md](./subgroups.md): the certificate's tag list gains `wallet`, and + the consent section's paragraph on the threshold gains the policy as the second + value the coordinator picks for other people. +- [README.md](./README.md): this note's row and a sentence on reading order. +- This note: *Built*, and a table of where the build chose differently. + +By hand, regtest, three emulators. The root makes two subgroups: a **guarded** +one, `M`, and an **unguarded** one, `U`. Then: + +1. `M`'s join screen and the root's certificate proposal both say *guarded*. + `U`'s both say *unguarded*. +2. `M`'s wallet screen offers one button, guarded. `U`'s offers one, plain. +3. **D4, at the picker.** `M`'s *add subgroup* picker shows *guarded* selected + and *unguarded* disabled with its reason. `M` makes a child `C`. `C`'s + certificate carries `M`'s key and the root's key one step further, and the + root's *Guarded wallets* list shows both `M` and `C`, the latter once + forwarded. +4. **D4, at the signers.** From `M`, propose an unguarded certificate directly. + This needs a debug build or a test hook, since the picker will not do it. + Every `M` signer's device drops it, and the reason is in the log. +5. **No downward rule under an unguarded parent.** `U`'s picker offers both + choices. `U` makes a guarded child, whose certificate carries only `U`'s key + (D2). The root's list does not show it. +6. A legacy subgroup made on the previous build still offers both buttons, and + so does its own picker. + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +--- + +## Order and size + +| phase | touches | ships | +|---|---|---| +| 1 | `nostr/subgroup/` and its test | dark — nothing writes the tag | +| 2 | DKG proposal tags, `DkgSession`, schema 29 | dark — nothing sets the policy | +| 3 | picker and join gate | **the switch**: the first phase a user can reach | +| 4 | certificate proposal and parent signer check | with 3 | +| 5 | key state, child signer check | with 3 | +| 6 | the child's wallet screen | with 3 | +| 7 | signing and reading statements | before or with 3 | +| 8 | detail screens | any time after 4 | +| 9 | docs and the emulator run | last | + +Phases 1, 2 and 7 can land before anybody can choose anything, and 7 should: +it is the one that makes a decided policy binding on a device that did not draw +the screen, so it wants to be on every member's phone before the first decided +certificate exists. Phases 3-6 go out together — a picker whose choice the +certificate did not carry would be a choice that meant nothing. + +--- + +## What this does not do + +**It does not make the policy cryptographic.** The child's key is the child's; a +quorum of modified clients can sign a plain statement in a guarded-only room, or +pay its coins anywhere. Every honest client refuses to take part, and that is the +whole of the guarantee. The UI says *decided*, never *cannot*. + +**It does not close the mixed-version risk for guarded-only children.** A child +member on a build older than Phase 7 sees keys and no tag it reads, offers both +buttons, and will sign a plain statement. New devices ignore that wallet +entirely, so coins paid to its addresses are watched only by the old ones. That +is today's risk in a new place, and the remedy is the same: everybody in a +guarded subgroup on a build that reads the policy. Unguarded children (D2) do not +have it. + +**It does not touch subgroups that already exist.** Their certificates read +*undecided* and keep both buttons. A fresh certificate cannot change that: the +key state carries the certificate the child was born with (D3). + +**It does not reach back into existing trees.** D4 binds only groups whose own +certificate is decided *guarded*, and none exists until this ships. A subtree +made before this keeps undecided groups, and an undecided group may still make +an unguarded child, which ends its ancestors' reach (D2). A root that wants its +whole tree guarded has to start new subgroups. + +**It does not let a group step out of a guarded subtree.** That is D4 working as +intended, and it is permanent: a guarded group's subgroups are guarded, theirs +are too, and no quorum below the first guarded certificate can change that. A +group that needs an unguarded wallet has to be made from somewhere outside that +subtree. + +**It does not give the parent a say over accounts.** A policy covers every +network and every account of the child's wallet; there is no "account 0 +guarded, account 1 not". + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| the policy only on the ceremony proposal | the parent's quorum never signs it, so it is the coordinator's word; and a member welcomed later, who holds no ceremony, cannot read it. The certificate is the only artefact that is both parent-signed and carried on every guarded statement | +| a separate parent-signed policy event | a second thing to disagree with the certificate, and one the statement would have to carry beside it | +| *unguarded* as keys present and a tag saying not to use them | D2's alternative: keeps the root's reach below the child, at the price of a new rule in `verifiedAgainst` and old clients offering a wallet the parent forbade | +| enforcing it in the address | there is no script that stops a key-path spend, and no covenant on mainnet to restrict where coins go | +| a separate policy *for descendants*, signed beside the child's own | D4 reads the constraint off the parent's own policy instead. A second tag would let a group be guarded while allowing unguarded children, or the reverse. That is two values to keep consistent, for a case nobody has asked for | +| treating an undecided parent with guardian keys as guarded | it would decide for a legacy group something its own ancestors left to it, and that group may already have opened a plain wallet | +| no downward rule: a guarded group may make an unguarded child | the first draft of D4. It lets any middle group cut the root out of a branch, which defeats the point of the root guarding the middle group | diff --git a/docs/subgroups.md b/docs/subgroups.md index c8fc3193..027262cf 100644 --- a/docs/subgroups.md +++ b/docs/subgroups.md @@ -164,9 +164,14 @@ tags: ["subgroup_key", ] ["frost_path", "m/9420/0/0"] ["name", ] + ["wallet", "guarded" | "unguarded"] since subgroup-wallet-policy.md; absent before ["p", ] ``` +A member's guarded wallet is not a subgroup and never a 30329: every reader of +this kind assumes a room. It has its own certificate, 30334 -- +[member-guarded-wallets.md](./member-guarded-wallets.md). + With those, a parent admin's device can check the thing that actually matters before it signs — `marmotGroupId(subgroup_key, frost_path) == content` — and `ProposedEvent` can render "Translation team, for Alice, Bob and Carol" rather @@ -800,6 +805,12 @@ proposal outside it, and the `HOST_KEY` gate is where each of them agrees to the `t`-of-`n` they can now see. Joining is the agreement; the coordinator only writes down what is being joined. +The subgroup's wallet policy, *guarded* or *unguarded*, is the second value the +coordinator picks for other people, and it is agreed to the same way: it rides on +the proposal, the join gate shows it, the parent's quorum signs it into the +certificate, and the child's quorum refuses a key state whose certificate says +otherwise. See [subgroup-wallet-policy.md](./subgroup-wallet-policy.md). + Confirm stays disabled below two selections, and below a threshold outside the range, with the reason stated rather than left to be guessed. @@ -907,6 +918,12 @@ second is refused rather than silently returning the first's key. ## Phase 10 — the ceremony moves into the parent's room +*Followed up by [ceremony-creation.md](./ceremony-creation.md): with the +ceremony in the parent's room, the shared-key screen's "Start key ceremony" +offered a whole-room ceremony there, and a failed subgroup was retried as one. +A Marmot room now refuses a ceremony of its own, and a failed subgroup is tried +again from this picker, filled in from the ceremony that failed.* + The thing [Phase 4](#why-not-the-parents-marmot-room) deferred, done, because the reason to wait was `docs/mls-skipped-keys.md` and that is being fixed. The child's ChillDKG and its key state now run in the parent's Marmot room on group events; @@ -1021,8 +1038,11 @@ is wanted, is the button. **A subgroup cannot sign for its parent, and the parent cannot sign for it.** Two independent keys, two independent quorums. The certificate is a claim about lineage, not a delegation of authority, and nothing in this design lets one group -act as the other. If delegation is ever wanted it is a different mechanism and it -should not be built on top of this one silently. +act as the other. Delegation is a different mechanism, and it was built as one: +[group-wallet-guardians.md](./group-wallet-guardians.md) lets a parent guard a +child's wallet, but only when the parent's quorum signs guardian keys into the +certificate *and* the child's quorum opens a guarded wallet naming them. The +certificate on its own still delegates nothing. **A member added to the parent later sees no subgroups, and a member added to the subgroup later cannot verify its parent.** One cause, two faces, and both are the