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 16142902..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": "1e74428a4c91d18f88a395a4add76229",
+ "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, `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 )",
+ "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",
@@ -908,11 +908,6 @@
"columnName": "walletPolicy",
"affinity": "TEXT"
},
- {
- "fieldPath": "guardianDelay",
- "columnName": "guardianDelay",
- "affinity": "INTEGER"
- },
{
"fieldPath": "stage",
"columnName": "stage",
@@ -2799,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 )",
@@ -4573,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, '1e74428a4c91d18f88a395a4add76229')"
+ "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/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 05ed982a..72877f8e 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -473,6 +473,14 @@
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
@@ -525,6 +533,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.
@@ -606,4 +615,71 @@
- about %1$d year
- about %1$d years
+
+
+ New guarded wallet
+ A group
+ Choose a group to guard it
+ You're in no groups that could guard a wallet for you.
+ 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.
+ 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
+ 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
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 9113e272..b3ee9ed8 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
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.database
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
@@ -78,6 +79,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
@@ -135,6 +138,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
MarmotPublishObligation::class,
MarmotOutboundGate::class,
MarmotRetainedEpochSecret::class,
+ MemberWallet::class,
+ MemberWalletSpend::class,
Mention::class,
NegentropySynchronizeRequest::class,
NegentropySynchronizeResult::class,
@@ -153,7 +158,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
- version = 30,
+ version = 31,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -355,10 +360,16 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// 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 adds the nullable DkgSession.guardianDelay: the delay a guarded
+ // 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 = 29, to = 30),
+ AutoMigration(from = 30, to = 31),
]
)
@ConstructedBy(BennuDatabaseConstructor::class)
@@ -395,6 +406,8 @@ abstract class BennuDatabase: RoomDatabase() {
abstract fun groupTransactionDao(): GroupTransactionDao
+ abstract fun memberWalletDao(): MemberWalletDao
+
abstract fun connectionDao(): ConnectionDao
abstract fun giftWrapMessageDao(): GiftWrapMessageDao
@@ -462,6 +475,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/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/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt
index 129fe10c..f1394197 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
@@ -12,6 +12,10 @@ 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
@@ -465,6 +469,17 @@ data class ChatMessage(
*/
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"
+
/**
* Every line the group signed, for the one check the transcript
* dispatches on. A type missing from here renders as a chat bubble,
@@ -480,6 +495,8 @@ data class ChatMessage(
TYPE_GROUP_TRANSACTION_CONFIRMED,
TYPE_GUARDED_WALLET_SHARED,
TYPE_GUARDIAN_SPEND,
+ TYPE_MEMBER_WALLET_REQUESTED,
+ TYPE_MEMBER_WALLET_GUARDED,
)
/**
@@ -980,6 +997,24 @@ data class ChatMessage(
return null
}
+ // 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,
+ chatRoomId = groupEventResult.groupId,
+ request = event,
+ userPublicKey = activeKeyPair.pubKey.toHex(),
+ )
+
+ return null
+ }
+
applyInnerEvent(
database = database,
groupId = groupEventResult.groupId,
@@ -1098,6 +1133,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,
@@ -1232,6 +1271,50 @@ data class ChatMessage(
)
}
+ // 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_MEMBER_WALLET_REQUESTED,
+ marmotGroupEventId = marmotGroupEventId,
+ marmotInnerEventId = marmotInnerEventId,
+ senderPublicKey = senderPublicKey,
+ isUserMessage = isUserMessage,
+ chatRoomId = groupId,
+ createdAt = createdAt,
+ content = "@${memberName(database, reading.memberPublicKey)} asked this group to guard a wallet",
+ )
+ }
+
+ // 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
+
+ ChatMessage(
+ giftWrapPayloadId = null,
+ messageType = TYPE_MEMBER_WALLET_GUARDED,
+ marmotGroupEventId = marmotGroupEventId,
+ marmotInnerEventId = marmotInnerEventId,
+ senderPublicKey = senderPublicKey,
+ isUserMessage = isUserMessage,
+ chatRoomId = groupId,
+ createdAt = createdAt,
+ content = "This group now guards a wallet for @${memberName(database, verified.memberPublicKey)}",
+ )
+ }
+
// 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
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 f0ed7081..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
@@ -52,6 +52,11 @@ data class GroupTransaction(
* 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,
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/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt
index 1308606a..d31bd046 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
@@ -186,6 +186,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/DatabaseMemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt
new file mode 100644
index 00000000..69285390
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt
@@ -0,0 +1,134 @@
+package com.machankura.bennu.compose.database.repository
+
+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 =
+ database.chatRoomDao().getChatRoomListByUserPublicKey(ownerPublicKey)
+ .filter { it.chatRoom.mlsGroupState != null }
+
+ 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) {
+ val wallet = database.memberWalletDao().getById(walletId) ?: throw IllegalStateException("No key for $walletId here")
+ check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" }
+ MemberWalletManager.askAgain(database, wallet)
+ }
+
+ 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 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/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt
index ed490ee8..59eeffd6 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
@@ -6,6 +6,7 @@ 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
@@ -573,6 +574,23 @@ object FrostSigningManager {
}
}
+ // 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
@@ -674,7 +692,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}")
}
@@ -752,7 +770,7 @@ object FrostSigningManager {
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))) {
+ 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}")
}
@@ -882,7 +900,7 @@ object FrostSigningManager {
guarded.account to guarded.spender(thresholdPublicKey)
}
- val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender)) {
+ 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")
@@ -1054,7 +1072,26 @@ object FrostSigningManager {
?: return null
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) as? GroupSpend.Result.Ok)?.checked
+ 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)
+ }
}
/**
@@ -1083,6 +1120,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)
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 a843c700..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
@@ -199,16 +199,10 @@ object GroupWalletDerivation {
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.
@@ -219,7 +213,7 @@ object GroupWalletDerivation {
account = account,
extendedPublicKey = DeterministicWallet.ExtendedPublicKey(
publickeybytes = accountKey.value,
- chaincode = ByteVector32(chainCode),
+ chaincode = chainCode,
depth = 0,
path = KeyPath.empty,
parent = 0L,
@@ -229,6 +223,24 @@ object GroupWalletDerivation {
)
}
+ /**
+ * 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].
*
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
index 6c59c6ad..463b8e64 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt
@@ -10,6 +10,8 @@ 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.nostr.subgroup.tags.GuardianTag
import com.machankura.bennu.compose.wallet.GroupSpend
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
@@ -43,22 +45,48 @@ object 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,
+ ) : 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,
- /** The descendant's signed statement, whole. */
+ /**
+ * 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,
- /** The descendant's birth certificate, carried in the statement. */
+ /** 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)),
) {
- /** What the descendant's parent certified it as. The founding name: a rename does not reach it. */
- val name: String? get() = SubgroupBirthCertificateEvent.parseName(certificate.tags)
+ /** 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
@@ -77,7 +105,14 @@ object GuardianManager {
/** 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 = name)
+ GroupSpend.Spender.Guardian(position = position, lineage = lineage, thresholdPublicKey = thresholdPublicKey, name = displayName)
+
+ /** 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))
+ }
}
/**
@@ -97,6 +132,7 @@ object GuardianManager {
* a leaf this group cannot sign, whatever the statement calls it.
*/
fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching {
+ if (statement.kind == MemberWalletCertificateEvent.KIND) return verifyMember(statement, ancestorChatRoomId, ancestorThresholdPublicKey)
if (statement.kind != GroupWalletStatementEvent.KIND) return null
val descendantChatRoomId = statement.pubKey
if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null
@@ -129,6 +165,42 @@ object GuardianManager {
)
}.getOrNull()
+ /**
+ * [certificate] as a member's guarded wallet [ancestorChatRoomId] guards, or
+ * null when it is not one: the guarding group signed it over the member's
+ * own request (`MemberWalletCertificateEvent.verify`), and -- rule 4 of
+ * [verify] -- the key it names for the ancestor is the key the ancestor's
+ * guardian root reaches down the line of descent, which ends in the
+ * wallet's id where a subgroup's ends in its room.
+ */
+ private fun verifyMember(certificate: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching {
+ val verified = MemberWalletCertificateEvent.verify(certificate, certificate.pubKey) ?: return null
+ val account = verified.account
+
+ val lineage = GuardianDerivation.lineage(account.guardians, verified.walletId, 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 = verified.walletId,
+ statement = certificate,
+ account = account,
+ certificate = certificate,
+ lineage = lineage,
+ subject = GuardedSubject.Member(verified.walletId, verified.memberPublicKey, verified.label),
+ )
+ }.getOrNull()
+
+ /** [wallet] with its member's profile name, where this device knows one. */
+ private suspend fun named(database: BennuDatabase, wallet: GuardedWallet): GuardedWallet {
+ val member = wallet.subject as? GuardedSubject.Member ?: return wallet
+ val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey()
+ return wallet.copy(subject = member.copy(ownerName = name))
+ }
+
/**
* Every guarded wallet [ancestorChatRoomId] has been told about and can sign
* for, one per descendant account on each network.
@@ -143,10 +215,19 @@ object GuardianManager {
val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, ancestorChatRoomId) ?: return emptyList()
val order = compareBy({ it.openedAt }, { it.statement.id })
- return database.marmotInnerEventDao()
+ // 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 told = database.marmotInnerEventDao()
.getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND))
.mapNotNull { row -> Event.fromJsonOrNull(row.content) }
+ val signed = database.groupSignedEventDao()
+ .getByChatRoomIdAndKind(ancestorChatRoomId, MemberWalletCertificateEvent.KIND)
+ .map { it.toEvent() }
+
+ return (told + signed)
.mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) }
+ .map { named(database, it) }
.groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) }
.mapNotNull { (_, statements) ->
val first = statements.minWithOrNull(order) ?: return@mapNotNull null
@@ -169,9 +250,12 @@ object GuardianManager {
/** 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. */
+ /** 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,
)
/**
@@ -188,25 +272,37 @@ object GuardianManager {
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 }
- .map { it.statement to it.name }
- return (listOfNotNull(own) + passedOn).mapNotNull { (statement, name) ->
- val rooms = targetsFor(database, statement, excluding = chatRoomId)
- rooms.takeIf { it.isNotEmpty() }?.let { Shareable(statement, name, it) }
+ 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)
+ }
+
+ return candidates.mapNotNull { candidate ->
+ val rooms = targetsFor(database, candidate.statement, excluding = chatRoomId)
+ rooms.takeIf { it.isNotEmpty() }?.let { candidate.copy(rooms = it) }
}
}
+ /** The guardians [statement] names, nearest first: a subgroup's statement's, or a member wallet certificate's. */
+ private fun guardiansNamedIn(statement: Event): List = when (statement.kind) {
+ MemberWalletCertificateEvent.KIND -> GuardianTag.parseAll(statement.tags).orEmpty()
+ else -> GroupWalletStatementEvent.read(statement.tags, statement.content)?.guardians.orEmpty()
+ }
+
/**
* The guardian rooms of [statement] this device can post into and has not
* told it yet. Only Marmot rooms: a guardian is a group with a key, and a
* group with a key has an MLS room.
*/
private suspend fun targetsFor(database: BennuDatabase, statement: Event, excluding: String): List {
- val guardians = GroupWalletStatementEvent.read(statement.tags, statement.content)?.guardians.orEmpty()
-
- return guardians
+ return guardiansNamedIn(statement)
.map { it.chatRoomId }
.filterNot { it.equals(excluding, ignoreCase = true) }
.mapNotNull { database.chatRoomDao().findChatRoomById(it) }
@@ -341,7 +437,10 @@ object GuardianManager {
val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null
val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null
- return wallet.name?.let { "Shared the guarded wallet of $it with this group." }
- ?: "Shared a subgroup's guarded wallet with this group."
+ return when (val subject = named(database, wallet).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."
+ }
}
}
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..37dc6853
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
@@ -0,0 +1,657 @@
+package com.machankura.bennu.compose.managers
+
+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) }
+ }
+
+ /**
+ * 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) },
+ )
+ 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,
+ }
+
+ /** 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
+ }
+ return 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 default, and every
+ * group above it at the delay it chose -- `docs/guardian-delay.md`. The same
+ * list the grant in [request] carries. Null when this device does not know
+ * the group's key.
+ */
+ suspend fun delaysOf(database: BennuDatabase, chatRoomId: String): List? =
+ groupKeyFor(database, chatRoomId)?.let { key -> listOf(GuardianDerivation.DEFAULT_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()
+
+ val walletPrivateKey = MemberWalletDerivation.generate()
+ val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey())
+ val grant = GuardianDerivation.grant(groupKey.thresholdPublicKey, chatRoomId.lowercase(), groupKey.guardians, walletId)
+ 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,
+ )
+ 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 with the request [wallet] was asked with, unchanged -- for a
+ * request no signer put to the group, or one the group did not sign.
+ */
+ suspend fun askAgain(database: BennuDatabase, wallet: MemberWallet) {
+ val request = Event.fromJsonOrNull(wallet.requestJson) ?: throw IllegalStateException("The stored request does not read")
+ send(database, wallet.guardingChatRoomId, request)
+ sponsorIfSigner(database, wallet.guardingChatRoomId, wallet.ownerPublicKey, request)
+ }
+
+ /**
+ * 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?,
+ ) {
+ 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)
+ }
+ 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 ${cap.sat} sats while member wallets are new" }
+ }
+
+ 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.
+ */
+ 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 expected = runCatching { SubgroupManager.grantFor(database, chatRoomId, thresholdPublicKey, verified.walletId) }.getOrNull()
+ ?: return "grants keys this device cannot check"
+ return if (verified.account.guardians == expected) null else "grants guardian keys this group does not"
+ }
+
+ /**
+ * 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 guarding group's room name here. */
+ val guardianName: String?,
+ /** Whether this device holds a share of that group's key, and so can propose a spend through its leaf. */
+ val canSpend: Boolean,
+ )
+
+ 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/nostr/wallet/GroupKeyNoticeEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt
new file mode 100644
index 00000000..e35f563f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt
@@ -0,0 +1,125 @@
+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.
+ *
+ * ### 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"
+
+ /** 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 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) },
+ ).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.
+ */
+ 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
+ }
+
+ GroupKey(chatRoomId = chatRoomId.lowercase(), thresholdPublicKey = thresholdPublicKey, certificate = certificate)
+ }.getOrNull()
+}
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/MemberWalletRequestEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt
new file mode 100644
index 00000000..912edf7f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt
@@ -0,0 +1,232 @@
+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"
+
+ /** 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,
+ )
+
+ /** 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,
+ )
+
+ /**
+ * 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,
+ ): 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)) },
+ 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
+
+ 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,
+ )
+ }.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.
+ *
+ * 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
+
+ Verified(request = event, reading = reading, account = account)
+ }.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/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt
index 6c7bcdd9..846c48b3 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
@@ -263,6 +263,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>
@@ -352,6 +355,7 @@ interface FrostSigningRepository {
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/MemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt
new file mode 100644
index 00000000..318c874e
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt
@@ -0,0 +1,103 @@
+package com.machankura.bennu.compose.repository
+
+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. */
+ suspend fun askAgain(walletId: 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
+
+ /** 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) = Unit
+ 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 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/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt
index 7bdfaef5..55d759d8 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
@@ -3,6 +3,9 @@ package com.machankura.bennu.compose.text
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.frost.GroupKeyStateEvent
import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent
@@ -27,7 +30,12 @@ object ProposedEvent {
*/
data class Summary(val label: String, val detail: String)
- fun summarize(event: Event): Summary = when (event.kind) {
+ /**
+ * [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:
@@ -97,6 +105,35 @@ object ProposedEvent {
} ?: "A wallet statement 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.
+ 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 a95f079b..180fa4b6 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
@@ -4,6 +4,7 @@ import com.machankura.bennu.compose.wallet.GroupSpend
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
@@ -15,16 +16,29 @@ object ProposedSpend {
ProposedEvent.Summary(
// 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 from the group's wallet"
+ null -> spend.fundings.singleOrNull()?.takeIf { spend.payments.size == 1 }
+ ?.let { "Fund ${nameOf(it)}'s guarded wallet" }
+ ?: "Spend from the group's wallet"
else -> "Spend from ${guardian.name ?: "a subgroup"}'s guarded wallet"
},
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 ${nameOf(funding)}'s guarded wallet"
+ }
+ 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 ${nameOf(funding)}'s guarded wallet, address ${funding.derived.index}"
+ }
}
)
+ private fun nameOf(funding: GroupSpend.Funding): String = funding.wallet.displayName ?: "a subgroup"
+
/** 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/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt
index c65a494b..3a845706 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
@@ -2,6 +2,22 @@ package com.machankura.bennu.compose.ui.composable
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
@@ -13,7 +29,6 @@ import bennu.composeapp.generated.resources.open_on_s
import bennu.composeapp.generated.resources.not_opened_yet
import bennu.composeapp.generated.resources.group_wallet
import bennu.composeapp.generated.resources.s_onchain_wallet
-import androidx.compose.material.icons.filled.AccountBalanceWallet
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -47,7 +62,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
@@ -68,7 +82,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
@@ -156,6 +169,7 @@ fun ChatRoomDetailScreen(
initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading,
nostrRepository: NostrRepository,
chatRepository: ChatRepository,
+ memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP,
onNavigateToRoute: (Route) -> Unit,
onPopBackToRoute: (Route) -> Unit,
onNavigateBack: () -> Unit,
@@ -167,9 +181,11 @@ fun ChatRoomDetailScreen(
initialChatRoomDetailUIState = initialChatRoomDetailUIState,
nostrRepository = nostrRepository,
chatRepository = chatRepository,
- 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.
@@ -449,6 +465,59 @@ 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) {
+ item { HorizontalDivider() }
+ item {
+ Text(
+ text = stringResource(Res.string.members_guarded_wallets),
+ style = MaterialTheme.typography.labelMedium
+ )
+ }
+ 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()
}
@@ -1037,6 +1106,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.
*
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 a960db03..271fe401 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
@@ -2,7 +2,26 @@ 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.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
@@ -114,6 +133,7 @@ fun GroupSendScreen(
frostSigningRepository: FrostSigningRepository,
wallets: GroupOnchainWallets?,
guardedChatRoomId: String? = null,
+ fundChatRoomId: String? = null,
onNavigateToRouteAndPopUpInclusive: (Route) -> Unit,
onNavigateBack: () -> Unit,
) {
@@ -127,6 +147,7 @@ fun GroupSendScreen(
frostSigningRepository = frostSigningRepository,
wallets = wallets,
guardedChatRoomId = guardedChatRoomId,
+ fundChatRoomId = fundChatRoomId,
)
)
@@ -143,11 +164,17 @@ fun GroupSendScreen(
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.
- val guardian = ((groupSendViewModel.groupSendUIState as? GroupSendUIState.Ready)?.spender as? GroupSpend.Spender.Guardian)
+ // 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 = if (guardian == null) stringResource(Res.string.send_from_the_group_s_wallet)
- else stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup)),
+ text = when {
+ guardian != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup))
+ funded != null -> 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
)
@@ -179,78 +206,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())) }
- // Why a guardian's balance can be lower than the
- // wallet's: only coins past its own leaf's lock.
- groupSendViewModel.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 = 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,
@@ -286,18 +262,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,
)
@@ -312,7 +451,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,
)
@@ -321,11 +460,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 cbe8418d..00924465 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
@@ -8,6 +8,14 @@ import bennu.composeapp.generated.resources.the_group_above_decided_this_wallet_
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
@@ -84,6 +92,7 @@ import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet
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
@@ -201,6 +210,18 @@ fun GroupWalletScreen(
)
)
}
+ // 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,
+ )
+ )
+ }
val onShare = { shareable: GuardianManager.Shareable ->
groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) })
}
@@ -304,6 +325,8 @@ fun GroupWalletScreen(
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,
)
}
}
@@ -347,6 +370,7 @@ fun GroupWalletScreen(
isPending = groupWalletViewModel.isActionPending.value,
onShare = onShare,
onSpend = if (state.canSign && state.canWatch) toGuardianSpend else null,
+ onFund = if (state.canSign && state.canWatch) toGuardianFund else null,
)
}
}
@@ -447,6 +471,7 @@ private fun OpenWallet(
isPending: Boolean,
onShare: (GuardianManager.Shareable) -> Unit,
onSpend: ((GuardedWalletRow) -> Unit)?,
+ onFund: ((GuardedWalletRow) -> Unit)?,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
@@ -612,6 +637,7 @@ private fun OpenWallet(
isPending = isPending,
onShare = onShare,
onSpend = onSpend,
+ onFund = onFund,
)
}
}
@@ -669,6 +695,7 @@ private fun LazyListScope.guardianItems(
isPending: Boolean,
onShare: (GuardianManager.Shareable) -> Unit,
onSpend: ((GuardedWalletRow) -> Unit)?,
+ onFund: ((GuardedWalletRow) -> Unit)?,
) {
if (guardedWallets.isNotEmpty()) {
item {
@@ -682,28 +709,7 @@ private fun LazyListScope.guardianItems(
)
}
items(guardedWallets, key = { "guarded-" + it.wallet.statement.id }) { row ->
- ListItem(
- leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) },
- headlineContent = { Text(row.wallet.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) },
- supportingContent = {
- Column {
- Text(
- row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) }
- ?: stringResource(Res.string.balance_not_known_yet)
- )
- // 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)))
- }
- },
- trailingContent = onSpend?.let { spend ->
- {
- TextButton(onClick = { spend(row) }) {
- Text(stringResource(Res.string.spend))
- }
- }
- },
- )
+ GuardedWalletCard(row = row, onSpend = onSpend, onFund = onFund)
}
}
@@ -713,7 +719,15 @@ private fun LazyListScope.guardianItems(
}
items(shareable, key = { "shareable-" + it.statement.id }) { candidate ->
ListItem(
- headlineContent = { Text(candidate.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ 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) {
@@ -750,8 +764,86 @@ private fun GuardianDelays(
}
}
+/**
+ * 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 BalanceCard(walletState: GroupWalletState?) {
+private fun GuardedWalletCard(
+ row: GuardedWalletRow,
+ onSpend: ((GuardedWalletRow) -> Unit)?,
+ onFund: ((GuardedWalletRow) -> Unit)?,
+) {
+ val name = guardedName(row.wallet.subject)
+ 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(name, 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)
+ }
+ // A member's label says which of their wallets it is.
+ val label = (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.label
+ Column {
+ Text(label?.let { stringResource(Res.string.s_dot_s, it, amounts) } ?: 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) {
+ val fundLabel = stringResource(Res.string.fund_s_s_guarded_wallet, name)
+ val spendLabel = stringResource(Res.string.spend_from_s_s_guarded_wallet, name)
+ 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))
+ }
+ }
+ }
+ }
+ }
+}
+
+/**
+ * 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),
@@ -778,7 +870,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/MemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
new file mode 100644
index 00000000..fe23a852
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
@@ -0,0 +1,402 @@
+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.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,
+ )
+ )
+ }
+ if (wallet.state != WalletState.SIGNING) {
+ item {
+ OutlinedButton(
+ onClick = { viewModel.askAgain(onAsked = {}, onFailure = { notify(couldNotAskAgain) }) },
+ enabled = !viewModel.isActionPending.value,
+ ) { Text(stringResource(Res.string.ask_again)) }
+ }
+ 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..e02cce7f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt
@@ -0,0 +1,248 @@
+package com.machankura.bennu.compose.ui.composable
+
+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.you_are_in_no_groups_that_can_guard_a_wallet
+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.you_are_in_no_groups_that_can_guard_a_wallet),
+ 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
+ }
+)
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..1814fa9e 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,19 @@
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.managers.GuardianManager
+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.s_dot_s
+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 +28,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 +59,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 +103,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 +208,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(
+ rows = personWalletsViewModel.rows,
+ onSpend = { row ->
+ onNavigateToRoute(
+ GroupSendRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ chatRoomId = row.wallet.ancestorChatRoomId,
+ relayHint = null,
+ guardedChatRoomId = row.wallet.descendantChatRoomId,
+ )
+ )
+ },
+ )
+ }
}
}
@@ -223,6 +262,33 @@ fun ProfilePreviewScreen(
}
}
+/**
+ * The person's guarded wallets as this profile's groups hold them: one row per
+ * guarding group, and -- where this device holds a share of that group's key --
+ * the way to spend through its leaf, which is the guardian spend the group's
+ * wallet screen already offers.
+ */
+@Composable
+private fun GuardedByYourGroups(
+ rows: List,
+ onSpend: (MemberWalletManager.GuardedHere) -> Unit,
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ Text(stringResource(Res.string.wallets_your_groups_guard), style = MaterialTheme.typography.titleMedium)
+ rows.forEach { row ->
+ val guardian = stringResource(Res.string.guarded_by_s, row.guardianName ?: stringResource(Res.string.a_group))
+ val label = (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.label
+ ListItem(
+ leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) },
+ headlineContent = { Text(label?.let { stringResource(Res.string.s_dot_s, it, guardian) } ?: guardian) },
+ trailingContent = if (row.canSpend) {
+ { TextButton(onClick = { onSpend(row) }) { 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/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt
index 7ea98d38..9825b82a 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
@@ -139,6 +139,13 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
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
@@ -208,6 +215,13 @@ fun BennuNavHost(
)
}
+ val databaseMemberWalletRepository = remember {
+ DatabaseMemberWalletRepository(
+ database = auxDatabaseManager.auxDatabase,
+ activeIdentity = sovereignWalletViewModel.activeIdentity,
+ )
+ }
+
val databaseMarmotRepository = remember {
DatabaseMarmotRepository(
database = auxDatabaseManager.auxDatabase,
@@ -909,6 +923,8 @@ fun BennuNavHost(
)
},
signOut = signOutOfReadOnlyIdentity,
+ memberWalletRepository = databaseMemberWalletRepository,
+ wallets = groupOnchainWallets,
)
}
composable { backStackEntry ->
@@ -1065,6 +1081,7 @@ fun BennuNavHost(
relayHint = route.relayHint,
nostrRepository = databaseNostrRepository,
chatRepository = databaseChatRepository,
+ memberWalletRepository = databaseMemberWalletRepository,
onNavigateToRoute = { actionRoute ->
navController.navigate(
route = actionRoute
@@ -1146,6 +1163,50 @@ 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()
+
+ NewMemberWalletScreen(
+ activeUserPublicKey = route.activeUserPublicKey,
+ chatRoomId = route.chatRoomId,
+ chain = NodeParamsManager.chain,
+ canWatch = groupOnchainWallets != null,
+ memberWalletRepository = databaseMemberWalletRepository,
+ onNavigateBack = {
+ navController.popBackStack()
+ }
+ )
+ }
composable { backStackEntry ->
val route = backStackEntry.toRoute()
@@ -1170,6 +1231,7 @@ fun BennuNavHost(
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.
@@ -1309,6 +1371,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/GroupSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt
index b18b67d2..55d19763 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
@@ -6,6 +6,10 @@ import kotlinx.serialization.Serializable
* 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(
@@ -13,4 +17,5 @@ data class GroupSendRoute(
val chatRoomId: String,
val relayHint: String?,
val guardedChatRoomId: String? = null,
+ val fundChatRoomId: String? = null,
): Route()
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberSendRoute.kt
new file mode 100644
index 00000000..116b0ad3
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberSendRoute.kt
@@ -0,0 +1,10 @@
+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 MemberSendRoute(
+ val activeUserPublicKey: String,
+ val walletId: 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/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt
index 7fa3d7ec..7b61abca 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
@@ -841,6 +842,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
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 ee05f2fb..0e4f879e 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
@@ -24,6 +24,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,
@@ -32,6 +35,8 @@ class ChatRoomDetailViewModel(
initialChatRoomDetailUIState: ChatRoomDetailUIState,
val nostrRepository: NostrRepository,
val chatRepository: ChatRepository,
+ /** 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)
@@ -98,11 +103,38 @@ class ChatRoomDetailViewModel(
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 && memberWalletRepository.refusal(chatRoomId, NodeParamsManager.chain).let {
+ it == null || it == MemberWalletManager.Refusal.KEY_UNKNOWN
+ },
+ canSponsor = canSign,
)
}
}
}
+ /**
+ * 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
@@ -215,6 +247,7 @@ class ChatRoomDetailViewModel(
initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading,
nostrRepository: NostrRepository,
chatRepository: ChatRepository,
+ memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
ChatRoomDetailViewModel(
@@ -224,6 +257,7 @@ class ChatRoomDetailViewModel(
initialChatRoomDetailUIState = initialChatRoomDetailUIState,
nostrRepository = nostrRepository,
chatRepository = chatRepository,
+ memberWalletRepository = memberWalletRepository,
)
}
}
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 9ed8509f..65c2b098 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
@@ -20,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
@@ -32,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
@@ -54,6 +56,8 @@ class GroupSendViewModel(
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)
@@ -77,20 +81,29 @@ class GroupSendViewModel(
return@launch
}
+ // 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 guarded = guardedChatRoomId?.let { descendant ->
- chatRepository.guardedWallets(chatRoomId).firstOrNull {
- it.descendantChatRoomId.equals(descendant, ignoreCase = true) && it.chain == chain
- }
+ 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
}
@@ -102,6 +115,7 @@ class GroupSendViewModel(
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
@@ -111,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 })
}
}
@@ -126,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 }
}
}
@@ -196,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, state.spender)
+ GroupSpendBuilder.sendAll(walletState, destination, feerate, state.reserved, state.spender)
} else {
- GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange, state.spender)
+ GroupSpendBuilder.send(walletState, destination, amount, feerate, state.reserved, state.reservedChange, state.spender)
}
return GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(chain))
}
@@ -250,11 +286,12 @@ class GroupSendViewModel(
frostSigningRepository: FrostSigningRepository,
wallets: GroupOnchainWallets?,
guardedChatRoomId: String? = null,
+ fundChatRoomId: String? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupSendViewModel(
activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState,
- chatRepository, frostSigningRepository, wallets, guardedChatRoomId,
+ chatRepository, frostSigningRepository, wallets, guardedChatRoomId, fundChatRoomId,
)
}
}
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..751e64b9
--- /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()?.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)
+ 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/MemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
new file mode 100644
index 00000000..0241d2ca
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
@@ -0,0 +1,151 @@
+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.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,
+ val walletId: String,
+ initialUIState: MemberWalletUIState,
+ private val memberWalletRepository: MemberWalletRepository,
+ private val wallets: GroupOnchainWallets?,
+) : ViewModel() {
+ private val logger = Logger.withTag(TAG)
+
+ 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)
+ // 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) {
+ 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)
+ val resent = if (confirmations == null) {
+ runCatching { wallets.broadcast(tx) }.getOrNull()?.let { Clock.System.now() }
+ } else null
+ memberWalletRepository.recordChain(spend.txid, confirmations, broadcastAt = resent)
+ }
+ }
+
+ fun askAgain(onAsked: () -> Unit, onFailure: () -> Unit) = act(onAsked, onFailure) {
+ 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..6c24786c
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt
@@ -0,0 +1,129 @@
+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)) }
+ )
+ 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 {
+ 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..fcc13d8f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/PersonGuardedWalletsViewModel.kt
@@ -0,0 +1,39 @@
+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*. 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() {
+ var rows: List by mutableStateOf(emptyList())
+ private set
+
+ fun initiate() {
+ viewModelScope.launch(Dispatchers.IO) { rows = 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/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt
index be72765e..cf98a65a 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,5 +1,6 @@
package com.machankura.bennu.compose.ui.view.state
+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
@@ -91,6 +92,16 @@ 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,
): ChatRoomDetailUIState
data class Error(
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 b5b0969e..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,6 +1,8 @@
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
@@ -25,6 +27,8 @@ sealed interface GroupSendUIState {
* 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. */
@@ -34,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 b59d2c7b..b74ea910 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
@@ -92,6 +92,19 @@ data class GuardedWalletRow(
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()
+ }
}
/** Where one of the room's spends has got to, as one fact a member reads. */
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/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..d679350f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/NewMemberWalletUIState.kt
@@ -0,0 +1,33 @@
+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, each with why it cannot guard a wallet, 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/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 0e34b15e..51889918 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
@@ -90,6 +90,19 @@ class GroupOnchainWallets(
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) {
+ electrum.broadcastTransaction(tx)
+ }
+
+ /** How deep [tx] is: 0 in the mempool, null while Electrum has not heard of it or cannot be asked. */
+ suspend fun confirmationsOf(tx: Transaction): Int? = runCatching { electrum.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 22204027..871bf960 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,6 +2,7 @@ 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
@@ -149,6 +150,12 @@ object GroupSpend {
*/
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
@@ -173,6 +180,59 @@ 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
@@ -298,6 +358,19 @@ object GroupSpend {
.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.
@@ -336,12 +409,18 @@ object GroupSpend {
* 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" }
@@ -354,11 +433,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")
}
}
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 b4725d19..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
@@ -27,11 +27,28 @@ import fr.acinq.lightning.utils.sum
* [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,
@@ -40,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
@@ -72,8 +91,18 @@ object GroupSpendBuilder {
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, address) ?: return Result.NotAnAddress
+ 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()
@@ -82,7 +111,7 @@ object GroupSpendBuilder {
if (amount < DUST) return Result.BelowDust
val tx = transaction(state, coins, listOf(TxOut(amount, script)), spender)
- return Result.Built(psbtOf(state, tx, coins, change = emptyMap()), amount, fee, change = null)
+ return Result.Built(psbtOf(state, tx, coins, change = emptyMap(), funded), amount, fee, change = null, funded = funded)
}
/**
@@ -98,8 +127,20 @@ object GroupSpendBuilder {
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, spender).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend }
@@ -116,7 +157,7 @@ object GroupSpendBuilder {
if (leftover >= DUST) {
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)), amount, withChange, leftover)
+ 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.
@@ -124,8 +165,9 @@ object GroupSpendBuilder {
if (total - amount >= withoutChange) {
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,
)
}
}
@@ -148,17 +190,20 @@ 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) },
)
}
@@ -191,9 +236,17 @@ object GroupSpendBuilder {
private fun lockOf(state: GroupWalletState, spender: GroupSpend.Spender): Long? =
(spender as? GroupSpend.Spender.Guardian)?.let { state.account.guardians[it.position].delay }
- private fun scriptOf(state: GroupWalletState, address: String): ByteVector? =
- Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, address.trim()).right
+ /**
+ * 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(state: GroupWalletState, coins: List, outputs: List, spender: GroupSpend.Spender) = Transaction(
version = 2,
@@ -226,6 +279,15 @@ object GroupSpendBuilder {
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/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt
index 3970edca..bb192e65 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
@@ -43,4 +43,25 @@ object GroupWalletRollout {
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 are offered one from
+ * the start. Shut until a three-level hierarchy has watched one member's
+ * wallet on signet and its root has made a guardian spend from it: the
+ * member's own spend is the first single-signer path this app has.
+ *
+ * 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 = false
+
+ fun offersMemberWalletsOn(chain: Chain): Boolean = MEMBER_WALLETS_ON_MAINNET || !chain.isMainnet()
+
+ /**
+ * The most a member's own spend from their guarded wallet may send on
+ * [chain]: [MAINNET_CAP] on mainnet until [MEMBER_WALLETS_ON_MAINNET] lifts,
+ * since the member's spend is signed by a path no group spend goes through.
+ */
+ fun memberCapFor(chain: Chain): Satoshi? = capFor(chain).takeIf { !MEMBER_WALLETS_ON_MAINNET }
}
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/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/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..08f8f12b
--- /dev/null
+++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt
@@ -0,0 +1,82 @@
+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.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)
+ }
+}
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/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/managers/GroupFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt
new file mode 100644
index 00000000..05ca1340
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt
@@ -0,0 +1,221 @@
+package com.machankura.bennu.compose.managers
+
+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))
+ }
+
+ /**
+ * [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)),
+ ): Event = signedAsRoom(
+ material = parent,
+ kind = SubgroupBirthCertificateEvent.KIND,
+ tags = SubgroupBirthCertificateEvent.assembleTags(
+ subgroupChatRoomId = roomOf(child),
+ parentChatRoomId = roomOf(parent),
+ thresholdPublicKey = thresholdKeyOf(child),
+ adminPublicKeys = admins,
+ name = "#Child",
+ 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..f3e4961f
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt
@@ -0,0 +1,139 @@
+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.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(asking.groupKeyStateDao().getByChatRoomId(groupRoom), "an answer is never filed as key state")
+ assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "nothing left to ask")
+ }
+
+ @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/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
index 8fc815db..7bedbf2c 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
@@ -580,6 +580,9 @@ class GuardianSigningJvmTest {
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
@@ -677,4 +680,131 @@ class GuardianSigningJvmTest {
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/MemberWalletGuardianJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
new file mode 100644
index 00000000..4d5ea6ae
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
@@ -0,0 +1,239 @@
+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)
+ }
+
+ 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)
+ assertTrue(GuardianManager.describeNotice(db, parentRoom, Event("1".repeat(64), memberPublicKey, 1, GuardedWalletNoticeEvent.KIND, emptyArray(), certificate().toJson(), ""))!!.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)
+ 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", 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..14d50912
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPagesJvmTest.kt
@@ -0,0 +1,103 @@
+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.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))
+
+ 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))
+ signingRoom(db, parent, members = listOf(alicePublicKey), holdsShare = false, subject = "#Root")
+ fileKeyState(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 }.guardianName)
+ assertTrue(MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, bobPublicKey).isEmpty())
+ }
+}
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..652382f9
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletRequestJvmTest.kt
@@ -0,0 +1,165 @@
+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))
+ }
+
+ 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))
+
+ 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")
+
+ assertEquals(Refusal.NOT_ON_THIS_NETWORK, 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..7014f273
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt
@@ -0,0 +1,201 @@
+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))
+ }
+
+ 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,
+ )
+
+ /** 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)
+ 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..f7a61e7d
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSpendJvmTest.kt
@@ -0,0 +1,138 @@
+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))
+ 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))
+ 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..d9e9e823
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt
@@ -0,0 +1,127 @@
+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))
+ }
+
+ 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/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/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/GuardedWalletCardJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt
new file mode 100644
index 00000000..09fdaddb
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt
@@ -0,0 +1,174 @@
+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.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()
+ }
+}
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/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/docs/README.md b/docs/README.md
index 17dc037b..32ac3700 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -16,6 +16,8 @@ silent, or a decision that looked arbitrary and was not.
| [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 |
| [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-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 |
@@ -54,6 +56,11 @@ 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 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
@@ -63,6 +70,11 @@ 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 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.
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
index 32a10ad5..15f41e51 100644
--- a/docs/group-wallet-guardians.md
+++ b/docs/group-wallet-guardians.md
@@ -341,6 +341,10 @@ 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.
+
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
@@ -431,6 +435,13 @@ One commit each.
## 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
@@ -453,7 +464,8 @@ 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`).
+`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
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
index db66f71e..6e40a571 100644
--- a/docs/guardian-delay.md
+++ b/docs/guardian-delay.md
@@ -25,7 +25,7 @@ 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 v30. `GuardianDerivation.DELAY_RANGE`,
+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.
@@ -40,6 +40,8 @@ moved; where the build chose differently the table says so.
| 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 still cannot choose the delay on its own leaf in a member's wallet |
Still to do by hand: the three-emulator run in Phase 8.
diff --git a/docs/member-guarded-wallets.md b/docs/member-guarded-wallets.md
new file mode 100644
index 00000000..ab9ace7c
--- /dev/null
+++ b/docs/member-guarded-wallets.md
@@ -0,0 +1,966 @@
+# 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, shut. 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 | not made. It is what lifts the gate |
+
+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 for 12 blocks, without asking and without warning. 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.
+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
+ ["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`
+
+The guardian side is built. What changes is what a guarded wallet can be.
+
+### `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. 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/subgroups.md b/docs/subgroups.md
index 099b6c83..027262cf 100644
--- a/docs/subgroups.md
+++ b/docs/subgroups.md
@@ -168,6 +168,10 @@ tags:
["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