diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 5caa64b2..566b9877 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -703,4 +703,5 @@
Put to the group
Couldn't put it to the group.
Wallets your groups guard
+ This device tells the groups above about these on its own when it can. Share now if a group above hasn't heard.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt
index a8fc62fa..4c84d7b5 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
@@ -972,6 +972,13 @@ data class ChatMessage(
// no table -- so all that is left is the line, and only for a
// notice this room can actually believe.
if (event.kind == GuardedWalletNoticeEvent.KIND) {
+ // And on, a generation further: the statement inside, to
+ // the groups above this one that this device is in. Any
+ // device that believes it can, whether or not it holds this
+ // room's key. docs/guarded-wallet-forwarding.md.
+ GuardedWalletNoticeEvent.statementOf(event)?.let {
+ GuardianManager.forwardOnArrival(database, it, groupEventResult.groupId)
+ }
val content = GuardianManager.describeNotice(database, groupEventResult.groupId, event)
?: return null
return ChatMessage(
@@ -1311,6 +1318,9 @@ data class ChatMessage(
// checks it there again.
MemberWalletCertificateEvent.KIND -> {
val verified = MemberWalletCertificateEvent.verify(event, groupId) ?: return null
+ // The groups above this one guard the wallet too, and learn
+ // of it only by being told. docs/guarded-wallet-forwarding.md.
+ GuardianManager.forwardOnArrival(database, event, groupId)
ChatMessage(
giftWrapPayloadId = null,
@@ -1361,6 +1371,9 @@ data class ChatMessage(
val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, groupId)
?: return null
val wallet = GroupWallet.of(signed, thresholdPublicKey) ?: return null
+ // A guarded wallet is one the groups above can find only by
+ // being told of it. docs/guarded-wallet-forwarding.md.
+ if (wallet.account.isGuarded) GuardianManager.forwardOnArrival(database, event, groupId)
ChatMessage(
giftWrapPayloadId = null,
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 0194a011..a336dc4a 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
@@ -192,6 +192,15 @@ class DatabaseChatRepository(
emptyList()
}
+ override suspend fun forwardGuardedWallets(chatRoomId: String): Int = try {
+ GuardianManager.forwardAll(database, chatRoomId)
+ } catch (e: Throwable) {
+ // A room that opens without telling the groups above is wrong and
+ // survivable, and the button is still there.
+ logger.e("Error forwarding $chatRoomId's guarded wallets upward", e)
+ 0
+ }
+
override suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int = try {
GuardianManager.share(database, shareable.statement, shareable.rooms, userPublicKey)
} 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
index 463b8e64..a658489b 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt
@@ -11,8 +11,8 @@ import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent
import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent
-import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag
import com.machankura.bennu.compose.wallet.GroupSpend
+import com.machankura.bennu.compose.wallet.GroupWalletRollout
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
@@ -116,23 +116,53 @@ object GuardianManager {
}
/**
- * [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:
+ * A guarded wallet statement believed on its own merits -- everything
+ * [verify] checks except the walk down from an ancestor's own guardian root,
+ * which only a device holding that ancestor's key can make. What a forwarder
+ * checks before passing a statement on (`docs/guarded-wallet-forwarding.md`,
+ * D2): a notice it would copy into every group above should be one it
+ * believes itself.
+ */
+ data class Believable(
+ val statement: Event,
+ /** The descendant's room id, or a member wallet's `W`: what the line of descent ends in. */
+ val descendantId: String,
+ /** The account the statement opens, rederived from the descendant's key. */
+ val account: GroupWalletDerivation.Account,
+ /** A subgroup's birth certificate, carried in the statement -- or, for a member, the certificate itself. */
+ val certificate: Event,
+ val subject: GuardedSubject,
+ ) {
+ /** Every guardian, nearest first: the groups that can be told. */
+ val guardians: List get() = account.guardians
+
+ val chain: Chain get() = account.chain
+ }
+
+ /**
+ * [statement] believed, or null:
*
* 1. it is a wallet statement, and the room it is authored by signed it;
* 2. it is guarded, and carries the certificate its guardians came from;
* 3. the certificate's key makes that room, and the statement's xpub, tree
* and descriptors all rederive from it -- `Reading.verifiedAgainst`, which
* also checks the certificate certifies the room and grants exactly those
- * guardians;
- * 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.
+ * guardians.
+ *
+ * Or a member wallet certificate the guarding group signed over the member's
+ * own request -- `MemberWalletCertificateEvent.verify`.
*/
- fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching {
- if (statement.kind == MemberWalletCertificateEvent.KIND) return verifyMember(statement, ancestorChatRoomId, ancestorThresholdPublicKey)
+ fun believable(statement: Event): Believable? = runCatching {
+ if (statement.kind == MemberWalletCertificateEvent.KIND) {
+ val verified = MemberWalletCertificateEvent.verify(statement, statement.pubKey) ?: return null
+ return Believable(
+ statement = statement,
+ descendantId = verified.walletId,
+ account = verified.account,
+ certificate = statement,
+ subject = GuardedSubject.Member(verified.walletId, verified.memberPublicKey, verified.label),
+ )
+ }
if (statement.kind != GroupWalletStatementEvent.KIND) return null
val descendantChatRoomId = statement.pubKey
if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null
@@ -149,35 +179,31 @@ object GuardianManager {
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,
+ Believable(
statement = statement,
+ descendantId = descendantChatRoomId,
account = account,
certificate = certificate,
- lineage = lineage,
+ subject = GuardedSubject.Subgroup(descendantChatRoomId, SubgroupBirthCertificateEvent.parseName(certificate.tags)),
)
}.getOrNull()
/**
- * [certificate] as a member's guarded wallet [ancestorChatRoomId] guards, or
- * null when it is not one: the guarding group signed it over the member's
- * own request (`MemberWalletCertificateEvent.verify`), and -- rule 4 of
- * [verify] -- the key it names for the ancestor is the key the ancestor's
- * guardian root reaches down the line of descent, which ends in the
- * wallet's id where a subgroup's ends in its room.
+ * [statement] as a guarded wallet [ancestorChatRoomId] guards, or null when
+ * it is not one -- believed on its own merits, never on the word of whoever
+ * forwarded it: [believable], and
+ *
+ * 4. the ancestor is among the guardians, and the key the statement names
+ * for it is the key [ancestorThresholdPublicKey]'s guardian root reaches
+ * down the line of descent the guardians name. A key it does not reach is
+ * a leaf this group cannot sign, whatever the statement calls it. The
+ * line ends in the descendant's room, or in a member wallet's id.
*/
- private fun verifyMember(certificate: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching {
- val verified = MemberWalletCertificateEvent.verify(certificate, certificate.pubKey) ?: return null
- val account = verified.account
+ fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching {
+ val believed = believable(statement) ?: return null
+ val account = believed.account
- val lineage = GuardianDerivation.lineage(account.guardians, verified.walletId, ancestorChatRoomId) ?: return null
+ val lineage = GuardianDerivation.lineage(account.guardians, believed.descendantId, ancestorChatRoomId) ?: return null
val named = account.guardians.first { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) }
val walked = GuardianDerivation.root(ancestorThresholdPublicKey).extendedPublicKey
.derivePublicKey(lineage.map(GuardianDerivation::childIndex))
@@ -185,22 +211,43 @@ object GuardianManager {
GuardedWallet(
ancestorChatRoomId = ancestorChatRoomId,
- descendantChatRoomId = verified.walletId,
- statement = certificate,
+ descendantChatRoomId = believed.descendantId,
+ statement = statement,
account = account,
- certificate = certificate,
+ certificate = believed.certificate,
lineage = lineage,
- subject = GuardedSubject.Member(verified.walletId, verified.memberPublicKey, verified.label),
+ subject = believed.subject,
)
}.getOrNull()
- /** [wallet] with its member's profile name, where this device knows one. */
- private suspend fun named(database: BennuDatabase, wallet: GuardedWallet): GuardedWallet {
- val member = wallet.subject as? GuardedSubject.Member ?: return wallet
- val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey()
- return wallet.copy(subject = member.copy(ownerName = name))
+ /**
+ * The guardian rooms a statement is told to from [chatRoomId]: those after it
+ * in [guardians], nearest first -- upward only
+ * (`docs/guarded-wallet-forwarding.md`, D3). A room the list does not name is
+ * the wallet's own, a subgroup's, and is told to every guardian.
+ *
+ * Every guardian *except* the room, which is what the button used to take,
+ * reaches down as well as up: from a root holding a grandchild's statement it
+ * would tell the middle group, which told the root.
+ */
+ fun upwardOf(guardians: List, chatRoomId: String): List {
+ val position = guardians.indexOfFirst { it.chatRoomId.equals(chatRoomId, ignoreCase = true) }
+ return guardians.drop(position + 1).map { it.chatRoomId }
}
+ /**
+ * Of [candidates] -- the members of both a room and a group above it, as this
+ * device's participant lists have them -- the one who sends a notice the
+ * moment a wallet arrives: the lowest key. Everybody else waits for the
+ * catch-up, by when the elected device's notice has usually arrived
+ * (`docs/guarded-wallet-forwarding.md`, D4). Null when there are none.
+ */
+ fun electedSender(candidates: Set): HexKey? = candidates.map { it.lowercase() }.minOrNull()
+
+ /** [wallet] with its member's profile name, where this device knows one. */
+ private suspend fun named(database: BennuDatabase, wallet: GuardedWallet): GuardedWallet =
+ wallet.copy(subject = named(database, wallet.subject))
+
/**
* Every guarded wallet [ancestorChatRoomId] has been told about and can sign
* for, one per descendant account on each network.
@@ -285,35 +332,106 @@ object GuardianManager {
}
return candidates.mapNotNull { candidate ->
- val rooms = targetsFor(database, candidate.statement, excluding = chatRoomId)
+ val rooms = targetsFor(database, candidate.statement, fromChatRoomId = chatRoomId)
rooms.takeIf { it.isNotEmpty() }?.let { candidate.copy(rooms = it) }
}
}
- /** The guardians [statement] names, nearest first: a subgroup's statement's, or a member wallet certificate's. */
- private fun guardiansNamedIn(statement: Event): List = when (statement.kind) {
- MemberWalletCertificateEvent.KIND -> GuardianTag.parseAll(statement.tags).orEmpty()
- else -> GroupWalletStatementEvent.read(statement.tags, statement.content)?.guardians.orEmpty()
+ /**
+ * The groups above [fromChatRoomId] that [statement] should be told to and
+ * this device can tell: [upwardOf] the room, Marmot rooms this device holds,
+ * belonging to the same profile as the room it is told from -- one database
+ * holds every profile, and a device must never post into a room as a
+ * profile that is not the one in it -- and not told yet. Nothing for a
+ * statement this device does not believe ([believable]).
+ */
+ private suspend fun targetsFor(database: BennuDatabase, statement: Event, fromChatRoomId: String): List {
+ val believed = believable(statement) ?: return emptyList()
+ val profile = database.chatRoomDao().findChatRoomById(fromChatRoomId)?.chatRoom?.userPublicKey
+
+ return upwardOf(believed.guardians, fromChatRoomId)
+ .mapNotNull { database.chatRoomDao().findChatRoomById(it) }
+ .filter { it.chatRoom.mlsGroupState != null }
+ .filter { profile == null || it.chatRoom.userPublicKey.equals(profile, ignoreCase = true) }
+ .filterNot { room -> told(database, room.chatRoom.id, statement.id) }
}
/**
- * 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.
+ * Whether [chatRoomId] holds the statement [statementId] in any form: a
+ * notice carrying it, or the signed event itself -- which is how a group
+ * holds a member wallet certificate it signed, and never as a notice.
*/
- private suspend fun targetsFor(database: BennuDatabase, statement: Event, excluding: String): List {
- return guardiansNamedIn(statement)
- .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) }
+ internal suspend fun told(database: BennuDatabase, chatRoomId: String, statementId: HexKey): Boolean =
+ database.groupSignedEventDao().getById(statementId)?.chatRoomId.equals(chatRoomId, ignoreCase = true) ||
+ database.marmotInnerEventDao()
+ .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND))
+ .any { Event.fromJsonOrNull(it.content)?.id == statementId }
+
+ /**
+ * Tells every group above [chatRoomId] that this device can tell, and that
+ * has not been told, about [statement] -- as the profile that is in
+ * [chatRoomId]. `docs/guarded-wallet-forwarding.md`, Phase 2.
+ *
+ * With [whenElected], only the groups this device is the elected sender for
+ * ([electedSender] over the members of both rooms, as this device's
+ * participant lists have them, itself always among them): the moment a wallet
+ * arrives every device in both rooms has it, and only one of them should
+ * post at once. The catch-up passes false, and tells whatever is still left.
+ *
+ * Returns the rooms told.
+ */
+ suspend fun forward(database: BennuDatabase, statement: Event, chatRoomId: String, whenElected: Boolean): List {
+ val sender = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey ?: return emptyList()
+ val members = database.participantDao().findParticipantsByChatRoomId(chatRoomId).map { it.participantPublicKey.lowercase() }.toSet()
+
+ val targets = targetsFor(database, statement, fromChatRoomId = chatRoomId).filter { target ->
+ if (!whenElected) return@filter true
+ val both = database.participantDao().findParticipantsByChatRoomId(target.chatRoom.id)
+ .map { it.participantPublicKey.lowercase() }
+ .filter { it in members }
+ .toSet() + sender.lowercase()
+ electedSender(both).equals(sender, ignoreCase = true)
+ }
+ if (targets.isNotEmpty()) share(database, statement, targets, sender)
+ return targets
}
- 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 }
+ /** Every network a guarded wallet can be on: the catch-up forwards them all. */
+ private val CHAINS: List = listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest)
+
+ /**
+ * The catch-up: everything [shareableFrom] would list from [chatRoomId], on
+ * every network, through [forward] without the election -- whatever the
+ * elected device never sent, whatever arrived while this one was offline,
+ * and everything filed before forwarding existed.
+ * `docs/guarded-wallet-forwarding.md`, Phase 4. Run as the group's chat and
+ * its wallet screen open. Returns how many groups were told.
+ */
+ suspend fun forwardAll(database: BennuDatabase, chatRoomId: String): Int {
+ if (!GroupWalletRollout.FORWARDS_GUARDED_WALLETS) return 0
+ val own = CHAINS.mapNotNull { chain ->
+ GroupWalletManager.walletFor(database, chatRoomId, chain)?.takeIf { it.account.isGuarded }?.signedEvent?.toEvent()
+ }
+ val held = guardedWalletsOf(database, chatRoomId).map { it.statement }
+
+ return (own + held).distinctBy { it.id }.sumOf { statement ->
+ runCatching { forward(database, statement, chatRoomId, whenElected = false).size }
+ .onFailure { logger.e("Could not forward ${statement.id.take(8)} from $chatRoomId", it) }
+ .getOrDefault(0)
+ }
+ }
+
+ /**
+ * [forward] on arrival, from the inbound path: elected, behind
+ * `GroupWalletRollout.FORWARDS_GUARDED_WALLETS`, and never failing the
+ * arrival it rides on -- forwarding is an extra, and the arrival is the thing.
+ */
+ suspend fun forwardOnArrival(database: BennuDatabase, statement: Event, chatRoomId: String) {
+ if (!GroupWalletRollout.FORWARDS_GUARDED_WALLETS) return
+ runCatching { forward(database, statement, chatRoomId, whenElected = true) }
+ .onSuccess { told -> if (told.isNotEmpty()) logger.i("Forwarded ${statement.id.take(8)} from $chatRoomId to ${told.size} group(s) above") }
+ .onFailure { logger.e("Could not forward ${statement.id.take(8)} from $chatRoomId", it) }
+ }
/**
* Tells every room in [rooms] about [statement], as [userPublicKey]: one
@@ -333,9 +451,30 @@ object GuardianManager {
): Int {
val content = statement.toJson()
+ // The sender is never handed its own MLS message back, so the line the
+ // other members' devices write when it arrives is written here for the
+ // sender's own -- before the notice, which then finds a line already
+ // there. docs/guarded-wallet-forwarding.md, D6.
+ val line = believable(statement)?.let { describe(named(database, it.subject)) }
+
rooms.forEach { room ->
val tags = arrayOf(arrayOf("h", room.chatRoom.id))
val id = EventHasher.hashId(userPublicKey, createdAt, GuardedWalletNoticeEvent.KIND, tags, content)
+ line?.takeIf { firstNoticeOf(database, room.chatRoom.id, statement.id, excludingNotice = id) }?.let {
+ database.chatMessageDao().upsert(
+ ChatMessage(
+ giftWrapPayloadId = null,
+ messageType = ChatMessage.TYPE_GUARDED_WALLET_SHARED,
+ marmotGroupEventId = null,
+ marmotInnerEventId = null,
+ senderPublicKey = userPublicKey,
+ isUserMessage = true,
+ chatRoomId = room.chatRoom.id,
+ createdAt = Instant.fromEpochSeconds(createdAt),
+ content = it,
+ )
+ )
+ }
database.marmotInnerEventDao().upsert(
MarmotInnerEvent(
id = id,
@@ -436,11 +575,36 @@ object GuardianManager {
val statement = GuardedWalletNoticeEvent.statementOf(notice) ?: return null
val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null
val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null
+ // One line per wallet per group: a second notice of a statement this room
+ // already holds -- told before, by another forwarder, or signed here --
+ // is filed and silent. docs/guarded-wallet-forwarding.md, D6.
+ if (!firstNoticeOf(database, chatRoomId, statement.id, excludingNotice = notice.id)) return null
- return when (val subject = named(database, wallet).subject) {
- is GuardedSubject.Member -> "Shared @${subject.ownerName ?: subject.ownerPublicKey.take(8)}'s guarded wallet with this group."
- is GuardedSubject.Subgroup -> subject.name?.let { "Shared the guarded wallet of $it with this group." }
- ?: "Shared a subgroup's guarded wallet with this group."
- }
+ return describe(named(database, wallet).subject)
+ }
+
+ private fun describe(subject: GuardedSubject): String = when (subject) {
+ is GuardedSubject.Member -> "Shared @${subject.ownerName ?: subject.ownerPublicKey.take(8)}'s guarded wallet with this group."
+ is GuardedSubject.Subgroup -> subject.name?.let { "Shared the guarded wallet of $it with this group." }
+ ?: "Shared a subgroup's guarded wallet with this group."
+ }
+
+ /** [subject] with its member's profile name, where this device knows one. */
+ private suspend fun named(database: BennuDatabase, subject: GuardedSubject): GuardedSubject {
+ val member = subject as? GuardedSubject.Member ?: return subject
+ val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey()
+ return member.copy(ownerName = name)
+ }
+
+ /**
+ * Whether a notice of [statementId] -- [excludingNotice], the one being
+ * filed or sent -- is the first [chatRoomId] holds: no other notice in the
+ * room carries the statement, and the room did not sign it itself.
+ */
+ private suspend fun firstNoticeOf(database: BennuDatabase, chatRoomId: String, statementId: HexKey, excludingNotice: HexKey): Boolean {
+ if (database.groupSignedEventDao().getById(statementId)?.chatRoomId.equals(chatRoomId, ignoreCase = true)) return false
+ return database.marmotInnerEventDao()
+ .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND))
+ .none { it.id != excludingNotice && Event.fromJsonOrNull(it.content)?.id == statementId }
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
index aebfb4f7..f19e55c8 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
@@ -128,6 +128,13 @@ interface ChatRepository {
/** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */
suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int
+ /**
+ * Tells the groups above this one about every guarded wallet it holds that
+ * they have not heard of -- the catch-up of `docs/guarded-wallet-forwarding.md`.
+ * Returns how many groups were told. Nothing, by default.
+ */
+ suspend fun forwardGuardedWallets(chatRoomId: String): Int = 0
+
/** Writes a transcript line for each guardian spend from this group's wallet it has none for yet. */
suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int
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 00924465..7d1bffc8 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
@@ -101,6 +101,7 @@ import bennu.composeapp.generated.resources.share
import bennu.composeapp.generated.resources.spend
import bennu.composeapp.generated.resources.shared_with_the_groups_above
import bennu.composeapp.generated.resources.tell_the_groups_above
+import bennu.composeapp.generated.resources.this_device_shares_these_on_its_own_when_it_can
import bennu.composeapp.generated.resources.wallets_of_groups_below_this_one
import com.machankura.bennu.compose.managers.GuardianManager
import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow
@@ -717,6 +718,16 @@ private fun LazyListScope.guardianItems(
item {
Text(text = stringResource(Res.string.tell_the_groups_above), style = MaterialTheme.typography.titleMedium)
}
+ // What is left here is what the automatic forwarding could not send --
+ // a notice lost on the wire, most often -- so the section says so, once.
+ // docs/guarded-wallet-forwarding.md, Phase 6.
+ item {
+ Text(
+ text = stringResource(Res.string.this_device_shares_these_on_its_own_when_it_can),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
items(shareable, key = { "shareable-" + it.statement.id }) { candidate ->
ListItem(
headlineContent = {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt
index 31fbbd42..81283a42 100755
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt
@@ -204,6 +204,7 @@ class ChatMessageListViewModel(
observeProposalsAwaitingYou()
observeCeremoniesAwaitingYou()
askForGroupHistory()
+ forwardGuardedWallets()
resumeSigningSessions()
}
@@ -311,6 +312,22 @@ class ChatMessageListViewModel(
}
}
+ /**
+ * Tells the groups above this one about every guarded wallet it holds that
+ * they have not heard of: the catch-up behind the arrival triggers, which
+ * covers a wallet that arrived while this device was offline, one the
+ * elected device never sent, and every one filed before forwarding existed.
+ * `docs/guarded-wallet-forwarding.md`, D5. A Marmot room only -- a guardian
+ * is a group with a key, and a group with a key has an MLS room.
+ */
+ private fun forwardGuardedWallets() {
+ if (localChatRoom.chatRoom.mlsGroupState == null) return
+ viewModelScope.launch(Dispatchers.IO) {
+ runCatching { chatRepository.forwardGuardedWallets(localChatRoom.chatRoom.id) }
+ .onFailure { logger.w(throwable = it) { "Could not tell the groups above about this group's guarded wallets" } }
+ }
+ }
+
/**
* Lets this room's answered signing sessions take any step they are able to.
*
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
index 3fd30148..9e6fabfe 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
@@ -81,6 +81,9 @@ class GroupWalletViewModel(
val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId)
val wallet = chatRepository.groupWallet(chatRoomId, chain)
val guarded = chatRepository.guardedWallets(chatRoomId).filter { it.chain == chain }
+ // The catch-up first, so what the screen offers to share is only what
+ // could not be sent. docs/guarded-wallet-forwarding.md, Phase 4.
+ chatRepository.forwardGuardedWallets(chatRoomId)
val shareable = chatRepository.shareableGuardedWallets(chatRoomId, chain)
val guardedRows = guarded.map { GuardedWalletRow(it, walletState = null) }
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt
index fe652571..b125f0f7 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt
@@ -60,6 +60,16 @@ object GroupWalletRollout {
fun offersMemberWalletsOn(chain: Chain): Boolean = MEMBER_WALLETS_ON_MAINNET || !chain.isMainnet()
+ /**
+ * Whether a device tells the groups above about a guarded wallet on its own
+ * -- as the wallet arrives, and as a group's chat or wallet screen opens --
+ * rather than only when somebody taps *Share*.
+ * `docs/guarded-wallet-forwarding.md`, D8. A behaviour that sends messages
+ * without a person, so it has a switch for the release it first ships in.
+ * The button does not read it.
+ */
+ const val FORWARDS_GUARDED_WALLETS: Boolean = true
+
/**
* The most a member's own spend from their guarded wallet may send on
* [chain]: [MAINNET_CAP] on mainnet, as every other spend is. The gate
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardJvmTest.kt
new file mode 100644
index 00000000..ccb8cc4f
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardJvmTest.kt
@@ -0,0 +1,325 @@
+package com.machankura.bennu.compose.managers
+
+import androidx.room3.Room
+import com.machankura.bennu.compose.database.BennuDatabase
+import com.machankura.bennu.compose.database.builder.getRoomDatabase
+import com.machankura.bennu.compose.database.model.GroupSignedEvent
+import com.machankura.bennu.compose.managers.GroupFixtures.birthCertificate
+import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState
+import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial
+import com.machankura.bennu.compose.managers.GroupFixtures.roomOf
+import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom
+import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom
+import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf
+import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent
+import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent
+import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent
+import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.crypto.frost.KeyMaterial
+import fr.acinq.secp256k1.Hex
+import kotlinx.coroutines.runBlocking
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+
+/**
+ * Telling the groups above about a guarded wallet, as a function: upward only,
+ * never a group that already holds it, never as another profile, and -- when
+ * a wallet has only just arrived -- only by the device elected to send at once.
+ * `docs/guarded-wallet-forwarding.md`, Phase 2.
+ *
+ * A root `R`, its guarded subgroup `M`, and `M`'s guarded subgroup `G`, which
+ * guards a member's wallet: the wallet's guardians are `G`, `M` and `R`.
+ */
+class GuardedWalletForwardJvmTest {
+ private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val chain = Chain.Regtest
+
+ private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0'))))
+
+ private val root = keyMaterial("7007")
+ private val middle = keyMaterial("9a9e")
+ private val group = keyMaterial("6a0b")
+ private val rootRoom = roomOf(root)
+ private val middleRoom = roomOf(middle)
+ private val groupRoom = roomOf(group)
+
+ /** `M`'s certificate from `R`, and `G`'s from `M` with `R`'s key passed one step further. */
+ private val middleCertificate = birthCertificate(root, middle, GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom))
+ private val groupCertificate = birthCertificate(
+ middle, group,
+ GuardianDerivation.grant(thresholdKeyOf(middle), middleRoom, SubgroupBirthCertificateEvent.parseGuardians(middleCertificate.tags)!!, groupRoom),
+ )
+
+ private val member = privateKey(0x3e3be7)
+ private val memberPublicKey = member.xOnlyPublicKey().value.toHex()
+ private val walletPrivateKey = privateKey(0xa11ce)
+ private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey())
+
+ private val certificate: Event = run {
+ val grant = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, SubgroupBirthCertificateEvent.parseGuardians(groupCertificate.tags)!!, walletId)
+ val request = MemberWalletRequestEvent.build(
+ memberPrivateKey = member,
+ groupChatRoomId = groupRoom,
+ walletPrivateKey = walletPrivateKey,
+ account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, grant),
+ label = null,
+ createdAt = 1_700_000_000,
+ )
+ val template = MemberWalletCertificateEvent.template(request)
+ signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt)
+ }
+
+ /** A member whose key sorts above this device's own, so this device stays the elected sender. */
+ private val laterMember = "f".repeat(64)
+
+ /** This device in [material]'s room, with its key state, and [members] beside it. */
+ private suspend fun inRoom(material: KeyMaterial, certificate: Event?, members: List = listOf(memberPublicKey, laterMember)) {
+ signingRoom(db, material, members = members, subject = "#" + roomOf(material).take(4), holdsShare = false)
+ fileKeyState(db, material, certificate)
+ }
+
+ private suspend fun inAllThree() {
+ inRoom(group, groupCertificate)
+ inRoom(middle, middleCertificate)
+ inRoom(root, null)
+ }
+
+ private suspend fun signedInGroup() =
+ db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null))
+
+ private suspend fun noticesIn(chatRoomId: String): List =
+ db.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)).mapNotNull { Event.fromJsonOrNull(it.content) }
+
+ @Test
+ fun `from the group that signed it, every group above is told, and the group is not`(): Unit = runBlocking {
+ inAllThree()
+ signedInGroup()
+
+ val told = GuardianManager.forward(db, certificate, groupRoom, whenElected = false).map { it.chatRoom.id }
+ assertEquals(listOf(middleRoom, rootRoom), told)
+ assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id })
+ assertTrue(noticesIn(groupRoom).isEmpty(), "the group holds what it signed")
+ assertTrue(GuardianManager.told(db, groupRoom, certificate.id), "a signed event counts as told")
+
+ assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = false).isEmpty(), "told once")
+ }
+
+ @Test
+ fun `from a group above, only the groups above it`(): Unit = runBlocking {
+ inAllThree()
+ signedInGroup()
+ // As though the middle group had been told by somebody else, and the
+ // root not yet.
+ GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom)), memberPublicKey)
+
+ assertEquals(listOf(rootRoom), GuardianManager.forward(db, certificate, middleRoom, whenElected = false).map { it.chatRoom.id })
+ assertTrue(GuardianManager.forward(db, certificate, rootRoom, whenElected = false).isEmpty(), "nothing goes back down")
+ }
+
+ @Test
+ fun `the button offers only what goes up`(): Unit = runBlocking {
+ inAllThree()
+ signedInGroup()
+ GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom), db.chatRoomDao().findChatRoomById(rootRoom)), memberPublicKey)
+
+ // The root holds it as a notice, the middle group too, and the group signed it.
+ assertTrue(GuardianManager.shareableFrom(db, rootRoom, chain).isEmpty(), "the root has nobody above it to tell")
+ assertTrue(GuardianManager.shareableFrom(db, middleRoom, chain).isEmpty())
+ assertTrue(GuardianManager.shareableFrom(db, groupRoom, chain).isEmpty())
+ }
+
+ @Test
+ fun `a group above that belongs to another profile on the device is never told`(): Unit = runBlocking {
+ inRoom(group, groupCertificate)
+ inRoom(middle, middleCertificate)
+ signedInGroup()
+ val other = "0f".repeat(32)
+ GroupFixtures.seedProfile(db, other)
+ val middleRow = db.chatRoomDao().findChatRoomById(middleRoom)!!.chatRoom
+ db.chatRoomDao().upsert(middleRow.copy(userPublicKey = other))
+
+ assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = false).isEmpty())
+ assertTrue(noticesIn(middleRoom).isEmpty())
+ }
+
+ @Test
+ fun `when a wallet has only just arrived, only the elected device sends`(): Unit = runBlocking {
+ // A member whose key sorts below this device's sits in both rooms.
+ val earlier = "00".repeat(31) + "01"
+ inRoom(group, groupCertificate, members = listOf(memberPublicKey, earlier))
+ inRoom(middle, middleCertificate, members = listOf(earlier))
+ signedInGroup()
+
+ assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = true).isEmpty(), "the earlier member sends")
+ assertEquals(listOf(middleRoom), GuardianManager.forward(db, certificate, groupRoom, whenElected = false).map { it.chatRoom.id }, "and the catch-up sends what is left")
+ }
+
+ @Test
+ fun `the elected device sends at once`(): Unit = runBlocking {
+ inRoom(group, groupCertificate)
+ inRoom(middle, middleCertificate)
+ signedInGroup()
+
+ assertEquals(listOf(middleRoom), GuardianManager.forward(db, certificate, groupRoom, whenElected = true).map { it.chatRoom.id })
+ }
+
+ @Test
+ fun `nothing it does not believe is forwarded anywhere`(): Unit = runBlocking {
+ inAllThree()
+ val forged = Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128))
+ assertTrue(GuardianManager.forward(db, forged, groupRoom, whenElected = false).isEmpty())
+ assertFalse(noticesIn(middleRoom).isNotEmpty())
+ }
+
+ // ---- Phase 3: on arrival, with nobody calling share -------------------
+
+ /** [event] arriving in [chatRoomId] as the inbound path and a completed signing session both deliver it. */
+ private suspend fun arrives(event: Event, chatRoomId: String) {
+ com.machankura.bennu.compose.database.model.ChatMessage.applyInnerEvent(
+ database = db,
+ groupId = chatRoomId,
+ event = event,
+ marmotGroupEventId = null,
+ marmotInnerEventId = null,
+ senderPublicKey = chatRoomId,
+ isUserMessage = false,
+ createdAt = kotlin.time.Instant.fromEpochSeconds(event.createdAt),
+ )
+ }
+
+ @Test
+ fun `a member's certificate signed in the group reaches the root two generations up`(): Unit = runBlocking {
+ inAllThree()
+ signedInGroup()
+
+ arrives(certificate, groupRoom)
+ assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }, "the group's devices told the middle group")
+ assertEquals(listOf(certificate.id), noticesIn(rootRoom).map { it.id }, "and, being in the root too, the root")
+
+ // The notice arriving in the middle group goes on, and not back down.
+ GuardianManager.forwardOnArrival(db, noticesIn(middleRoom).single(), middleRoom)
+ assertEquals(1, noticesIn(rootRoom).size, "the root was told once")
+ assertTrue(noticesIn(groupRoom).isEmpty())
+ }
+
+ @Test
+ fun `a notice arriving in the middle group is carried to the root`(): Unit = runBlocking {
+ // This device sits in the middle group and the root, not in the group below.
+ inRoom(middle, middleCertificate)
+ inRoom(root, null)
+ GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom)), memberPublicKey)
+
+ GuardianManager.forwardOnArrival(db, certificate, middleRoom)
+ assertEquals(listOf(certificate.id), noticesIn(rootRoom).map { it.id })
+ assertEquals(1, GuardianManager.guardedWalletsOf(db, rootRoom).size, "and the root lists it")
+ }
+
+ @Test
+ fun `a subgroup's own guarded wallet reaches every group above it`(): Unit = runBlocking {
+ inAllThree()
+ val guardians = SubgroupBirthCertificateEvent.parseGuardians(groupCertificate.tags)!!
+ val account = GroupWalletDerivation.account(thresholdKeyOf(group), chain, 0, guardians)
+ val template = com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent.template(account, groupCertificate)
+ val statement = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt)
+
+ arrives(statement, groupRoom)
+ assertEquals(listOf(statement.id), noticesIn(middleRoom).map { it.id })
+ assertEquals(listOf(statement.id), noticesIn(rootRoom).map { it.id })
+ }
+
+ @Test
+ fun `a plain wallet statement is told to nobody`(): Unit = runBlocking {
+ inAllThree()
+ val template = com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdKeyOf(middle), chain))
+ arrives(signedAsRoom(middle, template.kind, template.tags, template.content, template.createdAt), middleRoom)
+ assertTrue(noticesIn(rootRoom).isEmpty())
+ }
+
+ // ---- Phase 4: the catch-up ---------------------------------------------
+
+ @Test
+ fun `a certificate filed before forwarding existed is told the first time its group is opened`(): Unit = runBlocking {
+ // A lower-keyed member in both rooms: on arrival this device would have
+ // waited for them, and nobody sent anything.
+ val earlier = "00".repeat(31) + "01"
+ inRoom(group, groupCertificate, members = listOf(memberPublicKey, earlier))
+ inRoom(middle, middleCertificate, members = listOf(earlier))
+ signedInGroup()
+ assertTrue(noticesIn(middleRoom).isEmpty())
+
+ assertEquals(1, GuardianManager.forwardAll(db, groupRoom))
+ assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id })
+ assertEquals(0, GuardianManager.forwardAll(db, groupRoom), "and not again")
+ }
+
+ @Test
+ fun `the catch-up through the repository, as opening the room runs it`(): Unit = runBlocking {
+ inAllThree()
+ signedInGroup()
+ val repository = com.machankura.bennu.compose.database.repository.DatabaseChatRepository(db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO))
+
+ assertEquals(2, repository.forwardGuardedWallets(groupRoom), "the middle group and the root")
+ assertEquals(0, repository.forwardGuardedWallets(middleRoom), "the root has heard, and the group signed it")
+ }
+
+ // ---- Phase 5: the transcript ------------------------------------------
+
+ private suspend fun sharedLinesIn(chatRoomId: String) =
+ db.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).map { it.chatMessage }
+ .filter { it.messageType == com.machankura.bennu.compose.database.model.ChatMessage.TYPE_GUARDED_WALLET_SHARED }
+
+ /** A notice of [statement] from [forwarder], filed in [chatRoomId] as the inbound path files one. */
+ private suspend fun noticeFrom(forwarder: String, chatRoomId: String, statement: Event, at: Long): Event {
+ val tags = arrayOf(arrayOf("h", chatRoomId))
+ val id = com.vitorpamplona.quartz.nip01Core.crypto.EventHasher.hashId(forwarder, at, GuardedWalletNoticeEvent.KIND, tags, statement.toJson())
+ db.marmotInnerEventDao().upsert(
+ com.machankura.bennu.compose.database.model.MarmotInnerEvent(
+ id = id, publicKey = forwarder, kind = GuardedWalletNoticeEvent.KIND,
+ createdAt = kotlin.time.Instant.fromEpochSeconds(at), tags = tags, content = statement.toJson(), chatRoomId = chatRoomId,
+ )
+ )
+ return Event(id, forwarder, at, GuardedWalletNoticeEvent.KIND, tags, statement.toJson(), "")
+ }
+
+ @Test
+ fun `two forwarders' notices of one wallet give the group one line`(): Unit = runBlocking {
+ GroupFixtures.seedProfile(db, memberPublicKey, name = "alice")
+ inRoom(middle, middleCertificate)
+
+ val first = noticeFrom("a1".repeat(32), middleRoom, certificate, 1_700_000_100)
+ assertEquals("Shared @alice's guarded wallet with this group.", GuardianManager.describeNotice(db, middleRoom, first))
+
+ val second = noticeFrom("b2".repeat(32), middleRoom, certificate, 1_700_000_200)
+ assertEquals(null, GuardianManager.describeNotice(db, middleRoom, second), "the second is filed and silent")
+ assertEquals(1, GuardianManager.guardedWalletsOf(db, middleRoom).size, "and the wallet listed once")
+ }
+
+ @Test
+ fun `the forwarder sees its own line in the group it told`(): Unit = runBlocking {
+ GroupFixtures.seedProfile(db, memberPublicKey, name = "alice")
+ inRoom(group, groupCertificate)
+ inRoom(middle, middleCertificate)
+ signedInGroup()
+
+ GuardianManager.forward(db, certificate, groupRoom, whenElected = false)
+ val lines = sharedLinesIn(middleRoom)
+ assertEquals(1, lines.size)
+ assertTrue(lines.single().isUserMessage)
+ assertEquals("Shared @alice's guarded wallet with this group.", lines.single().content)
+ assertTrue(sharedLinesIn(groupRoom).isEmpty(), "nothing in the group that signed it")
+
+ // Another member's notice of the same wallet, arriving afterwards, writes nothing more.
+ assertEquals(null, GuardianManager.describeNotice(db, middleRoom, noticeFrom("b2".repeat(32), middleRoom, certificate, 1_800_000_000)))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardingRulesJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardingRulesJvmTest.kt
new file mode 100644
index 00000000..952b3e40
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardedWalletForwardingRulesJvmTest.kt
@@ -0,0 +1,116 @@
+package com.machankura.bennu.compose.managers
+
+import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial
+import com.machankura.bennu.compose.managers.GroupFixtures.roomOf
+import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom
+import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf
+import com.machankura.bennu.compose.managers.GuardianManager.GuardedSubject
+import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
+import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent
+import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.secp256k1.Hex
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+
+/**
+ * The rules forwarding is built on, with no database: which groups a statement
+ * is told to from a room -- upward only -- who sends at once, and what a
+ * forwarder believes before it passes anything on.
+ * `docs/guarded-wallet-forwarding.md`, Phase 1.
+ */
+class GuardedWalletForwardingRulesJvmTest {
+ private val chain = Chain.Regtest
+
+ private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0'))))
+
+ private val root = keyMaterial("7007")
+ private val middle = keyMaterial("9a9e")
+ private val group = keyMaterial("6a0b")
+ private val rootRoom = roomOf(root)
+ private val middleRoom = roomOf(middle)
+ private val groupRoom = roomOf(group)
+
+ /** A grandchild's guardians as its certificate lists them: its parent, then the root one step further. */
+ private val grandchildRoom = roomOf(keyMaterial("c1d0"))
+ private val grandchildGuardians = GuardianDerivation.grant(
+ thresholdKeyOf(middle), middleRoom,
+ GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom),
+ grandchildRoom,
+ )
+
+ @Test
+ fun `a grandchild's statement goes up from where it is, and never back down`() {
+ assertEquals(listOf(middleRoom, rootRoom), GuardianManager.upwardOf(grandchildGuardians, grandchildRoom), "from its own room, every guardian")
+ assertEquals(listOf(rootRoom), GuardianManager.upwardOf(grandchildGuardians, middleRoom), "from the middle group, the root alone")
+ assertEquals(emptyList(), GuardianManager.upwardOf(grandchildGuardians, rootRoom), "from the root, nothing: the middle group told it")
+ }
+
+ private val member = privateKey(0x3e3be7)
+ private val walletPrivateKey = privateKey(0xa11ce)
+ private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey())
+
+ /** A member's wallet under `group`, two levels below the root. */
+ private val memberGuardians = GuardianDerivation.grant(
+ thresholdKeyOf(group), groupRoom,
+ GuardianDerivation.grant(
+ thresholdKeyOf(middle), middleRoom,
+ GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom),
+ groupRoom,
+ ),
+ walletId,
+ )
+
+ private fun certificate(signer: fr.acinq.bitcoin.crypto.frost.KeyMaterial = group): Event {
+ val request = MemberWalletRequestEvent.build(
+ memberPrivateKey = member,
+ groupChatRoomId = groupRoom,
+ walletPrivateKey = walletPrivateKey,
+ account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, memberGuardians),
+ label = null,
+ createdAt = 1_700_000_000,
+ )
+ val template = MemberWalletCertificateEvent.template(request)
+ return signedAsRoom(signer, template.kind, template.tags, template.content, template.createdAt)
+ }
+
+ @Test
+ fun `a member's wallet goes up from the group that signed it`() {
+ assertEquals(listOf(middleRoom, rootRoom), GuardianManager.upwardOf(memberGuardians, groupRoom))
+ assertEquals(listOf(rootRoom), GuardianManager.upwardOf(memberGuardians, middleRoom))
+ }
+
+ @Test
+ fun `the lowest key sends at once`() {
+ assertEquals("0a".repeat(32), GuardianManager.electedSender(setOf("ff".repeat(32), "0A".repeat(32), "7c".repeat(32))))
+ assertNull(GuardianManager.electedSender(emptySet()))
+ }
+
+ @Test
+ fun `a forwarder believes a member's certificate the group signed`() {
+ val believed = assertNotNull(GuardianManager.believable(certificate()))
+ assertEquals(walletId, believed.descendantId)
+ assertEquals(memberGuardians, believed.guardians)
+ assertIs(believed.subject)
+ }
+
+ @Test
+ fun `a forwarder believes nothing it could not check`() {
+ // Signed by a group that was not the one asked.
+ assertNull(GuardianManager.believable(certificate(signer = middle)))
+ // A signature that is not one.
+ val certificate = certificate()
+ assertNull(GuardianManager.believable(Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128))))
+ // A plain wallet statement names no guardians.
+ val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdKeyOf(group), chain))
+ assertNull(GuardianManager.believable(signedAsRoom(group, plain.kind, plain.tags, plain.content, plain.createdAt)))
+ // Something else altogether.
+ assertNull(GuardianManager.believable(signedAsRoom(group, 1, emptyArray(), "hello")))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
index 7bedbf2c..fa7d9811 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
@@ -438,7 +438,11 @@ class GuardianSigningJvmTest {
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(), ""))
+ // The notice as it was filed: a second notice of the same statement
+ // would be filed and silent (docs/guarded-wallet-forwarding.md, D6).
+ ancestor.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND))
+ .first { Event.fromJsonOrNull(it.content)?.id == first.id }
+ .let { GuardianManager.describeNotice(ancestor.db, roomId, Event(it.id, it.publicKey, it.createdAt.epochSeconds, it.kind, it.tags, it.content, "")) }
)
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
index effe0858..d5fbd685 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
@@ -141,7 +141,9 @@ class MemberWalletGuardianJvmTest {
val listed = GuardianManager.guardedWalletsOf(db, parentRoom).single()
assertEquals(listOf(groupRoom, walletId), listed.lineage)
assertEquals(1, listed.position)
- assertTrue(GuardianManager.describeNotice(db, parentRoom, Event("1".repeat(64), memberPublicKey, 1, GuardedWalletNoticeEvent.KIND, emptyArray(), certificate().toJson(), ""))!!.startsWith("Shared @"))
+ // The notice as it was filed: a second of the same certificate would be silent.
+ val filed = db.marmotInnerEventDao().getByChatRoomAndKinds(parentRoom, listOf(GuardedWalletNoticeEvent.KIND)).single()
+ assertTrue(GuardianManager.describeNotice(db, parentRoom, Event(filed.id, filed.publicKey, filed.createdAt.epochSeconds, filed.kind, filed.tags, filed.content, ""))!!.startsWith("Shared @"))
}
@Test
diff --git a/docs/README.md b/docs/README.md
index e5204b50..629c1628 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -18,6 +18,7 @@ silent, or a decision that looked arbitrary and was not.
| [member-wallet-delay.md](./member-wallet-delay.md) | a group deciding whether it guards members' wallets, at what delay, and closing again -- why a group-signed event of its own rather than the birth certificate, why no event means not offered, why the request carries the policy it was built under, and why closing never releases a wallet already guarded |
| [guardian-delay.md](./guardian-delay.md) | a parent choosing how long a coin waits before a guardian can take it, from 6 blocks to BIP68's 65,535 -- why each ancestor keeps the delay it chose as its key goes down the tree, what a long delay gives the child, and how a number of blocks is said in time |
| [member-guarded-wallets.md](./member-guarded-wallets.md) | a guarded wallet a group keeps for one member — why the member makes the key and the leaves before asking, why the group signs a certificate of its own kind rather than a birth certificate, and why a member's wallet shows as `@name` and opens their profile |
+| [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md) | telling the groups above about a guarded wallet without anybody pressing *Share* — why it goes upward only, why one device sends at once and the rest catch up, and the two bugs in the button it fixes on the way |
| [guarded-wallet-funding.md](./guarded-wallet-funding.md) | a group paying into a descendant's guarded wallet — why the address is the first unreserved one from `current + 2`, why the claim rides in the PSBT output's derivation and every signer rederives it, and how the guarded wallet row makes room for *Fund* beside *Spend* |
| [group-wallet-addresses.md](./group-wallet-addresses.md) | listing the group wallet's receive addresses as Phoenix lists its swap-in ones — why the list stops at the current address plus two, why a paid address past that still shows, and why a used address can be copied but never shown as a QR code |
| [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device |
@@ -76,6 +77,11 @@ reads as the guardian-delay note's last build-table row answered: read the
member-wallets note and the guardian-delay note first, then its table of where
the delay should live, then its Phase 0, and its table of where the build chose
differently before the code.
+The guarded-wallet-forwarding note is a phased plan that has been built.
+It changes who sends a 30333 notice and when, and no format: read the guardians
+note's *How an ancestor finds the coins* and the member-guarded-wallets note's
+Phase 10 first, then its two bugs, its Phase 0, and its table of where the build
+chose differently before the code.
The guarded-wallet-funding note is a phased plan that has been built. It
reads as the guardians note run the other way, coins in rather than out: read
that note and the address note's *Why `+ 2`* first, then its seven decisions
diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md
index 15f41e51..f0e39fbd 100644
--- a/docs/group-wallet-guardians.md
+++ b/docs/group-wallet-guardians.md
@@ -345,6 +345,13 @@ Since [member-guarded-wallets.md](./member-guarded-wallets.md) the thing
forwarded may also be a member wallet certificate, which the guarding group
signed itself and so needs no forwarding into that group.
+Since [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md) nobody has to
+remember to. A device that files a guarded wallet it believes tells the groups
+above it is in -- upward only, never a group that already holds it, one elected
+device at once and the rest when a group's chat or wallet screen next opens --
+and *Share* is the fallback for a notice lost on the wire. Overlap is still what
+it needs: a device in both rooms, one generation at a time.
+
Once it has the statement, the ancestor watches the descendant's addresses on the
Electrum client it already holds — unknown script hashes are ignored, so this
costs subscriptions and nothing else — and its wallet screen grows a *Guarded
diff --git a/docs/guarded-wallet-forwarding.md b/docs/guarded-wallet-forwarding.md
new file mode 100644
index 00000000..518c160a
--- /dev/null
+++ b/docs/guarded-wallet-forwarding.md
@@ -0,0 +1,422 @@
+# Forwarding guarded wallets upward, without anybody pressing a button
+
+A guarded wallet carries a leaf for every group above it, but a group above can
+use its leaf only once it has been *told* about the wallet. Today that telling
+is a button. A member who sits in both rooms opens the lower group's wallet
+screen, finds *Tell the groups above*, and taps *Share* for each wallet. One tap
+carries one wallet one generation up. Nobody is prompted to do it. A root whose
+grandchildren's wallets nobody shared has a leaf in every address and no way to
+find a single coin.
+
+This plan makes the telling automatic. **Whenever a device files a guarded
+wallet it believes -- a subgroup's own guarded statement, a member wallet
+certificate its group signed, or a notice forwarded to it from below -- and it
+sits in a group above that has not been told, it tells that group. The same
+check runs again each time a group's room or wallet screen is opened, which
+catches up on everything filed before this existed or missed while offline.**
+The button stays, for the case a notice was lost on the wire.
+
+Read [group-wallet-guardians.md](./group-wallet-guardians.md), *How an ancestor
+finds the coins*, and [member-guarded-wallets.md](./member-guarded-wallets.md),
+Phase 10, first. This plan changes no format: the notice is the 30333
+`GuardedWalletNoticeEvent` it has always been, and everything an ancestor checks
+before believing one is unchanged. What changes is who sends it, when, and to
+which groups.
+
+**Built**, phases 1-7, one commit each, written against the code as it stood at
+`263a25a7`, schema v30; the build changes no schema and no format.
+`GuardianManager.believable`, `upwardOf`, `forward`, `forwardOnArrival` and
+`forwardAll` are the entry points, and `GroupWalletRollout.FORWARDS_GUARDED_WALLETS`
+is the switch. The phases below are kept as written; where the build chose
+differently the table says so.
+
+| what the plan said | what it turned out to be |
+|---|---|
+| Phase 1's tests are in commonTest | jvmTest, `GuardedWalletForwardingRulesJvmTest`: `believable` is tested against certificates a real quorum signed, and FROST runs on the JVM |
+| Phase 2: `forward` writes the forwarder's own line | `share` writes it, so the button writes it too -- the forwarder never seeing its own line was the button's gap as much as the automation's (Phase 5) |
+| Phase 3: the notice arm forwards after `describeNotice` believes it | before, and whether or not it does. `describeNotice` needs this room's key to make the ancestor's walk; forwarding needs only `believable`, so a device in a middle group that holds no key state for it still carries a notice on up |
+| Phase 3: a test with the switch off | not written: the switch is a `const`, and a test cannot turn it. Each trigger reads it in one line, `forwardOnArrival` and `forwardAll` |
+| Phase 3's notice test arrives through the inbound path | through `GuardianManager.forwardOnArrival`, which the inbound path calls: the 30333 arm sits inside MLS decryption, which a jvmTest does not drive. The certificate and statement arms are driven through `ChatMessage.applyInnerEvent` itself |
+| Phase 4: `ChatRepository.forwardGuardedWallets` | with a default body, so every fake repository in the tests needed no change |
+| Phase 5: nothing else changes | two older tests described a notice under an id other than the one they filed. Under the one-line rule that is a second notice, and silent; they now describe the notice they filed |
+| Phase 6: each row's supporting line explains the fallback | one line under the section's heading says it, and each row keeps *Not yet shared with the groups above that you're in*: the same sentence on every row was the same sentence N times |
+| Phase 7: the three-device run | not made |
+
+Still to do by hand: Phase 7's run on signet.
+
+---
+
+## What is there, and the two things wrong with it
+
+`GuardianManager.shareableFrom(chatRoomId, chain)` lists what a device could
+tell from a room. That is the room's own guarded wallet, if it has one, plus
+every guarded wallet the room holds: those it was told about, and those of its
+members it signed itself. Each comes with the guarding rooms this device is in
+and has not told yet (`targetsFor`). `GuardianManager.share` posts one notice
+per room. `GroupWalletViewModel.share` is the only caller, behind the button.
+
+Read as the basis for doing this without a person, two of its rules are wrong.
+
+**1. It tells groups below as well as above.** `targetsFor` takes every room
+the statement's guardian list names, except the room it is in. The list names
+*all* the wallet's guardians, nearest first. So from a middle group `M`, the
+targets of a grandchild `C`'s statement include the root `R`, which is right,
+and nothing below `M`. But from the root `R`, holding the same statement, the
+targets include `M`, which already holds it. Each tap there tells a group
+something it was told first. By hand that is a wasted tap. Automatically it is
+a notice into `M` from every device in both rooms, every time `R` is opened.
+
+**2. A guarding group's own certificate never counts as told.** `alreadyTold`
+reads the target room's 30333 notice rows. A member wallet certificate is held
+in the group that signed it as a `GroupSignedEvent` and never as a notice. So
+`R` holding a member's wallet that `G` signed would tell `G` again, for the
+same reason as above.
+
+Both are fixed by one rule: **a statement is told upward only**, to the guardian
+rooms after the room it is in. A room that holds the statement in any form,
+signed or as a notice, has been told.
+
+---
+
+## Phase 0 — decisions, before any code
+
+### D1. Which statements are forwarded
+
+**Recommended: exactly what `shareableFrom` lists today**, from a room this
+device is in:
+
+| statement | held in the room as | forwarded to |
+|---|---|---|
+| the room's own guarded wallet statement (30331) | a `GroupSignedEvent` the room's quorum signed | every guardian it names |
+| a member wallet certificate (30334) the room signed | a `GroupSignedEvent` | the guardians after the room, which is guardian 0 |
+| a statement or certificate a notice carried here (30333) | a `MarmotInnerEvent` row | the guardians after the room in the statement's list |
+
+A plain (unguarded) wallet statement is never forwarded: it names nobody.
+
+### D2. What the forwarder believes first
+
+The forwarder vouches for nothing. Every device in the target room runs
+`GuardianManager.verify` on what arrives, including the walk down from its own
+guardian root. But the forwarder should not pass on what it cannot believe
+itself, or a single bad notice is copied into every group above.
+
+**Recommended: everything `verify` checks except the ancestor's own walk**,
+which only a device holding that ancestor's key can make:
+
+- a 30331 statement: signed by its room, guarded, carrying a certificate whose
+ key makes that room, and with every value rederiving from it
+ (`Reading.verifiedAgainst`);
+- a 30334 certificate: `MemberWalletCertificateEvent.verify(certificate, certificate.pubKey)`.
+
+This is `GuardianManager.believable(statement)`, split out of `verify` so the
+two cannot drift. `verify` becomes `believable` plus the walk.
+
+### D3. Which groups count as "above"
+
+**Decided by the bug above: upward only.** In room `X`, a statement's targets are
+the guardians listed *after* `X`'s own position in its guardian list, nearest
+first. A room not in the list at all is the wallet's own room (a subgroup's own
+statement), and gets every guardian. For a member's wallet signed by `G`, `G` is
+guardian 0, so the targets start at `G`'s parent.
+
+A target counts as told when it holds the statement in any form: a 30333 row
+carrying it, or a `GroupSignedEvent` with its id.
+
+### D4. Who sends it, when several devices could
+
+Every device in both the lower group and the upper one could send the notice.
+When a member wallet certificate completes, every device in `G` files it within
+seconds of the others. Each of them that is also in `P` would then post into `P`
+at once. A burst like that is the shape [mls-skipped-keys.md](./mls-skipped-keys.md)
+warns of: one of two group events arriving back to back can be dropped for good.
+
+**Recommended: one sender is elected for the immediate send, and every device is a
+fallback for the catch-up.**
+
+- The **elected** device is the one whose profile's key sorts lowest among the
+ members of *both* rooms, as this device's participant lists have them. It
+ forwards on arrival.
+- Every **other** device forwards only in the catch-up pass (D5). By then the
+ elected device's notice has usually arrived, and the target counts as told.
+- Devices disagreeing about the participant lists can elect two senders. The
+ cost is one duplicate notice, which D6 keeps out of the transcript.
+
+The alternative, everybody sending at once, is simpler and correct, since
+`guardedWalletsOf` already collapses duplicates. It is rejected for the burst,
+not for the duplicates.
+
+### D5. When the catch-up runs
+
+**Recommended: when a Marmot room's chat is opened, and when a group's wallet
+screen is opened**, for that room. That is `ChatMessageListViewModel.initiate`,
+beside `askForGroupHistory`, and `GroupWalletViewModel.initiate`, which already
+reads `shareableGuardedWallets`.
+
+That covers:
+- certificates and statements signed before this ships;
+- a device that was offline when the elected one should have sent;
+- an elected device that never sent.
+
+A pass over every room at launch would cover more, and would put a notice burst
+on every room at once, on every launch. It is rejected for now and named under
+*what this does not do*.
+
+### D6. What the transcript says
+
+Today each notice writes a *Shared @alice's guarded wallet with this group*
+line, attributed to the member who forwarded it. The forwarder never sees its
+own line: a sender is not handed its own MLS message back.
+
+**Recommended:**
+- a line only for the **first** notice of a statement in a room. A notice whose
+ statement this room already holds, in any form, writes none;
+- the forwarding device writes the same line into the target room on its own
+ side as it sends, so it sees what it did, as the button's snackbar did.
+
+### D7. Which profile sends
+
+One database holds every profile on the device. A room row's `userPublicKey` is
+the profile that is in it.
+
+**Recommended: the notice is sent as the target room's own profile, and only when
+that is the source room's profile too.** The arrival path that files a 30334 or
+a 30331 (`ChatMessage.applyInnerEvent`) has no active key to hand. The room row
+has it, and a device must never post into a room as a profile that is not the
+one in it.
+
+### D8. A way to turn it off
+
+**Recommended: `GroupWalletRollout.FORWARDS_GUARDED_WALLETS = true`**, read by the
+arrival triggers and the catch-up, not by the button. It is a behaviour that
+sends messages without a person, so it gets one switch, in the same place as the
+other wallet gates, for the release where it first ships.
+
+---
+
+## Phase 1 — the rules, pure
+
+New in `GuardianManager` (or a small `GuardianForwarding` beside it, if it reads
+better):
+
+```kotlin
+/** [statement] believed on its own merits: everything [verify] checks except the ancestor's own walk. D2. */
+fun believable(statement: Event): Believable? // the guardians, the descendant id, the chain
+
+/** The guardian rooms [statement] is forwarded to from [chatRoomId]: those after it in the list, nearest first. D3. */
+fun upwardOf(guardians: List, chatRoomId: String): List
+
+/** Who sends at once, of [candidates] -- the members of both rooms: the lowest key. D4. */
+fun electedSender(candidates: Set): HexKey?
+```
+
+`verify` is rewritten as `believable(statement)` plus the walk, with its kdoc's
+four rules unchanged.
+
+**Tests**, commonTest:
+- `upwardOf` for a grandchild's statement: from the grandchild's own room, both
+ guardians; from the middle group, the root alone; from the root, nothing;
+- `upwardOf` for a member wallet from its guarding group, two levels up: the
+ parent and the root;
+- `believable` accepts what `verify` accepts and refuses each mutation
+ `verify`'s tests refuse, apart from the walk;
+- `electedSender` is the lowest key and is null for an empty set.
+
+---
+
+## Phase 2 — telling, as a function a trigger can call
+
+```kotlin
+/**
+ * Tells every group above [chatRoomId] that this device's profile is in, and that has
+ * not been told, about [statement]. [whenElected] restricts it to the targets this
+ * device is the elected sender for (D4); the catch-up passes false.
+ * Returns the rooms told.
+ */
+suspend fun forward(database: BennuDatabase, statement: Event, chatRoomId: String, whenElected: Boolean): List
+```
+
+1. `believable(statement)`, or nothing;
+2. targets: `upwardOf(guardians, chatRoomId)` → rooms on this device that are
+ Marmot rooms, belong to the source room's profile (D7), and have not been told
+ in either form (D3);
+3. with `whenElected`, keep a target only if this profile is
+ `electedSender(participants(source) ∩ participants(target))`;
+4. `share` into each, as that profile, and write the forwarder's own line (D6).
+
+`shareableFrom` and `targetsFor` move onto the same upward rule and the same
+*told* check, so the button and the automation cannot disagree about what is
+left to share. That fixes both bugs above for the button too.
+
+**Tests**, jvmTest, in the shape of `MemberWalletGuardianJvmTest`:
+- a member wallet certificate in `G`, this device in `G` and `P`: `forward`
+ tells `P` and not `G`;
+- the same from `P` holding the forwarded certificate: tells `R`, not `G`;
+- a target holding the statement as a `GroupSignedEvent` counts as told;
+- a target belonging to another profile on the device is never told;
+- `whenElected` with a lower-keyed member in both rooms tells nobody, and
+ without it tells `P`;
+- a statement that is not `believable` is forwarded nowhere.
+
+---
+
+## Phase 3 — the triggers on arrival
+
+Three places, each after the statement has been believed and filed, so the
+row the *told* check reads already exists:
+
+| arrival | where | forwards |
+|---|---|---|
+| a member wallet certificate is filed in `G` | `ChatMessage.applyInnerEvent`'s 30334 arm, reached from `FrostSigningManager.applySignedEvent` on every device that followed the session | the certificate, from `G`, `whenElected = true` |
+| a guarded wallet statement is filed in a subgroup | the 30331 arm, when `wallet.account.isGuarded` | the statement, from the subgroup's room |
+| a notice arrives in a group | the 30333 intercept in `ChatMessage`'s inbound path, after `describeNotice` believes it | the statement inside, from this group, onward |
+
+Each call is wrapped so a failure to forward is logged and never stops the line
+being written. Forwarding is an extra, and the arrival is the thing.
+
+All three read `GroupWalletRollout.FORWARDS_GUARDED_WALLETS` (D8).
+
+**Tests**, jvmTest: a three-level hierarchy on one device -- root `R`, middle
+`M`, grandchild `C`, this device a member of all three and the elected sender
+throughout:
+- `C`'s guarded statement filed in `C` ends with notices in `M` and in `R`, with
+ nobody calling `share`;
+- a member wallet certificate filed in `C` reaches `M` and `R` the same way;
+- the notice `M` receives does not travel back down into `C`;
+- with the switch off, nothing is sent.
+
+---
+
+## Phase 4 — the catch-up
+
+`GuardianManager.forwardAll(database, chatRoomId)`: every statement
+`shareableFrom` would list from the room, on every chain, through `forward` with
+`whenElected = false`. Called from:
+
+- `ChatMessageListViewModel.initiate`, beside `askForGroupHistory`, for a Marmot
+ room;
+- `GroupWalletViewModel.initiate`, before `shareableGuardedWallets` is read, so
+ the *Tell the groups above* section shows only what is truly left.
+
+Both go through `ChatRepository.forwardGuardedWallets(chatRoomId)`, so the view
+models still talk to repositories.
+
+**Tests**: a certificate signed before this existed -- filed with no trigger --
+is forwarded the first time its group's room is opened, and not again the second
+time. A non-elected device forwards in the catch-up what the elected one never
+sent.
+
+---
+
+## Phase 5 — the transcript
+
+- The 30333 intercept writes its line only when no other stored notice in the
+ room carries the same statement id, and the room does not hold the statement as
+ a `GroupSignedEvent`. A duplicate is filed and silent.
+- `forward` writes the forwarder's own line into each room it tells, typed
+ `TYPE_GUARDED_WALLET_SHARED`, `isUserMessage = true`, with the words the
+ receivers' devices write.
+
+**Tests**: two notices for one statement from two forwarders give one line; the
+forwarder's own device shows its line in the room it told.
+
+---
+
+## Phase 6 — the screen
+
+The *Tell the groups above* section on `GroupWalletScreen` stays, now as the
+fallback, and lists only what the catch-up could not send. In practice that
+means a notice lost on the wire, or a group above in which this device holds no
+row. Its supporting line becomes *This device shares these on its own when it
+can. Share now if a group above has not heard*. The strings go in
+`strings.xml`, in sentence case.
+
+The snackbar the button shows today stays as it is.
+
+---
+
+## Phase 7 — docs, and checking it on the emulators
+
+- [group-wallet-guardians.md](./group-wallet-guardians.md), *How an ancestor
+ finds the coins*: forwarding is automatic, one generation per device in both
+ rooms, with the button as a fallback.
+- [member-guarded-wallets.md](./member-guarded-wallets.md), Phase 10: a member's
+ wallet reaches the groups above without anybody sharing it.
+- [README.md](./README.md): this note's row.
+- This note: *Built*, and a table of where the build chose differently.
+
+By hand, signet, three devices. `R` is the root, `M` its guarded subgroup, `G`
+`M`'s guarded subgroup, and Alice is in `G`. Device 1 is in `G` and `M`, device
+2 in `M` and `R`.
+
+1. Alice asks `G` to guard a wallet, and `G` signs. With nobody touching
+ device 1, `M`'s wallet screen lists `@alice` within a minute.
+2. With nobody touching device 2, `R`'s does too, and `R`'s transcript has one
+ *Shared @alice's guarded wallet* line.
+3. `G`'s transcript has no line about its own member's wallet coming back down.
+4. Device 2 offline while `G` signs a second wallet: it appears in `R` the first
+ time device 2 opens `M`.
+5. `R` makes a guardian spend from Alice's wallet through its leaf.
+
+```bash
+./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest
+```
+
+```bash
+./gradlew :composeApp:m3Audit
+```
+
+---
+
+## Order and size
+
+| phase | touches | ships |
+|---|---|---|
+| 1 | `GuardianManager`, pure | dark |
+| 2 | `forward`, and the button's rules | **fixes both bugs in the button** |
+| 3 | three arrival arms | **the switch**: nothing sends without a person before this |
+| 4 | two view models, `ChatRepository` | with 3 |
+| 5 | the 30333 intercept, `forward`'s own line | with 3 |
+| 6 | `GroupWalletScreen` | any time after 4 |
+| 7 | docs and the run | last |
+
+Phase 2 is worth landing alone. It is a fix to the button that stands without the
+automation.
+
+---
+
+## What this does not do
+
+**It does not reach a group nobody sits in.** Forwarding needs a device in both
+rooms, one generation at a time. A group above that shares no member with the
+group below still cannot be told, and the remedy is the one the guardians note
+gives: a member in common.
+
+**It does not tell a member welcomed into a group above after the notice.**
+Notices are not chroniclable, so a device that joins `R` later holds none of the
+notices `R` was sent, and lists none of the wallets. The catch-up does not help
+it: the forwarder's device already holds its own copy of the notice and counts
+`R` as told. Telling late joiners is the chronicle's job, and this plan does not
+take it on.
+
+**It does not sweep every room at launch.** The catch-up runs per room as the
+room or its wallet screen is opened (D5). A device that never opens the lower
+group never forwards in the catch-up, though it still forwards on arrival when
+it is the elected sender.
+
+**It does not make a notice reliable on the wire.** A notice lost to the skipped-keys
+bug stays lost until a catch-up on another device sends one again, or somebody
+taps *Share*.
+
+**It does not change what a group above can do with what it is told.** It finds
+the wallet, watches it and can spend through its leaf after the delay. All of
+that is unchanged; only the finding no longer waits on a tap.
+
+## Appendix — what was considered and rejected
+
+| idea | why not |
+|---|---|
+| every device sends at once | correct, since duplicates collapse, but it puts a burst of group events into every group above at the moment a certificate completes, the one shape `mls-skipped-keys.md` says loses messages (D4) |
+| the member's own device forwards their wallet | the member is in `G` and seldom in the groups above, and a subgroup's statement has no single owner; the device in both rooms is the one that can |
+| a pass over every room at launch | catches the most, and sends the most at once, on every launch (D5) |
+| removing the button | a notice lost on the wire has no other way back until somebody opens the right room on the right device |
+| a new kind for an automatic notice | the 30333 notice already says everything, and every build that reads it today reads these |
diff --git a/docs/member-guarded-wallets.md b/docs/member-guarded-wallets.md
index bbe8149b..137525bd 100644
--- a/docs/member-guarded-wallets.md
+++ b/docs/member-guarded-wallets.md
@@ -758,6 +758,10 @@ replaces and settles.
## Phase 10 — the guardians see `@alice`
+> Since [guarded-wallet-forwarding.md](./guarded-wallet-forwarding.md) a member's
+> wallet reaches the groups above with nobody tapping *Share*: the group's devices
+> that are also in a group above tell it as the certificate is filed.
+
The guardian side is built. What changes is what a guarded wallet can be.
### `GuardianManager.GuardedWallet` learns its subject