diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index f73a2325..1a5ddf81 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -622,4 +622,5 @@ Your spends Sent, waiting for the network to report it In the mempool + @%1$s diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt index f0ed7081..0e3c7ba3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt @@ -52,6 +52,11 @@ data class GroupTransaction( * The descendant whose guarded wallet this spend draws from, through this * room's guardian leaf -- or null for a spend from the room's own wallet. * [account] is then the descendant's, from the statement this room was told. + * + * A descendant is a subgroup's room id or, since + * `docs/member-guarded-wallets.md`, a member wallet's `W`: either is what the + * line of descent ends in. The column keeps its name, because a rename is a + * migration for a word. */ val guardedChatRoomId: String? = null, 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 d1009ca9..908d2ad6 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 @@ -10,6 +10,8 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.machankura.bennu.compose.wallet.GroupSpend import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -43,22 +45,48 @@ object GuardianManager { private val logger = Logger.withTag(TAG) + /** + * Whose guarded wallet it is: a subgroup's, under its quorum's key, or one + * member's, under a key only they hold -- `docs/member-guarded-wallets.md`. + * Either way [id] is what the line of descent ends in, so every guardian + * signs for its leaf the same way. + */ + sealed interface GuardedSubject { + /** A room id, or a member wallet's `W`. */ + val id: String + + data class Subgroup(override val id: String, val name: String?) : GuardedSubject + + data class Member( + override val id: String, + val ownerPublicKey: HexKey, + 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, + ) : GuardedSubject + } + /** A descendant's guarded wallet, as one of its ancestors holds it. */ data class GuardedWallet( /** The ancestor holding it: the room it was told to. */ val ancestorChatRoomId: String, + /** [subject]'s id: the descendant's room, or a member wallet's `W`. */ val descendantChatRoomId: String, - /** The descendant's signed statement, whole. */ + /** + * What the ancestor believes it on, whole: a subgroup's signed statement, + * or the member wallet certificate the guarding group signed. + */ val statement: Event, /** The account the statement opens, rederived from the descendant's key. */ val account: GroupWalletDerivation.Account, - /** The descendant's birth certificate, carried in the statement. */ + /** A subgroup's birth certificate, carried in the statement -- or, for a member, the certificate itself. */ val certificate: Event, /** The rooms the ancestor walks from its own child down to the descendant -- `GuardianDerivation.lineage`. */ val lineage: List, + val subject: GuardedSubject = GuardedSubject.Subgroup(descendantChatRoomId, SubgroupBirthCertificateEvent.parseName(certificate.tags)), ) { - /** What the descendant's parent certified it as. The founding name: a rename does not reach it. */ - val name: String? get() = SubgroupBirthCertificateEvent.parseName(certificate.tags) + /** What the descendant's parent certified it as, for a subgroup. The founding name: a rename does not reach it. */ + val name: String? get() = (subject as? GuardedSubject.Subgroup)?.name val chain: Chain get() = account.chain @@ -69,7 +97,14 @@ object GuardianManager { /** The ancestor as the spender of a spend from this wallet, signing as [thresholdPublicKey] -- null to only build one. */ fun spender(thresholdPublicKey: HexKey? = null): GroupSpend.Spender.Guardian = - GroupSpend.Spender.Guardian(position = position, lineage = lineage, thresholdPublicKey = thresholdPublicKey, name = name) + GroupSpend.Spender.Guardian(position = position, lineage = lineage, thresholdPublicKey = thresholdPublicKey, name = displayName) + + /** How a spend from it names it: a subgroup's founding name, or `@` and a member's. */ + val displayName: String? + get() = when (val subject = subject) { + is GuardedSubject.Subgroup -> subject.name + is GuardedSubject.Member -> "@" + (subject.ownerName ?: subject.ownerPublicKey.take(8)) + } } /** @@ -89,6 +124,7 @@ object GuardianManager { * a leaf this group cannot sign, whatever the statement calls it. */ fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching { + if (statement.kind == MemberWalletCertificateEvent.KIND) return verifyMember(statement, ancestorChatRoomId, ancestorThresholdPublicKey) if (statement.kind != GroupWalletStatementEvent.KIND) return null val descendantChatRoomId = statement.pubKey if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null @@ -121,6 +157,42 @@ object GuardianManager { ) }.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. + */ + private fun verifyMember(certificate: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching { + val verified = MemberWalletCertificateEvent.verify(certificate, certificate.pubKey) ?: return null + val account = verified.account + + val lineage = GuardianDerivation.lineage(account.guardians, verified.walletId, 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 = verified.walletId, + statement = certificate, + account = account, + certificate = certificate, + lineage = lineage, + subject = GuardedSubject.Member(verified.walletId, verified.memberPublicKey, verified.label), + ) + }.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)) + } + /** * Every guarded wallet [ancestorChatRoomId] has been told about and can sign * for, one per descendant account on each network. @@ -135,10 +207,19 @@ object GuardianManager { val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, ancestorChatRoomId) ?: return emptyList() val order = compareBy({ it.openedAt }, { it.statement.id }) - return database.marmotInnerEventDao() + // What it was told, and -- for its own members' wallets -- what it signed: + // the group holds a member wallet certificate it signed, and needs no + // notice to learn of it. + val told = database.marmotInnerEventDao() .getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) .mapNotNull { row -> Event.fromJsonOrNull(row.content) } + val signed = database.groupSignedEventDao() + .getByChatRoomIdAndKind(ancestorChatRoomId, MemberWalletCertificateEvent.KIND) + .map { it.toEvent() } + + return (told + signed) .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) } + .map { named(database, it) } .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) } .mapNotNull { (_, statements) -> val first = statements.minWithOrNull(order) ?: return@mapNotNull null @@ -161,9 +242,12 @@ object GuardianManager { /** A guarded statement this device can carry upward, and the rooms it can carry it into. */ data class Shareable( val statement: Event, - /** What the statement's room was certified as, for the screen. */ + /** What the statement's room was certified as, for the screen. Null for a member's wallet. */ val name: String?, val rooms: List, + /** For a member's wallet: the member, and their profile name where this device knows one. */ + val ownerPublicKey: HexKey? = null, + val ownerName: String? = null, ) /** @@ -180,25 +264,37 @@ object GuardianManager { val certificate = GroupWalletStatementEvent.read(statement.tags, statement.content)?.certificate statement to (certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) }) } + // Everything it guards or was told of -- its own members' wallets among + // them, since it holds those certificates itself -- passed on a + // generation further. val passedOn = guardedWalletsOf(database, chatRoomId) .filter { it.chain == chain } - .map { it.statement to it.name } - return (listOfNotNull(own) + passedOn).mapNotNull { (statement, name) -> - val rooms = targetsFor(database, statement, excluding = chatRoomId) - rooms.takeIf { it.isNotEmpty() }?.let { Shareable(statement, name, it) } + val candidates = listOfNotNull(own?.let { (statement, name) -> Shareable(statement, name, emptyList()) }) + + passedOn.map { wallet -> + val member = wallet.subject as? GuardedSubject.Member + Shareable(wallet.statement, wallet.name, emptyList(), member?.ownerPublicKey, member?.ownerName) + } + + return candidates.mapNotNull { candidate -> + val rooms = targetsFor(database, candidate.statement, excluding = 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 guardian rooms of [statement] this device can post into and has not * told it yet. Only Marmot rooms: a guardian is a group with a key, and a * group with a key has an MLS room. */ private suspend fun targetsFor(database: BennuDatabase, statement: Event, excluding: String): List { - val guardians = GroupWalletStatementEvent.read(statement.tags, statement.content)?.guardians.orEmpty() - - return guardians + return guardiansNamedIn(statement) .map { it.chatRoomId } .filterNot { it.equals(excluding, ignoreCase = true) } .mapNotNull { database.chatRoomDao().findChatRoomById(it) } @@ -333,7 +429,10 @@ object GuardianManager { val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null - return wallet.name?.let { "Shared the guarded wallet of $it with this group." } - ?: "Shared a subgroup's guarded wallet with this group." + 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." + } } } 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 6043aeb0..cfc52221 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 @@ -80,6 +80,7 @@ import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet import bennu.composeapp.generated.resources.open_a_group_wallet import bennu.composeapp.generated.resources.open_a_guarded_wallet import bennu.composeapp.generated.resources.a_subgroup +import bennu.composeapp.generated.resources.at_s import bennu.composeapp.generated.resources.couldn_t_share_the_wallet import bennu.composeapp.generated.resources.guarded_wallets import bennu.composeapp.generated.resources.not_yet_shared_with_the_groups_above @@ -677,12 +678,13 @@ private fun LazyListScope.guardianItems( items(guardedWallets, key = { "guarded-" + it.wallet.statement.id }) { row -> ListItem( leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, - headlineContent = { Text(row.wallet.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + headlineContent = { Text(guardedName(row.wallet.subject), maxLines = 1, overflow = TextOverflow.Ellipsis) }, supportingContent = { - Text( - row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) } - ?: stringResource(Res.string.balance_not_known_yet) - ) + val reach = row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) } + ?: stringResource(Res.string.balance_not_known_yet) + // A member's label says which of their wallets it is. + val label = (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.label + Text(label?.let { stringResource(Res.string.s_dot_s, it, reach) } ?: reach) }, trailingContent = onSpend?.let { spend -> { @@ -701,7 +703,15 @@ private fun LazyListScope.guardianItems( } items(shareable, key = { "shareable-" + it.statement.id }) { candidate -> ListItem( - headlineContent = { Text(candidate.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + headlineContent = { + Text( + text = candidate.ownerPublicKey?.let { stringResource(Res.string.at_s, candidate.ownerName ?: it.take(8)) } + ?: candidate.name + ?: stringResource(Res.string.a_subgroup), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, supportingContent = { Text(stringResource(Res.string.not_yet_shared_with_the_groups_above)) }, trailingContent = { TextButton(onClick = { onShare(candidate) }, enabled = !isPending) { @@ -713,6 +723,18 @@ private fun LazyListScope.guardianItems( } } +/** + * A guarded wallet as an ancestor's list names it: a subgroup by the name its + * parent certified -- `#Translation` -- and a member by their profile's name -- + * `@alice` -- falling back to the start of their key. A person's name is theirs + * and live; the certificate fixes who they are, not what they are called. + */ +@Composable +internal fun guardedName(subject: GuardianManager.GuardedSubject): String = when (subject) { + is GuardianManager.GuardedSubject.Subgroup -> subject.name ?: stringResource(Res.string.a_subgroup) + is GuardianManager.GuardedSubject.Member -> stringResource(Res.string.at_s, subject.ownerName ?: subject.ownerPublicKey.take(8)) +} + @Composable internal fun BalanceCard(walletState: GroupWalletState?) { Card(modifier = Modifier.fillMaxWidth()) { 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 18e6b1db..05ca1340 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 @@ -31,6 +31,8 @@ import fr.acinq.bitcoin.crypto.frost.IndividualNonce import fr.acinq.bitcoin.crypto.frost.KeyMaterial import fr.acinq.bitcoin.crypto.frost.SecretNonce import fr.acinq.bitcoin.crypto.frost.Session +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.bitcoin.ByteVector64 import kotlin.time.Instant /** @@ -185,9 +187,11 @@ internal object GroupFixtures { return requireNotNull(db.chatRoomDao().findChatRoomById(roomId)) } - private fun signature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation.derive(thresholdKeyOf(material), path).cache - val message = ByteVector(eventId.hexToByteArray()) + private fun signature(material: KeyMaterial, eventId: String): String = + signWith(material, SharedKeyDerivation.derive(thresholdKeyOf(material), path).cache, ByteVector(eventId.hexToByteArray())).toHex() + + /** A 2-of-3 FROST signature by [material]'s quorum over [message] under [cache] -- a leaf's, an address's, the room's. */ + fun signWith(material: KeyMaterial, cache: TweakCache, message: ByteVector): ByteVector64 { val signerIds = listOf(0, 1) val nonces = signerIds.map { signerId -> @@ -212,6 +216,6 @@ internal object GroupFixtures { val partials = signerIds.mapIndexed { position, signerId -> session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!! } - return session.aggregateSigs(partials).right!!.toByteArray().toHex() + return session.aggregateSigs(partials).right!! } } 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 new file mode 100644 index 00000000..c6cad631 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt @@ -0,0 +1,205 @@ +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.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signWith +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.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * The guardians' side of a member's wallet: the group that signed its + * certificate lists it, a group above learns of it from a notice and lists it + * too, each finds its own leaf in the wallet's addresses, and a spend through + * that leaf is one the script interpreter takes once the coin is 12 blocks old. + */ +class MemberWalletGuardianJvmTest { + 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 parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + private val parentRoom = roomOf(parent) + + 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 grant = GuardianDerivation.grant( + thresholdKeyOf(group), groupRoom, + GuardianDerivation.grant(thresholdKeyOf(parent), parentRoom, emptyList(), groupRoom), + walletId, + ) + + private fun certificate(guardians: List = grant): Event { + val request = MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = groupRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians), + label = "Savings", + createdAt = 1_700_000_000, + ) + val template = MemberWalletCertificateEvent.template(request) + return signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + } + + /** This device in [material]'s room, holding its verified key state. */ + private suspend fun inRoom(material: fr.acinq.bitcoin.crypto.frost.KeyMaterial, certificate: Event? = null) { + signingRoom(db, material, members = listOf(memberPublicKey), subject = "#" + roomOf(material).take(4)) + fileKeyState(db, material, certificate) + } + + private suspend fun fileSigned(certificate: Event) = + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = groupRoom, 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, + ) + ) + + @Test + fun `the group that signed it lists its member's wallet as theirs`(): Unit = runBlocking { + GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") + inRoom(group, guardedCertificate(parent, group)) + fileSigned(certificate()) + + val listed = GuardianManager.guardedWalletsOf(db, groupRoom).single() + val subject = assertIs(listed.subject) + assertEquals(walletId, subject.id) + assertEquals(memberPublicKey, subject.ownerPublicKey) + assertEquals("alice", subject.ownerName) + assertEquals("Savings", subject.label) + assertEquals(walletId, listed.descendantChatRoomId) + assertEquals(listOf(walletId), listed.lineage) + assertEquals(0, listed.position) + assertNull(listed.name, "a member's wallet has no founding name") + assertEquals("@alice", listed.spender().name) + } + + @Test + fun `a group above learns of it from a notice, and walks down to its own leaf`(): Unit = runBlocking { + inRoom(parent) + noticeIn(parentRoom, certificate()) + + 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 @")) + } + + @Test + fun `a notice whose entry for this group is not the key it reaches is ignored`(): Unit = runBlocking { + inRoom(parent) + // The group signed a certificate naming the stranger's key under the parent's room. + val forged = listOf(grant[0], GuardianDerivation.grant(thresholdKeyOf(stranger), parentRoom, emptyList(), groupRoom).single().grantedTo(walletId)) + noticeIn(parentRoom, certificate(forged)) + assertTrue(GuardianManager.guardedWalletsOf(db, parentRoom).isEmpty()) + } + + @Test + fun `a member of both groups can carry it upward`(): Unit = runBlocking { + inRoom(group, guardedCertificate(parent, group)) + inRoom(parent) + fileSigned(certificate()) + + val shareable = GuardianManager.shareableFrom(db, groupRoom, chain).single() + assertEquals(memberPublicKey, shareable.ownerPublicKey) + assertEquals(listOf(parentRoom), shareable.rooms.map { it.chatRoom.id }) + + GuardianManager.share(db, shareable.statement, shareable.rooms, memberPublicKey) + assertEquals(walletId, GuardianManager.guardedWalletsOf(db, parentRoom).single().descendantChatRoomId) + assertTrue(GuardianManager.shareableFrom(db, groupRoom, chain).isEmpty(), "told once") + } + + @Test + fun `a guardian's spend through its leaf of a member's wallet`(): Unit = runBlocking { + inRoom(parent) + noticeIn(parentRoom, certificate()) + val wallet = GuardianManager.guardedWalletsOf(db, parentRoom).single() + + // One coin at receive address 2, confirmed long enough ago. + val derived = GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.RECEIVE, 2) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(60_000), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(2) + val receive = WalletState(mapOf(derived.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))) + val change = WalletState(mapOf(GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))) + val state = GroupWalletState(wallet.account, receive, change, tipHeight = 200) + + val spender = wallet.spender(thresholdKeyOf(parent)) + val built = assertIs(GroupSpendBuilder.sendAll(state, "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 3L, emptySet(), spender)) + val checked = assertIs(GroupSpend.check(built.psbt, wallet.account, spender)).checked + + val signatures = checked.inputs.map { signWith(parent, it.cache, it.sighash) } + val signed = checked.witnessed(signatures) + signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(3, signed.txIn.single().witness.stack.size, "signature, leaf, control block") + + // The member's own device names who took it. + val taken = GuardianManager.takenIn(signed, wallet.account, mapOf(funding.let { OutPoint(it, 0) } to (funding.txOut[0] to derived))) + assertEquals(parentRoom, taken.single().guardian.chatRoomId) + + // Eleven blocks is too soon: the same spend at sequence 11, signed properly + // for that sequence, so the only thing wrong with it is the lock. + val input = checked.inputs.single() + val unsigned = checked.tx.let { tx -> Transaction(tx.version, tx.txIn.map { it.copy(sequence = 11, witness = fr.acinq.bitcoin.ScriptWitness.empty) }, tx.txOut, tx.lockTime) } + val sighash = unsigned.hashForSigningTaprootScriptPath(0, checked.spentOutputs, fr.acinq.bitcoin.SigHash.SIGHASH_DEFAULT, input.leaf!!.hash()) + val early = unsigned.updateWitness(0, input.witness(signWith(parent, input.cache, sighash))) + assertFails { early.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) } + } +}