diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index c1ac4a99..d313760a 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -619,6 +619,14 @@
The groups above this one have agreed to guard its wallet. In a guarded wallet each of them can spend any coin once it has %1$d confirmations, without this group agreeing.
Open a guarded wallet
Open without guardians
+ Guarded wallets
+ Wallets of groups below this one. This group can spend a coin in them once it has %1$d confirmations.
+ %1$s sats within this group's reach
+ Tell the groups above
+ Not yet shared with the groups above that you're in
+ Share
+ Shared with the groups above
+ Couldn't share the wallet
Guarded: the groups above this one can spend any coin here once it has %1$d confirmations.
Balance
%1$s sats
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 dcfc8dac..e6a2c8be 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
@@ -14,6 +14,7 @@ import com.machankura.bennu.compose.exceptions.MarmotUnprocessableInnerEventExce
import com.machankura.bennu.compose.managers.ChronicleManager
import com.machankura.bennu.compose.managers.GroupKeyStateManager
import com.machankura.bennu.compose.managers.GroupWalletManager
+import com.machankura.bennu.compose.managers.GuardianManager
import com.machankura.bennu.compose.managers.SubgroupManager
import com.machankura.bennu.compose.extensions.toHex
import com.vitorpamplona.quartz.marmot.GroupEventResult
@@ -33,6 +34,7 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent
import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
+import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent
import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent
import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent
import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent
@@ -497,6 +499,14 @@ data class ChatMessage(
*/
const val TYPE_GROUP_TRANSACTION_CONFIRMED = "groupTransactionConfirmed"
+ /**
+ * A member told this group about a descendant's guarded wallet -- a
+ * `GuardedWalletNoticeEvent` this device checked and believes. Written
+ * from the notice, attributed to the member who forwarded it. See
+ * `docs/group-wallet-guardians.md`.
+ */
+ const val TYPE_GUARDED_WALLET_SHARED = "guardedWalletShared"
+
val GROUP_IDENTITY_TYPES = setOf(
TYPE_GROUP_PROFILE_SIGNED,
TYPE_GROUP_RELAYS_SIGNED,
@@ -505,6 +515,7 @@ data class ChatMessage(
TYPE_LEGACY_GROUP_ENTRY_CURATED,
TYPE_GROUP_WALLET_OPENED,
TYPE_GROUP_TRANSACTION_CONFIRMED,
+ TYPE_GUARDED_WALLET_SHARED,
)
/**
@@ -963,6 +974,26 @@ data class ChatMessage(
return null
}
+ // A descendant's guarded wallet, carried up by a member who is in
+ // both rooms. The row above is the whole record of it -- there is
+ // no table -- so all that is left is the line, and only for a
+ // notice this room can actually believe.
+ if (event.kind == GuardedWalletNoticeEvent.KIND) {
+ val content = GuardianManager.describeNotice(database, groupEventResult.groupId, event)
+ ?: return null
+ return ChatMessage(
+ giftWrapPayloadId = null,
+ messageType = TYPE_GUARDED_WALLET_SHARED,
+ marmotGroupEventId = groupEvent.id,
+ marmotInnerEventId = event.id,
+ senderPublicKey = senderIdentity ?: event.pubKey,
+ isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(),
+ chatRoomId = groupEventResult.groupId,
+ createdAt = Instant.fromEpochSeconds(event.createdAt),
+ content = content,
+ )
+ }
+
// Somebody in the room holds none of its signed work and is
// asking. Any member may answer and none is elected to: a
// duplicate answer costs bandwidth and nothing else, since
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt
index 3db6572a..afbbe830 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.database.repository
import fr.acinq.bitcoin.Chain
import com.machankura.bennu.compose.managers.GroupWalletManager
+import com.machankura.bennu.compose.managers.GuardianManager
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.database.GENESIS_AT
@@ -208,6 +209,27 @@ class DatabaseChatRepository(
null
}
+ override suspend fun guardedWallets(chatRoomId: String): List = try {
+ GuardianManager.guardedWalletsOf(database, chatRoomId)
+ } catch (e: Throwable) {
+ logger.e("Error reading the guarded wallets $chatRoomId was told about", e)
+ emptyList()
+ }
+
+ override suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List = try {
+ GuardianManager.shareableFrom(database, chatRoomId, chain)
+ } catch (e: Throwable) {
+ logger.e("Error reading what $chatRoomId can tell the groups above it", e)
+ emptyList()
+ }
+
+ override suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int = try {
+ GuardianManager.share(database, shareable.statement, shareable.rooms, userPublicKey)
+ } catch (e: Throwable) {
+ logger.e("Error telling the groups above about ${shareable.statement.pubKey}'s guarded wallet", e)
+ 0
+ }
+
override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try {
database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId }
} catch (e: Throwable) {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt
new file mode 100644
index 00000000..1f242e4b
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt
@@ -0,0 +1,242 @@
+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.MarmotInnerEvent
+import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
+import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent
+import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent
+import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
+import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
+import fr.acinq.bitcoin.Chain
+import kotlin.time.Clock
+import kotlin.time.Instant
+
+/**
+ * What an ancestor group knows of the guarded wallets beneath it, and how it
+ * comes to know.
+ *
+ * A descendant opens a guarded wallet in its own room. Its ancestors are not in
+ * that room, so a member who sits in both carries the signed statement across
+ * as a [GuardedWalletNoticeEvent]; every device in the ancestor's room checks it
+ * for itself, and from then on watches the wallet and can propose spending from
+ * it through its own leaf. See `docs/group-wallet-guardians.md`, "How an
+ * ancestor finds the coins".
+ *
+ * A notice forwarded into a middle group can be forwarded again from there, so
+ * a root needs a member in common with each generation, not with the grandchild.
+ */
+object GuardianManager {
+ private const val TAG = "GuardianManager"
+
+ private val logger = Logger.withTag(TAG)
+
+ /** 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,
+ val descendantChatRoomId: String,
+ /** The descendant's signed statement, whole. */
+ 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. */
+ val certificate: Event,
+ /** The rooms the ancestor walks from its own child down to the descendant -- `GuardianDerivation.lineage`. */
+ val lineage: List,
+ ) {
+ /** 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)
+
+ val chain: Chain get() = account.chain
+
+ val openedAt: Instant get() = Instant.fromEpochSeconds(statement.createdAt)
+ }
+
+ /**
+ * [statement] as a guarded wallet [ancestorChatRoomId] guards, or null when
+ * it is not one -- believed on its own merits, never on the word of whoever
+ * forwarded it:
+ *
+ * 1. it is a wallet statement, and the room it is authored by signed it;
+ * 2. it is guarded, and carries the certificate its guardians came from;
+ * 3. the certificate's key makes that room, and the statement's xpub, tree
+ * and descriptors all rederive from it -- `Reading.verifiedAgainst`, which
+ * also checks the certificate certifies the room and grants exactly those
+ * guardians;
+ * 4. the ancestor is among the guardians, and the key the statement names
+ * for it is the key [ancestorThresholdPublicKey]'s guardian root reaches
+ * down the line of descent the guardians name. A key it does not reach is
+ * a leaf this group cannot sign, whatever the statement calls it.
+ */
+ fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching {
+ if (statement.kind != GroupWalletStatementEvent.KIND) return null
+ val descendantChatRoomId = statement.pubKey
+ if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null
+
+ val reading = GroupWalletStatementEvent.read(statement.tags, statement.content) ?: return null
+ if (reading.guardians.isEmpty()) return null
+ val certificate = reading.certificate ?: return null
+
+ val descendantKey = SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags) ?: return null
+ if (!SharedKeyDerivation.marmotGroupId(descendantKey).equals(descendantChatRoomId, ignoreCase = true)) return null
+ val account = reading.verifiedAgainst(descendantKey) ?: return null
+
+ val lineage = GuardianDerivation.lineage(account.guardians, descendantChatRoomId, 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 = descendantChatRoomId,
+ statement = statement,
+ account = account,
+ certificate = certificate,
+ lineage = lineage,
+ )
+ }.getOrNull()
+
+ /**
+ * Every guarded wallet [ancestorChatRoomId] has been told about and can sign
+ * for, one per descendant account on each network.
+ *
+ * Read off the notices the room's inbound path filed, checked again each
+ * time. Where two statements describe one account, the rules
+ * `GroupWallet.newestAmong` applies to the descendant's own copy apply here:
+ * the earliest decides the guardians and a later one naming others is
+ * ignored, so a forwarder cannot move the addresses an ancestor watches.
+ */
+ suspend fun guardedWalletsOf(database: BennuDatabase, ancestorChatRoomId: String): List {
+ val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, ancestorChatRoomId) ?: return emptyList()
+ val order = compareBy({ it.openedAt }, { it.statement.id })
+
+ return database.marmotInnerEventDao()
+ .getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND))
+ .mapNotNull { row -> Event.fromJsonOrNull(row.content) }
+ .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) }
+ .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) }
+ .mapNotNull { (_, statements) ->
+ val first = statements.minWithOrNull(order) ?: return@mapNotNull null
+ statements.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order)
+ }
+ .sortedBy { it.name ?: it.descendantChatRoomId }
+ }
+
+ /** The guarded wallet [ancestorChatRoomId] holds for [descendantChatRoomId] on [chain] at [account], or null. */
+ suspend fun guardedWalletFor(
+ database: BennuDatabase,
+ ancestorChatRoomId: String,
+ descendantChatRoomId: String,
+ chain: Chain,
+ account: Long,
+ ): GuardedWallet? = guardedWalletsOf(database, ancestorChatRoomId).firstOrNull {
+ it.descendantChatRoomId.equals(descendantChatRoomId, ignoreCase = true) && it.chain == chain && it.account.account == account
+ }
+
+ /** A guarded statement this device can carry upward, and the rooms it can carry it into. */
+ data class Shareable(
+ val statement: Event,
+ /** What the statement's room was certified as, for the screen. */
+ val name: String?,
+ val rooms: List,
+ )
+
+ /**
+ * The guarded statements this device can tell to groups above [chatRoomId]:
+ * the room's own guarded wallet, and every one the room was itself told
+ * about -- passed on a generation further. Each with the guardian rooms this
+ * device is a member of and has not told yet.
+ */
+ suspend fun shareableFrom(database: BennuDatabase, chatRoomId: String, chain: Chain): List {
+ val own = GroupWalletManager.walletFor(database, chatRoomId, chain)
+ ?.takeIf { it.account.isGuarded }
+ ?.let { wallet ->
+ val statement = wallet.signedEvent.toEvent()
+ val certificate = GroupWalletStatementEvent.read(statement.tags, statement.content)?.certificate
+ statement to (certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) })
+ }
+ 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) }
+ }
+ }
+
+ /**
+ * 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
+ .map { it.chatRoomId }
+ .filterNot { it.equals(excluding, ignoreCase = true) }
+ .mapNotNull { database.chatRoomDao().findChatRoomById(it) }
+ .filter { it.chatRoom.mlsGroupState != null }
+ .filterNot { room -> alreadyTold(database, room.chatRoom.id, statement.id) }
+ }
+
+ private suspend fun alreadyTold(database: BennuDatabase, chatRoomId: String, statementId: HexKey): Boolean =
+ database.marmotInnerEventDao()
+ .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND))
+ .any { Event.fromJsonOrNull(it.content)?.id == statementId }
+
+ /**
+ * Tells every room in [rooms] about [statement], as [userPublicKey]: one
+ * notice each, queued for the outbound pipeline the way every inner event
+ * is. Returns how many were queued.
+ */
+ suspend fun share(
+ database: BennuDatabase,
+ statement: Event,
+ rooms: List,
+ userPublicKey: HexKey,
+ createdAt: Long = Clock.System.now().epochSeconds,
+ ): Int {
+ val content = statement.toJson()
+ val tags = emptyArray>()
+
+ rooms.forEach { room ->
+ val id = EventHasher.hashId(userPublicKey, createdAt, GuardedWalletNoticeEvent.KIND, tags, content)
+ database.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(
+ id = id,
+ publicKey = userPublicKey,
+ kind = GuardedWalletNoticeEvent.KIND,
+ createdAt = Instant.fromEpochSeconds(createdAt),
+ tags = tags,
+ content = content,
+ chatRoomId = room.chatRoom.id,
+ )
+ )
+ logger.i("Told ${room.chatRoom.id} about ${statement.pubKey}'s guarded wallet")
+ }
+
+ return rooms.size
+ }
+
+ /**
+ * What a notice that arrived in [chatRoomId] says, for its transcript line --
+ * or null when it is not one this room can believe, which gets no line: a
+ * line saying a wallet was shared would read as the group being told
+ * something it was not.
+ */
+ suspend fun describeNotice(database: BennuDatabase, chatRoomId: String, notice: Event): String? {
+ val statement = GuardedWalletNoticeEvent.statementOf(notice) ?: return null
+ val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null
+ val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null
+
+ return wallet.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/nostr/wallet/GuardedWalletNoticeEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt
new file mode 100644
index 00000000..8826113b
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt
@@ -0,0 +1,46 @@
+package com.machankura.bennu.compose.nostr.wallet
+
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.Kind
+
+/**
+ * A member telling an ancestor group about a descendant's guarded wallet.
+ *
+ * The descendant's quorum signed a guarded `GroupWalletStatementEvent` in its
+ * own room, and the ancestors whose keys are in it are not in that room. A
+ * member who sits in both carries the statement across, whole, as the content of
+ * one of these in the ancestor's MLS room:
+ *
+ * ```
+ * descendant's room every member holds the signed 30331 "we keep a guarded wallet"
+ * member in both --[ 30333 carrying it ]-> the ancestor's room
+ * every ancestor device checks it on its own, and watches the wallet
+ * ```
+ *
+ * The forwarder vouches for nothing. A device believes the statement inside for
+ * the same reasons a descendant member does -- the descendant's room signed it,
+ * a certificate it carries certifies that room, the xpub rederives from the key
+ * the certificate names -- plus one of its own: its own guardian key in the
+ * statement is the key its group's walk reaches. See `GuardianManager.verify`.
+ *
+ * No table: the row the inbound path files for every inner event is the record,
+ * and each read checks it again.
+ *
+ * ### Never on a relay
+ *
+ * The statement inside is an xpub, which is every address and the whole
+ * balance. Like the statement, this only ever lives inside an encryption a relay
+ * cannot open: it is an MLS application message and nothing else.
+ *
+ * ### Why 30333
+ *
+ * The first free number past the transaction proposal (30332), beside the
+ * statement it carries.
+ */
+object GuardedWalletNoticeEvent {
+ val KIND: Kind = 30333
+
+ /** The statement a notice carries, or null when its content is not an event. Nothing is verified here. */
+ fun statementOf(notice: Event): Event? =
+ notice.takeIf { it.kind == KIND }?.let { Event.fromJsonOrNull(it.content) }
+}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
index 1351e00d..6f4a9cae 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
@@ -3,6 +3,7 @@ package com.machankura.bennu.compose.repository
import fr.acinq.bitcoin.Chain
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.managers.GroupWalletManager
+import com.machankura.bennu.compose.managers.GuardianManager
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.database.model.ChatRoom
import com.machankura.bennu.compose.database.model.GiftWrapPayload
@@ -127,6 +128,15 @@ interface ChatRepository {
*/
suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening?
+ /** The guarded wallets of groups below this one that it has been told about and can sign for. */
+ suspend fun guardedWallets(chatRoomId: String): List
+
+ /** The guarded statements this device can carry from this group to the groups above it, with where to. */
+ suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List
+
+ /** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */
+ suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int
+
/**
* The kind:1s this group signed, newest first.
*
@@ -391,6 +401,18 @@ interface ChatRepository {
chain: Chain
): GroupWalletManager.GuardedOpening? = null
+ override suspend fun guardedWallets(chatRoomId: String): List = emptyList()
+
+ override suspend fun shareableGuardedWallets(
+ chatRoomId: String,
+ chain: Chain
+ ): List = emptyList()
+
+ override suspend fun shareGuardedWallet(
+ shareable: GuardianManager.Shareable,
+ userPublicKey: HexKey
+ ): Int = 0
+
override suspend fun groupPosts(chatRoomId: String): List = emptyList()
override suspend fun groupSignedEvent(
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 a2e00a82..b648c2d1 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
@@ -74,6 +74,18 @@ import bennu.composeapp.generated.resources.group_wallet
import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet
import bennu.composeapp.generated.resources.open_a_group_wallet
import bennu.composeapp.generated.resources.open_a_guarded_wallet
+import bennu.composeapp.generated.resources.a_subgroup
+import bennu.composeapp.generated.resources.couldn_t_share_the_wallet
+import bennu.composeapp.generated.resources.guarded_wallets
+import bennu.composeapp.generated.resources.not_yet_shared_with_the_groups_above
+import bennu.composeapp.generated.resources.s_sats_within_this_group_s_reach
+import bennu.composeapp.generated.resources.share
+import bennu.composeapp.generated.resources.shared_with_the_groups_above
+import bennu.composeapp.generated.resources.tell_the_groups_above
+import bennu.composeapp.generated.resources.wallets_of_groups_below_this_one
+import com.machankura.bennu.compose.managers.GuardianManager
+import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow
+import androidx.compose.foundation.lazy.LazyListScope
import bennu.composeapp.generated.resources.open_without_guardians
import bennu.composeapp.generated.resources.the_groups_above_this_one_have_agreed_to_guard_it
import bennu.composeapp.generated.resources.guarded_the_groups_above_this_one_can_spend
@@ -165,6 +177,11 @@ fun GroupWalletScreen(
val couldNotOpen = stringResource(Res.string.couldn_t_ask_the_group_to_open_a_wallet)
val sentAgain = stringResource(Res.string.sent_again)
val couldNotBump = stringResource(Res.string.couldn_t_bump_the_fee)
+ val shared = stringResource(Res.string.shared_with_the_groups_above)
+ val couldNotShare = stringResource(Res.string.couldn_t_share_the_wallet)
+ val onShare = { shareable: GuardianManager.Shareable ->
+ groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) })
+ }
val toSession = { sessionId: String ->
onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId))
}
@@ -200,8 +217,8 @@ fun GroupWalletScreen(
}
is GroupWalletUIState.NotOpened -> {
- EmptyState(
- modifier = Modifier.padding(padding).readableContent(),
+ val notOpened = @Composable { modifier: Modifier -> EmptyState(
+ modifier = modifier,
message = stringResource(Res.string.this_group_has_not_opened_a_wallet),
icon = Icons.Default.AccountBalanceWallet,
// Hidden rather than disabled, the way every gated way in
@@ -232,7 +249,27 @@ fun GroupWalletScreen(
)
}
} else null
- )
+ ) }
+
+ if (state.guardedWallets.isEmpty() && state.shareable.isEmpty()) {
+ notOpened(Modifier.padding(padding).readableContent())
+ } else {
+ // A group with no wallet of its own can still guard others',
+ // and still carry a descendant's upward.
+ LazyColumn(
+ modifier = Modifier.padding(padding).readableContent().fillMaxSize()
+ .padding(MaterialTheme.spacing.screenMargin),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
+ ) {
+ item { notOpened(Modifier) }
+ guardianItems(
+ guardedWallets = state.guardedWallets,
+ shareable = state.shareable,
+ isPending = groupWalletViewModel.isActionPending.value,
+ onShare = onShare,
+ )
+ }
+ }
}
is GroupWalletUIState.Loaded -> {
@@ -270,6 +307,8 @@ fun GroupWalletScreen(
groupWalletViewModel.bumpFee(sessionId, onSuccess = toSession, onFailure = { notify(couldNotBump) })
}
} else null,
+ isPending = groupWalletViewModel.isActionPending.value,
+ onShare = onShare,
)
}
}
@@ -337,6 +376,8 @@ private fun OpenWallet(
onOpenSpend: (sessionId: String) -> Unit,
onSendAgain: ((sessionId: String) -> Unit)?,
onBump: ((sessionId: String) -> Unit)?,
+ isPending: Boolean,
+ onShare: (GuardianManager.Shareable) -> Unit,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
@@ -495,6 +536,13 @@ private fun OpenWallet(
)
}
}
+
+ guardianItems(
+ guardedWallets = state.guardedWallets,
+ shareable = state.shareable,
+ isPending = isPending,
+ onShare = onShare,
+ )
}
}
@@ -540,6 +588,60 @@ private fun SpendStatus.label() = when (this) {
}
/** Confirmed and on-the-way said apart: only the first can be spent by a send-all. */
+/**
+ * The guarded wallets of groups below this one, and the guarded statements this
+ * device can still carry to the groups above. Both under the room's own wallet,
+ * or in place of it for a group that has none.
+ */
+private fun LazyListScope.guardianItems(
+ guardedWallets: List,
+ shareable: List,
+ isPending: Boolean,
+ onShare: (GuardianManager.Shareable) -> Unit,
+) {
+ if (guardedWallets.isNotEmpty()) {
+ item {
+ Text(text = stringResource(Res.string.guarded_wallets), style = MaterialTheme.typography.titleMedium)
+ }
+ item {
+ Text(
+ text = stringResource(Res.string.wallets_of_groups_below_this_one, GuardianDerivation.ANCESTOR_DELAY.toInt()),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ 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 = {
+ Text(
+ row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) }
+ ?: stringResource(Res.string.balance_not_known_yet)
+ )
+ },
+ )
+ }
+ }
+
+ if (shareable.isNotEmpty()) {
+ item {
+ Text(text = stringResource(Res.string.tell_the_groups_above), style = MaterialTheme.typography.titleMedium)
+ }
+ items(shareable, key = { "shareable-" + it.statement.id }) { candidate ->
+ ListItem(
+ headlineContent = { Text(candidate.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) },
+ supportingContent = { Text(stringResource(Res.string.not_yet_shared_with_the_groups_above)) },
+ trailingContent = {
+ TextButton(onClick = { onShare(candidate) }, enabled = !isPending) {
+ Text(stringResource(Res.string.share))
+ }
+ },
+ )
+ }
+ }
+}
+
@Composable
private fun BalanceCard(walletState: GroupWalletState?) {
Card(modifier = Modifier.fillMaxWidth()) {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
index 7c09ed3f..5f9d8439 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
@@ -7,8 +7,12 @@ import com.machankura.bennu.compose.wallet.GroupSpend
import com.machankura.bennu.compose.wallet.GroupSpendBuilder
import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
import com.machankura.bennu.compose.wallet.GroupWalletRollout
+import com.machankura.bennu.compose.managers.GuardianManager
+import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow
+import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -71,16 +75,29 @@ class GroupWalletViewModel(
val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId)
val wallet = chatRepository.groupWallet(chatRoomId, chain)
+ val guarded = chatRepository.guardedWallets(chatRoomId).filter { it.chain == chain }
+ val shareable = chatRepository.shareableGuardedWallets(chatRoomId, chain)
+ val guardedRows = guarded.map { GuardedWalletRow(it, walletState = null) }
+
+ watching?.cancel()
if (wallet == null) {
- groupWalletUIState = GroupWalletUIState.NotOpened(
+ val notOpened = GroupWalletUIState.NotOpened(
localChatRoom = localChatRoom,
account = chatRepository.groupWalletAccount(chatRoomId, chain),
canSign = canSign,
guarded = if (GroupWalletRollout.offersGuardiansOn(chain)) {
chatRepository.groupWalletGuardedOpening(chatRoomId, chain)
} else null,
+ guardedWallets = guardedRows,
+ shareable = shareable,
)
+ groupWalletUIState = notOpened
+ if (guarded.isNotEmpty()) {
+ watching = viewModelScope.launch(Dispatchers.IO) {
+ guardedStates(guarded).collect { rows -> groupWalletUIState = notOpened.copy(guardedWallets = rows) }
+ }
+ }
return@launch
}
@@ -90,23 +107,64 @@ class GroupWalletViewModel(
walletState = null,
canWatch = wallets != null,
canSign = canSign,
+ guardedWallets = guardedRows,
+ shareable = shareable,
)
groupWalletUIState = loaded
- // The chain and the room's spends, as one state: either changing
- // redraws the screen, and neither may overwrite the other.
+ // The chain, the room's spends and the wallets it guards, as one
+ // state: any of them changing redraws the screen, and none may
+ // overwrite another.
val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null)
- watching?.cancel()
watching = viewModelScope.launch(Dispatchers.IO) {
- combine(chainState, frostSigningRepository.observeGroupTransactions(chatRoomId)) { state, transactions ->
- state to transactions.map { rowOf(it) }
- }.collect { (state, rows) ->
- groupWalletUIState = loaded.copy(walletState = state, spends = rows)
+ combine(
+ chainState,
+ frostSigningRepository.observeGroupTransactions(chatRoomId),
+ guardedStates(guarded),
+ ) { state, transactions, guardedWallets ->
+ Triple(state, transactions.map { rowOf(it) }, guardedWallets)
+ }.collect { (state, rows, guardedWallets) ->
+ groupWalletUIState = loaded.copy(walletState = state, spends = rows, guardedWallets = guardedWallets)
}
}
}
}
+ /**
+ * Each guarded wallet with what the chain says of it, on the identity's own
+ * Electrum client -- or with nothing, for a profile that cannot watch.
+ */
+ private suspend fun guardedStates(guarded: List): Flow> {
+ val wallets = wallets
+ if (wallets == null || guarded.isEmpty()) return flowOf(guarded.map { GuardedWalletRow(it, walletState = null) })
+
+ val states = guarded.map { wallet -> wallets.walletFor(wallet.account).state.map { GuardedWalletRow(wallet, it) } }
+ return combine(states) { it.toList() }
+ }
+
+ /**
+ * Tells the groups above about [shareable]'s guarded wallet: one notice into
+ * each of their rooms this device is in. What is told stays told, so the
+ * row goes from the screen once it is sent.
+ */
+ fun share(shareable: GuardianManager.Shareable, onShared: () -> Unit, onFailure: () -> Unit) {
+ if (isActionPending.value) return
+ isActionPending.value = true
+
+ viewModelScope.launch(Dispatchers.IO) {
+ val told = chatRepository.shareGuardedWallet(shareable, activeUserPublicKey)
+ if (told > 0) {
+ groupWalletUIState = when (val state = groupWalletUIState) {
+ is GroupWalletUIState.Loaded -> state.copy(shareable = state.shareable - shareable)
+ is GroupWalletUIState.NotOpened -> state.copy(shareable = state.shareable - shareable)
+ else -> state
+ }
+ }
+ withContext(Dispatchers.Main) { if (told > 0) onShared() else onFailure() }
+ isActionPending.value = false
+ }
+ }
+
/** Checked once per session: the PSBT is write-once, so what it says cannot change. */
private val checkedSpends = mutableMapOf()
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 d8379218..12691e90 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
@@ -3,6 +3,10 @@ package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.managers.GroupWalletManager
+import com.machankura.bennu.compose.managers.GuardianDerivation
+import com.machankura.bennu.compose.managers.GuardianManager
+import fr.acinq.bitcoin.Satoshi
+import fr.acinq.lightning.utils.sum
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.wallet.GroupWalletState
import com.machankura.bennu.compose.wallet.GroupSpend
@@ -27,6 +31,10 @@ sealed interface GroupWalletUIState {
val account: GroupWalletDerivation.Account?,
val canSign: Boolean,
val guarded: GroupWalletManager.GuardedOpening? = null,
+ /** Guarded wallets of groups below this one. A group with no wallet of its own can still guard others'. */
+ val guardedWallets: List = emptyList(),
+ /** Guarded statements this device can carry to the groups above. */
+ val shareable: List = emptyList(),
): GroupWalletUIState
/**
@@ -44,6 +52,10 @@ sealed interface GroupWalletUIState {
val canSign: Boolean,
/** The room's spends, newest first. */
val spends: List = emptyList(),
+ /** Guarded wallets of groups below this one. */
+ val guardedWallets: List = emptyList(),
+ /** Guarded statements this device can carry to the groups above. */
+ val shareable: List = emptyList(),
): GroupWalletUIState
data class Error(
@@ -53,6 +65,22 @@ sealed interface GroupWalletUIState {
data object Loading: GroupWalletUIState
}
+/** A descendant's guarded wallet, as an ancestor's wallet screen lists it. */
+data class GuardedWalletRow(
+ val wallet: GuardianManager.GuardedWallet,
+ /** Null before Electrum's first answer, and for a profile that cannot watch the chain. */
+ val walletState: GroupWalletState?,
+) {
+ /**
+ * What this group could spend now: coins confirmed at least as deep as its
+ * leaf's lock. Null while the chain is not known.
+ */
+ val withinReach: Satoshi?
+ get() = walletState?.let { state ->
+ state.utxos.filter { state.confirmations(it) >= GuardianDerivation.ANCESTOR_DELAY }.map { it.amount }.sum()
+ }
+}
+
/** Where one of the room's spends has got to, as one fact a member reads. */
enum class SpendStatus {
WAITING_FOR_SIGNATURES,
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
index c8418a88..cf275df8 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
@@ -29,6 +29,17 @@ import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.time.Instant
+import com.machankura.bennu.compose.database.model.GroupSignedEvent
+import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
+import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.crypto.frost.IndividualNonce
+import fr.acinq.bitcoin.crypto.frost.SecretNonce
+import fr.acinq.bitcoin.crypto.frost.Session
+import kotlin.test.assertTrue
/**
* A group's guardian keys through the real signing manager, between two of its
@@ -187,4 +198,160 @@ class GuardianSigningJvmTest {
assertNull(other.session(session.id), "refused at acceptance, so nothing of the member's is ever published for it")
}
+
+ // ---- Telling an ancestor about a guarded wallet -----------------------
+
+ /** The child as a group of its own, so its room can sign its statement. */
+ private val childMaterial: KeyMaterial = Frost.trustedDealerKeygen(
+ thresholdSecretKey = PrivateKey(ByteVector32("c41d".padEnd(62, '0') + "b2")),
+ nParticipants = participants,
+ threshold = threshold,
+ )
+ private val guardedChildKey = childMaterial.thresholdPublicKey.value.toHex()
+ private val guardedChildRoomId = SharedKeyDerivation.marmotGroupId(guardedChildKey)
+
+ /** [material]'s room signing [id], as a quorum of its trusted-dealer shares. */
+ private fun roomSignature(material: KeyMaterial, id: String): String {
+ val cache = SharedKeyDerivation.derive(material.thresholdPublicKey.value.toHex()).cache
+ val message = ByteVector(id.hexToByteArray())
+ val signerIds = listOf(0, 1)
+ val nonces = signerIds.map { signerId ->
+ SecretNonce.generate(
+ sessionRandom = ByteVector32("b".repeat(63) + "${signerId + 1}"),
+ secretShare = material.secretShares[signerId],
+ publicShare = material.publicShares[signerId],
+ tweakedThresholdPublicKey = cache.tweakedPublicKey,
+ message = message,
+ extraInput = null,
+ )
+ }
+ val session = Session.create(
+ aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!,
+ signerIds = signerIds.map { it.toUInt() },
+ signerPublicShares = signerIds.map { material.publicShares[it] },
+ nParticipants = participants,
+ threshold = threshold,
+ tweakCache = cache,
+ message = message,
+ )
+ val partials = signerIds.mapIndexed { position, signerId ->
+ session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!!
+ }
+ return session.aggregateSigs(partials).right!!.toByteArray().toHex()
+ }
+
+ private fun signedBy(material: KeyMaterial, kind: Int, tags: Array>, content: String, createdAt: Long = 1_700_000_000): Event {
+ val author = SharedKeyDerivation.marmotGroupId(material.thresholdPublicKey.value.toHex())
+ val id = EventHasher.hashId(author, createdAt, kind, tags, content)
+ return Event(id, author, createdAt, kind, tags, content, roomSignature(material, id))
+ }
+
+ /** The ancestor certifies the child with [guardians], and the child signs a guarded statement under them. */
+ private fun guardedStatement(
+ guardians: List = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId),
+ createdAt: Long = 1_700_000_000,
+ ): Event {
+ val certificate = signedBy(
+ keyMaterial, SubgroupBirthCertificateEvent.KIND,
+ SubgroupBirthCertificateEvent.assembleTags(
+ subgroupChatRoomId = guardedChildRoomId, parentChatRoomId = roomId, thresholdPublicKey = guardedChildKey,
+ adminPublicKeys = members, name = "Translation team", guardians = guardians,
+ ),
+ guardedChildRoomId,
+ )
+ val account = GroupWalletDerivation.account(guardedChildKey, Chain.Regtest, guardians = guardians)
+ val template = GroupWalletStatementEvent.template(account, certificate, createdAt)
+ return signedBy(childMaterial, template.kind, template.tags, template.content, createdAt)
+ }
+
+ private suspend fun tell(device: Device, statement: Event, from: HexKey = members[2], createdAt: Long = 1_700_000_100) {
+ val content = statement.toJson()
+ device.db.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(
+ id = EventHasher.hashId(from, createdAt, GuardedWalletNoticeEvent.KIND, emptyArray(), content),
+ publicKey = from, kind = GuardedWalletNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(createdAt),
+ tags = emptyArray(), content = content, chatRoomId = roomId,
+ )
+ )
+ }
+
+ @Test
+ fun `an ancestor believes a statement naming a key its own walk reaches, and nothing else`() {
+ val statement = guardedStatement()
+
+ val wallet = assertNotNull(GuardianManager.verify(statement, roomId, thresholdPublicKey))
+ assertEquals(guardedChildRoomId, wallet.descendantChatRoomId)
+ assertEquals(listOf(guardedChildRoomId), wallet.lineage)
+ assertEquals("Translation team", wallet.name)
+ assertTrue(wallet.account.isGuarded)
+
+ val strangerKey = PrivateKey(ByteVector32(ByteArray(32) { 0x55 })).publicKey().toString()
+ val refusals = mapOf(
+ "a group that is not among its guardians" to GuardianManager.verify(statement, guardedChildRoomId, guardedChildKey),
+ "a key the ancestor's walk does not reach" to GuardianManager.verify(
+ guardedStatement(GuardianDerivation.grant(strangerKey, roomId, emptyList(), guardedChildRoomId)), roomId, thresholdPublicKey,
+ ),
+ "a statement the child's room did not sign" to GuardianManager.verify(Event(statement.id, statement.pubKey, statement.createdAt, statement.kind, statement.tags, statement.content, "0".repeat(128)), roomId, thresholdPublicKey),
+ "a plain statement" to run {
+ val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(guardedChildKey, Chain.Regtest))
+ GuardianManager.verify(signedBy(childMaterial, plain.kind, plain.tags, plain.content), roomId, thresholdPublicKey)
+ },
+ )
+ refusals.forEach { (name, verified) -> assertNull(verified, name) }
+ }
+
+ @Test
+ fun `a notice in the ancestor's room is a guarded wallet it holds, under its first guardians`() = runBlocking {
+ val ancestor = device(members[0], signerIndex = 0)
+ val first = guardedStatement(createdAt = 1_700_000_000)
+ tell(ancestor, first)
+ // A later statement for the same account, naming other guardians, cannot
+ // move what the ancestor watches -- the earliest decides.
+ val second = guardedStatement(
+ GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId).map { it.copy(delay = 13) },
+ createdAt = 1_700_000_500,
+ )
+ tell(ancestor, second, createdAt = 1_700_000_600)
+ // And nonsense is read past, not believed.
+ ancestor.db.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(id = "f".repeat(64), publicKey = members[2], kind = GuardedWalletNoticeEvent.KIND,
+ createdAt = Instant.fromEpochSeconds(1), tags = emptyArray(), content = "not an event", chatRoomId = roomId)
+ )
+
+ val held = GuardianManager.guardedWalletsOf(ancestor.db, roomId)
+ assertEquals(listOf(first.id), held.map { it.statement.id })
+ assertEquals(
+ "Shared the guarded wallet of Translation team with this group.",
+ GuardianManager.describeNotice(ancestor.db, roomId, Event("1".repeat(64), members[2], 1, GuardedWalletNoticeEvent.KIND, emptyArray(), first.toJson(), ""))
+ )
+ }
+
+ @Test
+ fun `a member in both rooms carries the child's statement up, once`() = runBlocking {
+ val member = device(members[0], signerIndex = 0)
+ // This device is also in the child's room, and holds its signed statement there.
+ member.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = member.publicKey, subject = "Translation team", description = null, mlsGroupState = "00"))
+ member.db.groupKeyStateDao().upsert(
+ com.machankura.bennu.compose.database.model.GroupKeyState(
+ chatRoomId = guardedChildRoomId, dkgSessionId = "child-ceremony", thresholdPublicKey = guardedChildKey,
+ derivationPath = SharedKeyDerivation.formatPath(), announcedBy = guardedChildRoomId,
+ announcedAt = Instant.fromEpochSeconds(1_700_000_000),
+ )
+ )
+ val statement = guardedStatement()
+ member.db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(statement, chatRoomId = guardedChildRoomId))
+
+ val shareable = GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest).single()
+ assertEquals(statement.id, shareable.statement.id)
+ assertEquals(listOf(roomId), shareable.rooms.map { it.chatRoom.id })
+
+ assertEquals(1, GuardianManager.share(member.db, shareable.statement, shareable.rooms, member.publicKey))
+ val queued = member.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND)).single()
+ assertEquals(member.publicKey, queued.publicKey)
+ assertNull(queued.marmotGroupEventId, "queued for the outbound pipeline, not yet sent")
+
+ // Told is told: nothing left to share, and the ancestor's own device reads it back.
+ assertEquals(emptyList(), GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest))
+ assertEquals(listOf(statement.id), GuardianManager.guardedWalletsOf(member.db, roomId).map { it.statement.id })
+ }
}