feat(wallet): broadcast signed spends and settle what a confirmation decides (Phase 9, part 1)

GroupTransactionWatcher, one per identity beside its wallets: every
signed spend still on its way is sent from this device too, sent again
every ten minutes while Electrum has not reported it -- its broadcast
reports success whatever the server said -- and followed to a
confirmation. FrostSigningManager.recordConfirmed then settles every
other spend of the same coins: one still collecting is abandoned as
spent by another transaction, one already signed is marked replaced
rather than failed, and the room gets one line saying it confirmed.

GroupSpendBuilder.bump re-spends the same coins at a higher feerate,
the extra taken from the change or, for a send-all, the one payment.

The test caught a stale write: a pass followed each spend from the list
it started with, so settling one spend was undone by writing the next
back from its old copy. follow() reads its row again first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 08:43:19 +02:00
1 parent b1d5963b53
commit 58da7c1285
8 files changed
+439

No files matched your search

@@ -22,6 +22,17 @@ abstract class GroupTransactionDao {
@Query("SELECT * FROM GroupTransaction WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
abstract fun observeByChatRoomId(chatRoomId: String): Flow<List<GroupTransaction>>
/**
* Every signed transaction still on its way: not yet seen confirmed, and not
* replaced by another spend of the same coins that was. What the watcher
* broadcasts and looks for.
*/
@Query("SELECT * FROM GroupTransaction WHERE signedTransaction IS NOT NULL AND confirmedAt IS NULL AND replacedByTxid IS NULL")
abstract suspend fun getUnsettled(): List<GroupTransaction>
@Query("SELECT * FROM GroupTransaction WHERE signedTransaction IS NOT NULL AND confirmedAt IS NULL AND replacedByTxid IS NULL")
abstract fun observeUnsettled(): Flow<List<GroupTransaction>>
/**
* The first write, at proposal or acceptance. Ignores a second: the PSBT is
* write-once, and a row for this session already holds the one every item's
@@ -504,6 +504,13 @@ data class ChatMessage(
*/
const val TYPE_GROUP_WALLET_OPENED = "groupWalletOpened"
/**
* A transaction from the group's wallet confirmed. Written by each device
* from what its own Electrum client reported, once -- the confirmation is
* a fact about the chain, and every device can read the chain.
*/
const val TYPE_GROUP_TRANSACTION_CONFIRMED = "groupTransactionConfirmed"
val GROUP_IDENTITY_TYPES = setOf(
TYPE_GROUP_PROFILE_SIGNED,
TYPE_GROUP_RELAYS_SIGNED,
@@ -511,6 +518,7 @@ data class ChatMessage(
TYPE_GROUP_SCHEMA_SIGNED,
TYPE_GROUP_ENTRY_CURATED,
TYPE_GROUP_WALLET_OPENED,
TYPE_GROUP_TRANSACTION_CONFIRMED,
)
/**
@@ -871,6 +871,64 @@ object FrostSigningManager {
.flatMap { transaction -> GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }.orEmpty() }
.toSet()
/**
* A spend seen confirmed: recorded, and every other spend of the same coins
* settled by it.
*
* Only one spend of a coin can ever confirm, so the rest are over whatever
* stage they are in. One still collecting is abandoned -- its signatures, if
* it ever got them, would be over a transaction nobody can mine. One already
* signed is a transaction this one replaced, a fee bump or a race, and is
* marked so rather than failed: it was signed, and saying otherwise would
* misreport what the group did.
*
* Once per transaction, by the read of `confirmedAt` before the write; the
* transcript line rides on the same guard.
*/
suspend fun recordConfirmed(database: BennuDatabase, sessionId: String, at: Instant = Clock.System.now()) {
val confirmed = database.groupTransactionDao().getBySessionId(sessionId) ?: return
if (confirmed.confirmedAt != null) return
val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return
database.groupTransactionDao().upsert(confirmed.copy(confirmedAt = at, seenAt = confirmed.seenAt ?: at))
val coins = coinsOf(confirmed)
database.groupTransactionDao().getByChatRoomId(confirmed.chatRoomId)
.filter { it.frostSigningSessionId != sessionId && (coinsOf(it) intersect coins).isNotEmpty() }
.forEach { other ->
val otherSession = database.frostSigningSessionDao().getSessionById(other.frostSigningSessionId)
?: return@forEach
when (otherSession.stage) {
FrostSigningStage.COMPLETE -> if (other.confirmedAt == null && other.replacedByTxid == null) {
database.groupTransactionDao().upsert(other.copy(replacedByTxid = confirmed.txid))
}
FrostSigningStage.FAILED -> Unit
else -> fail(
database = database,
session = otherSession,
reason = "Spent by another transaction",
content = "abandoned a spend: another of the group's transactions spent its coins first. " +
"Nothing was signed."
)
}
}
val sent = checkedSpend(database, sessionId)?.amountSent
announce(
database = database,
session = session,
messageType = ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED,
content = if (sent != null) "The group's transaction confirmed: ${sent.sat} sats sent."
else "The group's transaction confirmed.",
actor = session.coordinatorPublicKey
)
}
private fun coinsOf(transaction: GroupTransaction): Set<OutPoint> =
GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }?.toSet().orEmpty()
/**
* Verifies the group's signatures, puts them on the transaction, and closes
* the session -- for a spend, the counterpart of [complete].
@@ -165,6 +165,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrPr
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute
import com.machankura.bennu.compose.wallet.GroupChainWallets
import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
import fr.acinq.phoenix.managers.NodeParamsManager
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedSchemasRoute
@@ -282,6 +283,18 @@ fun BennuNavHost(
onDispose { groupChainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } }
}
// Sends the group's signed spends to the network from this device too, and
// follows them to a confirmation -- whether or not anybody opens the wallet.
// Same lifetime as the wallets: the identity's node, and nothing longer.
val groupTransactionWatcher = remember(activeIdentityForWallets?.business) {
activeIdentityForWallets?.business?.let {
GroupTransactionWatcher(auxDatabaseManager.auxDatabase, it.electrumClient, applicationIOScope).also { watcher -> watcher.start() }
}
}
DisposableEffect(groupTransactionWatcher) {
onDispose { groupTransactionWatcher?.stop() }
}
val navigationViewModel: NavigationViewModel = viewModel (
factory = NavigationViewModel.factory(
activeIdentity = sovereignWalletViewModel.activeIdentity,
@@ -32,6 +32,8 @@ object GroupSpendBuilder {
data object NothingToSpend : Result
data object NotEnough : Result
data object BelowDust : Result
/** A bump has to pay more than the spend it replaces. */
data object NotHigher : Result
}
/** Every confirmed, unreserved coin, to [address], less the fee. */
@@ -88,6 +90,36 @@ object GroupSpendBuilder {
return Result.NotEnough
}
/**
* [spend] again at [feeratePerVbyte]: the same coins and the same outputs,
* with the extra fee taken from the change -- or, for a send-all, from the
* one payment. RBF, which every spend allows; a new proposal, with new
* signatures, because a retry is a new session.
*/
fun bump(spend: GroupSpend.Checked, feeratePerVbyte: Long): Result {
val fee = Satoshi(feeratePerVbyte * ((spend.weight + 3) / 4))
val extra = fee - spend.fee
if (extra.sat <= 0) return Result.NotHigher
val target = spend.outputs.firstOrNull { it.isChange } ?: spend.payments.singleOrNull() ?: return Result.NotEnough
val reduced = target.txOut.amount - extra
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 })
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,
)
return Result.Built(
psbt = psbt,
amount = if (target.isChange) spend.amountSent else reduced,
fee = fee,
change = if (target.isChange) reduced else null,
)
}
private fun spendable(state: GroupWalletState, reserved: Set<OutPoint>): List<GroupUtxo> =
state.utxos.filter { it.isConfirmed && it.utxo.outPoint !in reserved }
@@ -0,0 +1,118 @@
package com.machankura.bennu.compose.wallet
import co.touchlab.kermit.Logger
import com.machankura.bennu.compose.database.BennuDatabase
import com.machankura.bennu.compose.database.model.GroupTransaction
import com.machankura.bennu.compose.managers.FrostSigningManager
import fr.acinq.bitcoin.Transaction
import fr.acinq.lightning.blockchain.electrum.IElectrumClient
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
/**
* Sends the group's signed transactions to the network, and watches for them.
*
* Every member with an Electrum client broadcasts. The transaction is identical
* on every device, so a second broadcast is nothing to the network, and nobody's
* phone being asleep holds up the group -- unlike a group event, whose sending is
* a separate decision, the quorum has already decided the one thing broadcasting
* does.
*
* Electrum's broadcast reports success whatever the server said, so a broadcast
* is recorded when it was sent and nothing more; [GroupTransaction.seenAt] is
* written only when Electrum reports the transaction back, and an unseen one is
* sent again every [REBROADCAST_AFTER], which is what `IElectrumClient` asks of
* its callers. A confirmation goes through [FrostSigningManager.recordConfirmed],
* which settles every other spend of the same coins.
*/
class GroupTransactionWatcher(
private val database: BennuDatabase,
private val electrum: IElectrumClient,
private val scope: CoroutineScope,
private val now: () -> Instant = { Clock.System.now() },
) {
private val logger = Logger.withTag("GroupTransactionWatcher")
private var job: Job? = null
/** Runs a pass whenever a transaction is signed, and every [POLL] while any is on its way. */
fun start() {
job?.cancel()
job = scope.launch {
database.groupTransactionDao().observeUnsettled().collectLatest { unsettled ->
while (isActive && unsettled.isNotEmpty()) {
pass()
delay(POLL)
}
}
}
}
fun stop() {
job?.cancel()
job = null
}
/** One look at every transaction still on its way. */
suspend fun pass() {
database.groupTransactionDao().getUnsettled().forEach { transaction ->
try {
follow(transaction)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
logger.e("Could not follow transaction ${transaction.txid}", e)
}
}
}
/** Sends [sessionId]'s transaction again now, whatever was last sent. False when there is nothing signed to send. */
suspend fun broadcastAgain(sessionId: String): Boolean {
val transaction = database.groupTransactionDao().getBySessionId(sessionId) ?: return false
val signed = transaction.signedTransaction?.let { Transaction.read(it) } ?: return false
electrum.broadcastTransaction(signed)
database.groupTransactionDao().upsert(transaction.copy(broadcastAt = now()))
return true
}
private suspend fun follow(listed: GroupTransaction) {
// Read again rather than taken from the list the pass started with: a
// confirmation earlier in the same pass settles every other spend of its
// coins, and writing this row back from the stale copy would undo that.
val transaction = database.groupTransactionDao().getBySessionId(listed.frostSigningSessionId) ?: return
if (transaction.confirmedAt != null || transaction.replacedByTxid != null) return
val signed = Transaction.read(transaction.signedTransaction ?: return)
var row = transaction
val due = row.broadcastAt?.let { now() - it >= REBROADCAST_AFTER } ?: true
if (row.seenAt == null && due) {
electrum.broadcastTransaction(signed)
row = row.copy(broadcastAt = now())
database.groupTransactionDao().upsert(row)
}
// Null while disconnected, or while Electrum has not heard of it.
val confirmations = electrum.getConfirmations(signed) ?: return
if (row.seenAt == null) {
row = row.copy(seenAt = now())
database.groupTransactionDao().upsert(row)
}
if (confirmations >= 1) {
FrostSigningManager.recordConfirmed(database, row.frostSigningSessionId, now())
}
}
companion object {
val POLL: Duration = 30.seconds
val REBROADCAST_AFTER: Duration = 10.minutes
}
}