Retry publishing txs evicted by unconfirmed conflicts (#3397)
What changed, and why it matters
This commit fixes a security bug in the Eclair Lightning node where a malicious peer could trick the node into permanently giving up on publishing its own commitment or penalty transactions. By publishing and then double-spending a conflicting transaction, an attacker could prevent the node from claiming funds it was owed, potentially allowing the attacker to steal HTLCs or delay justice transactions. The fix makes the node keep retrying publication each block until the conflicting transaction actually confirms.
Treat this as a security fix and include in release notes. Operators running Eclair nodes, especially those using anchor outputs and/or 0-conf channels, should upgrade promptly. Review whether any channels were force-closed around the affected code versions and monitor for delayed commitment or penalty publication.
Security signals we found
The commit message explicitly describes theft risk: "This lets them steal HTLCs by publishing their commitment later"
Attack vector involves a malicious peer withholding tx_signatures and double-spending a splice input
Fix changes abandonment logic for local commit anchor preconditions
Fix removes differential handling of PublishFinalTx vs PublishReplaceableTx for unconfirmed conflicts
Adds test cases reproducing the attack path for both confirmed and zero-conf funding transactions
Reported by external security researchers (project-loupe, erickcestari)
Evidence from the diff
The patch changes transaction publication retry logic in ReplaceableTxPrePublisher and TxPublisher. Previously, when a local commit tx or final (non-replaceable) tx was rejected due to an unconfirmed conflicting transaction in the mempool, Eclair would stop retrying. A malicious peer could exploit this by publishing a splice tx that spends the funding output (without sending tx_signatures, forcing the victim to use an older commitment), then double-spending the splice tx’s own wallet input to evict it from the mempool. The victim’s commit tx would then become valid again, but Eclair had already abandoned it. Similarly, final penalty/HTLC transactions could be abandoned. The fix: (1) only skips the local anchor when a remote commit tx is actually available or the funding output is spent by a confirmed tx; (2) retries local anchors when the funding output is spent by an unconfirmed tx, including 0-conf funding cases; (3) retries final txs every block for ConflictingTxUnconfirmed, matching replaceable tx behavior. Tests simulate the attack for both confirmed and zero-conf funding.
Changed components
eclair-core/src/main/scala/fr/acinq/eclair/channel/publish/ReplaceableTxPrePublisher.scalaeclair-core/src/main/scala/fr/acinq/eclair/channel/publish/TxPublisher.scalaLightning channel force-close / anchor transaction publicationFinal (non-replaceable) transaction publication retry logicInspect captured patch +100 / −25
### eclair-core/src/main/scala/fr/acinq/eclair/channel/publish/ReplaceableTxPrePublisher.scala
@@ -47,6 +47,7 @@ object ReplaceableTxPrePublisher {
private case object CommitTxRecentlyConfirmed extends Command
private case object CommitTxDeeplyConfirmed extends Command
private case object ConcurrentCommitAvailable extends Command
+ private case object FundingOutputSpentByUnconfirmedTx extends Command
private case object ConcurrentCommitRecentlyConfirmed extends Command
private case object ConcurrentCommitDeeplyConfirmed extends Command
private case object OutputAlreadySpent extends Command
@@ -66,7 +67,7 @@ object ReplaceableTxPrePublisher {
case CheckPreconditions(replyTo, txInfo, commitTx, concurrentCommitTxs) =>
val prePublisher = new ReplaceableTxPrePublisher(nodeParams, replyTo, bitcoinClient, context)
txInfo match {
- case _: ClaimLocalAnchorTx => prePublisher.checkLocalCommitAnchorPreconditions(commitTx)
+ case _: ClaimLocalAnchorTx => prePublisher.checkLocalCommitAnchorPreconditions(commitTx, concurrentCommitTxs)
case _: ClaimRemoteAnchorTx => prePublisher.checkRemoteCommitAnchorPreconditions(commitTx)
case _: SignedHtlcTx | _: ClaimHtlcTx => prePublisher.check2ndStageTxPreconditions(txInfo, commitTx, concurrentCommitTxs)
case _: ClaimRemoteMainOutputTx => prePublisher.check2ndStageTxPreconditions(txInfo, commitTx, concurrentCommitTxs)
@@ -95,10 +96,10 @@ private class ReplaceableTxPrePublisher(nodeParams: NodeParams,
* - our local commitment is unconfirmed
* - and we haven't seen a remote commitment (in which case it is more interesting to spend than the local commitment)
*/
- private def checkLocalCommitAnchorPreconditions(commitTx: Transaction): Behavior[Command] = {
+ private def checkLocalCommitAnchorPreconditions(commitTx: Transaction, concurrentCommitTxs: Set[TxId]): Behavior[Command] = {
val fundingOutpoint = commitTx.txIn.head.outPoint
context.pipeToSelf(bitcoinClient.getTxConfirmations(fundingOutpoint.txid).flatMap {
- case Some(_) =>
+ case Some(fundingTxConfirmations) =>
// The funding transaction was found, let's see if we can still spend it.
bitcoinClient.isTransactionOutputSpendable(fundingOutpoint.txid, fundingOutpoint.index.toInt, includeMempool = true).flatMap {
case true =>
@@ -111,10 +112,21 @@ private class ReplaceableTxPrePublisher(nodeParams: NodeParams,
case Success(Some(confirmations)) if confirmations > 0 => Future.successful(CommitTxRecentlyConfirmed)
case Success(Some(0)) => Future.successful(ParentTxOk(confirmed = false)) // our commit tx is unconfirmed, let's publish our anchor transaction
case _ =>
- // Our commit tx is unconfirmed and cannot be found in our mempool: this means that a remote commit is
- // either confirmed or in our mempool. In that case, we don't want to use our local commit tx: the
- // remote commit is more interesting to us because we won't have any CSV delays on our outputs.
- Future.successful(ConcurrentCommitAvailable)
+ // Our commit tx is unconfirmed and cannot be found in our mempool. If a remote commit is confirmed or in
+ // our mempool, we don't want to use our local commit tx: the remote commit is more interesting to us
+ // because we won't have any CSV delays on our outputs. Otherwise, if the funding output is spent by an
+ // unconfirmed transaction, it may be a splice transaction that our peer published without sending us
+ // their tx_signatures, and that they may double-spend later: we must keep trying to publish our commit tx.
+ checkConcurrentCommits(concurrentCommitTxs.toSeq).flatMap {
+ case Some(_) => Future.successful(ConcurrentCommitAvailable)
+ // If the funding transaction is unconfirmed (e.g. when using 0-conf), its outputs can only be spent by
+ // unconfirmed transactions (and they're not in the UTXO set, so we cannot use the check below).
+ case None if fundingTxConfirmations == 0 => Future.successful(FundingOutputSpentByUnconfirmedTx)
+ case None => bitcoinClient.isTransactionOutputSpendable(fundingOutpoint.txid, fundingOutpoint.index.toInt, includeMempool = false).map {
+ case true => FundingOutputSpentByUnconfirmedTx
+ case false => ConcurrentCommitAvailable
+ }
+ }
}
}
case None =>
@@ -144,6 +156,10 @@ private class ReplaceableTxPrePublisher(nodeParams: NodeParams,
log.warn("not publishing local anchor for commitTxId={}: we will use the remote commit tx instead", commitTx.txid)
replyTo ! PreconditionsFailed(TxPublisher.TxRejectedReason.TxSkipped(retryNextBlock = false))
Behaviors.stopped
+ case FundingOutputSpentByUnconfirmedTx =>
+ log.warn("not publishing local anchor for commitTxId={}: funding output is spent by an unconfirmed transaction, let's check again later", commitTx.txid)
+ replyTo ! PreconditionsFailed(TxPublisher.TxRejectedReason.TxSkipped(retryNextBlock = true))
+ Behaviors.stopped
case UnknownFailure(reason) =>
log.error("could not check local anchor preconditions, proceeding anyway: ", reason)
// If our checks fail, we don't want it to prevent us from trying to publish our commit tx.
### eclair-core/src/main/scala/fr/acinq/eclair/channel/publish/TxPublisher.scala
@@ -294,17 +294,13 @@ private class TxPublisher(nodeParams: NodeParams, factory: TxPublisher.ChildFact
val retryNextBlock2 = if (retry) retryNextBlock ++ rejectedAttempts.map(_.cmd) else retryNextBlock
run(pending2, retryNextBlock2, channelContext)
case TxRejectedReason.ConflictingTxUnconfirmed =>
- cmd match {
- case _: PublishFinalTx =>
- // Our transaction is not replaceable, and the mempool contains a transaction that pays more fees, so
- // it doesn't make sense to retry, we will keep getting rejected.
- run(pending2, retryNextBlock, channelContext)
- case _: PublishReplaceableTx =>
- // The mempool contains a transaction that pays more fees, but as we get closer to the confirmation
- // target, we will try to publish with higher fees, so if the conflicting transaction doesn't confirm,
- // we should be able to replace it before we reach the confirmation target.
- run(pending2, retryNextBlock ++ rejectedAttempts.map(_.cmd), channelContext)
- }
+ // The mempool contains a transaction that pays more fees, but it may not confirm:
+ // - for replaceable transactions, we will try to publish with higher fees as we get closer to the
+ // confirmation target, so we should be able to replace it before we reach the confirmation target
+ // - for final transactions, the conflicting transaction may be evicted from the mempool (e.g. if our
+ // peer double-spends one of its other inputs), in which case our transaction becomes valid again
+ // We thus retry at every block until the conflicting transaction confirms.
+ run(pending2, retryNextBlock ++ rejectedAttempts.map(_.cmd), channelContext)
case TxRejectedReason.ConflictingTxConfirmed =>
// Our transaction was double-spent by a competing transaction that has been confirmed, so it doesn't make
// sense to retry.
### eclair-core/src/test/scala/fr/acinq/eclair/channel/publish/ReplaceableTxPublisherSpec.scala
@@ -21,8 +21,9 @@ import akka.actor.typed.scaladsl.adapter.{ClassicActorSystemOps, actorRefAdapter
import akka.pattern.pipe
import akka.testkit.{TestFSMRef, TestProbe}
import com.softwaremill.quicklens.ModifyPimp
-import fr.acinq.bitcoin.scalacompat.{Block, BtcAmount, MilliBtcDouble, MnemonicCode, OutPoint, SatoshiLong, Script, ScriptElt, Transaction, TxId}
+import fr.acinq.bitcoin.scalacompat.{Block, BtcAmount, MilliBtcDouble, MnemonicCode, OutPoint, SatoshiLong, Script, ScriptElt, Transaction, TxId, TxIn, TxOut, computeP2WpkhAddress}
import fr.acinq.eclair.NotificationsLogger.NotifyNodeOperator
+import fr.acinq.eclair.blockchain.WatcherSpec
import fr.acinq.eclair.blockchain.bitcoind.BitcoindService
import fr.acinq.eclair.blockchain.bitcoind.ZmqWatcher._
import fr.acinq.eclair.blockchain.bitcoind.rpc.BitcoinCoreClient.MempoolTx
@@ -138,7 +139,7 @@ class ReplaceableTxPublisherSpec extends TestKitBaseClass with AnyFunSuiteLike w
}
// NB: we can't use ScalaTest's fixtures, they would see uninitialized bitcoind fields because they sandbox each test.
- private def withFixture(utxos: Seq[BtcAmount], channelType: SupportedChannelType)(testFun: Fixture => Any): Unit = {
+ private def withFixture(utxos: Seq[BtcAmount], channelType: SupportedChannelType, zeroConf: Boolean = false)(testFun: Fixture => Any): Unit = {
// Create a unique wallet for this test and ensure it has some btc.
val testId = UUID.randomUUID()
val (walletRpcClient, walletClient) = createTestWallet(s"lightning-$testId")
@@ -162,13 +163,13 @@ class ReplaceableTxPublisherSpec extends TestKitBaseClass with AnyFunSuiteLike w
case _: ChannelTypes.ZeroFeeCommitments => Set(ChannelStateTestsTags.ZeroFeeCommitments, ChannelStateTestsTags.NoMaxHtlcValueInFlight)
case _ => Set.empty[String]
}
- reachNormal(setup, testTags)
+ reachNormal(setup, if (zeroConf) testTags + ChannelStateTestsTags.ZeroConf else testTags)
import setup._
awaitAssert(assert(alice.stateName == NORMAL))
awaitAssert(assert(bob.stateName == NORMAL))
- // Generate blocks to ensure the funding tx is confirmed.
- generateBlocks(1)
+ // Generate blocks to ensure the funding tx is confirmed (unless we're testing zero-conf).
+ if (!zeroConf) generateBlocks(1)
// Execute our test.
val publisher = system.spawn(ReplaceableTxPublisher(aliceNodeParams, walletClient, TxPublishContext(testId, TestConstants.Bob.nodeParams.nodeId, None)), testId.toString)
@@ -425,6 +426,66 @@ class ReplaceableTxPublisherSpec extends TestKitBaseClass with AnyFunSuiteLike w
}
}
+ private def testFundingOutputSpentByUnconfirmedTx(zeroConf: Boolean): Unit = {
+ // When using zero-conf, the change output of the funding transaction is unconfirmed: we need another utxo to fund our anchor transaction.
+ withFixture(Seq(500 millibtc, 200 millibtc), ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), zeroConf) { f =>
+ import f._
+
+ val commitment = alice.stateData.asInstanceOf[DATA_NORMAL].commitments.latest.commitment
+ val (aliceFundingKey, bobFundingKey) = (commitment.localFundingKey(alice.underlyingActor.channelKeys), commitment.localFundingKey(bob.underlyingActor.channelKeys))
+ val fundingInput = commitment.commitInput(aliceFundingKey)
+ val (localCommit, anchorTx) = closeChannelWithoutHtlcs(f, aliceBlockHeight() + 12)
+
+ // Our peer publishes a splice transaction that spends the funding output and one of their wallet inputs, without
+ // sending us their tx_signatures (which means we're force-closing with the previous commitment).
+ val attackerKey = randomKey()
+ val attackerTx = sendToAddress(computeP2WpkhAddress(attackerKey.publicKey, Block.RegtestGenesisBlock.hash), 100_000 sat, probe)
+ // When using zero-conf, the funding transaction must stay unconfirmed.
+ if (!zeroConf) generateBlocks(1)
+ val attackerInput = OutPoint(attackerTx, attackerTx.txOut.indexWhere(_.publicKeyScript == Script.write(Script.pay2wpkh(attackerKey.publicKey))))
+ val unsignedSpliceTx = Transaction(2, Seq(TxIn(fundingInput.outPoint, Nil, 0xfffffffdL), TxIn(attackerInput, Nil, 0xfffffffdL)), Seq(TxOut(fundingInput.txOut.amount + 100_000.sat - 25_000.sat, Script.pay2wpkh(randomKey().publicKey))), 0)
+ val extraUtxos = Map(attackerInput -> attackerTx.txOut(attackerInput.index.toInt))
+ val spliceTx = {
+ val tx = SpliceTx(fundingInput, unsignedSpliceTx)
+ val aliceSig = tx.sign(aliceFundingKey, bobFundingKey.publicKey, extraUtxos)
+ val bobSig = tx.sign(bobFundingKey, aliceFundingKey.publicKey, extraUtxos)
+ val signedFundingInput = tx.aggregateSigs(aliceFundingKey.publicKey, bobFundingKey.publicKey, aliceSig, bobSig)
+ val sig = Transaction.signInput(signedFundingInput, 1, Script.pay2pkh(attackerKey.publicKey), fr.acinq.bitcoin.SigHash.SIGHASH_ALL, 100_000 sat, fr.acinq.bitcoin.SigVersion.SIGVERSION_WITNESS_V0, attackerKey)
+ signedFundingInput.updateWitness(1, Script.witnessPay2wpkh(attackerKey.publicKey, sig))
+ }
+ wallet.publishTransaction(spliceTx).pipeTo(probe.ref)
+ probe.expectMsg(spliceTx.txid)
+ wallet.getTxConfirmations(fundingInput.outPoint.txid).pipeTo(probe.ref)
+ if (zeroConf) probe.expectMsg(Some(0)) else assert(probe.expectMsgType[Option[Int]].exists(_ > 0))
+
+ // Our commit tx cannot be published, but no remote commit is available: we must retry later.
+ setFeerate(FeeratePerKw(10_000 sat))
+ publisher ! Publish(probe.ref, anchorTx)
+ val result = probe.expectMsgType[TxRejected]
+ assert(result.cmd == anchorTx)
+ assert(result.reason == TxSkipped(retryNextBlock = true))
+
+ // Our peer double-spends their wallet input: the funding output is unspent again.
+ val doubleSpendTx = WatcherSpec.createSpendP2WPKH(attackerTx, attackerKey, randomKey().publicKey, 50_000 sat, 0xfffffffdL, 0)
+ wallet.publishTransaction(doubleSpendTx).pipeTo(probe.ref)
+ probe.expectMsg(doubleSpendTx.txid)
+ assert(!isInMempool(spliceTx.txid))
+
+ // When retrying, we publish our commit tx and our anchor.
+ val publisher2 = createPublisher()
+ publisher2 ! Publish(probe.ref, anchorTx)
+ awaitAssert(assert(isInMempool(localCommit.tx.txid)), interval = 200 millis)
+ }
+ }
+
+ test("funding output spent by an unconfirmed transaction, retrying local anchor output") {
+ testFundingOutputSpentByUnconfirmedTx(zeroConf = false)
+ }
+
+ test("funding output spent by an unconfirmed transaction, retrying local anchor output (zero-conf)") {
+ testFundingOutputSpentByUnconfirmedTx(zeroConf = true)
+ }
+
test("remote commit tx replaces local commit tx, not spending anchor output") {
withFixture(Seq(500 millibtc), ChannelTypes.AnchorOutputsZeroFeeHtlcTx()) { f =>
import f._
### eclair-core/src/test/scala/fr/acinq/eclair/channel/publish/TxPublisherSpec.scala
@@ -301,10 +301,12 @@ class TxPublisherSpec extends TestKitBaseClass with FixtureAnyFunSuiteLike {
txPublisher ! TxRejected(attempt.id, cmd, ConflictingTxUnconfirmed)
attempt.actor.expectMsg(FinalTxPublisher.Stop)
+ factory.expectNoMessage(100 millis)
- // We don't retry, even after a new block has been found:
+ // The conflicting transaction may be evicted from the mempool, so we retry when a new block is found:
system.eventStream.publish(CurrentBlockHeight(BlockHeight(8200)))
- factory.expectNoMessage(100 millis)
+ val attempt2 = factory.expectMsgType[FinalTxPublisherSpawned]
+ assert(attempt2.actor.expectMsgType[FinalTxPublisher.Publish].cmd == cmd)
}
test("publishing attempt fails (unconfirmed conflicting replaceable transaction)") { f =>Why this scored 82/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.