feat(lightning): what the operator's snapshots say happened, as lines (Phase 5)
A channel opening or closing, and a payment received, sent or failed, each get one line however many snapshots repeat them. The snapshot restates the whole wallet, so the line is keyed on the fact, not the message: ChatMessage.lightningFactKey (v34, an AutoMigration) holds the channel's or the payment's id. A payment's line sits where the payment happened, and a channel a newer snapshot no longer holds is said to have closed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1b4ed09798
commit
3ec79b95ad
8 files changed
+5679
-4
No files matched your search
+6
-1
@@ -188,7 +188,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
UnsignedNostrEvent::class,
|
||||
Zap::class
|
||||
],
|
||||
version = 33,
|
||||
version = 34,
|
||||
autoMigrations = [
|
||||
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
|
||||
// generate the migration itself — nothing existing changes shape.
|
||||
@@ -411,6 +411,11 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
// v33 deletes the raw-JSON chat lines the group Lightning wallet's own messages left
|
||||
// (docs/group-lightning-transcript.md, Phase 1). Manual -- it deletes rows -- so it is
|
||||
// MIGRATION_32_33 in `getRoomDatabase`, not an entry here.
|
||||
//
|
||||
// v34 adds the nullable ChatMessage.lightningFactKey: the channel or payment a Lightning
|
||||
// wallet line reports (docs/group-lightning-transcript.md, Phase 5). Null on every line
|
||||
// before it, none of which is one.
|
||||
AutoMigration(from = 33, to = 34),
|
||||
]
|
||||
)
|
||||
@ConstructedBy(BennuDatabaseConstructor::class)
|
||||
|
||||
+4
@@ -45,6 +45,10 @@ interface ChatMessageDao {
|
||||
@Query("SELECT * FROM ChatMessage WHERE marmotInnerEventId = :marmotInnerEventId ORDER BY createdAt DESC")
|
||||
suspend fun getChatMessagesByMarmotInnerEventId(marmotInnerEventId: HexKey): ChatMessage?
|
||||
|
||||
/** The room's line of [messageType] about one Lightning wallet fact, if it has one. */
|
||||
@Query("SELECT * FROM ChatMessage WHERE chatRoomId = :chatRoomId AND messageType = :messageType AND lightningFactKey = :lightningFactKey LIMIT 1")
|
||||
suspend fun getLightningFactLine(chatRoomId: String, messageType: String, lightningFactKey: String): ChatMessage?
|
||||
|
||||
@Query("SELECT * FROM ChatMessage WHERE marmotGroupEventId = :marmotGroupEventId ORDER BY createdAt DESC")
|
||||
suspend fun getChatMessagesByMarmotGroupEventId(marmotGroupEventId: HexKey): ChatMessage?
|
||||
|
||||
|
||||
+29
@@ -154,6 +154,18 @@ data class ChatMessage(
|
||||
*/
|
||||
val dkgSessionId: String? = null,
|
||||
|
||||
/**
|
||||
* The fact a Lightning wallet line reports, for the lines that come from the operator's
|
||||
* snapshots rather than from a message: a channel's id, or a payment's. Null for
|
||||
* anything else.
|
||||
*
|
||||
* A snapshot restates the whole wallet every few minutes, so the message it came in
|
||||
* cannot be what makes its line one line -- the channel or the payment is. Kept on the
|
||||
* row, like [frostSigningSessionId], because nothing in its type or time can say which
|
||||
* channel it was. docs/group-lightning-transcript.md, Phase 5.
|
||||
*/
|
||||
val lightningFactKey: String? = null,
|
||||
|
||||
override val createdAt: Instant = Clock.System.now(),
|
||||
override val updatedAt: Instant = createdAt,
|
||||
override val savedAt: Instant = Clock.System.now(),
|
||||
@@ -592,12 +604,29 @@ data class ChatMessage(
|
||||
const val TYPE_LIGHTNING_INVOICE_ISSUED = "lightningInvoiceIssued"
|
||||
const val TYPE_LIGHTNING_OPERATOR_STOPPED = "lightningOperatorStopped"
|
||||
|
||||
/**
|
||||
* What the operator's snapshots say happened, one line per fact rather than per
|
||||
* snapshot: a channel opening and closing, a payment settling or failing. No actor --
|
||||
* the node did these, and naming the operator would read as them having chosen to.
|
||||
* Keyed on [lightningFactKey]. docs/group-lightning-transcript.md, Phase 5.
|
||||
*/
|
||||
const val TYPE_LIGHTNING_CHANNEL_OPENED = "lightningChannelOpened"
|
||||
const val TYPE_LIGHTNING_CHANNEL_CLOSED = "lightningChannelClosed"
|
||||
const val TYPE_LIGHTNING_PAYMENT_RECEIVED = "lightningPaymentReceived"
|
||||
const val TYPE_LIGHTNING_PAYMENT_SENT = "lightningPaymentSent"
|
||||
const val TYPE_LIGHTNING_PAYMENT_FAILED = "lightningPaymentFailed"
|
||||
|
||||
/** 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,
|
||||
TYPE_LIGHTNING_CHANNEL_OPENED,
|
||||
TYPE_LIGHTNING_CHANNEL_CLOSED,
|
||||
TYPE_LIGHTNING_PAYMENT_RECEIVED,
|
||||
TYPE_LIGHTNING_PAYMENT_SENT,
|
||||
TYPE_LIGHTNING_PAYMENT_FAILED,
|
||||
)
|
||||
|
||||
/** As [DKG_AUTHORED_TYPES]: content written to follow the actor's name. The node's answer has no actor. */
|
||||
|
||||
+32
@@ -48,4 +48,36 @@ internal object GroupLightningLines {
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the line for one fact the operator's snapshots report, unless the room already has it.
|
||||
* There is no message to hang it off: the same fact arrives in every snapshot until it stops
|
||||
* being true, so [factKey] -- the channel, the payment -- is what makes it one line.
|
||||
*/
|
||||
suspend fun writeFact(
|
||||
database: BennuDatabase,
|
||||
chatRoomId: String,
|
||||
messageType: String,
|
||||
factKey: String,
|
||||
reportedBy: HexKey,
|
||||
content: String,
|
||||
createdAt: Instant,
|
||||
) {
|
||||
if (database.chatMessageDao().getLightningFactLine(chatRoomId, messageType, factKey) != null) return
|
||||
val reader = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey
|
||||
database.chatMessageDao().upsert(
|
||||
ChatMessage(
|
||||
senderPublicKey = reportedBy,
|
||||
isUserMessage = reader != null && reader.equals(reportedBy, ignoreCase = true),
|
||||
giftWrapPayloadId = null,
|
||||
marmotGroupEventId = null,
|
||||
marmotInnerEventId = null,
|
||||
chatRoomId = chatRoomId,
|
||||
content = content,
|
||||
messageType = messageType,
|
||||
lightningFactKey = factKey,
|
||||
createdAt = createdAt,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
+68
-3
@@ -44,7 +44,7 @@ object GroupLightningReports {
|
||||
/** Sends [snapshot] to the room, and files it here as every member would. */
|
||||
suspend fun publishSnapshot(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, snapshot: WalletWire.Snapshot) {
|
||||
GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.SNAPSHOT, CommonJson.encodeToString(WalletWire.Snapshot.serializer(), snapshot))
|
||||
file(database, userPublicKey, snapshot)
|
||||
file(database, localChatRoom.chatRoom.id, userPublicKey, snapshot)
|
||||
}
|
||||
|
||||
/** Routes one inbound snapshot or invoice. Invoice requests are read by the running node, not here. */
|
||||
@@ -67,7 +67,7 @@ object GroupLightningReports {
|
||||
val operator = GroupLightningOperatorManager.ofTerm(database, localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet, snapshot.term)
|
||||
if (operator?.publicKey != innerEvent.pubKey) return logger.w("Snapshot ${innerEvent.id} is not from the operator of term ${snapshot.term}")
|
||||
// An offer is kept only if it is the one the group's node derives: the seed says which.
|
||||
file(database, innerEvent.pubKey, snapshot.copy(offer = snapshot.offer?.takeIf { it == offerOf(wallet) }))
|
||||
file(database, localChatRoom.chatRoom.id, innerEvent.pubKey, snapshot.copy(offer = snapshot.offer?.takeIf { it == offerOf(wallet) }))
|
||||
// The round-one labels the operator handed out, so whoever operates next signs under them.
|
||||
val dao = database.icebergCoSigningDao()
|
||||
snapshot.assignments.forEach { (purpose, counter) ->
|
||||
@@ -88,9 +88,10 @@ object GroupLightningReports {
|
||||
return OfferManager.deterministicOffer(wallet.statement.chain.chainHash, nodeKey, PublicKey.fromHex(wallet.statement.lspNodeId), null, null, null).offer.encode()
|
||||
}
|
||||
|
||||
private suspend fun file(database: BennuDatabase, sentBy: HexKey, snapshot: WalletWire.Snapshot) {
|
||||
private suspend fun file(database: BennuDatabase, chatRoomId: String, sentBy: HexKey, snapshot: WalletWire.Snapshot) {
|
||||
val dao = database.groupLightningRecordsDao()
|
||||
val held = dao.snapshot(snapshot.wallet)
|
||||
val previous = held?.let { runCatching { CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), it.content) }.getOrNull() }
|
||||
val newer = held == null || snapshot.term > held.term || (snapshot.term == held.term && snapshot.sentAt >= held.sentAt.epochSeconds)
|
||||
if (newer) {
|
||||
dao.upsertSnapshot(GroupLightningSnapshotRow(snapshot.wallet, sentBy, snapshot.term, CommonJson.encodeToString(WalletWire.Snapshot.serializer(), snapshot), Instant.fromEpochSeconds(snapshot.sentAt)))
|
||||
@@ -99,6 +100,70 @@ object GroupLightningReports {
|
||||
snapshot.payments.forEach { p ->
|
||||
dao.upsertPayment(GroupLightningPaymentRow(snapshot.wallet, p.id, p.incoming, p.amountMsat, p.feesMsat, p.paymentHash, p.description, p.completedAt?.let(Instant::fromEpochMilliseconds), p.succeeded))
|
||||
}
|
||||
sayWhatHappened(database, chatRoomId, sentBy, snapshot, previous.takeIf { newer })
|
||||
}
|
||||
|
||||
/** lightning-kmp's channel states from the moment a close begins: what a snapshot says a closing channel is. */
|
||||
private val CLOSING_STATES = setOf("ShuttingDown", "Negotiating", "Closing", "Closed")
|
||||
|
||||
/**
|
||||
* The lines for what [snapshot] says happened (docs/group-lightning-transcript.md, Phase 5): a
|
||||
* channel this room has not been told of, a channel that began to close, a payment that settled or
|
||||
* failed. Each is written once whatever the number of snapshots that repeat it, because the line is
|
||||
* keyed on the channel or the payment. [previous] is the snapshot this one replaces, when it does:
|
||||
* a channel it held that this one does not is gone, and closed.
|
||||
*/
|
||||
private suspend fun sayWhatHappened(
|
||||
database: BennuDatabase,
|
||||
chatRoomId: String,
|
||||
sentBy: HexKey,
|
||||
snapshot: WalletWire.Snapshot,
|
||||
previous: WalletWire.Snapshot?,
|
||||
) {
|
||||
val sentAt = Instant.fromEpochSeconds(snapshot.sentAt)
|
||||
fun sats(msat: Long) = "${Satoshi(msat / 1000).grouped()} sats"
|
||||
|
||||
suspend fun closed(channel: WalletWire.ChannelView) = GroupLightningLines.writeFact(
|
||||
database, chatRoomId, ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED, channel.channelId, sentBy,
|
||||
if (channel.oursMsat >= 1000) "A Lightning channel closed. Its ${sats(channel.oursMsat)} go to the onchain wallet."
|
||||
else "A Lightning channel closed, with nothing of the group's in it.",
|
||||
sentAt,
|
||||
)
|
||||
|
||||
snapshot.channels.forEach { channel ->
|
||||
if (channel.state in CLOSING_STATES) {
|
||||
closed(channel)
|
||||
} else {
|
||||
GroupLightningLines.writeFact(
|
||||
database, chatRoomId, ChatMessage.TYPE_LIGHTNING_CHANNEL_OPENED, channel.channelId, sentBy,
|
||||
"The group's Lightning node opened a channel of ${Satoshi(channel.capacitySat).grouped()} sats.",
|
||||
sentAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
previous?.channels
|
||||
?.filter { held -> snapshot.channels.none { it.channelId == held.channelId } }
|
||||
?.forEach { closed(it) }
|
||||
|
||||
snapshot.payments.forEach { payment ->
|
||||
val completedAt = payment.completedAt?.let(Instant::fromEpochMilliseconds) ?: return@forEach
|
||||
val (type, content) = when {
|
||||
payment.incoming && payment.succeeded -> ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED to buildString {
|
||||
append("The group's Lightning wallet received ${sats(payment.amountMsat)}")
|
||||
payment.description?.takeIf { it.isNotBlank() }?.let { append(", for \u201c$it\u201d") }
|
||||
append(".")
|
||||
}
|
||||
payment.incoming -> return@forEach
|
||||
payment.succeeded -> ChatMessage.TYPE_LIGHTNING_PAYMENT_SENT to buildString {
|
||||
append("The group's Lightning wallet sent ${sats(payment.amountMsat)}")
|
||||
if (payment.feesMsat > 0) append(", with ${Satoshi((payment.feesMsat + 999) / 1000).grouped()} sats in fees")
|
||||
append(".")
|
||||
}
|
||||
else -> ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED to
|
||||
"A Lightning payment of ${sats(payment.amountMsat)} failed. Nothing left the wallet."
|
||||
}
|
||||
GroupLightningLines.writeFact(database, chatRoomId, type, payment.id, sentBy, content, completedAt)
|
||||
}
|
||||
}
|
||||
|
||||
/** A snapshot, with each of its channels checked against this device's own ledger. */
|
||||
|
||||
+10
@@ -1,5 +1,9 @@
|
||||
package com.machankura.bennu.compose.ui.composable.widgets.chat
|
||||
|
||||
import androidx.compose.material.icons.filled.CallMade
|
||||
import androidx.compose.material.icons.filled.CallReceived
|
||||
import androidx.compose.material.icons.filled.LinkOff
|
||||
import androidx.compose.material.icons.filled.AddLink
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
@@ -951,6 +955,11 @@ private fun RitualNotice(
|
||||
ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED -> Icons.Default.RequestQuote
|
||||
ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED -> Icons.Default.Receipt
|
||||
ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED -> Icons.Default.PowerSettingsNew
|
||||
ChatMessage.TYPE_LIGHTNING_CHANNEL_OPENED -> Icons.Default.AddLink
|
||||
ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED -> Icons.Default.LinkOff
|
||||
ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED -> Icons.Default.CallReceived
|
||||
ChatMessage.TYPE_LIGHTNING_PAYMENT_SENT -> Icons.Default.CallMade
|
||||
ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED -> Icons.Default.ErrorOutline
|
||||
|
||||
else -> Icons.Default.PanTool
|
||||
}
|
||||
@@ -973,6 +982,7 @@ private fun RitualNotice(
|
||||
chatMessage.messageType == ChatMessage.TYPE_ICEBERG_FAILED ||
|
||||
chatMessage.messageType == ChatMessage.TYPE_FROST_FAILED ||
|
||||
chatMessage.messageType == ChatMessage.TYPE_MEMBER_INVITE_FAILED ||
|
||||
chatMessage.messageType == ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED ||
|
||||
chatMessage.messageType == ChatMessage.TYPE_CHANGE_REJECTED ->
|
||||
MaterialTheme.colorScheme.error
|
||||
isRequest -> MaterialTheme.colorScheme.primary
|
||||
|
||||
Reference in new issue
Block a user