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 4b28c771..264bca52 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 @@ -13,6 +13,7 @@ import com.machankura.bennu.compose.database.model.traits.UserViewableEntity import com.machankura.bennu.compose.exceptions.MarmotUnprocessableInnerEventException import com.machankura.bennu.compose.managers.ChronicleManager import com.machankura.bennu.compose.managers.GroupKeyStateManager +import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.extensions.toHex import com.vitorpamplona.quartz.marmot.GroupEventResult @@ -33,6 +34,8 @@ import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent @@ -491,12 +494,23 @@ data class ChatMessage( */ const val TYPE_GROUP_ENTRY_CURATED = "groupEntryCurated" + /** + * The group opened a wallet. + * + * A system line like the others in [GROUP_IDENTITY_TYPES]: nobody said it, + * the group signed it. It names the network and nothing else -- the + * addresses are on the wallet's screen, derived there from the room's key, + * and the statement's xpub is not something a transcript should repeat. + */ + const val TYPE_GROUP_WALLET_OPENED = "groupWalletOpened" + val GROUP_IDENTITY_TYPES = setOf( TYPE_GROUP_PROFILE_SIGNED, TYPE_GROUP_RELAYS_SIGNED, TYPE_GROUP_POST_SIGNED, TYPE_GROUP_SCHEMA_SIGNED, TYPE_GROUP_ENTRY_CURATED, + TYPE_GROUP_WALLET_OPENED, ) /** @@ -1650,6 +1664,31 @@ data class ChatMessage( // `GroupRelayList` reads the lists straight off those; this arm // exists so a signed relay list is a line in the transcript rather // than raw JSON in a bubble. + // The group opening a wallet. Checked the whole way -- the room's + // signature, and the statement rederiving from the room's own key -- + // because a line saying "the group opened a wallet" is a line people + // will send money on. A statement that fails either gets no line; + // it is filed as a `GroupSignedEvent` all the same, and `GroupWallet` + // refuses it there for the same reasons. + GroupWalletStatementEvent.KIND -> { + val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, groupId) + ?: return null + val wallet = GroupWallet.of(signed, thresholdPublicKey) ?: return null + + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_GROUP_WALLET_OPENED, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = "The group opened a wallet on ${GroupWalletStatementEvent.chainName(wallet.chain)}" + ) + } + in GroupRelaySet.KINDS -> { val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) if (!signed.verifies()) return 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 1e4f35e7..650e3379 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 @@ -1,5 +1,9 @@ package com.machankura.bennu.compose.database.repository +import fr.acinq.bitcoin.Chain +import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.GENESIS_AT import com.machankura.bennu.compose.database.BennuDatabase import kotlinx.coroutines.flow.MutableStateFlow @@ -212,6 +216,20 @@ class DatabaseChatRepository( emptyList() } + override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = try { + GroupWalletManager.walletFor(database, chatRoomId, chain) + } catch (e: Throwable) { + logger.e("Error reading the wallet of $chatRoomId", e) + null + } + + override suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? = try { + GroupWalletManager.accountFor(database, chatRoomId, chain) + } catch (e: Throwable) { + logger.e("Error deriving the wallet account of $chatRoomId", e) + null + } + override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt new file mode 100644 index 00000000..a0386631 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt @@ -0,0 +1,55 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain + +/** + * Where a room's wallet is read from: its threshold key, and the statement the + * group signed opening a wallet under it. + */ +object GroupWalletManager { + /** + * The threshold key [chatRoomId] signs with, or null for a room without one. + * + * The room's verified key state first -- which every member who was in the + * ceremony holds, whether or not they are a signer -- and the key this device + * would sign with behind it, for a room whose state this device never filed. + * Either way it is a key the room's id rederives from, so a wallet read under + * it is the room's. + */ + suspend fun thresholdKeyFor(database: BennuDatabase, chatRoomId: String): HexKey? = + GroupKeyStateManager.keyStateFor(database, chatRoomId) + ?.takeIf { it.verifies() } + ?.thresholdPublicKey + ?: FrostSigningManager.completedKey(database, chatRoomId)?.thresholdPublicKey + + /** The account [chatRoomId] would open on [chain], whether or not it has: what a statement proposing it carries. */ + suspend fun accountFor( + database: BennuDatabase, + chatRoomId: String, + chain: Chain, + account: Long = 0L, + ): GroupWalletDerivation.Account? = + thresholdKeyFor(database, chatRoomId)?.let { GroupWalletDerivation.account(it, chain, account) } + + /** The wallet [chatRoomId] has opened on [chain], or null when the group has not opened one. */ + suspend fun walletFor( + database: BennuDatabase, + chatRoomId: String, + chain: Chain, + account: Long = 0L, + ): GroupWallet? { + val thresholdPublicKey = thresholdKeyFor(database, chatRoomId) ?: return null + + return GroupWallet.newestAmong( + signedEvents = database.groupSignedEventDao() + .getByChatRoomIdAndKind(chatRoomId, GroupWalletStatementEvent.KIND), + thresholdPublicKey = thresholdPublicKey, + chain = chain, + account = account, + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt new file mode 100644 index 00000000..1587e43a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt @@ -0,0 +1,70 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import kotlin.time.Instant + +/** + * A wallet the group has opened: its statement, and the account that statement + * rederives to. + * + * There is no table. A wallet is a signed event plus a derivation, and every + * address, every balance and every check below is recomputed from the room's + * threshold key -- [account] is what [GroupWalletStatementEvent.Reading.verifiedAgainst] + * returned, never what the statement said. + * + * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies], the way + * `GroupRelayList` is: only an event the room itself authored is the group + * speaking. + */ +data class GroupWallet( + val signedEvent: GroupSignedEvent, + val account: GroupWalletDerivation.Account, +) { + val chain: Chain get() = account.chain + + /** When the group opened it. */ + val openedAt: Instant get() = signedEvent.createdAt + + companion object { + /** + * The wallet one signed event opens, or null when it does not open one. + * + * Four refusals: the wrong kind, a signature that is not the room's, tags + * that do not read as a statement, and a statement [thresholdPublicKey] + * does not rederive. + */ + fun of(signedEvent: GroupSignedEvent, thresholdPublicKey: HexKey): GroupWallet? { + if (signedEvent.kind != GroupWalletStatementEvent.KIND) return null + if (!signedEvent.verifies()) return null + + val account = GroupWalletStatementEvent.read(signedEvent.tags, signedEvent.content) + ?.verifiedAgainst(thresholdPublicKey) + ?: return null + + return GroupWallet(signedEvent = signedEvent, account = account) + } + + /** + * The newest wallet the group opened on [chain] at [account], or null for + * one it never has. + * + * Newest by the group's own timestamp with the id breaking a tie, for the + * reason `GroupRelayList.newestAmong` gives: two devices reading the same + * events in different orders have to agree. + */ + fun newestAmong( + signedEvents: List, + thresholdPublicKey: HexKey, + chain: Chain, + account: Long = 0L, + ): GroupWallet? = + signedEvents + .asSequence() + .mapNotNull { of(it, thresholdPublicKey) } + .filter { it.chain == chain && it.account.account == account } + .maxWithOrNull(compareBy({ it.openedAt }, { it.signedEvent.id })) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt new file mode 100644 index 00000000..c00421d0 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt @@ -0,0 +1,149 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import fr.acinq.bitcoin.Chain +import kotlin.time.Clock + +/** + * The group saying it keeps coins on chain, at one account on one network. + * + * Every room with a key *could* receive coins without this -- the addresses are a + * function of the threshold key -- and that is the wrong default for money. A + * member should not be able to show an address the group never agreed to look + * after, and somebody paying one deserves to know the group said so. So a wallet + * exists when a quorum has signed one of these, and not before. + * + * ``` + * member --[ 30320 proposal over a 30331 ]-> the room + * ...a signing session... + * everyone holds the signed 30331 "the group keeps a wallet at this account" + * ``` + * + * ### Trusted no further than it can be checked + * + * Content is the account's xpub; the tags carry the network, the account number + * and the two descriptors. A reader accepts a statement only when the room signed + * it *and* [GroupWalletDerivation.account] rederives every one of those values + * from the room's threshold key -- the same two checks `GroupKeyStateEvent` asks + * of a key state. The second is the load-bearing one. This is a record that the + * group agreed, not a source of keys: nothing reads an address out of it, and a + * statement naming any xpub but the rederived one is not the group's wallet, + * whoever signed it. + * + * ### Never on a relay + * + * The xpub is every address and the whole balance, to whoever has it. Like the + * signing kinds this only ever lives inside an encryption a relay cannot open, + * and the broadcast screen refuses it by kind -- see [NEVER_BROADCAST]. + * + * ### Why 30331 + * + * Next to the signing family in the app's private inner-event space. 30327-30330 + * were taken by the chronicle, its request, the subgroup certificate and the + * decline (the last also shared with the direct-message envelope), so this is the + * first free number past them, and the transaction proposal that is opened + * against it sits beside it at 30332. + */ +object GroupWalletStatementEvent { + val KIND: Kind = 30331 + + /** The kinds a member may never send to a relay, whatever the group signed. */ + val NEVER_BROADCAST: Set = setOf(KIND) + + private const val D_TAG = "d" + private const val CHAIN_TAG = "chain" + private const val ACCOUNT_TAG = "account" + private const val DESCRIPTOR_TAG = "descriptor" + private const val RECEIVE_MARKER = "receive" + private const val CHANGE_MARKER = "change" + + /** + * What a statement says, read but not yet believed. [verifiedAgainst] is what + * turns it into a wallet. + */ + data class Reading( + val chain: Chain, + val account: Long, + val xpub: String, + val receiveDescriptor: String, + val changeDescriptor: String, + ) { + /** + * The account this statement describes, if [thresholdPublicKey] rederives + * every value it carries; null otherwise. + */ + fun verifiedAgainst(thresholdPublicKey: HexKey): GroupWalletDerivation.Account? { + val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account) } + .getOrNull() + ?: return null + + return account.takeIf { + it.xpub == xpub && + it.receiveDescriptor == receiveDescriptor && + it.changeDescriptor == changeDescriptor + } + } + } + + /** + * The `d` tag: one statement per network and account, the newest winning, so a + * group that signs a second one for the same account replaces rather than adds. + */ + fun identifier(chain: Chain, account: Long): String = "${chainName(chain)}:$account" + + fun template(account: GroupWalletDerivation.Account, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = + EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf( + arrayOf(D_TAG, identifier(account.chain, account.account)), + arrayOf(CHAIN_TAG, chainName(account.chain)), + arrayOf(ACCOUNT_TAG, account.account.toString()), + arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), + arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), + ), + content = account.xpub, + ) + + /** The statement's fields, or null when any is missing or unreadable. Nothing is verified here. */ + fun read(tags: Array>, content: String): Reading? { + fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + fun descriptor(marker: String): String? = + tags.firstOrNull { it.size >= 3 && it[0] == DESCRIPTOR_TAG && it[2] == marker }?.get(1) + + val chain = value(CHAIN_TAG)?.let(::chainNamed) ?: return null + val account = value(ACCOUNT_TAG)?.toLongOrNull() ?: return null + val receive = descriptor(RECEIVE_MARKER) ?: return null + val change = descriptor(CHANGE_MARKER) ?: return null + if (content.isBlank()) return null + // A `d` tag that disagrees with the fields would let two statements for one + // account both stand; reading it back here keeps "newest per account" one rule. + if (value(D_TAG) != identifier(chain, account)) return null + + return Reading(chain, account, content, receive, change) + } + + /** + * Lower-case names, written into a tag. Spelled out rather than taken from + * [Chain.name], whose capitalisation is the library's to change. + */ + fun chainName(chain: Chain): String = when (chain) { + Chain.Mainnet -> "mainnet" + Chain.Testnet3 -> "testnet3" + Chain.Testnet4 -> "testnet4" + Chain.Signet -> "signet" + Chain.Regtest -> "regtest" + } + + fun chainNamed(name: String): Chain? = when (name) { + "mainnet" -> Chain.Mainnet + "testnet3" -> Chain.Testnet3 + "testnet4" -> Chain.Testnet4 + "signet" -> Chain.Signet + "regtest" -> Chain.Regtest + else -> null + } +} 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 32c412e0..8df157b6 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 @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.repository +import fr.acinq.bitcoin.Chain +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload import com.machankura.bennu.compose.database.model.GroupKeyState @@ -106,6 +109,18 @@ interface ChatRepository { */ suspend fun groupRelayLists(chatRoomId: String): List + /** + * The wallet this group has opened on [chain], or null when it has not -- + * read off the group's signed statement and rederived from the room's key. + */ + suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? + + /** + * The account this group *would* open on [chain], whether or not it has, or + * null for a room with no key: what a statement proposing the wallet carries. + */ + suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? + /** * The kind:1s this group signed, newest first. * @@ -382,6 +397,13 @@ interface ChatRepository { override suspend fun groupRelayLists(chatRoomId: String): List = GroupRelayList.allAmong(emptyList(), chatRoomId) + override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = null + + override suspend fun groupWalletAccount( + chatRoomId: String, + chain: Chain + ): GroupWalletDerivation.Account? = null + override suspend fun groupPosts(chatRoomId: String): List = emptyList() override suspend fun groupCuratedSchemas( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 96759804..7cfc2773 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -10,6 +10,7 @@ import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent import com.machankura.bennu.compose.nostr.curated.CuratedSchemaEvent 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.nip30303.ArtifactEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent @@ -225,6 +226,18 @@ object ProposedEvent { } ) + // The group opening a wallet. What a member is agreeing to is that the + // group keeps coins here, so the summary names the network -- the one + // thing that changes what the coins are worth -- and the account, and + // not the xpub, which is a derivation of the room's key nobody can check + // by eye. + GroupWalletStatementEvent.KIND -> Summary( + label = "Open a group wallet", + detail = GroupWalletStatementEvent.read(event.tags, event.content)?.let { statement -> + "On ${GroupWalletStatementEvent.chainName(statement.chain)}, account ${statement.account}" + } ?: "A wallet statement this device cannot read" + ) + else -> Summary(label = "Event of kind ${event.kind}", detail = event.content) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt index a753fecd..e9997409 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.view.model +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf @@ -177,6 +178,13 @@ class BroadcastGroupSignedEventViewModel( "This device doesn't hold that signed event" ) + // The group's wallet statement carries its xpub: on a relay it is + // every address and the whole balance, to anyone. + signedEvent.kind in GroupWalletStatementEvent.NEVER_BROADCAST -> + BroadcastGroupSignedEventUIState.Error( + "The group's wallet stays inside the group" + ) + else -> BroadcastGroupSignedEventUIState.Loaded( localChatRoom = localChatRoom, signedEvent = signedEvent, @@ -322,6 +330,12 @@ class BroadcastGroupSignedEventViewModel( targets: List, onOutcome: (NormalizedRelayUrl, RelayOutcome) -> Unit = { _, _ -> }, ): Map { + // The second line of the refusal the loader makes, for the callers that + // never pass through it -- "Broadcast all" among them. + require(signedEvent.kind !in GroupWalletStatementEvent.NEVER_BROADCAST) { + "kind ${signedEvent.kind} never leaves the group" + } + val outcomes = mutableMapOf() fun settle(relay: NormalizedRelayUrl, outcome: RelayOutcome) { diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt new file mode 100644 index 00000000..f707eb15 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt @@ -0,0 +1,129 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * A wallet statement, read and believed. + * + * The statement is a record that the group agreed, not a source of keys, so most + * of what is here is refusals: a statement is only a wallet when the room signed + * it *and* the room's threshold key rederives every value it carries. + */ +class GroupWalletStatementEventTest { + private fun key(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val thresholdKey = key(0x1c0ffee) + private val otherThresholdKey = key(0xdecaf) + + /** + * The room, as a key whose secret the test holds -- `GroupSignedEvent.verifies` + * asks only that the room's id signed it, and a real FROST signature over the + * same id is `GroupWalletSpendRoundTest`'s business. + */ + private val roomKey = PrivateKey(ByteVector32(Hex.decode("07".repeat(32)))) + private val roomId = roomKey.publicKey().xOnly().value.toString() + + private fun signed(tags: Array>, content: String, createdAt: Long = 1_700_000_000, by: PrivateKey = roomKey): GroupSignedEvent { + val pubKey = by.publicKey().xOnly().value.toString() + val id = EventHasher.hashId(pubKey, createdAt, GroupWalletStatementEvent.KIND, tags, content) + val sig = Crypto.signSchnorr(ByteVector32(id), by, null).toString() + return GroupSignedEvent.fromEvent( + Event(id, pubKey, createdAt, GroupWalletStatementEvent.KIND, tags, content, sig), + chatRoomId = roomId, + ) + } + + private fun statement(account: GroupWalletDerivation.Account, createdAt: Long = 1_700_000_000): GroupSignedEvent { + val template = GroupWalletStatementEvent.template(account, createdAt) + return signed(template.tags, template.content, createdAt) + } + + private val mainnet = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet) + + @Test + fun `a statement reads back as what was written`() { + val template = GroupWalletStatementEvent.template(mainnet) + val reading = assertNotNull(GroupWalletStatementEvent.read(template.tags, template.content)) + + assertEquals(Chain.Mainnet, reading.chain) + assertEquals(0L, reading.account) + assertEquals(mainnet.xpub, reading.xpub) + assertEquals(mainnet.receiveDescriptor, reading.receiveDescriptor) + assertEquals(mainnet.changeDescriptor, reading.changeDescriptor) + assertEquals(mainnet, reading.verifiedAgainst(thresholdKey)) + } + + @Test + fun `the room's statement opens the room's wallet`() { + val wallet = assertNotNull(GroupWallet.of(statement(mainnet), thresholdKey)) + + assertEquals(mainnet, wallet.account) + assertEquals(Chain.Mainnet, wallet.chain) + } + + @Test + fun `a statement another key rederives is not this room's wallet`() { + // Signed by the room, every field well formed -- and naming the xpub of a + // different group. Whoever signed it, it is not a wallet this room's key holds. + val foreign = GroupWalletDerivation.account(otherThresholdKey, Chain.Mainnet) + + assertNull(GroupWallet.of(statement(foreign), thresholdKey)) + } + + @Test + fun `an xpub edited after the fact is refused`() { + val template = GroupWalletStatementEvent.template(mainnet) + val other = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, account = 1) + + assertNull(GroupWallet.of(signed(template.tags, other.xpub), thresholdKey)) + } + + @Test + fun `a statement the room did not sign is a member's, not the group's`() { + val template = GroupWalletStatementEvent.template(mainnet) + val member = PrivateKey(ByteVector32(Hex.decode("09".repeat(32)))) + + assertNull(GroupWallet.of(signed(template.tags, template.content, by = member), thresholdKey)) + } + + @Test + fun `a d tag that disagrees with the fields is not read`() { + val template = GroupWalletStatementEvent.template(mainnet) + val tags = template.tags.map { if (it[0] == "d") arrayOf("d", "regtest:0") else it }.toTypedArray() + + assertNull(GroupWalletStatementEvent.read(tags, template.content)) + } + + @Test + fun `the newest statement for the asked network wins, and another network's is not it`() { + val regtest = GroupWalletDerivation.account(thresholdKey, Chain.Regtest) + val older = statement(mainnet, createdAt = 1_700_000_000) + val newer = statement(mainnet, createdAt = 1_700_000_100) + + val wallet = assertNotNull( + GroupWallet.newestAmong(listOf(newer, statement(regtest), older), thresholdKey, Chain.Mainnet) + ) + assertEquals(newer.id, wallet.signedEvent.id) + assertNull(GroupWallet.newestAmong(listOf(older, newer), thresholdKey, Chain.Signet)) + } + + @Test + fun `every network name round trips`() { + listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest).forEach { + assertEquals(it, GroupWalletStatementEvent.chainNamed(GroupWalletStatementEvent.chainName(it))) + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt index 20f56ffa..51d8340d 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt @@ -26,6 +26,7 @@ import com.machankura.bennu.compose.nostr.GroupRelay import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.Relays +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.nostr.GroupCuratedSchema import com.machankura.bennu.compose.nostr.curated.CuratedEntryEvent import com.machankura.bennu.compose.nostr.curated.CuratedSchema @@ -38,6 +39,7 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @@ -417,4 +419,25 @@ class BroadcastGroupSignedEventViewModelJvmTest { assertEquals(event.signature, wire["sig"]!!.jsonPrimitive.content) assertEquals("""[["alt","The group's profile"]]""", wire["tags"].toString()) } + + // -- what never goes at all ------------------------------------------------ + + @Test + fun `the group's wallet statement is never handed to a relay`() { + val transport = FakeTransport(mapOf(one.url to ok(one))) + + // The xpub on a relay is every address and the whole balance, to anyone. + // A refusal nobody tested is the one that disappears in a refactor of + // what the broadcast list accepts. + assertFailsWith { + runBlocking { + BroadcastGroupSignedEventViewModel.sendToRelays( + publishTransport = transport, + signedEvent = signedEvent(kind = GroupWalletStatementEvent.KIND), + targets = listOf(one), + ) + } + } + assertNull(transport.sent, "nothing reached the transport") + } } diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index 570d9099..2e815cba 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -24,6 +24,9 @@ kept as written; where the build chose differently the table below says so. |---|---| | one `tr([fp]xpub/<0;1>/*)` descriptor | two, `…/0/*` and `…/1/*`, as bitcoin-kmp's `BIP84Descriptors` does. Many watch-only importers, Bitcoin Core's `importdescriptors` among them, refuse a multipath descriptor | | `derive(account, thresholdPublicKey, change, index)` | `derive(account, change, index)`: the `Account` carries the cache that signs as its key, so the threshold key is not asked for twice and cannot be passed in mismatched | +| late members get the statement through the chronicle | they do not: `ChronicleEvent`'s allowlist carries document kinds only, and leaves out every group-signed statement *about* the group — relay lists and profile included — for the replay reason its kdoc gives. A member who joined later sees *Open a group wallet* instead, and signing it again is harmless: a statement for one account is the same values under the same `d` tag, and the newest replaces the rest | +| the descriptor rides in a `descriptor` tag | two, each marked `receive` or `change`, and the `d` tag is read back and checked against the network and account, so "newest per account" cannot be split by a `d` that disagrees with the fields | +| the transcript line is checked by signature | by signature *and* rederivation, through `GroupWallet.of` — a line people will send money on is held to the same check as the wallet screen | The headline: **the best path is BIP86's own unhardened tail, `//`, hung under an account key the group's threshold key is tweaked to, with the