diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 62f35455..63f78041 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -382,6 +382,7 @@ Open the shared key ceremony Open the Lightning wallet's key ceremony Open the proposal + Open the Lightning wallet You approved this Open Ask again diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt index c538144a..3afcc821 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.database.dao +import com.machankura.bennu.compose.managers.GroupLightningOperatorManager import com.machankura.bennu.compose.managers.GroupLightningCoSigner import com.machankura.bennu.compose.managers.GroupLightningReports import com.machankura.bennu.compose.managers.GroupLightningWalletManager @@ -1626,13 +1627,23 @@ abstract class NostrDao( // What the operator says about the Lightning wallet, and the // invoices it makes for members who ask. - innerEvent.kind == GroupLightningEvents.SNAPSHOT || innerEvent.kind == GroupLightningEvents.INVOICE -> + innerEvent.kind == GroupLightningEvents.SNAPSHOT || + innerEvent.kind == GroupLightningEvents.INVOICE || + innerEvent.kind == GroupLightningEvents.INVOICE_REQUEST -> GroupLightningReports.process( database = database, localChatRoom = localChatRoom, innerEvent = innerEvent, ) + // An operator's node stopping: a line, from whoever ran that term. + innerEvent.kind == GroupLightningEvents.STOPPED -> + GroupLightningOperatorManager.receiveStopped( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + ) + // The group Lightning wallet's key ceremony. Marmot only: // it runs where the onchain wallet it closes to already is. innerEvent.kind in GroupLightningEvents.CEREMONY -> 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 49b23101..2e65b626 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 @@ -564,6 +564,49 @@ data class ChatMessage( TYPE_MEMBER_WALLET_POLICY, ) + /** The lines in [GROUP_IDENTITY_TYPES] about the Lightning wallet, which open its screen. */ + val GROUP_LIGHTNING_SIGNED_TYPES = setOf( + TYPE_GROUP_LIGHTNING_WALLET_OPENED, + TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED, + TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED, + ) + + /** + * What the group Lightning wallet's devices tell each other outside its two protocols, + * as lines: a member handing out the node's seed, a member asking the operator's node + * to be paid and the node's answer, and an operator stopping. docs/group-lightning- + * transcript.md, Phase 4. + * + * One line per message, written by the manager that acts on it -- on the way out by + * the device that sends it, which cannot read its own message back, and on arrival by + * every other -- and keyed on the message's inner event, so a redelivery is not a + * second line. Nonce batches, echoes, signing requests and signature shares are never + * lines: there are thousands of them and none says anything a member would tell + * another. + * + * Not group-signed, so not in [GROUP_IDENTITY_TYPES], and none asks the reader for + * anything: an invoice request is answered by the operator's node, not by a person. + */ + const val TYPE_LIGHTNING_SEED_SHARED = "lightningSeedShared" + const val TYPE_LIGHTNING_INVOICE_REQUESTED = "lightningInvoiceRequested" + const val TYPE_LIGHTNING_INVOICE_ISSUED = "lightningInvoiceIssued" + const val TYPE_LIGHTNING_OPERATOR_STOPPED = "lightningOperatorStopped" + + /** Every Lightning wallet line, for the one check the transcript dispatches on. */ + val LIGHTNING_TYPES = setOf( + TYPE_LIGHTNING_SEED_SHARED, + TYPE_LIGHTNING_INVOICE_REQUESTED, + TYPE_LIGHTNING_INVOICE_ISSUED, + TYPE_LIGHTNING_OPERATOR_STOPPED, + ) + + /** As [DKG_AUTHORED_TYPES]: content written to follow the actor's name. The node's answer has no actor. */ + val LIGHTNING_AUTHORED_TYPES = setOf( + TYPE_LIGHTNING_SEED_SHARED, + TYPE_LIGHTNING_INVOICE_REQUESTED, + TYPE_LIGHTNING_OPERATOR_STOPPED, + ) + /** * Every subgroup line, for the one check the transcript dispatches on. * @@ -1491,10 +1534,11 @@ data class ChatMessage( isUserMessage = isUserMessage, chatRoomId = groupId, createdAt = createdAt, - content = if (statement.operator == null) { - "Nobody runs the group's Lightning wallet now (term ${statement.term}). It stops until someone is chosen." - } else { - "The group chose who runs its Lightning wallet (term ${statement.term})." + // Who, since that is the one thing the line is for. The term is + // a counter the wallet's screen keeps; it means nothing to a reader. + content = when (val operator = statement.operator) { + null -> "Nobody runs the group's Lightning wallet now. It stops until someone is chosen." + else -> "@${memberName(database, operator)} runs the group's Lightning wallet now." } ) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningLines.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningLines.kt new file mode 100644 index 00000000..f9ff0cae --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningLines.kt @@ -0,0 +1,51 @@ +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.ChatMessage +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant + +/** + * Writes the group Lightning wallet's lines into its room's transcript ([ChatMessage.LIGHTNING_TYPES]). + * See docs/group-lightning-transcript.md, Phase 4. + * + * Each line hangs off the inner event it describes, which is what makes it one line: the device + * that sends a message writes it on the way out, every other device writes it on arrival, and a + * redelivery or a replay finds the line already there. The inner event row exists in both cases -- + * `GroupLightningWalletManager.queue` writes it on the way out, and the inbound path files every + * inner event before its manager sees it -- which the foreign key on [ChatMessage.marmotInnerEventId] + * needs. + */ +internal object GroupLightningLines { + private val logger = Logger.withTag("GroupLightningLines") + + suspend fun write( + database: BennuDatabase, + chatRoomId: String, + innerEventId: HexKey, + messageType: String, + actor: HexKey, + content: String, + createdAt: Instant, + ) { + if (database.chatMessageDao().getChatMessagesByMarmotInnerEventId(innerEventId) != null) return + if (database.marmotInnerEventDao().getById(innerEventId) == null) { + return logger.w("No inner event $innerEventId is stored to hang a $messageType line off; writing none") + } + val reader = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = actor, + isUserMessage = reader != null && reader.equals(actor, ignoreCase = true), + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = innerEventId, + chatRoomId = chatRoomId, + content = content, + messageType = messageType, + createdAt = createdAt, + ) + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt index 3387bde8..e35b5c14 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningOperatorManager.kt @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.GroupSignedEvent @@ -87,12 +90,31 @@ object GroupLightningOperatorManager { return current(database, chatRoomId, chain, wallet)?.publicKey == userPublicKey } + private const val STOPPED = "stopped running the group's Lightning node." + /** Tells the room this device's node stopped, and where its channels were (kind 30366). */ suspend fun announceStopped(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long, term: Long, commitmentNumbers: Map) { - GroupLightningWalletManager.queue( + val queued = GroupLightningWalletManager.queue( database, localChatRoom, userPublicKey, GroupLightningEvents.STOPPED, CommonJson.encodeToString(Stopped.serializer(), Stopped(term, commitmentNumbers)), tags = arrayOf(arrayOf("d", GroupLightningWalletStatementEvent.identifier(chain, wallet))), ) + GroupLightningLines.write(database, localChatRoom.chatRoom.id, queued.id, ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED, userPublicKey, STOPPED, queued.createdAt) + } + + /** + * An operator's stop, as its line: only from whoever ran that term's node. Their commitment + * numbers are read by the next operator's node from the stored event, not from here. + */ + suspend fun receiveStopped(database: BennuDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { + val identifier = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == "d" }?.get(1)?.split(':') ?: return + val chain = identifier.getOrNull(0)?.let(GroupWalletStatementEvent::chainNamed) ?: return + val wallet = identifier.getOrNull(1)?.toLongOrNull() ?: return + val stopped = runCatching { CommonJson.decodeFromString(Stopped.serializer(), innerEvent.content) }.getOrNull() ?: return + if (ofTerm(database, localChatRoom.chatRoom.id, chain, wallet, stopped.term)?.publicKey != innerEvent.pubKey) return + GroupLightningLines.write( + database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED, + innerEvent.pubKey, STOPPED, Instant.fromEpochSeconds(innerEvent.createdAt), + ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt index 1af38996..7924e2fc 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.text.grouped +import fr.acinq.bitcoin.Satoshi +import com.machankura.bennu.compose.database.model.ChatMessage import co.touchlab.kermit.Logger import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.GroupLightningInvoiceRow @@ -50,6 +53,7 @@ object GroupLightningReports { when (innerEvent.kind) { GroupLightningEvents.SNAPSHOT -> receiveSnapshot(database, localChatRoom, innerEvent) GroupLightningEvents.INVOICE -> receiveInvoice(database, localChatRoom, innerEvent) + GroupLightningEvents.INVOICE_REQUEST -> receiveInvoiceRequest(database, localChatRoom, innerEvent) } }.onFailure { logger.w("Could not read wallet report ${innerEvent.id}: ${it.message}") } } @@ -119,10 +123,37 @@ object GroupLightningReports { val key = GroupLightningCoSigner.walletKey(localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet) val requestId = RandomInstance.bytes(16).toHex() val request = WalletWire.InvoiceRequest(key, requestId, amountMsat, description) - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.INVOICE_REQUEST, CommonJson.encodeToString(WalletWire.InvoiceRequest.serializer(), request)) + val queued = GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.INVOICE_REQUEST, CommonJson.encodeToString(WalletWire.InvoiceRequest.serializer(), request)) + GroupLightningLines.write(database, localChatRoom.chatRoom.id, queued.id, ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED, userPublicKey, asked(request), queued.createdAt) return requestId } + /** A member's invoice request, as its line: only for a wallet this room has. The operator's node answers it. */ + private suspend fun receiveInvoiceRequest(database: BennuDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { + val request = CommonJson.decodeFromString(WalletWire.InvoiceRequest.serializer(), innerEvent.content) + GroupLightningCoSigner.walletOf(database, localChatRoom.chatRoom.id, request.wallet) ?: return + GroupLightningLines.write( + database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED, + innerEvent.pubKey, asked(request), Instant.fromEpochSeconds(innerEvent.createdAt), + ) + } + + /** What a member asked for, to follow their name. The description is theirs and is quoted as it is. */ + private fun asked(request: WalletWire.InvoiceRequest): String = buildString { + append("asked the operator's node for an invoice") + request.amountMsat?.let { append(" of ${Satoshi(it / 1000).grouped()} sats") } + request.description.takeIf { it.isNotBlank() }?.let { append(", for \u201c$it\u201d") } + append(".") + } + + /** The node's answer to [requestId], as its line: naming whoever asked, when this device has their request. */ + private suspend fun invoiceIssued(database: BennuDatabase, chatRoomId: String, requestId: String): String { + val asker = database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GroupLightningEvents.INVOICE_REQUEST)) + .firstOrNull { runCatching { CommonJson.decodeFromString(WalletWire.InvoiceRequest.serializer(), it.content) }.getOrNull()?.requestId == requestId } + ?.publicKey + return if (asker == null) "The operator's node made an invoice." else "The operator's node made @${ChatMessage.memberName(database, asker)}'s invoice." + } + /** The invoice requests for [walletKey] in the room that no invoice answers yet, oldest first. */ suspend fun unanswered(database: BennuDatabase, chatRoomId: String, walletKey: String): List = database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GroupLightningEvents.INVOICE_REQUEST)) @@ -133,8 +164,12 @@ object GroupLightningReports { /** Sends the room the operator's invoice for [request], and files it here. */ suspend fun answer(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, request: WalletWire.InvoiceRequest, bolt11: String) { val reply = WalletWire.InvoiceReply(request.wallet, request.requestId, bolt11) - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.INVOICE, CommonJson.encodeToString(WalletWire.InvoiceReply.serializer(), reply)) + val queued = GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.INVOICE, CommonJson.encodeToString(WalletWire.InvoiceReply.serializer(), reply)) database.groupLightningRecordsDao().upsertInvoice(GroupLightningInvoiceRow(request.wallet, request.requestId, bolt11)) + GroupLightningLines.write( + database, localChatRoom.chatRoom.id, queued.id, ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED, + userPublicKey, invoiceIssued(database, localChatRoom.chatRoom.id, request.requestId), queued.createdAt, + ) } private suspend fun receiveInvoice(database: BennuDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { @@ -146,5 +181,9 @@ object GroupLightningReports { val invoice = Bolt11Invoice.read(reply.bolt11).get() if (invoice.nodeId.toString() != wallet.statement.nodeId) return logger.w("Invoice ${innerEvent.id} pays a node that is not the group's") database.groupLightningRecordsDao().upsertInvoice(GroupLightningInvoiceRow(reply.wallet, reply.requestId, reply.bolt11)) + GroupLightningLines.write( + database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED, + innerEvent.pubKey, invoiceIssued(database, localChatRoom.chatRoom.id, reply.requestId), Instant.fromEpochSeconds(innerEvent.createdAt), + ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt index a74821ff..0df499c8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.database.model.ChatMessage import co.touchlab.kermit.Logger import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.FrostSigningSession @@ -174,7 +175,8 @@ object GroupLightningWalletManager { val to = ceremony.participants().filter { it != userPublicKey.lowercase() }.associateWith { recipient -> Nip44.encrypt(seed.toHex(), nostrPrivateKey, recipient.hexToByteArray()).encodePayload() } - queue(database, localChatRoom, userPublicKey, GroupLightningEvents.NODE_SEED, CommonJson.encodeToString(SeedMessage.serializer(), SeedMessage(chainName, wallet, nodeId, to))) + val seedMessage = queue(database, localChatRoom, userPublicKey, GroupLightningEvents.NODE_SEED, CommonJson.encodeToString(SeedMessage.serializer(), SeedMessage(chainName, wallet, nodeId, to))) + GroupLightningLines.write(database, roomId, seedMessage.id, ChatMessage.TYPE_LIGHTNING_SEED_SHARED, userPublicKey, SEED_SHARED, seedMessage.createdAt) val statement = GroupLightningWalletStatementEvent.Statement( chain = chain, @@ -200,7 +202,14 @@ object GroupLightningWalletManager { suspend fun receiveSeed(database: BennuDatabase, localChatRoom: LocalChatRoom, innerEvent: Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray) { val message = runCatching { CommonJson.decodeFromString(SeedMessage.serializer(), innerEvent.content) }.getOrNull() ?: return val chain = GroupWalletStatementEvent.chainNamed(message.chain) ?: return - val ciphertext = message.to[userPublicKey.lowercase()] ?: return + suspend fun line() = GroupLightningLines.write( + database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_SEED_SHARED, + innerEvent.pubKey, SEED_SHARED, Instant.fromEpochSeconds(innerEvent.createdAt), + ) + // A member it was not sent to cannot check it, and is told it happened all the same: + // that the node has a seed, and who made it, is the group's business. A member it was + // sent to is told only once the seed proves to be the node's. + val ciphertext = message.to[userPublicKey.lowercase()] ?: return line() val seedHex = runCatching { Nip44.decrypt(ciphertext, nostrPrivateKey, innerEvent.pubKey.hexToByteArray()) }.getOrNull() ?: return val seed = runCatching { ByteVector(seedHex) }.getOrNull()?.takeIf { it.size() == 32 } ?: return val nodeId = nodeIdOf(seed, chain).value.toHex() @@ -209,14 +218,21 @@ object GroupLightningWalletManager { return } database.groupLightningSeedDao().insertIfAbsent(GroupLightningSeed(localChatRoom.chatRoom.id, nodeId, message.chain, message.wallet, seed.toHex(), innerEvent.pubKey)) + line() } - /** Queues one of this device's messages as a Marmot inner event for the room, as the ritual managers do. */ - internal suspend fun queue(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, kind: Int, content: String, tags: Array> = emptyArray()) { + /** + * Queues one of this device's messages as a Marmot inner event for the room, as the ritual managers do, + * and returns the row: a message worth a line gets it from here, since this device never reads its own back. + */ + internal suspend fun queue(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, kind: Int, content: String, tags: Array> = emptyArray()): MarmotInnerEvent { val createdAt = Clock.System.now().epochSeconds val id = EventHasher.hashId(pubKey = userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content) - database.marmotInnerEventDao().upsert( - MarmotInnerEvent(id = id, publicKey = userPublicKey, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt), tags = tags, content = content, chatRoomId = localChatRoom.chatRoom.id) - ) + val queued = MarmotInnerEvent(id = id, publicKey = userPublicKey, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt), tags = tags, content = content, chatRoomId = localChatRoom.chatRoom.id) + database.marmotInnerEventDao().upsert(queued) + return queued } + + private const val SEED_SHARED = "gave each key holder the Lightning node's seed, encrypted to each of them." + } 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 bd6160f8..7a145505 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 @@ -38,6 +38,12 @@ import bennu.composeapp.generated.resources.open_a_lightning_wallet import bennu.composeapp.generated.resources.open_the_shared_key_ceremony import bennu.composeapp.generated.resources.open_the_lightning_wallet_s_key_ceremony import bennu.composeapp.generated.resources.open_the_proposal +import bennu.composeapp.generated.resources.open_the_lightning_wallet +import androidx.compose.material.icons.filled.Badge +import androidx.compose.material.icons.filled.Payments +import androidx.compose.material.icons.filled.RequestQuote +import androidx.compose.material.icons.filled.Receipt +import androidx.compose.material.icons.filled.PowerSettingsNew import bennu.composeapp.generated.resources.you_approved_this import androidx.compose.material.icons.filled.AccessTime import androidx.compose.material.icons.filled.Block @@ -391,18 +397,35 @@ fun ChatTranscript( return@items } - // Something the group signed. Same treatment and for - // the same reason: nobody said it. Answered and - // settled because it reports rather than asks -- a - // quorum has already signed by the time this line - // exists. It leads nowhere. - if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { + // What the Lightning wallet's devices told each other. + // Reports, not asks -- an invoice request is the + // operator's node's to answer -- so they stay quiet, + // and each leads to the wallet it is about. + if (localChatMessage.chatMessage.messageType in ChatMessage.LIGHTNING_TYPES) { RitualNotice( localChatMessage = localChatMessage, isAnswered = true, isSettled = true, - onClick = null, - opens = null, + onClick = onOpenLightningWallet, + opens = stringResource(Res.string.open_the_lightning_wallet), + ) + return@items + } + + // Something the group signed. Same treatment and for + // the same reason: nobody said it. Answered and + // settled because it reports rather than asks -- a + // quorum has already signed by the time this line + // exists. It leads nowhere, except the Lightning + // wallet's, which lead to the wallet. + if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { + val isLightning = localChatMessage.chatMessage.messageType in ChatMessage.GROUP_LIGHTNING_SIGNED_TYPES + RitualNotice( + localChatMessage = localChatMessage, + isAnswered = true, + isSettled = true, + onClick = if (isLightning) onOpenLightningWallet else null, + opens = if (isLightning) stringResource(Res.string.open_the_lightning_wallet) else null, ) return@items } @@ -921,6 +944,14 @@ private fun RitualNotice( ChatMessage.TYPE_MEMBER_INVITE_FAILED -> Icons.Default.ErrorOutline ChatMessage.TYPE_CHANGE_REJECTED -> Icons.Default.ErrorOutline + ChatMessage.TYPE_GROUP_LIGHTNING_WALLET_OPENED -> Icons.Default.Bolt + ChatMessage.TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED -> Icons.Default.Badge + ChatMessage.TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED -> Icons.Default.Payments + ChatMessage.TYPE_LIGHTNING_SEED_SHARED -> Icons.Default.Key + ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED -> Icons.Default.RequestQuote + ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED -> Icons.Default.Receipt + ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED -> Icons.Default.PowerSettingsNew + else -> Icons.Default.PanTool } @@ -976,7 +1007,8 @@ private fun RitualNotice( // placeholder a member is given the moment they are first seen. if (chatMessage.messageType in ChatMessage.DKG_AUTHORED_TYPES || chatMessage.messageType in ChatMessage.ICEBERG_AUTHORED_TYPES || - chatMessage.messageType in ChatMessage.FROST_AUTHORED_TYPES + chatMessage.messageType in ChatMessage.FROST_AUTHORED_TYPES || + chatMessage.messageType in ChatMessage.LIGHTNING_AUTHORED_TYPES ) { withStyle( SpanStyle(color = ProfileColor.fromPublicKey(chatMessage.senderPublicKey)) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt index d209054d..29f17b4b 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.database.model.ChatMessage import androidx.room3.Room import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.builder.getRoomDatabase @@ -109,10 +110,15 @@ class GroupLightningFixture(val n: Int = 4, val frostThreshold: Int = 3, val cha in FrostSigningEvents.ALL -> FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey) in GroupLightningEvents.CEREMONY -> IcebergRitualManager.processCeremonyPayload(to.db, to.room, event, to.publicKey, to.privateKey) GroupLightningEvents.NODE_SEED -> GroupLightningWalletManager.receiveSeed(to.db, to.room, event, to.publicKey, to.privateKey) - GroupLightningEvents.SNAPSHOT, GroupLightningEvents.INVOICE -> GroupLightningReports.process(to.db, to.room, event) + GroupLightningEvents.SNAPSHOT, GroupLightningEvents.INVOICE, GroupLightningEvents.INVOICE_REQUEST -> GroupLightningReports.process(to.db, to.room, event) + GroupLightningEvents.STOPPED -> GroupLightningOperatorManager.receiveStopped(to.db, to.room, event) } } + /** The Lightning wallet's lines of [type] in [device]'s copy of the room. */ + suspend fun lines(device: Device, type: String): List = + device.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }.filter { it.messageType == type } + suspend fun pump(between: List, kinds: Set) { var moved = true while (moved) { diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt index 7a938db2..aea3b2e5 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.MarmotGroupEvent import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.network.serialization.CommonJson @@ -142,6 +143,19 @@ class GroupLightningNodeJvmTest { val body = CommonJson.decodeFromString(GroupLightningOperatorManager.Stopped.serializer(), stopped.content) assertEquals(1, body.term) assertEquals(mapOf("ab".repeat(32) to 7L), body.commitmentNumbers) + + // The room is told in words too, on every device, by the operator of the term it names. + fixture.pump(all, setOf(GroupLightningEvents.STOPPED)) + all.forEach { d -> + val line = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED).single() + assertEquals(all[1].publicKey, line.senderPublicKey) + assertEquals("stopped running the group's Lightning node.", line.content) + } + // A stop from anybody else is nobody's. + val forged = with(fixture) { stopped.copy(id = "f".repeat(64), publicKey = all[3].publicKey).asEvent() } + all[2].db.marmotInnerEventDao().upsert(stopped.copy(id = "f".repeat(64), publicKey = all[3].publicKey)) + GroupLightningOperatorManager.receiveStopped(all[2].db, all[2].room, forged) + assertEquals(1, fixture.lines(all[2], ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED).size) } @Test diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt index 84ee7577..c408cbe6 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.IcebergChannelLedger import com.machankura.bennu.compose.database.model.MarmotGroupEvent import com.machankura.bennu.compose.database.model.NostrEvent @@ -162,6 +163,13 @@ class GroupLightningReportsJvmTest { assertEquals(wallet.statement.nodeId, invoice.nodeId.toString()) assertEquals(21_000_000.msat, invoice.amount) assertEquals("lunch", invoice.description) + + // Who asked, for how much, and that the node answered, on every device. + val asked = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED).single() + assertEquals(all[3].publicKey, asked.senderPublicKey) + assertEquals("asked the operator's node for an invoice of 21,000 sats, for \u201clunch\u201d.", asked.content) + val issued = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED).single() + assertEquals("The operator's node made @${ChatMessage.memberName(d.db, all[3].publicKey)}'s invoice.", issued.content) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt index cf3fc6ed..3b654a4f 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletJvmTest.kt @@ -63,7 +63,16 @@ class GroupLightningWalletJvmTest { all.forEach { d -> val lines = d.db.chatMessageDao().getChatMessagesByChatRoomId(fixture.roomId).map { it.chatMessage.messageType } assertTrue(ChatMessage.TYPE_GROUP_LIGHTNING_WALLET_OPENED in lines) + // And who handed the seed out: one line, written by the proposer on the way out + // and by everyone else as it arrived. docs/group-lightning-transcript.md, Phase 4. + val seedLine = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_SEED_SHARED).single() + assertEquals(all[0].publicKey, seedLine.senderPublicKey) + assertEquals(d === all[0], seedLine.isUserMessage) } + // Delivered again, it is not a second line. + all.forEach { it.received.clear() } + fixture.pump(all, setOf(GroupLightningEvents.NODE_SEED)) + all.forEach { assertEquals(1, fixture.lines(it, ChatMessage.TYPE_LIGHTNING_SEED_SHARED).size) } } @Test @@ -75,8 +84,10 @@ class GroupLightningWalletJvmTest { val body = CommonJson.parseToJsonElement(message.content).jsonObject val lying = JsonObject(body + ("nodeId" to JsonPrimitive("02" + "ab".repeat(32)))) val event = with(fixture) { message.copy(content = lying.toString()).asEvent() } + all[1].db.marmotInnerEventDao().upsert(message.copy(content = lying.toString())) GroupLightningWalletManager.receiveSeed(all[1].db, all[1].room, event, all[1].publicKey, all[1].privateKey) assertNull(all[1].db.groupLightningSeedDao().get(fixture.roomId, "02" + "ab".repeat(32))) + assertTrue(fixture.lines(all[1], ChatMessage.TYPE_LIGHTNING_SEED_SHARED).isEmpty(), "and the room is not told a seed was shared") } @Test @@ -119,6 +130,9 @@ class GroupLightningWalletJvmTest { val current = assertNotNull(GroupLightningOperatorManager.current(d.db, fixture.roomId, fixture.chain)) assertEquals(all[1].publicKey, current.publicKey) assertEquals(1, current.term) + // The line says who, which is the one thing it is for. + val elected = fixture.lines(d, ChatMessage.TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED).single() + assertEquals("@${ChatMessage.memberName(d.db, all[1].publicKey)} runs the group's Lightning wallet now.", elected.content) } val second = GroupLightningOperatorManager.nominateSelf(all[2].db, all[2].room, all[2].publicKey, fixture.chain) fixture.signSession(all, all[2], second.id)