From a91bcfc2694a4965a6d70513e0f82ecbc0714920 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sat, 24 Oct 2026 11:51:42 +0200 Subject: [PATCH] feat(wallet): a member's wallet is named by the group that guards it, where this device can check (Phase 2) GuardedSubject.Member gains guardianName and branchName, filled in GuardianManager.named beside ownerName, so every caller of guardedWalletsOf gets them without a lookup in a composable. Each name is the room's founding name, read off a birth certificate its parent signed and checked with SubgroupBirthCertificateEvent.certifies, whoever handed it over: the certificates the parent signed, the room's own key state, or one a subgroup's statement told to the holding room carries. Without one, the room's name here; without that, null. Co-Authored-By: Claude Opus 5.5 --- .../bennu/compose/managers/GuardianManager.kt | 74 +++++++- .../bennu/compose/managers/LineageExample.kt | 6 +- .../bennu/compose/managers/GroupFixtures.kt | 3 +- .../managers/GuardingGroupNameJvmTest.kt | 169 ++++++++++++++++++ 4 files changed, 246 insertions(+), 6 deletions(-) create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt 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 95145ac6..40e4206f 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 @@ -63,6 +63,15 @@ object GuardianManager { val label: String?, /** The member's profile name on this device, where one is known; filled where a database is to hand. */ val ownerName: String? = null, + /** + * The group that directly guards it, by its founding name where this + * device can check a birth certificate for it, else its room name here; + * null when neither is known. Filled where a database is to hand. + * `docs/member-wallet-guarding-group.md`, D2. + */ + val guardianName: String? = null, + /** The holding group's own child it sits under, named the same way; null when the holder guards it directly. */ + val branchName: String? = null, ) : GuardedSubject } @@ -212,11 +221,63 @@ object GuardianManager { ) }.getOrNull() - /** [wallet] with its member's profile name, where this device knows one. */ - private suspend fun named(database: BennuDatabase, wallet: GuardedWallet): GuardedWallet { + /** + * [wallet] with its member's profile name, and the names of the group that + * directly guards it and of the branch it sits under, where this device knows + * them. [known] are birth certificates that came to hand some other way -- + * those the statements told to the holding room carry. + */ + private suspend fun named(database: BennuDatabase, wallet: GuardedWallet, known: List = emptyList()): 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)) + val guardians = wallet.account.guardians + + // Founding name first, then the room's name here: the order D2 of + // docs/member-wallet-guarding-group.md gives, so the card agrees with a + // subgroup row in the same list naming the same room. + suspend fun nameOf(position: Int): String? { + val roomId = guardians[position].chatRoomId + val parentRoomId = guardians.getOrNull(position + 1)?.chatRoomId + return parentRoomId?.let { foundingNameOf(database, roomId, it, known) } + ?: database.chatRoomDao().findChatRoomById(roomId)?.chatRoom?.subject?.takeIf { it.isNotBlank() } + } + + return wallet.copy( + subject = member.copy( + ownerName = name, + guardianName = nameOf(0), + branchName = wallet.position.takeIf { it > 0 }?.let { nameOf(it - 1) }, + ) + ) + } + + /** + * What [roomId] was called at its founding, read off a birth certificate + * [parentRoomId] signed for it -- or null when this device holds none it can + * check. Each candidate is checked with `SubgroupBirthCertificateEvent.certifies`, + * whoever handed it over: [carried] first, then the certificates the parent + * signed (every device in the parent holds them), then the one in [roomId]'s + * own key state (every device in the room). `docs/member-wallet-guarding-group.md`, D3. + */ + suspend fun foundingNameOf( + database: BennuDatabase, + roomId: String, + parentRoomId: String, + carried: List = emptyList(), + ): String? { + fun List.name(): String? = firstNotNullOfOrNull { certificate -> + certificate.takeIf { SubgroupBirthCertificateEvent.certifies(it, roomId, parentRoomId) } + ?.let { SubgroupBirthCertificateEvent.parseName(it.tags) } + } + + carried.name()?.let { return it } + database.groupSignedEventDao() + .getByChatRoomIdAndKind(parentRoomId, SubgroupBirthCertificateEvent.KIND) + .map { it.toEvent() } + .name()?.let { return it } + return listOfNotNull( + database.groupKeyStateDao().getByChatRoomId(roomId)?.birthCertificateJson?.let { Event.fromJsonOrNull(it) } + ).name() } /** @@ -243,9 +304,14 @@ object GuardianManager { .getByChatRoomIdAndKind(ancestorChatRoomId, MemberWalletCertificateEvent.KIND) .map { it.toEvent() } + // A subgroup's statement carries the birth certificate its parent signed, + // which names that subgroup for any member wallet guarded beneath it. + val known = told.filter { it.kind == GroupWalletStatementEvent.KIND } + .mapNotNull { GroupWalletStatementEvent.read(it.tags, it.content)?.certificate } + return (told + signed) .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) } - .map { named(database, it) } + .map { named(database, it, known) } .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) } .mapNotNull { (_, statements) -> val first = statements.minWithOrNull(order) ?: return@mapNotNull null diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt index 248605b4..c8853eeb 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/LineageExample.kt @@ -52,7 +52,7 @@ object LineageExample { /** * Alice's wallet [walletId] under [guardians], as [ancestor] holds it. - * [label] and [ownerName] are what `GuardianManager.named` would fill. + * [label] and the names are what `GuardianManager.named` would fill. */ fun heldBy( ancestor: String, @@ -61,6 +61,8 @@ object LineageExample { label: String? = null, ownerPublicKey: String = alice, ownerName: String? = "alice", + guardianName: String? = null, + branchName: String? = null, walletKey: Int = 0xdecaf, ): GuardianManager.GuardedWallet { val account = GroupWalletDerivation.account(key(walletKey), Chain.Regtest, guardians = guardians) @@ -77,6 +79,8 @@ object LineageExample { ownerPublicKey = ownerPublicKey, label = label, ownerName = ownerName, + guardianName = guardianName, + branchName = branchName, ), ) } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt index 5cc8ab0d..21a54efd 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt @@ -103,6 +103,7 @@ internal object GroupFixtures { guardians: List, policy: SubgroupWalletPolicy? = if (guardians.isEmpty()) SubgroupWalletPolicy.UNGUARDED else SubgroupWalletPolicy.GUARDED, admins: List = listOf("a".repeat(64)), + name: String = "#Child", ): Event = signedAsRoom( material = parent, kind = SubgroupBirthCertificateEvent.KIND, @@ -111,7 +112,7 @@ internal object GroupFixtures { parentChatRoomId = roomOf(parent), thresholdPublicKey = thresholdKeyOf(child), adminPublicKeys = admins, - name = "#Child", + name = name, path = path, guardians = guardians, walletPolicy = policy, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt new file mode 100644 index 00000000..cbe88d70 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardingGroupNameJvmTest.kt @@ -0,0 +1,169 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.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.managers.GuardianManager.GuardedSubject +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.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.assertIs +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * The names a member's wallet is shown under in a group above it: the group + * that directly guards it, and the branch of the holder's tree it sits under -- + * each from a birth certificate this device can check, whoever handed it over, + * and never from one it cannot. `docs/member-wallet-guarding-group.md`, Phase 2. + * + * The tree is R ⊃ P ⊃ M, and M guards Alice's Savings. + */ +class GuardingGroupNameJvmTest { + 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 r = keyMaterial("7007") + private val p = keyMaterial("9a9e") + private val m = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val rRoom = roomOf(r) + private val pRoom = roomOf(p) + private val mRoom = roomOf(m) + + 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 pGrant = GuardianDerivation.grant(thresholdKeyOf(r), rRoom, emptyList(), pRoom) + private val mGrant = GuardianDerivation.grant(thresholdKeyOf(p), pRoom, pGrant, mRoom) + private val savingsGrant = GuardianDerivation.grant(thresholdKeyOf(m), mRoom, mGrant, walletId) + + /** R's certificate for P, and P's for M, as their founding named them. */ + private val pCertificate = birthCertificate(r, p, pGrant, name = "#P") + private val mCertificate = birthCertificate(p, m, mGrant, name = "#M") + + /** M's certificate for Alice's Savings, guarded by `[M, P, R]`. */ + private val savings: Event = run { + val request = MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = mRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, savingsGrant), + label = "Savings", + createdAt = 1_700_000_000, + ) + val template = MemberWalletCertificateEvent.template(request) + signedAsRoom(m, template.kind, template.tags, template.content, template.createdAt) + } + + /** This device in [material]'s room, holding its key state. */ + private suspend fun inRoom(material: KeyMaterial, certificate: Event? = null, subject: String = "#" + roomOf(material).take(4)) { + signingRoom(db, material, members = listOf(memberPublicKey), subject = subject) + fileKeyState(db, material, certificate) + } + + /** [certificate] as one of [signer]'s own signed events here. */ + private suspend fun fileSigned(certificate: Event, signer: String) = + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = signer, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + private suspend fun noticeIn(room: String, statement: Event) = + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = statement.id.take(60) + "0000", + publicKey = memberPublicKey, + kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1_700_000_100), + tags = arrayOf(arrayOf("h", room)), + content = statement.toJson(), + chatRoomId = room, + ) + ) + + private suspend fun heldByR(): GuardedSubject.Member { + val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() + assertEquals(mRoom, listed.directGuardianChatRoomId) + return assertIs(listed.subject) + } + + @Test + fun `a device in R and P names M from the certificate P signed`(): Unit = runBlocking { + inRoom(r) + inRoom(p, pCertificate) + fileSigned(pCertificate, signer = rRoom) + fileSigned(mCertificate, signer = pRoom) + noticeIn(rRoom, savings) + + val subject = heldByR() + assertEquals("#M", subject.guardianName) + assertEquals("#P", subject.branchName) + } + + @Test + fun `a device in R only knows its own branch, and not the group below it`(): Unit = runBlocking { + inRoom(r) + fileSigned(pCertificate, signer = rRoom) + noticeIn(rRoom, savings) + + val subject = heldByR() + assertNull(subject.guardianName) + assertEquals("#P", subject.branchName) + } + + @Test + fun `a certificate for M that P did not sign names nothing`(): Unit = runBlocking { + inRoom(r) + inRoom(p, pCertificate) + fileSigned(pCertificate, signer = rRoom) + // Filed under P, signed by a stranger: it does not certify M as P's child. + fileSigned(birthCertificate(stranger, m, mGrant, name = "#Impostor"), signer = pRoom) + noticeIn(rRoom, savings) + + assertNull(heldByR().guardianName) + } + + @Test + fun `a renamed M is still shown by its founding name`(): Unit = runBlocking { + inRoom(r) + inRoom(m, mCertificate, subject = "#Renamed") + fileSigned(pCertificate, signer = rRoom) + noticeIn(rRoom, savings) + + assertEquals("#M", heldByR().guardianName) + } + + @Test + fun `with no certificate to check, the room's name here is used`(): Unit = runBlocking { + inRoom(r) + inRoom(m, subject = "#Here") + noticeIn(rRoom, savings) + + assertEquals("#Here", heldByR().guardianName) + } +}