diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 67e99aac..31cca5d0 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -694,7 +694,7 @@ Signed, sending it to the network Sent, waiting for a confirmation Confirmed - Replaced by a later spend + Replaced by another spend of the same coins Send again Bump the fee Sent again 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 f6586e03..627147f7 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 @@ -1072,28 +1072,7 @@ object FrostSigningManager { 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." - ) - } - } + settleSpendsOf(database, confirmed.chatRoomId, coinsOf(confirmed), byTxid = confirmed.txid, except = sessionId) val sent = checkedSpend(database, sessionId)?.amountSent announce( @@ -1106,6 +1085,67 @@ object FrostSigningManager { ) } + /** + * A spend whose coins a transaction the room never proposed has taken, as + * [conflictTxid] confirmed: marked replaced, and every other spend of the same + * coins settled with it. + * + * A guarded wallet's coins have two kinds of spender. The child's own spend + * can lose a coin to a guardian's, and a guardian's to the child's, and the + * winner is never a row in the loser's room -- so [recordConfirmed] cannot be + * what settles the loser. The watcher is: it asks the chain whether a signed + * spend's coins are still there, and calls this when one was taken by a + * confirmed transaction. Once per spend, by the read of `replacedByTxid`. + */ + suspend fun recordReplaced(database: BennuDatabase, sessionId: String, conflictTxid: String) { + val lost = database.groupTransactionDao().getBySessionId(sessionId) ?: return + if (lost.confirmedAt != null || lost.replacedByTxid != null) return + + database.groupTransactionDao().upsert(lost.copy(replacedByTxid = conflictTxid)) + settleSpendsOf(database, lost.chatRoomId, coinsOf(lost), byTxid = conflictTxid, except = sessionId) + logger.i("Spend $sessionId lost its coins to $conflictTxid") + } + + /** + * Every spend in [chatRoomId] other than [except] that wants any of [coins], + * settled by [byTxid] having taken them: 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 + * [byTxid] 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. + */ + private suspend fun settleSpendsOf( + database: BennuDatabase, + chatRoomId: String, + coins: Set, + byTxid: String, + except: String, + ) { + database.groupTransactionDao().getByChatRoomId(chatRoomId) + .filter { it.frostSigningSessionId != except && (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 = byTxid)) + } + + FrostSigningStage.FAILED -> Unit + + else -> fail( + database = database, + session = otherSession, + reason = "Spent by another transaction", + content = "abandoned a spend: another transaction spent its coins first. " + + "Nothing was signed." + ) + } + } + } + private fun coinsOf(transaction: GroupTransaction): Set = GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }?.toSet().orEmpty() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt index 75cc0f13..9faaf536 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt @@ -4,7 +4,10 @@ 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.Crypto import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.byteVector32 import fr.acinq.lightning.blockchain.electrum.IElectrumClient import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -34,6 +37,15 @@ import kotlin.time.Instant * 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. + * + * A spend Electrum has not heard of may have lost its coins. Only the group can + * spend a plain wallet's coins, so there the loser is always another of the + * room's own spends and the winner's confirmation settles it. A guarded wallet's + * coins have a second spender, in another room: so an unseen spend asks the + * chain whether its coins are still there, and one taken by a *confirmed* + * transaction it is not goes through [FrostSigningManager.recordReplaced]. A + * conflict still in the mempool settles nothing -- ours may yet be the one that + * confirms. */ class GroupTransactionWatcher( private val database: BennuDatabase, @@ -100,8 +112,12 @@ class GroupTransactionWatcher( database.groupTransactionDao().upsert(row) } - // Null while disconnected, or while Electrum has not heard of it. - val confirmations = electrum.getConfirmations(signed) ?: return + // Null while disconnected, or while Electrum has not heard of it -- which + // is also what a spend whose coins somebody else took looks like. + val confirmations = electrum.getConfirmations(signed) ?: run { + conflictOf(row, signed)?.let { FrostSigningManager.recordReplaced(database, row.frostSigningSessionId, it.toString()) } + return + } if (row.seenAt == null) { row = row.copy(seenAt = now()) database.groupTransactionDao().upsert(row) @@ -111,6 +127,34 @@ class GroupTransactionWatcher( } } + /** + * A confirmed transaction other than [signed] that spent one of its coins, or + * null when every coin is still unspent, or was only taken by something + * unconfirmed, or the chain cannot be asked right now. + * + * Read per coin off the address it is at: is it still unspent there, and if + * not, which transaction in that address's history spent it. The address is + * the spent output's script, which the proposed PSBT carries for every input. + */ + private suspend fun conflictOf(transaction: GroupTransaction, signed: Transaction): TxId? { + val psbt = GroupSpend.decode(transaction.psbt) ?: return null + + signed.txIn.forEachIndexed { index, input -> + val txOut = (psbt.inputs.getOrNull(index) as? fr.acinq.bitcoin.psbt.Input.WitnessInput)?.txOut ?: return@forEachIndexed + val scriptHash = Crypto.sha256(txOut.publicKeyScript).byteVector32().reversed() + + val unspent = electrum.getScriptHashUnspents(scriptHash) + .any { it.txid == input.outPoint.txid && it.outputIndex.toLong() == input.outPoint.index } + if (unspent) return@forEachIndexed + + electrum.getScriptHashHistory(scriptHash) + .filter { it.blockHeight > 0 && it.txid != signed.txid } + .firstOrNull { item -> electrum.getTx(item.txid)?.txIn?.any { it.outPoint == input.outPoint } == true } + ?.let { return it.txid } + } + return null + } + companion object { val POLL: Duration = 30.seconds val REBROADCAST_AFTER: Duration = 10.minutes diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt index 97a16184..615300dc 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt @@ -59,17 +59,21 @@ class GroupTransactionWatcherJvmTest { val broadcasts = mutableListOf() /** Confirmations by txid; absent is "Electrum has not heard of it". */ val confirmations = mutableMapOf() + /** What each script hash still holds, has seen, and the transactions behind both. */ + val unspents = mutableMapOf>() + val histories = mutableMapOf>() + val txs = mutableMapOf() override val notifications = MutableSharedFlow() override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid.also { broadcasts += it } override suspend fun getConfirmations(tx: Transaction): Int? = confirmations[tx.txid] - override suspend fun getTx(txId: TxId): Transaction? = null + override suspend fun getTx(txId: TxId): Transaction? = txs[txId] override suspend fun getHeader(blockHeight: Int): BlockHeader? = null override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() - override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = emptyList() + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = histories[scriptHash].orEmpty() + override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null override suspend fun startScriptHashSubscription(scriptHash: ByteVector32) = ScriptHashSubscriptionResponse(scriptHash, null) override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) @@ -173,4 +177,70 @@ class GroupTransactionWatcherJvmTest { assertEquals(1, lines.size) assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "neither signed spend is still on its way") } + + // ---- Coins another room's transaction took ------------------------------ + + /** The script the guarded coin sits at, and its Electrum script hash. */ + private val coinScript = ByteVector("5120" + "ab".repeat(32)) + private val coinHash = ByteVector32(fr.acinq.bitcoin.Crypto.sha256(coinScript.toByteArray()).reversedArray()) + + /** A signed spend of [coin] whose PSBT names the output it spends, as every real proposal's does. */ + private suspend fun signedSpendOfCoin(id: String, tx: Transaction) { + db.frostSigningSessionDao().upsert( + FrostSigningSession( + id = id, chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, dkgSessionId = "dkg", + threshold = 2, participantCount = 3, signerId = 0, stage = FrostSigningStage.COMPLETE, subject = FrostSigningSubject.TRANSACTION, + ) + ) + val psbt = Psbt(tx).updateWitnessInput(coin, TxOut(Satoshi(10_000), coinScript)).right!! + db.groupTransactionDao().insertIfAbsent( + GroupTransaction( + frostSigningSessionId = id, chatRoomId = room, chain = "regtest", account = 0, + psbt = GroupSpend.encode(psbt), txid = tx.txid.toString(), signedTransaction = Hex.encode(Transaction.write(tx)), + ) + ) + } + + /** Somebody else -- a guardian, or the guarded group itself -- spends [coin], at [height] (0 for the mempool). */ + private fun takenElsewhere(height: Int): Transaction { + val theirs = spending(coin, pay = 7_000).copy(txOut = listOf(TxOut(Satoshi(7_000), ByteVector("0014" + "11".repeat(20))))) + electrum.txs[theirs.txid] = theirs + electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid), TransactionHistoryItem(height, theirs.txid)) + return theirs + } + + @Test + fun `a spend whose coin another transaction took is replaced once that transaction confirms`(): Unit = runBlocking { + seed() + val ours = spending(coin, pay = 9_000) + signedSpendOfCoin("ours", ours) + // Another of this room's spends of the same coin, still collecting. + spend("collecting", spending(coin, OutPoint(TxId(ByteVector32(ByteArray(32) { 6 })), 0), pay = 12_000), FrostSigningStage.COLLECTING_NONCES, signed = false) + + val theirs = takenElsewhere(height = 101) + watcher.pass() + + assertEquals(theirs.txid.toString(), db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + assertEquals(FrostSigningStage.COMPLETE, db.frostSigningSessionDao().getSessionById("ours")?.stage, "it was signed, and stays so") + assertEquals(FrostSigningStage.FAILED, db.frostSigningSessionDao().getSessionById("collecting")?.stage) + assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "nothing is left being sent again every ten minutes") + } + + @Test + fun `a coin taken only in the mempool, or not taken at all, settles nothing`(): Unit = runBlocking { + seed() + signedSpendOfCoin("ours", spending(coin, pay = 9_000)) + + // Still unspent where it sits. + electrum.unspents[coinHash] = listOf(UnspentItem(coin.txid, coin.index.toInt(), 10_000, 90)) + electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid)) + watcher.pass() + assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + + // Spent by something unconfirmed: ours may yet be the one that confirms. + electrum.unspents.remove(coinHash) + takenElsewhere(height = 0) + watcher.pass() + assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + } } diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md index 59cc79a8..07772ee1 100644 --- a/docs/group-wallet-guardians.md +++ b/docs/group-wallet-guardians.md @@ -25,6 +25,7 @@ below are kept as written; where the build chose differently the table says so. | `check` asks the proposer's device whether a coin has 12 confirmations | the builder does: it only offers a guardian coins its lock has already let go of. `check` cannot ask, because a signer with no node has no tip, and a coin spent too early is a transaction nobody can mine rather than a loss | | `GroupTransactionWatcher` notices a guardian's spend | the wallet screen's view model does, each time the guarded wallet's coins change, by reading every used address's history off Electrum -- so a device asleep when the coin moved still finds it, and whichever device reads first writes the one line. A device that never opens the wallet screen writes nothing | | schema unchanged | v27: `GroupTransaction.guardedChatRoomId`, the descendant a guardian's spend draws from. A spend's account is otherwise read from the statement, and a guardian's is the descendant's statement, not the room's | +| a spend that lost its coins to the other side is never settled -- this note's own *What this does not do*, as first written | settled. `GroupTransactionWatcher` asks the chain, for a signed spend Electrum has not heard of, whether each coin is still unspent at its address and, if not, which transaction in that address's history took it; once that transaction is confirmed, `FrostSigningManager.recordReplaced` marks the spend replaced and settles every other spend of the coin, as `recordConfirmed` does for the room's own. A conflict still in the mempool settles nothing | | nothing outside the plan | a bug older than it: bitcoin-kmp reads a taproot derivation's fingerprint back from a PSBT as a signed int, so for half of all accounts every member but the proposer refused every spend as not the wallet's own. Fixed on its own, in `fix(wallet): read a PSBT's key fingerprint as unsigned`, because it reaches every plain wallet too | Still to do by hand, and the condition the mainnet gate lifts on: a guardian @@ -415,15 +416,6 @@ threshold key, so to the shares of the ceremony that made it, including the shares of members who have since left. This is the wallet note's *removal from the group does not un-know a key*, inherited one level down. -**It does not settle a spend that lost its coins to the other side.** The -wallet note settles conflicting spends when one of the group's own confirms, -because "only the group can spend its coins". A guarded wallet's coins have -other spenders now. A child's open spend whose coin a guardian took, or a -guardian's whose coin the child moved first, is never marked replaced: it sits -as signed, rebroadcast every ten minutes, until somebody abandons it. The fix is -for `GroupTransactionWatcher` to ask whether an unconfirmed spend's inputs are -still unspent, and it is a follow-up rather than a line here. - **It does not tell the child before it happens**, and it does not constrain where the coins go. "Only back into the child, at a new address" is a covenant, and there is none on mainnet to write it with (`OP_CHECKTEMPLATEVERIFY`,