diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt index 1308606a..d31bd046 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -186,6 +186,13 @@ class DatabaseFrostSigningRepository( emptySet() } + override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = try { + FrostSigningManager.reservedFundingIndices(database, chatRoomId, account) + } catch (e: Throwable) { + logger.e("Error reading the funding addresses reserved in $chatRoomId", e) + emptySet() + } + override fun observeGroupTransactions(chatRoomId: String): Flow> = database.groupTransactionDao().observeByChatRoomId(chatRoomId) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index ed490ee8..75c9da59 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -674,7 +674,7 @@ object FrostSigningManager { val wallet = GroupWalletManager.walletFor(database, chatRoomId, thresholdPublicKey, chain, account) ?: throw IllegalStateException("This group has not opened a wallet on ${GroupWalletStatementEvent.chainName(chain)}") - val checked = when (val result = GroupSpend.check(psbt, wallet.account)) { + val checked = when (val result = GroupSpend.check(psbt, wallet.account).withFundings(database, chatRoomId)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") } @@ -752,7 +752,7 @@ object FrostSigningManager { val guarded = GuardianManager.guardedWalletFor(database, chatRoomId, descendantChatRoomId, chain, account) ?: throw IllegalStateException("This group guards no wallet of $descendantChatRoomId on ${GroupWalletStatementEvent.chainName(chain)}") - val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) { + val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey)).withFundings(database, chatRoomId)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") } @@ -882,7 +882,7 @@ object FrostSigningManager { guarded.account to guarded.spender(thresholdPublicKey) } - val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender)) { + val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender).withFundings(database, localChatRoom.chatRoom.id)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> { logger.w("Spend proposal $sessionId ${result.reason}; dropping") @@ -1054,7 +1054,26 @@ object FrostSigningManager { ?: return null val context = spendContext(database, session, thresholdPublicKey) ?: return null val psbt = GroupSpend.decode(context.transaction.psbt) ?: return null - return (GroupSpend.check(psbt, context.account, context.spender) as? GroupSpend.Result.Ok)?.checked + return (GroupSpend.check(psbt, context.account, context.spender).withFundings(database, context.transaction.chatRoomId) as? GroupSpend.Result.Ok)?.checked + } + + /** + * A checked spend with its payments into descendants' guarded wallets read + * against the ones [chatRoomId] holds -- `GroupSpend.fundingsOf` -- or + * refused for a claim that does not derive. Every place a spend is checked + * for a member to read or sign reads its fundings here, so the label a + * signer sees is the one every other signer's device derived too. + * + * A spend none of whose payments claims anything -- every spend to a typed + * address -- reads no guarded wallets at all. + */ + private suspend fun GroupSpend.Result.withFundings(database: BennuDatabase, chatRoomId: String): GroupSpend.Result { + val checked = (this as? GroupSpend.Result.Ok)?.checked ?: return this + if (checked.payments.all { checked.psbt.outputs[it.index].taprootDerivationPaths.isEmpty() }) return this + return when (val reading = GroupSpend.fundingsOf(checked, GuardianManager.guardedWalletsOf(database, chatRoomId))) { + is GroupSpend.FundingReading.Ok -> GroupSpend.Result.Ok(checked.copy(fundings = reading.fundings)) + is GroupSpend.FundingReading.Refused -> GroupSpend.Result.Refused(reading.reason) + } } /** @@ -1083,6 +1102,21 @@ object FrostSigningManager { .flatMap { GroupSpend.claimedChangeIndices(it, account) } .toSet() + /** + * The receive addresses of [account] -- a descendant's guarded wallet -- that + * a room's open spends fund, which a new funding should not pay as well. + * Held by the same sessions as [reservedOutPoints], for the reason + * [reservedChangeIndices] gives. + */ + suspend fun reservedFundingIndices( + database: BennuDatabase, + chatRoomId: String, + account: GroupWalletDerivation.Account, + ): Set = + openSpends(database, chatRoomId) + .flatMap { GroupSpend.claimedFundingIndices(it, account) } + .toSet() + /** The PSBT of every spend in the room whose session has not failed. */ private suspend fun openSpends(database: BennuDatabase, chatRoomId: String): List = database.groupTransactionDao().getByChatRoomId(chatRoomId) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt index 6c7bcdd9..846c48b3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt @@ -263,6 +263,9 @@ interface FrostSigningRepository { /** The change indices under [account] the room's open spends already pay back to. */ suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set + /** The receive indices of [account], a descendant's guarded wallet, the room's open spends already fund. */ + suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set + /** Every spend the room has proposed, newest first, as it moves from proposed to confirmed. */ fun observeGroupTransactions(chatRoomId: String): Flow> @@ -352,6 +355,7 @@ interface FrostSigningRepository { override suspend fun reservedOutPoints(chatRoomId: String): Set = emptySet() override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet() + override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet() override fun observeGroupTransactions(chatRoomId: String): Flow> = flowOf(emptyList()) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt index a95f079b..bb81b740 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt @@ -4,6 +4,7 @@ import com.machankura.bennu.compose.wallet.GroupSpend import fr.acinq.bitcoin.Bitcoin import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Satoshi /** * A spend the group is being asked to sign, said in words -- [ProposedEvent]'s @@ -15,16 +16,29 @@ object ProposedSpend { ProposedEvent.Summary( // A guardian's spend takes a descendant's coins, so whose they are // is the first thing a signer reads. + // A funding comes next: where the money goes, as every signer's + // device derived it -- never the proposer's word for it. label = when (val guardian = spend.spender as? GroupSpend.Spender.Guardian) { - null -> "Spend from the group's wallet" + null -> spend.fundings.singleOrNull()?.takeIf { spend.payments.size == 1 } + ?.let { "Fund ${nameOf(it)}'s guarded wallet" } + ?: "Spend from the group's wallet" else -> "Spend from ${guardian.name ?: "a subgroup"}'s guarded wallet" }, detail = when (val payment = spend.payments.singleOrNull()) { - null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" - else -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}" + null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" + when (val funding = spend.fundings.singleOrNull()) { + null -> if (spend.fundings.isEmpty()) "" else + ", ${Satoshi(spend.fundings.sumOf { spend.tx.txOut[it.outputIndex].amount.sat }).grouped()} of them to ${spend.fundings.size} guarded wallets" + else -> ", ${spend.tx.txOut[funding.outputIndex].amount.grouped()} of them to ${nameOf(funding)}'s guarded wallet" + } + else -> when (val funding = spend.fundings.singleOrNull()) { + null -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}" + else -> "Send ${payment.txOut.amount.grouped()} sats to ${nameOf(funding)}'s guarded wallet, address ${funding.derived.index}" + } } ) + private fun nameOf(funding: GroupSpend.Funding): String = funding.wallet.name ?: "a subgroup" + /** The address [script] pays, or the script itself where it has no address. */ fun addressOf(script: ByteVector, chain: Chain): String = Bitcoin.addressFromPublicKeyScript(chain.chainHash, script.toByteArray()).right ?: script.toHex() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt index 08f705b7..e1171c72 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.managers.GuardianDerivation import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector @@ -149,6 +150,12 @@ object GroupSpend { */ val weight: Int, val spender: Spender = Spender.Owner, + /** + * The payments that fund a descendant's guarded wallet, each claim derived + * again -- [fundingsOf]. Empty until a caller holding the room's guarded + * wallets has read them, which [check] alone cannot. + */ + val fundings: List = emptyList(), ) { val tx: Transaction get() = psbt.global.tx @@ -173,6 +180,59 @@ object GroupSpend { data class Refused(val reason: String) : Result } + /** A payment into a descendant's guarded wallet, at [derived] under its account -- the claim, derived again. */ + data class Funding( + val outputIndex: Int, + val wallet: GuardianManager.GuardedWallet, + val derived: GroupWalletDerivation.Derived, + ) + + sealed interface FundingReading { + data class Ok(val fundings: List) : FundingReading + data class Refused(val reason: String) : FundingReading + } + + /** + * Which of [checked]'s payments fund one of [guarded] -- the descendants' + * guarded wallets the room holds -- read off each payment's derivation and + * derived again, the way change is. `docs/guarded-wallet-funding.md`, D4: + * + * - a claim under a wallet in [guarded] that derives to the payment's script + * is a funding; + * - a claim under a wallet in [guarded] that does not -- another index, + * another branch, another key -- refuses the spend, so no proposer can put + * a descendant's name on a payment to an address it does not own; + * - a claim under any other account is not this device's to check, and the + * payment is read as the bare address it is. + * + * Fingerprints are four bytes, so every held wallet sharing one is tried + * before a claim is refused. + */ + fun fundingsOf(checked: Checked, guarded: List): FundingReading { + val fundings = checked.payments.mapNotNull { payment -> + val paths = checked.psbt.outputs[payment.index].taprootDerivationPaths + val (internalKey, path, candidates) = paths.entries.firstNotNullOfOrNull { (internalKey, path) -> + guarded.filter { it.chain == checked.account.chain && isOurs(path, it.account) } + .takeIf { it.isNotEmpty() } + ?.let { Triple(internalKey, path, it) } + } ?: return@mapNotNull null + + val (branch, index) = path.keyPath.path.takeIf { it.size == 2 && path.leaves.isEmpty() } + ?: return FundingReading.Refused("output ${payment.index} claims a place in a guarded wallet that is not one") + if (branch != GroupWalletDerivation.RECEIVE || index !in 0L..MAX_ADDRESS_INDEX) { + return FundingReading.Refused("output ${payment.index} claims $branch/$index, which is not a receive address") + } + candidates.firstNotNullOfOrNull { wallet -> + GroupWalletDerivation.derive(wallet.account, branch, index) + .takeIf { it.pubkeyScript == payment.txOut.publicKeyScript && it.internalKey == internalKey } + ?.let { Funding(payment.index, wallet, it) } + } ?: return FundingReading.Refused( + "output ${payment.index} claims $branch/$index of ${candidates.first().name ?: "a subgroup"}'s guarded wallet, which is not where it pays" + ) + } + return FundingReading.Ok(fundings) + } + /** * The checks a member makes before signing, in the order `docs/group-chain-wallet.md` * numbers them, against [account] -- which comes from the room's verified diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt index cf84d8c9..35627cec 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt @@ -190,17 +190,20 @@ object GroupSpendBuilder { if (reduced < DUST) return Result.NotEnough val tx = spend.tx.copy(txOut = spend.tx.txOut.mapIndexed { index, out -> if (index == target.index) out.copy(amount = reduced) else out }) + // A funding keeps its claim, or the bump would read as a payment to a bare address. val psbt = GroupSpend.psbtOf( tx, spend.inputs.map { it.txOut to it.derivation }, spend.outputs.mapNotNull { output -> output.change?.let { output.index to it } }.toMap(), spend.account, + funding = spend.fundings.associate { it.outputIndex to (it.wallet.account to it.derived) }, ) return Result.Built( psbt = psbt, amount = if (target.isChange) spend.amountSent else reduced, fee = fee, change = if (target.isChange) reduced else null, + funded = spend.fundings.singleOrNull()?.let { Destination.Funding(it.wallet.account, it.derived) }, ) } 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 45e22bf8..6eece51e 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 @@ -625,4 +625,131 @@ class GuardianSigningJvmTest { val psbt = GroupSpend.psbtOf(unlocked, listOf(funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0)), emptyMap(), guarded.account) assertIs(GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) } + + // ---- Funding a descendant's guarded wallet ------------------------------- + + /** The room opens its own plain wallet, signed by a quorum, so it has coins to fund with. */ + private suspend fun openOwnWallet(proposer: Device, other: Device): GroupWalletDerivation.Account { + val own = GroupWalletDerivation.account(thresholdPublicKey, chain) + val template = GroupWalletStatementEvent.template(own) + val session = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + listOf(proposer, other).forEach { assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "the room's own wallet is open") } + return own + } + + /** The room's own wallet holding one confirmed coin at its first receive address. */ + private fun ownState(own: GroupWalletDerivation.Account): GroupWalletState { + val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) + val paid = Transaction( + 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x71 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(80_000), coin.pubkeyScript)), 0, + ) + val meta = WalletState.AddressMeta.Derived(0) + val receive = WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(paid.txid, 0, 100, paid, meta))))) + val change = WalletState((0 until 3).associate { index -> + GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) + }) + return GroupWalletState(own, receive, change, tipHeight = 110) + } + + private fun fundingTo(guarded: GuardianManager.GuardedWallet, index: Long) = + GroupSpendBuilder.Destination.Funding(guarded.account, GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, index)) + + @Test + fun `a funding is read as one by every device holding the wallet, and its address is held`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + tell(other, statement) + val own = openOwnWallet(proposer, other) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val built = assertIs( + GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet()) + ) + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) + pump(proposer, other) + + val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) + val funding = seen.fundings.single() + assertEquals(guardedChildRoomId, funding.wallet.descendantChatRoomId) + assertEquals(2L, funding.derived.index) + assertEquals( + com.machankura.bennu.compose.text.ProposedEvent.Summary( + "Fund Translation team's guarded wallet", + "Send 30,000 sats to Translation team's guarded wallet, address 2", + ), + com.machankura.bennu.compose.text.ProposedSpend.summarize(seen, chain), + ) + assertEquals(setOf(2L), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account)) + + // A bump keeps the claim, or it would read as a payment to a bare address. + val bumped = assertIs(GroupSpendBuilder.bump(seen, 5)) + assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(bumped.psbt, guarded.account)) + assertEquals(2L, bumped.funded?.derived?.index) + + // Abandoned, it lets the address go. + other.db.frostSigningSessionDao().upsert(other.session(session.id)!!.copy(stage = FrostSigningStage.FAILED)) + assertEquals(emptySet(), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account)) + } + + @Test + fun `a funding claiming an address it does not pay is refused by every device that can tell`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + // Only the other device holds the wallet, so only it can check the claim. + tell(other, guardedStatement()) + val own = openOwnWallet(proposer, other) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(other.db, roomId, guardedChildRoomId, chain, 0)) + val honest = assertIs( + GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet()) + ) + // Pays address 2, says address 3. + val claimed = GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, 3) + val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) + val lying = GroupSpend.psbtOf( + honest.psbt.global.tx, + listOf(TxOut(Satoshi(80_000), coin.pubkeyScript) to coin), + mapOf(1 to GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0)), + own, + funding = mapOf(0 to (guarded.account to claimed)), + ) + assertIs( + GroupSpend.fundingsOf(assertIs(GroupSpend.check(lying, own)).checked, listOf(guarded)) + ) + + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, lying, chain) + pump(proposer, other) + assertNull(other.session(session.id), "the device that holds the wallet never puts it to the member") + } + + @Test + fun `a device never told about the wallet reads a funding as the bare address it pays`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + tell(proposer, guardedStatement()) + val own = openOwnWallet(proposer, other) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val destination = fundingTo(guarded, 2) + val built = assertIs( + GroupSpendBuilder.send(ownState(own), destination, Satoshi(30_000), 2, emptySet()) + ) + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) + pump(proposer, other) + + val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id), "accepted: the address is the truth") + assertEquals(emptyList(), seen.fundings) + assertEquals( + "Send 30,000 sats to ${destination.derived.address(chain)}", + com.machankura.bennu.compose.text.ProposedSpend.summarize(seen, chain).detail, + ) + assertEquals(1, assertNotNull(FrostSigningManager.checkedSpend(proposer.db, session.id)).fundings.size, "and the proposer's own device still names it") + } }