feat(wallet): a subgroup's transcript names the guardian that spent from it (Phase 8)

Whenever a guarded wallet's coins change, the wallet screen reads every used
address's history off Electrum, recognises a guardian's leaf in the witness
that spent a coin, and writes one transcript line per transaction saying
which group above took how much -- the child's only notice, since nobody in
its room signed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 15:40:43 +02:00
1 parent 00df58c1f3
commit 2b44ebcbbc
9 files changed
+320 -1

No files matched your search

@@ -507,6 +507,13 @@ data class ChatMessage(
*/
const val TYPE_GUARDED_WALLET_SHARED = "guardedWalletShared"
/**
* One of this group's guardians spent from its guarded wallet through its
* leaf. Read off the chain by `GuardianManager.takenIn`, and the child's
* only notice of it: nobody in this room signed it.
*/
const val TYPE_GUARDIAN_SPEND = "guardianSpend"
val GROUP_IDENTITY_TYPES = setOf(
TYPE_GROUP_PROFILE_SIGNED,
TYPE_GROUP_RELAYS_SIGNED,
@@ -516,6 +523,7 @@ data class ChatMessage(
TYPE_GROUP_WALLET_OPENED,
TYPE_GROUP_TRANSACTION_CONFIRMED,
TYPE_GUARDED_WALLET_SHARED,
TYPE_GUARDIAN_SPEND,
)
/**
@@ -230,6 +230,13 @@ class DatabaseChatRepository(
0
}
override suspend fun recordGuardianSpends(chatRoomId: String, taken: List<GuardianManager.Taken>): Int = try {
GuardianManager.recordTaken(database, chatRoomId, taken)
} catch (e: Throwable) {
logger.e("Error recording guardian spends from $chatRoomId's wallet", e)
0
}
override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try {
database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId }
} catch (e: Throwable) {
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.managers
import co.touchlab.kermit.Logger
import com.machankura.bennu.compose.database.BennuDatabase
import com.machankura.bennu.compose.database.model.ChatMessage
import com.machankura.bennu.compose.database.model.MarmotInnerEvent
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent
@@ -13,6 +14,12 @@ import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.OutPoint
import fr.acinq.bitcoin.Satoshi
import fr.acinq.bitcoin.Transaction
import fr.acinq.bitcoin.TxId
import fr.acinq.bitcoin.TxOut
import fr.acinq.lightning.utils.sum
import kotlin.time.Clock
import kotlin.time.Instant
@@ -233,6 +240,79 @@ object GuardianManager {
return rooms.size
}
/** Coins of a guarded wallet one of its guardians took, in one transaction. */
data class Taken(
val txid: TxId,
val guardian: GuardianDerivation.Guardian,
val amount: Satoshi,
)
/**
* Which guardians of [account] took which of [coins] in [spending] -- one
* entry per guardian -- read off the witnesses alone.
*
* A guardian's input carries three things: a signature, a leaf, and the
* control block proving the leaf is in the address. The leaf is matched
* against the guardian leaves of the address the coin was at, so a leaf is
* named only by a guardian whose key it is; anything else -- the wallet's own
* key-path spend, a witness of another shape -- names nobody.
*/
fun takenIn(
spending: Transaction,
account: GroupWalletDerivation.Account,
coins: Map<OutPoint, Pair<TxOut, GroupWalletDerivation.Derived>>,
): List<Taken> {
if (!account.isGuarded) return emptyList()
return spending.txIn.mapNotNull { input ->
val (txOut, derivation) = coins[input.outPoint] ?: return@mapNotNull null
val stack = input.witness.stack.takeIf { it.size == 3 } ?: return@mapNotNull null
val leaves = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)
val position = leaves.indexOfFirst { it.script == stack[1] }.takeIf { it >= 0 } ?: return@mapNotNull null
account.guardians[position] to txOut.amount
}
.groupBy({ it.first }, { it.second })
.map { (guardian, amounts) -> Taken(spending.txid, guardian, amounts.sum()) }
}
/**
* Writes a transcript line in [chatRoomId] for each of [taken] it has no line
* for yet. Returns how many it wrote.
*
* The whole of the child's notice that an ancestor spent from its wallet --
* there is no channel from the ancestor's room into this one -- so it is
* written by whichever device reads the chain first, and every device that
* reads it afterwards finds it already there.
*/
suspend fun recordTaken(database: BennuDatabase, chatRoomId: String, taken: List<Taken>): Int {
val written = database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId)
.map { it.chatMessage }
.filter { it.messageType == ChatMessage.TYPE_GUARDIAN_SPEND }
.map { it.content }
val fresh = taken.filter { spend -> written.none { it.contains(spend.txid.toString()) } }
fresh.forEach { spend ->
val name = database.chatRoomDao().findChatRoomById(spend.guardian.chatRoomId)?.chatRoom?.subject
?.takeIf { it.isNotBlank() }
?: "A group above this one"
database.chatMessageDao().upsert(
ChatMessage(
senderPublicKey = spend.guardian.chatRoomId,
isUserMessage = false,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
chatRoomId = chatRoomId,
content = "$name took ${spend.amount.sat} sats from this wallet through its guardian leaf, " +
"in transaction ${spend.txid}.",
messageType = ChatMessage.TYPE_GUARDIAN_SPEND,
)
)
logger.i("${spend.guardian.chatRoomId} took ${spend.amount.sat} sats from $chatRoomId's guarded wallet in ${spend.txid}")
}
return fresh.size
}
/**
* What a notice that arrived in [chatRoomId] says, for its transcript line --
* or null when it is not one this room can believe, which gets no line: a
@@ -137,6 +137,9 @@ interface ChatRepository {
/** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */
suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int
/** Writes a transcript line for each guardian spend from this group's wallet it has none for yet. */
suspend fun recordGuardianSpends(chatRoomId: String, taken: List<GuardianManager.Taken>): Int
/**
* The kind:1s this group signed, newest first.
*
@@ -413,6 +416,11 @@ interface ChatRepository {
userPublicKey: HexKey
): Int = 0
override suspend fun recordGuardianSpends(
chatRoomId: String,
taken: List<GuardianManager.Taken>
): Int = 0
override suspend fun groupPosts(chatRoomId: String): List<GroupPost> = emptyList()
override suspend fun groupSignedEvent(
@@ -13,6 +13,8 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChangedBy
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -116,6 +118,7 @@ class GroupWalletViewModel(
// state: any of them changing redraws the screen, and none may
// overwrite another.
val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null)
noticeGuardianSpends(wallet.account)
watching = viewModelScope.launch(Dispatchers.IO) {
combine(
chainState,
@@ -142,6 +145,26 @@ class GroupWalletViewModel(
return combine(states) { it.toList() }
}
private var noticing: Job? = null
/**
* For a guarded wallet: each time its coins change, reads the chain for
* spends a guardian made from it and writes the transcript line for any that
* has none -- the group's only notice, since nobody in it signed them.
*/
private suspend fun noticeGuardianSpends(account: GroupWalletDerivation.Account) {
val wallets = wallets ?: return
if (!account.isGuarded) return
val onchain = wallets.walletFor(account)
noticing?.cancel()
noticing = viewModelScope.launch(Dispatchers.IO) {
onchain.state
.distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint }.toSet() }
.collect { state -> chatRepository.recordGuardianSpends(chatRoomId, wallets.guardianSpends(state)) }
}
}
/**
* Tells the groups above about [shareable]'s guarded wallet: one notice into
* each of their rooms this device is in. What is told stays told, so the
@@ -1,6 +1,12 @@
package com.machankura.bennu.compose.wallet
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.managers.GuardianManager
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.OutPoint
import fr.acinq.bitcoin.Transaction
import fr.acinq.bitcoin.TxId
import fr.acinq.bitcoin.byteVector32
import fr.acinq.lightning.blockchain.electrum.IElectrumClient
import fr.acinq.lightning.blockchain.fee.FeeratePerByte
import kotlinx.coroutines.CoroutineScope
@@ -42,6 +48,48 @@ class GroupOnchainWallets(
suspend fun suggestedFeeratePerVbyte(): Long? =
electrum.estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1)
/** Transactions fetched for [guardianSpends], which never change once mined or seen. */
private val transactions = mutableMapOf<TxId, Transaction>()
/**
* Every spend a guardian of [state]'s account made from it, read off the
* history of each address the wallet has used. Empty for an unguarded
* account, and for whatever Electrum cannot answer right now -- the next look
* asks again.
*
* History rather than a watch on coins disappearing: a device asleep when the
* coin moved still finds it, since the chain keeps the record and nothing
* here has to have been running at the time.
*/
suspend fun guardianSpends(state: GroupWalletState): List<GuardianManager.Taken> {
val account = state.account
if (!account.isGuarded) return emptyList()
val used = listOf(GroupWalletDerivation.RECEIVE to state.receive, GroupWalletDerivation.CHANGE to state.change)
.flatMap { (branch, wallet) ->
wallet.addresses.values.filter { it.alreadyUsed }.mapNotNull { address ->
address.meta.indexOrNull?.let { GroupWalletDerivation.derive(account, branch, it.toLong()) }
}
}
val ours = used.associateBy { it.pubkeyScript }
val history = used.flatMap { derived ->
runCatching { electrum.getScriptHashHistory(Crypto.sha256(derived.pubkeyScript).byteVector32().reversed()) }
.getOrDefault(emptyList())
.map { it.txid }
}.distinct().mapNotNull { txid -> transactionOf(txid) }
val coins = history.flatMap { tx ->
tx.txOut.mapIndexedNotNull { index, out -> ours[out.publicKeyScript]?.let { OutPoint(tx, index.toLong()) to (out to it) } }
}.toMap()
return history.flatMap { GuardianManager.takenIn(it, account, coins) }
}
private suspend fun transactionOf(txid: TxId): Transaction? =
mutex.withLock { transactions[txid] }
?: runCatching { electrum.getTx(txid) }.getOrNull()?.also { tx -> mutex.withLock { transactions[txid] = tx } }
suspend fun stop() = mutex.withLock {
wallets.values.forEach { it.stop() }
wallets.clear()
@@ -447,6 +447,44 @@ class GuardianSigningJvmTest {
}
}
@Test
fun `the child reads off the chain which guardian took its coins, and says so once`(): 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 guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0))
val funding = fundingOf(guarded.account)
val built = assertIs<GroupSpendBuilder.Result.Built>(
GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender())
)
val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain)
pump(proposer, other)
FrostSigningManager.approve(other.db, other.room, session.id)
pump(proposer, other)
val signed = Transaction.read(assertNotNull(proposer.db.groupTransactionDao().getBySessionId(session.id)?.signedTransaction))
// What the child's device knows: its own coin, and the transaction that spent it.
val coins = mapOf(OutPoint(funding, 0) to (funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0)))
val taken = GuardianManager.takenIn(signed, guarded.account, coins)
assertEquals(listOf(GuardianManager.Taken(signed.txid, guarded.account.guardians[0], Satoshi(50_000))), taken)
// The child's own key-path spend names nobody.
val ownSpend = signed.updateWitness(0, fr.acinq.bitcoin.ScriptWitness(listOf(ByteVector(ByteArray(64)))))
assertEquals(emptyList(), GuardianManager.takenIn(ownSpend, guarded.account, coins))
// The line, written once, in the child's room -- the ancestor's name from
// this device's own copy of its room.
proposer.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = proposer.publicKey, subject = "Translation team", description = null, mlsGroupState = "00"))
assertEquals(1, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken))
assertEquals(0, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken), "a second reading of the chain writes nothing")
val line = proposer.db.chatMessageDao().getChatMessagesByChatRoomId(guardedChildRoomId).map { it.chatMessage }
.single { it.messageType == com.machankura.bennu.compose.database.model.ChatMessage.TYPE_GUARDIAN_SPEND }
assertTrue(line.content.startsWith("Council took 50000 sats from this wallet through its guardian leaf"), line.content)
}
@Test
fun `a guardian's spend is refused for a wallet the room was not told about, or without the lock`(): Unit = runBlocking {
val proposer = device(members[0], signerIndex = 0)
@@ -41,6 +41,9 @@ internal class FakeElectrum : IElectrumClient {
/** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */
private val history = mutableMapOf<ByteVector32, Int>()
/** The transactions that touched each script, in order: what `get_history` answers. */
private val historyTxs = mutableMapOf<ByteVector32, List<TxId>>()
private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" }
/** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */
@@ -55,6 +58,7 @@ internal class FakeElectrum : IElectrumClient {
val hash = scriptHash(script)
unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height)
history[hash] = (history[hash] ?: 0) + 1
historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid
notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash)))
}
@@ -66,6 +70,17 @@ internal class FakeElectrum : IElectrumClient {
notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash)))
}
/** The transaction paying [script] most recently, as [pay] made it. */
fun fundingOf(script: ByteVector): Transaction = txs.getValue(historyTxs.getValue(scriptHash(script)).last())
/** Spends what [script] holds with [tx] itself, which joins its history as a real spend would. */
suspend fun spendWith(script: ByteVector, tx: Transaction) {
val hash = scriptHash(script)
txs[tx.txid] = tx
historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid
spend(script)
}
override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse {
subscribed += scriptHash
return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash))
@@ -76,7 +91,8 @@ internal class FakeElectrum : IElectrumClient {
override suspend fun getHeader(blockHeight: Int): BlockHeader? = null
override suspend fun getHeaders(startHeight: Int, count: Int): List<BlockHeader> = emptyList()
override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null
override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List<TransactionHistoryItem> = emptyList()
override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List<TransactionHistoryItem> =
historyTxs[scriptHash].orEmpty().map { TransactionHistoryItem(100, it) }
override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid
override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null
override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header)
@@ -0,0 +1,91 @@
package com.machankura.bennu.compose.wallet
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.managers.GuardianDerivation
import com.machankura.bennu.compose.managers.GuardianManager
import com.machankura.bennu.compose.managers.SharedKeyDerivation
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.Script
import fr.acinq.bitcoin.ScriptWitness
import fr.acinq.bitcoin.Transaction
import fr.acinq.bitcoin.TxIn
import fr.acinq.bitcoin.TxOut
import fr.acinq.lightning.blockchain.electrum.WalletState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* A guarded wallet reading its own history for spends its guardians made --
* the child's only notice of one, since nobody in its room signed it.
*
* The witnesses here are the right shape and carry no valid signature: what is
* under test is which leaf a spend used, which the chain records whether or not
* anybody checks the signature again. `GuardianSigningJvmTest` spends for real.
*/
class GuardianSpendNoticeJvmTest {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@AfterTest
fun stop() = scope.cancel()
private fun key(seed: Int): String = PrivateKey(ByteVector32(ByteArray(32) { seed.toByte() })).publicKey().toString()
private val chain = Chain.Regtest
private val parentRoom = SharedKeyDerivation.marmotGroupId(key(1))
private val childKey = key(2)
private val childRoom = SharedKeyDerivation.marmotGroupId(childKey)
private val grant = GuardianDerivation.grant(key(1), parentRoom, emptyList(), childRoom)
private val account = GroupWalletDerivation.account(childKey, chain, guardians = grant)
private val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0)
private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey())))
/** The wallet after its one coin has been spent: the address used, nothing left on it. */
private val spentState = GroupWalletState(
account,
WalletState(mapOf(coin.address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), alreadyUsed = true, utxos = emptyList()))),
WalletState(emptyMap()),
tipHeight = 200,
)
private fun spending(funding: Transaction, witness: ScriptWitness) = Transaction(
2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GuardianDerivation.ANCESTOR_DELAY, witness)),
listOf(TxOut(Satoshi(49_000), elsewhere)), 0,
)
@Test
fun `a spend through the parent's leaf is read off the address's history`(): Unit = runBlocking {
val electrum = FakeElectrum()
electrum.pay(coin.pubkeyScript, Satoshi(50_000))
val funding = electrum.fundingOf(coin.pubkeyScript)
val leaf = GuardianDerivation.leaves(grant, chain, 0, coin.change, coin.index)[0]
val taken = spending(funding, Script.witnessScriptPathPay2tr(coin.internalKey, leaf, ScriptWitness(listOf(ByteVector(ByteArray(64)))), coin.tree!!))
electrum.spendWith(coin.pubkeyScript, taken)
val wallets = GroupOnchainWallets(electrum, scope)
assertEquals(
listOf(GuardianManager.Taken(taken.txid, grant[0], Satoshi(50_000))),
wallets.guardianSpends(spentState),
)
}
@Test
fun `the group's own key-path spend names no guardian`(): Unit = runBlocking {
val electrum = FakeElectrum()
electrum.pay(coin.pubkeyScript, Satoshi(50_000))
val own = spending(electrum.fundingOf(coin.pubkeyScript), Script.witnessKeyPathPay2tr(fr.acinq.bitcoin.ByteVector64.Zeroes))
electrum.spendWith(coin.pubkeyScript, own)
assertEquals(emptyList(), GroupOnchainWallets(electrum, scope).guardianSpends(spentState))
}
}