feat(wallet): every signer derives a funding's address again before naming it (Phase 3)
GroupSpend.fundingsOf reads each payment's derivation against the guarded wallets the room holds: a claim that derives is a funding, one that does not refuses the spend, and one under an account this device does not hold is left as the bare address. Every proposal and acceptance path and checkedSpend read it, ProposedSpend says "Fund X's guarded wallet", open fundings hold their addresses, and a bump keeps the claim. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fcf4b8e104
commit
2b0cd72d8b
7 files changed
+256
-7
No files matched your search
+7
@@ -186,6 +186,13 @@ class DatabaseFrostSigningRepository(
|
||||
emptySet()
|
||||
}
|
||||
|
||||
override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set<Long> = 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<List<GroupTransaction>> =
|
||||
database.groupTransactionDao().observeByChatRoomId(chatRoomId)
|
||||
|
||||
|
||||
+38
-4
@@ -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<Long> =
|
||||
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<Psbt> =
|
||||
database.groupTransactionDao().getByChatRoomId(chatRoomId)
|
||||
|
||||
+4
@@ -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<Long>
|
||||
|
||||
/** 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<Long>
|
||||
|
||||
/** Every spend the room has proposed, newest first, as it moves from proposed to confirmed. */
|
||||
fun observeGroupTransactions(chatRoomId: String): Flow<List<GroupTransaction>>
|
||||
|
||||
@@ -352,6 +355,7 @@ interface FrostSigningRepository {
|
||||
|
||||
override suspend fun reservedOutPoints(chatRoomId: String): Set<OutPoint> = emptySet()
|
||||
override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set<Long> = emptySet()
|
||||
override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set<Long> = emptySet()
|
||||
|
||||
override fun observeGroupTransactions(chatRoomId: String): Flow<List<GroupTransaction>> = flowOf(emptyList())
|
||||
|
||||
|
||||
+17
-3
@@ -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()
|
||||
|
||||
@@ -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<Funding> = 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<Funding>) : 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<GuardianManager.GuardedWallet>): 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
|
||||
|
||||
+3
@@ -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) },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user