What changed, and why it matters
This commit hardens Eclair's Lightning channel 'splicing' feature against a malicious peer. Splicing lets users resize a channel by creating a new funding transaction. The patch fixes several ways an attacker could exploit unconfirmed splice transactions: by double-spending inputs to make the splice invalid, by adding so many inputs/outputs that the honest node can't afford to speed it up (CPFP), or by publishing an old commitment while a splice is stuck. The changes add a new default-on setting that requires splice inputs to be confirmed, limit how many inputs/outputs a peer can add, make force-closing pick a commitment whose funding transaction is actually known to the node's own Bitcoin Core, include unconfirmed ancestors when paying to speed up a commitment, and claim outputs from an old remote commitment as soon as it confirms. The commit message explicitly warns that using zero-fee commitments with splicing and untrusted peers can lead to loss of funds.
Review and merge promptly; this is a defensive hardening patch for a known high-risk area. Operators should ensure `require-confirmed-inputs-for-splicing` remains enabled and should avoid enabling `zero_fee_commitments` when splicing with untrusted peers, as documented. After deployment, monitor for any force-close edge cases involving unconfirmed splices.
Security signals we found
New default-on configuration `require-confirmed-inputs-for-splicing` to prevent double-spend of unconfirmed splice inputs
Limit on remote splice inputs/outputs (10) to bound CPFP cost
Force-close now selects a commitment whose funding tx is known to bitcoind, re-evaluated per block and splice spend events
CPFP anchor funding now includes unconfirmed ancestor weight/fees
Previous remote commitment outputs claimed at depth 1 instead of waiting for min-depth
Stale local commit tx recognized as local after commitment switch, avoiding information-leak / revoked-commit misclassification
Explicit documentation of fund-loss risk when combining `zero_fee_commitments` with splicing and untrusted peers
Evidence from the diff
The patch addresses multiple interrelated security issues in Eclair’s splicing implementation. It introduces require-confirmed-inputs-for-splicing (default true), decoupling splicing from the dual-funding confirmed-inputs setting. It prevents initiating a splice on top of an unconfirmed splice and validates that remote splice inputs are confirmed. It caps remote splice inputs/outputs at MAX_REMOTE_SPLICE_INPUTS_OUTPUTS = 10. During force-close, checkLocalCommitFundingTx now selects the most recent commitment whose funding tx is known to bitcoind (mempool or confirmed), re-evaluating on each block and when splice transactions spend funding outputs. ReplaceableTxFunder now accounts for unconfirmed ancestors’ weight and fees when CPFP-ing a commit tx via UnconfirmedAncestors. When a previous remote commitment confirms, outputs are claimed immediately at depth 1 (WatchAlternativeCommitTxConfirmed with minDepth=1) while still waiting for minDepth before forgetting other commitments. A stale local commit tx that confirms after switching commitments is now recognized as local rather than remote, avoiding ERR_INFORMATION_LEAK or incorrect revoked-commit handling. The reference.conf comment explicitly documents that zero_fee_commitments with splicing and untrusted peers can let a malicious peer prevent the commit tx from confirming before HTLC timeouts, causing fund loss.
Changed components
eclair-core/src/main/resources/reference.confeclair-core/src/main/scala/fr/acinq/eclair/NodeParams.scalaeclair-core/src/main/scala/fr/acinq/eclair/channel/fsm/Channel.scalaeclair-core/src/main/scala/fr/acinq/eclair/channel/fsm/ErrorHandlers.scalaeclair-core/src/main/scala/fr/acinq/eclair/channel/fund/InteractiveTxBuilder.scalaeclair-core/src/main/scala/fr/acinq/eclair/channel/publish/ReplaceableTxFunder.scalaInspect captured patch +518 / −60
### eclair-core/src/main/resources/reference.conf
@@ -80,6 +80,10 @@ eclair {
// If you don't want to relay onion messages at all, you should disable both features.
option_onion_messages = optional
option_onion_messages_only_channels = disabled
+ // NB: with zero_fee_commitments, our commit tx cannot spend an unconfirmed splice transaction (TRUC rules), so we
+ // cannot CPFP a splice transaction that our peer published with a low feerate when we need to force-close. This lets
+ // a malicious peer prevent our commit tx from confirming before our HTLCs time out, which can lead to loss of funds.
+ // Do not enable zero_fee_commitments if you allow splicing with untrusted peers.
zero_fee_commitments = disabled
// This feature should only be enabled when acting as an LSP for mobile wallets.
// When activating this feature, the peer-storage section should be customized to match desired SLAs.
@@ -143,6 +147,11 @@ eclair {
min-private-funding-satoshis = 100000
max-funding-satoshis = 5000000000 // 50 BTC: we reject channels that are larger than this
require-confirmed-inputs-for-dual-funding = false // if true, only confirmed inputs will be accepted for channel dual funding
+ // If true, splices only spend confirmed transactions: our peer's inputs must be confirmed, and we don't splice on top
+ // of an unconfirmed splice transaction. Setting this to false is unsafe: our peer may then double-spend an unconfirmed
+ // parent after signing, which makes the splice transaction invalid and can put our HTLCs at risk if we force-close
+ // using it.
+ require-confirmed-inputs-for-splicing = true
to-remote-delay-blocks = 720 // number of blocks that the other node's to-self outputs must be delayed (720 ~ 5 days)
max-to-local-delay-blocks = 2016 // maximum number of blocks that we are ready to accept for our own delayed outputs (2016 ~ 2 weeks)
### eclair-core/src/main/scala/fr/acinq/eclair/NodeParams.scala
@@ -638,6 +638,7 @@ object NodeParams extends Logging {
unhandledExceptionStrategy = unhandledExceptionStrategy,
revocationTimeout = FiniteDuration(config.getDuration("channel.revocation-timeout").getSeconds, TimeUnit.SECONDS),
requireConfirmedInputsForDualFunding = config.getBoolean("channel.require-confirmed-inputs-for-dual-funding"),
+ requireConfirmedInputsForSplicing = config.getBoolean("channel.require-confirmed-inputs-for-splicing"),
channelOpenerWhitelist = channelOpenerWhitelist,
maxPendingChannelsPerPeer = maxPendingChannelsPerPeer,
maxTotalPendingChannelsPrivateNodes = maxTotalPendingChannelsPrivateNodes,
### eclair-core/src/main/scala/fr/acinq/eclair/channel/fsm/Channel.scala
@@ -103,6 +103,7 @@ object Channel {
unhandledExceptionStrategy: UnhandledExceptionStrategy,
revocationTimeout: FiniteDuration,
requireConfirmedInputsForDualFunding: Boolean,
+ requireConfirmedInputsForSplicing: Boolean,
channelOpenerWhitelist: Set[PublicKey],
maxPendingChannelsPerPeer: Int,
maxTotalPendingChannelsPrivateNodes: Int,
@@ -199,6 +200,8 @@ object Channel {
private[channel] case object BITCOIN_FUNDING_PUBLISH_FAILED extends BitcoinEvent
private[channel] case object BITCOIN_FUNDING_TIMEOUT extends BitcoinEvent
private[channel] case class BITCOIN_FUNDING_DOUBLE_SPENT(fundingTxIds: Set[TxId]) extends BitcoinEvent
+ /** Our local commit tx should spend a different funding tx, which our bitcoind knows (see checkLocalCommitFundingTx). */
+ private[channel] case class PublishableCommitmentFound(commitTxId: TxId, fundingTxId: TxId) extends BitcoinEvent
// @formatter:on
case object TickChannelOpenTimeout
@@ -1041,6 +1044,10 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
log.warning("cannot initiate splice, the previous splice has unconfirmed rbf attempts")
cmd.replyTo ! RES_FAILURE(cmd, InvalidSpliceWithUnconfirmedTx(d.channelId, d.commitments.latest.fundingTxId))
stay()
+ } else if (requireConfirmedSpliceParent(d) && d.commitments.latest.localFundingStatus.isInstanceOf[LocalFundingStatus.DualFundedUnconfirmedFundingTx]) {
+ log.warning("cannot initiate splice, the previous funding transaction is unconfirmed")
+ cmd.replyTo ! RES_FAILURE(cmd, InvalidSpliceWithUnconfirmedTx(d.channelId, d.commitments.latest.fundingTxId))
+ stay()
} else {
d.spliceStatus match {
case SpliceStatus.NoSplice =>
@@ -1201,7 +1208,7 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
fundingContribution = willFund_opt.map(_.purchase.amount).getOrElse(0 sat),
fundingPubKey = localFundingPubKey,
pushAmount = 0.msat,
- requireConfirmedInputs = nodeParams.channelConf.requireConfirmedInputsForDualFunding,
+ requireConfirmedInputs = requireConfirmedRemoteSpliceInputs(d),
willFund_opt = willFund_opt.map(_.willFund),
feeCreditUsed_opt = msg.useFeeCredit_opt,
channelType_opt = msg.channelType_opt
@@ -2212,9 +2219,22 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
case Left(_) => stay()
}
+ case Event(ProcessCurrentBlockHeight(_), d: DATA_CLOSING) =>
+ checkLocalCommitFundingTx(d)
+ stay()
+
+ case Event(e: PublishableCommitmentFound, d: DATA_CLOSING) =>
+ (d.localCommitPublished.filter(lcp => lcp.commitTx.txid == e.commitTxId && !lcp.isConfirmed), d.commitments.active.find(_.fundingTxId == e.fundingTxId)) match {
+ case (Some(lcp), Some(commitment)) =>
+ log.warning("force-closing again using fundingTxIndex={} fundingTxId={}: the funding tx of our local commit tx {} is unknown or a more recent one was published", commitment.fundingTxIndex, commitment.fundingTxId, lcp.commitTx.txid)
+ spendLocalCurrent(d, d.maxClosingFeerate_opt, commitment_opt = Some(FullCommitment(d.commitments.channelParams, d.commitments.changes, commitment)))
+ case _ => stay()
+ }
+
case Event(WatchFundingSpentTriggered(tx), d: DATA_CLOSING) =>
if (d.commitments.all.map(_.fundingTxId).contains(tx.txid)) {
- // if the spending tx is itself a funding tx, this is a splice and there is nothing to do
+ // If the spending tx is itself a funding tx, this is a splice: we may need to use the corresponding commitment.
+ checkLocalCommitFundingTx(d)
stay()
} else if (d.mutualClosePublished.exists(_.tx.txid == tx.txid)) {
// we already know about this tx, probably because we have published it ourselves after successful negotiation
@@ -2226,6 +2246,12 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
} else if (d.localCommitPublished.exists(_.commitTx.txid == tx.txid)) {
// this is because WatchSpent watches never expire and we are notified multiple times
stay()
+ } else if (d.commitments.all.exists(_.localCommit.txId == tx.txid)) {
+ // This is one of our local commit txs that we published before switching to a different commitment (see
+ // checkLocalCommitFundingTx): it may still confirm, so we must track it and claim its outputs.
+ val commitment = d.commitments.all.find(_.localCommit.txId == tx.txid).get
+ log.warning("our local commit tx {} for fundingTxIndex={} was published, using it instead of {}", tx.txid, commitment.fundingTxIndex, d.localCommitPublished.map(_.commitTx.txid))
+ spendLocalCurrent(d, d.maxClosingFeerate_opt, commitment_opt = Some(FullCommitment(d.commitments.channelParams, d.commitments.changes, commitment)))
} else if (d.remoteCommitPublished.exists(_.commitTx.txid == tx.txid)) {
// this is because WatchSpent watches never expire and we are notified multiple times
stay()
@@ -2248,7 +2274,8 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
d.commitments.resolveCommitment(tx) match {
case Some(commitment) =>
log.warning("a commit tx for an older commitment has been published fundingTxId={} fundingTxIndex={}", tx.txid, commitment.fundingTxIndex)
- blockchain ! WatchAlternativeCommitTxConfirmed(self, tx.txid, nodeParams.channelConf.minDepth)
+ // We react as soon as it confirms (see WatchAlternativeCommitTxConfirmedTriggered).
+ blockchain ! WatchAlternativeCommitTxConfirmed(self, tx.txid, minDepth = 1)
stay()
case None =>
// This must be a former funding tx that has already been pruned, because watches are unordered.
@@ -2257,6 +2284,18 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
}
}
+ case Event(WatchAlternativeCommitTxConfirmedTriggered(blockHeight, _, tx), d: DATA_CLOSING) if nodeParams.currentBlockHeight - blockHeight + 1 < nodeParams.channelConf.minDepth =>
+ // A commit tx for a previous commitment confirmed, but it may still be reorged out: we wait until it is deeply
+ // confirmed to forget our other commitments, but if this is our peer's commit tx, we claim its outputs right now.
+ blockchain ! WatchAlternativeCommitTxConfirmed(self, tx.txid, nodeParams.channelConf.minDepth)
+ d.commitments.resolveCommitment(tx).map(c => FullCommitment(d.commitments.channelParams, d.commitments.changes, c)) match {
+ case Some(commitment) if commitment.remoteCommit.txId == tx.txid && commitment.remoteCommit.index == d.commitments.remoteCommitIndex =>
+ claimPreviousRemoteCommitOutputs(tx, d, commitment, commitment.remoteCommit, isNextRemoteCommit = false)
+ case Some(commitment) if commitment.nextRemoteCommit_opt.exists(_.txId == tx.txid) && commitment.remoteCommit.index == d.commitments.remoteCommitIndex && d.commitments.remoteNextCommitInfo.isLeft =>
+ claimPreviousRemoteCommitOutputs(tx, d, commitment, commitment.nextRemoteCommit_opt.get, isNextRemoteCommit = true)
+ case _ => stay()
+ }
+
case Event(WatchAlternativeCommitTxConfirmedTriggered(_, _, tx), d: DATA_CLOSING) =>
d.commitments.resolveCommitment(tx) match {
case Some(commitment) =>
@@ -3303,7 +3342,8 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
case Some(commitment) =>
log.warning("a commit tx for an older commitment has been published fundingTxId={} fundingTxIndex={}", tx.txid, commitment.fundingTxIndex)
// We watch the commitment tx, in the meantime we force close using the latest commitment.
- blockchain ! WatchAlternativeCommitTxConfirmed(self, tx.txid, nodeParams.channelConf.minDepth)
+ // We react as soon as it confirms (see WatchAlternativeCommitTxConfirmedTriggered).
+ blockchain ! WatchAlternativeCommitTxConfirmed(self, tx.txid, minDepth = 1)
spendLocalCurrent(d, maxClosingFeerateOverride_opt = None)
case None =>
// This must be a former funding tx that has already been pruned, because watches are unordered.
@@ -3863,7 +3903,7 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
feerate = targetFeerate,
fundingPubKey = channelKeys.fundingKey(parentCommitment.fundingTxIndex + 1).publicKey,
pushAmount = cmd.pushAmount,
- requireConfirmedInputs = nodeParams.channelConf.requireConfirmedInputsForDualFunding,
+ requireConfirmedInputs = requireConfirmedRemoteSpliceInputs(d),
requestFunding_opt = cmd.requestFunding_opt,
channelType_opt = cmd.channelType_opt
)
@@ -3890,6 +3930,16 @@ class Channel(val nodeParams: NodeParams, val channelKeys: ChannelKeys, val wall
})
}
+ /**
+ * Splices must only spend confirmed transactions (see require-confirmed-inputs-for-splicing): otherwise our peer may
+ * make the splice transaction invalid after signing by double-spending one of its unconfirmed parents. Our own wallet
+ * inputs are safe, since bitcoind never selects unconfirmed outputs of transactions that have inputs we don't own.
+ */
+ private def requireConfirmedRemoteSpliceInputs(d: DATA_NORMAL): Boolean = nodeParams.channelConf.requireConfirmedInputsForSplicing
+
+ /** We don't splice on top of an unconfirmed splice transaction (see require-confirmed-inputs-for-splicing). */
+ private def requireConfirmedSpliceParent(d: DATA_NORMAL): Boolean = nodeParams.channelConf.requireConfirmedInputsForSplicing
+
private def getSpliceRbfContext(cmd_opt: Option[CMD_BUMP_FUNDING_FEE], d: DATA_NORMAL): Either[ChannelException, InteractiveTxBuilder.SpliceTxRbf] = {
d.commitments.latest.localFundingStatus match {
case fundingTx: LocalFundingStatus.DualFundedUnconfirmedFundingTx =>
### eclair-core/src/main/scala/fr/acinq/eclair/channel/fsm/ErrorHandlers.scala
@@ -27,13 +27,14 @@ import fr.acinq.eclair.blockchain.fee.FeeratePerKw
import fr.acinq.eclair.channel.Helpers.Closing
import fr.acinq.eclair.channel.Helpers.Closing.RemoteClose
import fr.acinq.eclair.channel._
-import fr.acinq.eclair.channel.fsm.Channel.UnhandledExceptionStrategy
+import fr.acinq.eclair.channel.fsm.Channel.{PublishableCommitmentFound, UnhandledExceptionStrategy}
import fr.acinq.eclair.channel.publish.TxPublisher.{PublishFinalTx, PublishReplaceableTx, PublishTx}
import fr.acinq.eclair.transactions.Transactions._
import fr.acinq.eclair.wire.protocol.{AcceptChannel, ChannelReestablish, Error, OpenChannel, Warning}
import scodec.bits.ByteVector
import java.sql.SQLException
+import scala.concurrent.Future
/**
* Created by t-bast on 28/03/2022.
@@ -217,7 +218,11 @@ trait ErrorHandlers extends CommonHandlers {
}
}
- def spendLocalCurrent(d: ChannelDataWithCommitments, maxClosingFeerateOverride_opt: Option[FeeratePerKw], remoteFuturePerCommitmentPoint_opt: Option[PublicKey] = None): FSM.State[ChannelState, ChannelData] = {
+ /**
+ * @param commitment_opt commitment to use, when we know that our bitcoind cannot publish the commit tx of the latest
+ * commitment that we're able to publish (see [[checkLocalCommitFundingTx]]).
+ */
+ def spendLocalCurrent(d: ChannelDataWithCommitments, maxClosingFeerateOverride_opt: Option[FeeratePerKw], remoteFuturePerCommitmentPoint_opt: Option[PublicKey] = None, commitment_opt: Option[FullCommitment] = None): FSM.State[ChannelState, ChannelData] = {
val outdatedCommitment = d match {
case _: DATA_WAIT_FOR_REMOTE_PUBLISH_FUTURE_COMMITMENT => true
case closing: DATA_CLOSING if closing.futureRemoteCommitPublished.isDefined => true
@@ -230,8 +235,8 @@ trait ErrorHandlers extends CommonHandlers {
val finalScriptPubKey = getOrGenerateFinalScriptPubKey(d)
// If our peer hasn't sent their tx_signatures for our latest splice transaction(s), we cannot publish them and
// the corresponding commit txs cannot confirm: we force-close using the latest commitment that can confirm.
- val commitment = d.commitments.latestPublishable
- if (commitment.fundingTxIndex < d.commitments.latest.fundingTxIndex) {
+ val commitment = commitment_opt.getOrElse(d.commitments.latestPublishable)
+ if (commitment_opt.isEmpty && commitment.fundingTxIndex < d.commitments.latest.fundingTxIndex) {
log.warning("our peer hasn't sent their tx_signatures for fundingTxIndex={}, using fundingTxIndex={} instead", d.commitments.latest.fundingTxIndex, commitment.fundingTxIndex)
}
log.error(s"force-closing with fundingIndex=${commitment.fundingTxIndex}")
@@ -245,7 +250,36 @@ trait ErrorHandlers extends CommonHandlers {
case negotiating: DATA_NEGOTIATING_SIMPLE => DATA_CLOSING(d.commitments, waitingSince = nodeParams.currentBlockHeight, finalScriptPubKey = finalScriptPubKey, mutualCloseProposed = negotiating.proposedClosingTxs.flatMap(_.all), mutualClosePublished = negotiating.publishedClosingTxs, localCommitPublished = Some(localCommitPublished))
case _ => DATA_CLOSING(d.commitments, waitingSince = nodeParams.currentBlockHeight, finalScriptPubKey = finalScriptPubKey, mutualCloseProposed = Nil, localCommitPublished = Some(localCommitPublished), maxClosingFeerate_opt = maxClosingFeerateOverride_opt, remoteFuturePerCommitmentPoint_opt = remoteFuturePerCommitmentPoint_opt)
}
- goto(CLOSING) using nextData storing() calling doPublish(localCommitPublished, closingTxs, commitment)
+ goto(CLOSING) using nextData storing() calling doPublish(localCommitPublished, closingTxs, commitment) calling checkLocalCommitFundingTx(nextData)
+ }
+ }
+
+ /**
+ * When we force-close using a commitment whose funding tx is unconfirmed (a splice transaction), our commit tx can only
+ * confirm if that funding tx confirms. Without zero-conf, our peer may prevent that, for example by double-spending one
+ * of its inputs, while it can still publish its commit tx for the previous funding output whenever it wants. Our peer
+ * may also publish a splice transaction for which it didn't send us its tx_signatures, after we force-closed using the
+ * previous commitment, in which case we need to use the splice commitment to be able to CPFP it.
+ *
+ * We thus use the most recent commitment whose funding tx is known by our bitcoind (in our mempool or confirmed), or
+ * the most recent confirmed commitment otherwise. This must be checked again whenever our mempool may have changed.
+ */
+ def checkLocalCommitFundingTx(d: DATA_CLOSING): Unit = {
+ d.localCommitPublished.filterNot(_.isConfirmed) match {
+ case Some(lcp) if !d.commitments.channelParams.zeroConf =>
+ val current = d.commitmentFor(lcp.commitTx.txid)
+ // Active commitments are ordered from the most recent one: confirmed commitments are the oldest ones.
+ val (unconfirmed, confirmed) = d.commitments.active.span(c => !c.localFundingStatus.isInstanceOf[LocalFundingStatus.ConfirmedFundingTx])
+ if (unconfirmed.nonEmpty) {
+ // If we cannot reach our bitcoind, we keep the commitment we've already published.
+ Future.sequence(unconfirmed.map(c => wallet.getTxConfirmations(c.fundingTxId).map(_.nonEmpty))).foreach { known =>
+ unconfirmed.zip(known).collectFirst { case (c, true) => c }.orElse(confirmed.headOption) match {
+ case Some(c) if c.fundingTxId != current.fundingTxId => self ! PublishableCommitmentFound(lcp.commitTx.txid, c.fundingTxId)
+ case _ => ()
+ }
+ }
+ }
+ case _ => ()
}
}
@@ -334,6 +368,19 @@ trait ErrorHandlers extends CommonHandlers {
goto(CLOSING) using nextData storing() calling doPublish(remoteCommitPublished, closingTxs, commitment)
}
+ /**
+ * Our peer published its (current or next) commit tx for a previous commitment, which double-spends our more recent
+ * splice transactions. It isn't deeply confirmed yet, so we don't forget our other commitments, but we claim its outputs
+ * immediately: our peer may claim our outgoing HTLCs with htlc-success transactions one block after it confirms.
+ */
+ def claimPreviousRemoteCommitOutputs(commitTx: Transaction, d: DATA_CLOSING, commitment: FullCommitment, remoteCommit: RemoteCommit, isNextRemoteCommit: Boolean): FSM.State[ChannelState, ChannelData] = {
+ log.warning("claiming outputs of remote commit txid={} for fundingTxIndex={} before it is deeply confirmed", commitTx.txid, commitment.fundingTxIndex)
+ val closingFeerate = nodeParams.onChainFeeConf.getClosingFeerate(nodeParams.currentBitcoinCoreFeerates, d.maxClosingFeerate_opt)
+ val (remoteCommitPublished, closingTxs) = Closing.RemoteClose.claimCommitTxOutputs(channelKeys, commitment, remoteCommit, commitTx, closingFeerate, nodeParams.currentBitcoinCoreFeerates, d.finalScriptPubKey, nodeParams.onChainFeeConf.spendAnchorWithoutHtlcs)
+ val d1 = if (isNextRemoteCommit) d.copy(nextRemoteCommitPublished = Some(remoteCommitPublished)) else d.copy(remoteCommitPublished = Some(remoteCommitPublished))
+ stay() using d1 storing() calling doPublish(remoteCommitPublished, closingTxs, commitment)
+ }
+
/** Publish 2nd-stage transactions for the remote commitment (no need for 3rd-stage transactions in that case). */
def doPublish(rcp: RemoteCommitPublished, txs: Closing.RemoteClose.SecondStageTransactions, commitment: FullCommitment): Unit = {
val remoteCommit = commitment.nextRemoteCommit_opt match {
### eclair-core/src/main/scala/fr/acinq/eclair/channel/fund/InteractiveTxBuilder.scala
@@ -456,6 +456,9 @@ object InteractiveTxBuilder {
// We restrict the number of inputs / outputs that our peer can send us to ensure the protocol eventually ends.
val MAX_INPUTS_OUTPUTS_RECEIVED = 4096
+ // Maximum number of inputs and outputs that our peer can add to a splice transaction: this limits the size
+ // of the splice transaction, which we may need to pay for with CPFP if we force-close before it confirms.
+ val MAX_REMOTE_SPLICE_INPUTS_OUTPUTS = 10
// Our peer may have seen a few more blocks than us, but a later lock time would let them prevent us from publishing
// the transaction (and thus the commitments that spend it) for as long as they want.
@@ -822,6 +825,14 @@ private class InteractiveTxBuilder(replyTo: ActorRef[InteractiveTxBuilder.Respon
log.warn("invalid interactive tx ({} local inputs, {} remote inputs, {} local outputs and {} remote outputs)", session.localInputs.length, session.remoteInputs.length, session.localOutputs.length, session.remoteOutputs.length)
return Left(InvalidCompleteInteractiveTx(fundingParams.channelId, "too many inputs or outputs"))
}
+ if (fundingParams.sharedInput_opt.nonEmpty) {
+ val remoteInputsCount = session.remoteInputs.count(_.isInstanceOf[Input.Remote])
+ val remoteOutputsCount = session.remoteOutputs.count(_.isInstanceOf[Output.Remote])
+ if (remoteInputsCount > MAX_REMOTE_SPLICE_INPUTS_OUTPUTS || remoteOutputsCount > MAX_REMOTE_SPLICE_INPUTS_OUTPUTS) {
+ log.warn("invalid splice tx: too many remote inputs or outputs ({} remote inputs, {} remote outputs)", remoteInputsCount, remoteOutputsCount)
+ return Left(InvalidCompleteInteractiveTx(fundingParams.channelId, "too many remote inputs or outputs"))
+ }
+ }
if (fundingParams.lockTime > nodeParams.currentBlockHeight.toLong + MAX_LOCKTIME_AHEAD_BLOCKS) {
log.warn("invalid interactive tx: lock time is too far in the future (lockTime={}, currentBlockHeight={})", fundingParams.lockTime, nodeParams.currentBlockHeight)
return Left(InvalidCompleteInteractiveTx(fundingParams.channelId, "lock time too far in the future"))
### eclair-core/src/main/scala/fr/acinq/eclair/channel/publish/ReplaceableTxFunder.scala
@@ -24,7 +24,7 @@ import fr.acinq.bitcoin.scalacompat.{Satoshi, SatoshiLong, Transaction, TxIn, Tx
import fr.acinq.eclair.NotificationsLogger.NotifyNodeOperator
import fr.acinq.eclair.blockchain.bitcoind.rpc.BitcoinCoreClient
import fr.acinq.eclair.blockchain.fee.{FeeratePerKw, FeeratesPerKw, OnChainFeeConf}
-import fr.acinq.eclair.channel.FullCommitment
+import fr.acinq.eclair.channel.{FullCommitment, LocalFundingStatus}
import fr.acinq.eclair.channel.publish.TxPublisher.TxPublishContext
import fr.acinq.eclair.transactions.Transactions
import fr.acinq.eclair.transactions.Transactions._
@@ -52,6 +52,7 @@ object ReplaceableTxFunder {
private case class AddInputsFailed(reason: Throwable) extends Command
private case class SignWalletInputsOk(signedTx: Transaction) extends Command
private case class SignWalletInputsFailed(reason: Throwable) extends Command
+ private case class WrappedUnconfirmedAncestors(cmd: FundTransaction, ancestors: UnconfirmedAncestors) extends Command
private case object UtxosUnlocked extends Command
// @formatter:on
@@ -60,6 +61,13 @@ object ReplaceableTxFunder {
val fee: Satoshi = txInfo.fee + walletInputs_opt.map(_.fee).getOrElse(0 sat)
}
+ /** Unconfirmed ancestors of a commit tx (e.g. an unconfirmed splice transaction), that we pay for when CPFP-ing it. */
+ case class UnconfirmedAncestors(weight: Int, fee: Satoshi)
+
+ object UnconfirmedAncestors {
+ val empty: UnconfirmedAncestors = UnconfirmedAncestors(0, 0 sat)
+ }
+
// @formatter:off
sealed trait FundingResult
case class TransactionReady(fundedTx: FundedTx) extends FundingResult
@@ -71,23 +79,39 @@ object ReplaceableTxFunder {
Behaviors.withMdc(txPublishContext.mdc()) {
Behaviors.receiveMessagePartial {
case cmd: FundTransaction =>
- val txInfo = cmd.txInfo.fold(fundedTx => fundedTx.txInfo, tx => tx)
- val targetFeerate = cmd.targetFeerate.min(maxFeerate(txInfo, cmd.commitTx, cmd.commitment, nodeParams.currentBitcoinCoreFeerates, nodeParams.onChainFeeConf))
- val txFunder = new ReplaceableTxFunder(cmd.replyTo, cmd.commitTx, cmd.commitment, bitcoinClient, context)
- cmd.txInfo match {
- case Right(txInfo) => txFunder.fund(txInfo, targetFeerate)
- case Left(previousTx) => txFunder.bump(previousTx, targetFeerate)
+ cmd.txInfo.fold(fundedTx => fundedTx.txInfo, tx => tx) match {
+ case _: ClaimAnchorTx if cmd.commitment.localFundingStatus.isInstanceOf[LocalFundingStatus.UnconfirmedFundingTx] =>
+ // Our commit tx spends an unconfirmed funding tx: our anchor tx must also pay for its unconfirmed ancestors.
+ context.pipeToSelf(bitcoinClient.getMempoolPackage(Set(cmd.commitment.fundingTxId))(ExecutionContext.Implicits.global)) {
+ case Success(txs) => WrappedUnconfirmedAncestors(cmd, UnconfirmedAncestors(txs.values.map(_.weight.toInt).sum, txs.values.map(_.fees).sum))
+ // The funding tx isn't in our mempool: it is either confirmed, or our commit tx cannot be published anyway.
+ case Failure(_) => WrappedUnconfirmedAncestors(cmd, UnconfirmedAncestors.empty)
+ }
+ Behaviors.receiveMessagePartial {
+ case WrappedUnconfirmedAncestors(cmd, ancestors) => startFunding(nodeParams, bitcoinClient, context, cmd, ancestors)
+ }
+ case _ => startFunding(nodeParams, bitcoinClient, context, cmd, UnconfirmedAncestors.empty)
}
}
}
}
}
+ private def startFunding(nodeParams: NodeParams, bitcoinClient: BitcoinCoreClient, context: ActorContext[Command], cmd: FundTransaction, ancestors: UnconfirmedAncestors): Behavior[Command] = {
+ val txInfo = cmd.txInfo.fold(fundedTx => fundedTx.txInfo, tx => tx)
+ val targetFeerate = cmd.targetFeerate.min(maxFeerate(txInfo, cmd.commitTx, cmd.commitment, nodeParams.currentBitcoinCoreFeerates, nodeParams.onChainFeeConf, ancestors.weight))
+ val txFunder = new ReplaceableTxFunder(cmd.replyTo, cmd.commitTx, cmd.commitment, ancestors, bitcoinClient, context)
+ cmd.txInfo match {
+ case Right(txInfo) => txFunder.fund(txInfo, targetFeerate)
+ case Left(previousTx) => txFunder.bump(previousTx, targetFeerate)
+ }
+ }
+
/**
* The on-chain feerate can be arbitrarily high, but it wouldn't make sense to pay more fees than the amount we're
* trying to claim on-chain. We compute how much funds we have at risk and the feerate that matches this amount.
*/
- def maxFeerate(tx: ForceCloseTransaction, commitTx: Transaction, commitment: FullCommitment, currentFeerates: FeeratesPerKw, feeConf: OnChainFeeConf): FeeratePerKw = {
+ def maxFeerate(tx: ForceCloseTransaction, commitTx: Transaction, commitment: FullCommitment, currentFeerates: FeeratesPerKw, feeConf: OnChainFeeConf, unconfirmedAncestorsWeight: Int = 0): FeeratePerKw = {
// We don't want to pay more in fees than the amount at risk in pending HTLCs.
val maxFee = tx match {
case _: ClaimAnchorTx =>
@@ -101,9 +125,9 @@ object ReplaceableTxFunder {
}
// We cannot know beforehand how many wallet inputs will be added, but an estimation should be good enough.
val weight = tx match {
- // When claiming our anchor output, it must pay for the weight of the commitment transaction.
- // We usually add a wallet input and a change output.
- case tx: ClaimAnchorTx => commitTx.weight() + tx.expectedWeight + Transactions.maxWalletInputWeight + Transactions.maxWalletOutputWeight
+ // When claiming our anchor output, it must pay for the weight of the commitment transaction and its unconfirmed
+ // ancestors. We usually add a wallet input and a change output.
+ case tx: ClaimAnchorTx => commitTx.weight() + unconfirmedAncestorsWeight + tx.expectedWeight + Transactions.maxWalletInputWeight + Transactions.maxWalletOutputWeight
// For HTLC transactions, we usually add a wallet input and a change output.
case tx: SignedHtlcTx => tx.expectedWeight + Transactions.maxWalletInputWeight + Transactions.maxWalletOutputWeight
// Other transactions don't use any additional inputs or outputs.
@@ -119,23 +143,27 @@ object ReplaceableTxFunder {
private class ReplaceableTxFunder(replyTo: ActorRef[ReplaceableTxFunder.FundingResult],
commitTx: Transaction,
commitment: FullCommitment,
+ unconfirmedAncestors: ReplaceableTxFunder.UnconfirmedAncestors,
bitcoinClient: BitcoinCoreClient,
context: ActorContext[ReplaceableTxFunder.Command])(implicit ec: ExecutionContext = ExecutionContext.Implicits.global) {
import ReplaceableTxFunder._
private val dustLimit = commitment.localCommitParams.dustLimit
private val commitFee: Satoshi = commitment.capacity - commitTx.txOut.map(_.amount).sum
- private val commitFeerate: FeeratePerKw = Transactions.fee2rate(commitFee, commitTx.weight())
+ // When CPFP-ing our commit tx, our anchor tx must pay for the whole package, including unconfirmed ancestors.
+ private val packageFee: Satoshi = commitFee + unconfirmedAncestors.fee
+ private val packageWeight: Int = commitTx.weight() + unconfirmedAncestors.weight
+ private val packageFeerate: FeeratePerKw = Transactions.fee2rate(packageFee, packageWeight)
private val log = context.log
def fund(tx: ForceCloseTransaction, targetFeerate: FeeratePerKw): Behavior[Command] = {
log.info("funding {} tx (targetFeerate={})", tx.desc, targetFeerate)
tx match {
case anchorTx: ClaimAnchorTx =>
- if (targetFeerate <= commitFeerate) {
- log.info("skipping {}: commit feerate is high enough (feerate={})", tx.desc, commitFeerate)
+ if (targetFeerate <= packageFeerate) {
+ log.info("skipping {}: commit feerate is high enough (feerate={})", tx.desc, packageFeerate)
// We set retry = true in case the on-chain feerate rises before the commit tx is confirmed: if that happens
// we'll want to claim our anchor to raise the feerate of the commit tx and get it confirmed faster.
replyTo ! FundingFailed(TxPublisher.TxRejectedReason.TxSkipped(retryNextBlock = true))
@@ -168,8 +196,8 @@ private class ReplaceableTxFunder(replyTo: ActorRef[ReplaceableTxFunder.FundingR
log.info("bumping {} tx (targetFeerate={})", previousTx.txInfo.desc, targetFeerate)
val targetFee = previousTx.txInfo match {
case _: ClaimAnchorTx =>
- val totalWeight = previousTx.signedTx.weight() + commitTx.weight()
- weight2fee(targetFeerate, totalWeight) - commitFee
+ val totalWeight = previousTx.signedTx.weight() + packageWeight
+ weight2fee(targetFeerate, totalWeight) - packageFee
case _ =>
weight2fee(targetFeerate, previousTx.signedTx.weight())
}
@@ -302,7 +330,7 @@ private class ReplaceableTxFunder(replyTo: ActorRef[ReplaceableTxFunder.FundingR
case Right(signedTx) =>
val actualFees = kmp2scala(processPsbtResponse.psbt.computeFees())
val actualWeight = tx match {
- case _: ClaimAnchorTx => signedTx.weight() + commitTx.weight()
+ case _: ClaimAnchorTx => signedTx.weight() + packageWeight
case _: SignedHtlcTx => signedTx.weight()
}
val actualFeerate = Transactions.fee2rate(actualFees, actualWeight)
@@ -355,9 +383,9 @@ private class ReplaceableTxFunder(replyTo: ActorRef[ReplaceableTxFunder.FundingR
// commit tx: it would fail because it cannot find the input in the utxo set. So we instead ask bitcoind to fund an
// empty transaction that pays the fees we must add to the transaction package, and we then add the input spending
// the commit tx and adjust the change output.
- val expectedCommitFee = Transactions.weight2fee(targetFeerate, commitTx.weight())
+ val expectedPackageFee = Transactions.weight2fee(targetFeerate, packageWeight)
val anchorFee = Transactions.weight2fee(targetFeerate, anchorTx.expectedWeight)
- val missingFee = expectedCommitFee - commitFee + anchorFee
+ val missingFee = expectedPackageFee - packageFee + anchorFee
for {
changeScript <- bitcoinClient.getChangePublicKeyScript()
txNotFunded = Transaction(2, Nil, TxOut(dustLimit + missingFee, changeScript) :: Nil, 0)
@@ -367,10 +395,10 @@ private class ReplaceableTxFunder(replyTo: ActorRef[ReplaceableTxFunder.FundingR
} yield {
// We merge our dummy change output with the one added by Bitcoin Core, if any, and adjust the change amount to
// pay the expected package feerate.
- val packageWeight = commitTx.weight() + anchorTx.commitmentFormat.anchorInputWeight + fundTxResponse.tx.weight()
- val expectedFee = Transactions.weight2fee(targetFeerate, packageWeight)
+ val totalWeight = packageWeight + anchorTx.commitmentFormat.anchorInputWeight + fundTxResponse.tx.weight()
+ val expectedFee = Transactions.weight2fee(targetFeerate, totalWeight)
// Note that we haven't taken into account yet the amount of the anchor output, so we add it here.
- val currentFee = commitFee + fundTxResponse.fee + anchorTx.input.txOut.amount
+ val currentFee = packageFee + fundTxResponse.fee + anchorTx.input.txOut.amount
val changeAmount = (fundTxResponse.tx.txOut.map(_.amount).sum - expectedFee + currentFee).max(dustLimit)
WalletInputs(walletInputs, changeOutput_opt = Some(TxOut(changeAmount, changeScript)))
}
### eclair-core/src/test/scala/fr/acinq/eclair/TestConstants.scala
@@ -154,6 +154,7 @@ object TestConstants {
minFundingPrivateSatoshis = 900 sat,
maxFundingSatoshis = 10_000_000_000L sat,
requireConfirmedInputsForDualFunding = false,
+ requireConfirmedInputsForSplicing = true,
channelOpenerWhitelist = Set.empty,
maxPendingChannelsPerPeer = 3,
maxTotalPendingChannelsPrivateNodes = 99,
@@ -379,6 +380,7 @@ object TestConstants {
minFundingPrivateSatoshis = 900 sat,
maxFundingSatoshis = 10_000_000_000L sat,
requireConfirmedInputsForDualFunding = false,
+ requireConfirmedInputsForSplicing = true,
channelOpenerWhitelist = Set.empty,
maxPendingChannelsPerPeer = 3,
maxTotalPendingChannelsPrivateNodes = 99,
### eclair-core/src/test/scala/fr/acinq/eclair/blockchain/DummyOnChainWallet.scala
@@ -119,6 +119,8 @@ class SingleKeyOnChainWallet extends OnChainWallet with OnChainAddressCache {
var rolledback = Seq.empty[Transaction]
var doubleSpent = Set.empty[TxId]
var abandoned = Set.empty[TxId]
+ // By default, the inputs we use to fund transactions are confirmed: this can be disabled to test unconfirmed inputs.
+ var fundWithUnconfirmedInputs = false
override def onChainBalance()(implicit ec: ExecutionContext): Future[OnChainBalance] = Future.successful(OnChainBalance(1105 sat, 561 sat))
@@ -138,6 +140,7 @@ class SingleKeyOnChainWallet extends OnChainWallet with OnChainAddressCache {
val dummyP2trWitness = Script.witnessKeyPathPay2tr(ByteVector64.Zeroes)
val inputTx = Transaction(2, Seq(TxIn(OutPoint(randomTxId(), 1), Nil, 0)), Seq(TxOut(inputAmount, script)), 0)
inputs = inputs :+ inputTx
+ if (!fundWithUnconfirmedInputs) SingleKeyOnChainWallet.confirmedInputTxs.put(inputTx.txid, ())
val dummySignedTx = tx.copy(
txIn = tx.txIn.filterNot(i => externalInputsWeight.contains(i.outPoint)).appended(TxIn(OutPoint(inputTx, 0), ByteVector.empty, 0, ScriptWitness.empty)).map(txIn => {
val isP2tr = inputs.find(_.txid == txIn.outPoint.txid).map(_.txOut(txIn.outPoint.index.toInt).publicKeyScript).map(Script.parse).exists(Script.isPay2tr)
@@ -216,7 +219,12 @@ class SingleKeyOnChainWallet extends OnChainWallet with OnChainAddressCache {
}
}
- override def getTxConfirmations(txid: TxId)(implicit ec: ExecutionContext): Future[Option[Int]] = Future.successful(None)
+ override def getTxConfirmations(txid: TxId)(implicit ec: ExecutionContext): Future[Option[Int]] = {
+ val confirmedInput_opt = Some(6).filter(_ => SingleKeyOnChainWallet.confirmedInputTxs.contains(txid))
+ // Transactions that we have published are in our mempool, unless they have been confirmed.
+ val published_opt = published.get(txid).map(_ => 0)
+ Future.successful(confirmedInput_opt.orElse(published_opt))
+ }
override def isTransactionOutputSpendable(txid: TxId, outputIndex: Int, includeMempool: Boolean)(implicit ec: ExecutionContext): Future[Boolean] = Future.successful(true)
@@ -241,6 +249,12 @@ class SingleKeyOnChainWallet extends OnChainWallet with OnChainAddressCache {
}
}
+object SingleKeyOnChainWallet {
+ // Parent transactions of the inputs that our test wallets use to fund transactions: they are shared between all test
+ // wallets, so that a node can verify that its peer's inputs are confirmed.
+ private val confirmedInputTxs = scala.collection.concurrent.TrieMap.empty[TxId, Unit]
+}
+
/** A wallet that blocks when called to fund transactions (useful to test events happening while funding). */
class BlockingOnChainWallet extends SingleKeyOnChainWallet {
override def makeFundingTx(pubkeyScript: ByteVector, amount: Satoshi, feeRatePerKw: FeeratePerKw, feeBudget_opt: Option[Satoshi])(implicit ec: ExecutionContext): Future[MakeFundingTxResponse] = {
### eclair-core/src/test/scala/fr/acinq/eclair/channel/InteractiveTxBuilderSpec.scala
@@ -2957,6 +2957,45 @@ class InteractiveTxBuilderSpec extends TestKitBaseClass with AnyFunSuiteLike wit
assert(probe.expectMsgType[RemoteFailure].cause == InvalidCompleteInteractiveTx(params.channelId, "too many inputs or outputs"))
}
+ test("too many remote inputs in splice") {
+ val probe = TestProbe()
+ val wallet = new SingleKeyOnChainWallet()
+ val params = createFixtureParams(ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), 75_000 sat, 25_000 sat, FeeratePerKw(5000 sat), 500 sat, 0)
+ val previousCommitment = CommitmentsSpec.makeCommitments(25_000_000 msat, 75_000_000 msat).active.head
+ val fundingParams = params.fundingParamsB.copy(localContribution = 0 sat, remoteContribution = 0 sat, sharedInput_opt = Some(params.dummySharedInputB(100_000 sat)))
+ val bob = params.spawnTxBuilderSpliceBob(fundingParams, previousCommitment, wallet)
+ bob ! Start(probe.ref)
+ (1 to InteractiveTxBuilder.MAX_REMOTE_SPLICE_INPUTS_OUTPUTS + 1).foreach(i => {
+ // Alice --- tx_add_input --> Bob
+ bob ! ReceiveMessage(createInput(params.channelId, UInt64(2 * i), 5000 sat))
+ // Alice <-- tx_complete --- Bob
+ probe.expectMsgType[SendMessage]
+ })
+ // Alice --- tx_complete --> Bob
+ bob ! ReceiveMessage(TxComplete(params.channelId))
+ assert(probe.expectMsgType[RemoteFailure].cause == InvalidCompleteInteractiveTx(params.channelId, "too many remote inputs or outputs"))
+ }
+
+ test("too many remote outputs in splice") {
+ val probe = TestProbe()
+ val wallet = new SingleKeyOnChainWallet()
+ val params = createFixtureParams(ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), 75_000 sat, 25_000 sat, FeeratePerKw(5000 sat), 500 sat, 0)
+ val previousCommitment = CommitmentsSpec.makeCommitments(25_000_000 msat, 75_000_000 msat).active.head
+ val fundingParams = params.fundingParamsB.copy(localContribution = 0 sat, remoteContribution = 0 sat, sharedInput_opt = Some(params.dummySharedInputB(100_000 sat)))
+ val validScript = Script.write(Script.pay2wpkh(randomKey().publicKey))
+ val bob = params.spawnTxBuilderSpliceBob(fundingParams, previousCommitment, wallet)
+ bob ! Start(probe.ref)
+ (1 to InteractiveTxBuilder.MAX_REMOTE_SPLICE_INPUTS_OUTPUTS + 1).foreach(i => {
+ // Alice --- tx_add_output --> Bob
+ bob ! ReceiveMessage(TxAddOutput(params.channelId, UInt64(2 * i), 2500 sat, validScript))
+ // Alice <-- tx_complete --- Bob
+ probe.expectMsgType[SendMessage]
+ })
+ // Alice --- tx_complete --> Bob
+ bob ! ReceiveMessage(TxComplete(params.channelId))
+ assert(probe.expectMsgType[RemoteFailure].cause == InvalidCompleteInteractiveTx(params.channelId, "too many remote inputs or outputs"))
+ }
+
test("missing funding output") {
val probe = TestProbe()
val wallet = new SingleKeyOnChainWallet()
### eclair-core/src/test/scala/fr/acinq/eclair/channel/publish/ReplaceableTxPublisherSpec.scala
@@ -578,6 +578,36 @@ class ReplaceableTxPublisherSpec extends TestKitBaseClass with AnyFunSuiteLike w
}
}
+ test("commit tx feerate too low, spending anchor output (unconfirmed funding tx)") {
+ // NB: the funding tx spends one of our utxos: we need another confirmed utxo to fund our anchor tx.
+ withFixture(Seq(500 millibtc, 200 millibtc), ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), zeroConf = true) { f =>
+ import f._
+
+ // The funding transaction is unconfirmed (it could also be an unconfirmed splice transaction).
+ val fundingTxId = alice.stateData.asInstanceOf[DATA_NORMAL].commitments.latest.fundingTxId
+ assert(isInMempool(fundingTxId))
+ val (commitTx, anchorTx) = closeChannelWithoutHtlcs(f, aliceBlockHeight() + 30)
+ wallet.publishTransaction(commitTx.tx).pipeTo(probe.ref)
+ probe.expectMsg(commitTx.tx.txid)
+ assert(getMempool().length == 2)
+
+ // Our target feerate is higher than the feerate of the funding transaction: our anchor tx must also pay for it.
+ val targetFeerate = FeeratePerKw(14_000 sat)
+ assert(TestConstants.feeratePerKw < targetFeerate)
+ setFeerate(targetFeerate, blockTarget = 12)
+ publisher ! Publish(probe.ref, anchorTx)
+
+ // The funding tx, commit tx and anchor tx are in the mempool, and the package reaches our target feerate.
+ val mempoolTxs = getMempoolTxs(3)
+ assert(mempoolTxs.map(_.txid).toSet.contains(fundingTxId))
+ assert(mempoolTxs.map(_.txid).toSet.contains(commitTx.tx.txid))
+ val targetFee = Transactions.weight2fee(targetFeerate, mempoolTxs.map(_.weight).sum.toInt)
+ val actualFee = mempoolTxs.map(_.fees).sum
+ // NB: if we ignored the funding tx, we would be short by its weight multiplied by the feerate difference (~10%).
+ assert(targetFee * 0.97 <= actualFee && actualFee <= targetFee * 1.1, s"actualFee=$actualFee targetFee=$targetFee")
+ }
+ }
+
test("commit tx feerate too low, spending anchor output (local commit, zero-fee-commitments)") {
withFixture(Seq(500 millibtc), ChannelTypes.ZeroFeeCommitments()) { f =>
import f._
### eclair-core/src/test/scala/fr/acinq/eclair/channel/states/e/NormalSplicesStateSpec.scala
@@ -27,12 +27,14 @@ import fr.acinq.eclair._
import fr.acinq.eclair.blockchain.bitcoind.ZmqWatcher._
import fr.acinq.eclair.blockchain.fee.FeeratePerKw
import fr.acinq.eclair.blockchain.{NewTransaction, SingleKeyOnChainWallet}
+import fr.acinq.eclair.blockchain.CurrentBlockHeight
import fr.acinq.eclair.channel.LocalFundingStatus.DualFundedUnconfirmedFundingTx
import fr.acinq.eclair.channel._
import fr.acinq.eclair.channel.fsm.Channel
+import fr.acinq.eclair.channel.fsm.Channel.ProcessCurrentBlockHeight
import fr.acinq.eclair.channel.fund.InteractiveTxBuilder.FullySignedSharedTransaction
import fr.acinq.eclair.channel.fund.InteractiveTxSigningSession
-import fr.acinq.eclair.channel.publish.TxPublisher.{PublishFinalTx, SetChannelId}
+import fr.acinq.eclair.channel.publish.TxPublisher.{PublishFinalTx, PublishReplaceableTx, SetChannelId}
import fr.acinq.eclair.channel.states.ChannelStateTestsBase.{FakeTxPublisherFactory, PimpTestFSM}
import fr.acinq.eclair.channel.states.{ChannelStateTestsBase, ChannelStateTestsTags}
import fr.acinq.eclair.crypto.keymanager.RemoteCommitmentKeys
@@ -61,9 +63,19 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
implicit val log: akka.event.LoggingAdapter = akka.event.NoLogging
+ /**
+ * If set, Alice and Bob don't require confirmed inputs for splicing, which is unsafe. We only use it to test scenarios
+ * with multiple unconfirmed splices, which can still happen with zero-conf.
+ */
+ private val DontRequireConfirmedInputsForSplicing = "dont_require_confirmed_inputs_for_splicing"
+
override def withFixture(test: OneArgTest): Outcome = {
val tags = test.tags + ChannelStateTestsTags.DualFunding
- val setup = init(tags = tags)
+ val nodeParamsA = TestConstants.Alice.nodeParams
+ .modify(_.channelConf.requireConfirmedInputsForSplicing).setToIf(tags.contains(DontRequireConfirmedInputsForSplicing))(false)
+ val nodeParamsB = TestConstants.Bob.nodeParams
+ .modify(_.channelConf.requireConfirmedInputsForSplicing).setToIf(tags.contains(DontRequireConfirmedInputsForSplicing))(false)
+ val setup = init(nodeParamsA = nodeParamsA, nodeParamsB = nodeParamsB, tags = tags)
import setup._
reachNormal(setup, tags)
alice2bob.ignoreMsg { case _: ChannelUpdate => true }
@@ -731,6 +743,42 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
awaitCond(bob.stateData.asInstanceOf[DATA_NORMAL].spliceStatus == SpliceStatus.NoSplice)
}
+ test("recv splice_init (unconfirmed remote inputs)") { f =>
+ import f._
+
+ // Alice splices in using unconfirmed wallet inputs: Bob rejects them.
+ aliceWallet.asInstanceOf[SingleKeyOnChainWallet].fundWithUnconfirmedInputs = true
+ val sender = initiateSpliceWithoutSigs(f, spliceIn_opt = Some(SpliceIn(500_000 sat)), sendTxComplete = false)
+ bob2alice.expectMsgType[TxComplete]
+ bob2alice.forward(alice)
+ alice2bob.expectMsgType[TxComplete]
+ alice2bob.forward(bob)
+ // Alice has no remote inputs to validate, so she signs before receiving Bob's tx_abort.
+ alice2bob.expectMsgType[CommitSig]
+ sender.expectMsgType[RES_SPLICE]
+ val txAbortBob = bob2alice.expectMsgType[TxAbort]
+ assert(txAbortBob.toAscii == UnconfirmedInteractiveTxInputs(bob.stateData.asInstanceOf[DATA_NORMAL].channelId).getMessage)
+ bob2alice.forward(alice, txAbortBob)
+ val txAbortAlice = alice2bob.expectMsgType[TxAbort]
+ alice2bob.forward(bob, txAbortAlice)
+ awaitCond(alice.stateData.asInstanceOf[DATA_NORMAL].spliceStatus == SpliceStatus.NoSplice)
+ awaitCond(bob.stateData.asInstanceOf[DATA_NORMAL].spliceStatus == SpliceStatus.NoSplice)
+ assert(alice.commitments.active.size == 1)
+ assert(bob.commitments.active.size == 1)
+ }
+
+ test("recv CMD_SPLICE (unconfirmed previous splice)") { f =>
+ import f._
+
+ val spliceTx = initiateSplice(f, spliceOut_opt = Some(SpliceOut(100_000 sat, defaultSpliceOutScriptPubKey)))
+ assert(alice.commitments.latest.fundingTxId == spliceTx.txid)
+ // Alice cannot splice on top of an unconfirmed splice transaction: it would spend an unconfirmed parent.
+ val sender = TestProbe()
+ alice ! CMD_SPLICE(sender.ref, spliceIn_opt = Some(SpliceIn(500_000 sat)), spliceOut_opt = None, requestFunding_opt = None, channelType_opt = None)
+ assert(sender.expectMsgType[RES_FAILURE[_, _]].t == InvalidSpliceWithUnconfirmedTx(alice.stateData.asInstanceOf[DATA_NORMAL].channelId, spliceTx.txid))
+ alice2bob.expectNoMessage(100 millis)
+ }
+
test("recv CMD_SPLICE (remote splices out below its reserve)") { f =>
import f._
@@ -798,14 +846,14 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(alice2bob.expectMsgType[TxAbort].toAscii.contains("the current funding transaction is still unconfirmed"))
}
- test("recv CMD_SPLICE (unconfirmed previous tx)") { f =>
+ test("recv CMD_SPLICE (unconfirmed previous tx)", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
// We create a first unconfirmed splice.
initiateSplice(f, spliceIn_opt = Some(SpliceIn(500_000 sat)))
assert(alice.stateData.asInstanceOf[DATA_NORMAL].commitments.latest.localFundingStatus.isInstanceOf[LocalFundingStatus.DualFundedUnconfirmedFundingTx])
- // We allow initiating such splice...
+ // When allowed by our configuration, we can initiate such splice...
val probe = TestProbe()
alice ! CMD_SPLICE(probe.ref, Some(SpliceIn(250_000 sat)), None, None, None)
alice2bob.expectMsgType[Stfu]
@@ -1267,7 +1315,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
bob2alice.forward(alice)
}
- test("splice local/remote locking", Tag(ChannelStateTestsTags.NoMaxHtlcValueInFlight)) { f =>
+ test("splice local/remote locking", Tag(ChannelStateTestsTags.NoMaxHtlcValueInFlight), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val fundingInput = alice.commitments.latest.fundingInput
@@ -1359,7 +1407,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(bob.stateData.asInstanceOf[DATA_NORMAL].commitments.inactive.map(_.fundingTxId).contains(fundingTx1.txid))
}
- test("splice local/remote locking (intermingled)", Tag(ChannelStateTestsTags.NoMaxHtlcValueInFlight)) { f =>
+ test("splice local/remote locking (intermingled)", Tag(ChannelStateTestsTags.NoMaxHtlcValueInFlight), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val fundingInput = alice.commitments.latest.fundingInput
@@ -1448,7 +1496,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
crossSign(bob, alice, bob2alice, alice2bob)
}
- test("emit post-splice events", Tag(ChannelStateTestsTags.NoMaxHtlcValueInFlight)) { f =>
+ test("emit post-splice events", Tag(ChannelStateTestsTags.NoMaxHtlcValueInFlight), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
// Alice and Bob asynchronously exchange HTLCs, which makes their commit indices diverge.
@@ -1878,7 +1926,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(alice.stateData.asInstanceOf[DATA_NORMAL].commitments.inactive.head.localCommit.spec.htlcs.size == 1)
}
- test("recv UpdateAddHtlc while splice is being locked", Tag(ChannelStateTestsTags.ZeroConf)) { f =>
+ test("recv UpdateAddHtlc while splice is being locked", Tag(ChannelStateTestsTags.ZeroConf), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val spliceTx1 = initiateSplice(f, spliceOut_opt = Some(SpliceOut(50_000 sat, defaultSpliceOutScriptPubKey)))
@@ -2479,7 +2527,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(alice.stateName == NORMAL)
}
- test("disconnect (commit_sig not received, missing next nonce)", Tag(ChannelStateTestsTags.OptionSimpleTaproot)) { f =>
+ test("disconnect (commit_sig not received, missing next nonce)", Tag(ChannelStateTestsTags.OptionSimpleTaproot), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
setupHtlcs(f)
@@ -3146,7 +3194,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
resolveHtlcs(f, htlcs)
}
- test("don't resend splice_locked when zero-conf channel confirms", Tag(ChannelStateTestsTags.ZeroConf)) { f =>
+ test("don't resend splice_locked when zero-conf channel confirms", Tag(ChannelStateTestsTags.ZeroConf), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val fundingTx = initiateSplice(f, spliceIn_opt = Some(SpliceIn(500_000 sat, pushAmount = 0 msat)))
@@ -3245,11 +3293,11 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
}
}
- test("re-send splice_locked on reconnection") { f =>
+ test("re-send splice_locked on reconnection", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
resendSpliceLockedOnReconnection(f)
}
- test("re-send splice_locked on reconnection (taproot channels)", Tag(ChannelStateTestsTags.OptionSimpleTaproot)) { f =>
+ test("re-send splice_locked on reconnection (taproot channels)", Tag(ChannelStateTestsTags.OptionSimpleTaproot), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
resendSpliceLockedOnReconnection(f)
}
@@ -3795,7 +3843,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
}
}
- test("force-close with multiple splices (simple)") { f =>
+ test("force-close with multiple splices (simple)", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val htlcs = setupHtlcs(f)
@@ -3888,6 +3936,185 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(bob.stateData.asInstanceOf[DATA_CLOSED].fundingTxId == fundingTx2.txid)
}
+ test("force-close with fully signed splice that cannot be published") { f =>
+ import f._
+
+ setupHtlcs(f)
+ val fundingInput = bob.commitments.latest.fundingInput
+ val fundingTxIndex = bob.commitments.latest.fundingTxIndex
+ val spliceTx = initiateSplice(f, spliceIn_opt = Some(SpliceIn(500_000 sat)))
+ alice2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ bob2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ assert(bob.commitments.latest.fundingTxId == spliceTx.txid)
+
+ // The splice transaction is not in Bob's mempool: Alice may for example have double-spent one of her inputs.
+ val bobWallet1 = bobWallet.asInstanceOf[SingleKeyOnChainWallet]
+ awaitCond(bobWallet1.published.contains(spliceTx.txid))
+ bobWallet1.published.remove(spliceTx.txid)
+
+ // Bob force-closes: his commit tx for the splice cannot confirm, so he must use the previous commitment instead.
+ bob ! CMD_FORCECLOSE(ActorRef.noSender)
+ bob2alice.expectMsgType[Error]
+ val commitTx = bob2blockchain.fishForMessage() {
+ case p: PublishFinalTx => p.desc == "commit-tx" && p.tx.txIn.map(_.outPoint) == Seq(fundingInput)
+ case _ => false
+ }.asInstanceOf[PublishFinalTx].tx
+ awaitCond(bob.stateData.asInstanceOf[DATA_CLOSING].localCommitPublished.map(_.commitTx.txid).contains(commitTx.txid))
+ assert(bob.stateData.asInstanceOf[DATA_CLOSING].commitmentFor(commitTx.txid).fundingTxIndex == fundingTxIndex)
+ // The splice commitment is kept, in case the splice transaction confirms after all.
+ assert(bob.stateData.asInstanceOf[DATA_CLOSING].commitments.latest.fundingTxId == spliceTx.txid)
+ }
+
+ test("force-close with fully signed splice that is double-spent after force-closing") { f =>
+ import f._
+
+ setupHtlcs(f)
+ val fundingInput = bob.commitments.latest.fundingInput
+ val fundingTxIndex = bob.commitments.latest.fundingTxIndex
+ val spliceTx = initiateSplice(f, spliceIn_opt = Some(SpliceIn(500_000 sat)))
+ alice2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ bob2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ val bobWallet1 = bobWallet.asInstanceOf[SingleKeyOnChainWallet]
+ awaitCond(bobWallet1.published.contains(spliceTx.txid))
+
+ // Bob force-closes while the splice transaction is in his mempool.
+ bob ! CMD_FORCECLOSE(ActorRef.noSender)
+ bob2alice.expectMsgType[Error]
+ val commitTx1 = bob2blockchain.expectFinalTxPublished("commit-tx").tx
+ assert(commitTx1.txIn.map(_.outPoint.txid) == Seq(spliceTx.txid))
+
+ // Alice then double-spends one of her inputs: the splice transaction is evicted from Bob's mempool.
+ bobWallet1.published.remove(spliceTx.txid)
+ bob ! ProcessCurrentBlockHeight(CurrentBlockHeight(BlockHeight(400_001)))
+ val commitTx2 = bob2blockchain.fishForMessage() {
+ case p: PublishFinalTx => p.desc == "commit-tx" && p.tx.txIn.map(_.outPoint) == Seq(fundingInput)
+ case _ => false
+ }.asInstanceOf[PublishFinalTx].tx
+ awaitCond(bob.stateData.asInstanceOf[DATA_CLOSING].localCommitPublished.map(_.commitTx.txid).contains(commitTx2.txid))
+ assert(bob.stateData.asInstanceOf[DATA_CLOSING].commitmentFor(commitTx2.txid).fundingTxIndex == fundingTxIndex)
+ }
+
+ test("force-close with fully signed splice that confirms after we switched commitments") { f =>
+ import f._
+
+ setupHtlcs(f)
+ val fundingInput = bob.commitments.latest.fundingInput
+ val spliceTx = initiateSplice(f, spliceIn_opt = Some(SpliceIn(500_000 sat)))
+ alice2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ bob2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ val bobWallet1 = bobWallet.asInstanceOf[SingleKeyOnChainWallet]
+ awaitCond(bobWallet1.published.contains(spliceTx.txid))
+
+ // Bob force-closes while the splice transaction is in his mempool.
+ bob ! CMD_FORCECLOSE(ActorRef.noSender)
+ bob2alice.expectMsgType[Error]
+ val commitTx1 = bob2blockchain.expectFinalTxPublished("commit-tx").tx
+ assert(commitTx1.txIn.map(_.outPoint.txid) == Seq(spliceTx.txid))
+
+ // The splice transaction is evicted from Bob's mempool: he switches to the previous commitment.
+ bobWallet1.published.remove(spliceTx.txid)
+ bob ! ProcessCurrentBlockHeight(CurrentBlockHeight(BlockHeight(400_001)))
+ val commitTx2 = bob2blockchain.fishForMessage() {
+ case p: PublishFinalTx => p.desc == "commit-tx" && p.tx.txIn.map(_.outPoint) == Seq(fundingInput)
+ case _ => false
+ }.asInstanceOf[PublishFinalTx].tx
+ awaitCond(bob.stateData.asInstanceOf[DATA_CLOSING].localCommitPublished.map(_.commitTx.txid).contains(commitTx2.txid))
+
+ // Miners still had the splice transaction and Bob's first commit tx: they are both included in a block.
+ bobWallet1.published.put(spliceTx.txid, spliceTx)
+ bob ! WatchFundingSpentTriggered(commitTx1)
+ bob ! WatchFundingSpentTriggered(spliceTx)
+ // Bob recognizes his own commit tx and claims its outputs, instead of treating it as a remote commit.
+ bob2blockchain.fishForMessage() {
+ case p: PublishFinalTx => p.desc == "commit-tx" && p.tx.txid == commitTx1.txid
+ case _ => false
+ }
+ awaitCond(bob.stateData.asInstanceOf[DATA_CLOSING].localCommitPublished.map(_.commitTx.txid).contains(commitTx1.txid))
+ assert(bob.stateName == CLOSING)
+ assert(bob.stateData.asInstanceOf[DATA_CLOSING].revokedCommitPublished.isEmpty)
+ }
+
+ test("force-close with unsigned splice published by our peer") { f =>
+ import f._
+
+ setupHtlcs(f)
+ val fundingInput = bob.commitments.latest.fundingInput
+ val fundingTxIndex = bob.commitments.latest.fundingTxIndex
+
+ // Alice splices in: Bob doesn't contribute any input, so he must send his tx_signatures first.
+ val sender = initiateSpliceWithoutSigs(f, spliceIn_opt = Some(SpliceIn(500_000 sat)))
+ alice2bob.expectMsgType[CommitSig]
+ alice2bob.forward(bob)
+ bob2alice.expectMsgType[CommitSig]
+ bob2alice.forward(alice)
+ val bobSigs = bob2alice.expectMsgType[TxSignatures] // Alice doesn't send her tx_signatures to Bob
+ bob2blockchain.expectWatchFundingConfirmed(bobSigs.txId)
+ awaitCond(bob.stateData.asInstanceOf[DATA_NORMAL].spliceStatus == SpliceStatus.NoSplice)
+
+ // Bob cannot publish the splice transaction, so he force-closes using the previous commitment.
+ bob ! CMD_FORCECLOSE(ActorRef.noSender)
+ bob2alice.expectMsgType[Error]
+ val commitTx1 = bob2blockchain.expectFinalTxPublished("commit-tx").tx
+ assert(commitTx1.txIn.map(_.outPoint) == Seq(fundingInput))
+
+ // Alice publishes the splice transaction, which double-spends Bob's commit tx: it may stay unconfirmed for a long
+ // time, so Bob must force-close using the splice commitment to be able to CPFP it.
+ bob2alice.forward(alice, bobSigs)
+ alice2bob.expectMsgType[TxSignatures]
+ sender.expectMsgType[RES_SPLICE]
+ val spliceTx = alice.stateData.asInstanceOf[DATA_NORMAL].commitments.latest.localFundingStatus.signedTx_opt.get
+ assert(spliceTx.txid == bobSigs.txId)
+ bobWallet.asInstanceOf[SingleKeyOnChainWallet].published.put(spliceTx.txid, spliceTx)
+ bob ! WatchFundingSpentTriggered(spliceTx)
+ val commitTx2 = bob2blockchain.fishForMessage() {
+ case p: PublishFinalTx => p.desc == "commit-tx" && p.tx.txIn.map(_.outPoint.txid) == Seq(spliceTx.txid)
+ case _ => false
+ }.asInstanceOf[PublishFinalTx].tx
+ Transaction.correctlySpends(commitTx2, Seq(spliceTx), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS)
+ awaitCond(bob.stateData.asInstanceOf[DATA_CLOSING].localCommitPublished.map(_.commitTx.txid).contains(commitTx2.txid))
+ assert(bob.stateData.asInstanceOf[DATA_CLOSING].commitmentFor(commitTx2.txid).fundingTxIndex == fundingTxIndex + 1)
+ }
+
+ test("claim htlc outputs of previous remote commit tx before it is deeply confirmed") { f =>
+ import f._
+
+ val htlcs = setupHtlcs(f)
+ val spliceTx = initiateSplice(f, spliceIn_opt = Some(SpliceIn(500_000 sat)))
+ alice2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+ bob2blockchain.expectWatchFundingConfirmed(spliceTx.txid)
+
+ // Bob publishes his commit tx for the previous commitment, which double-spends the splice transaction.
+ val bobCommitments = bob.stateData.asInstanceOf[ChannelDataWithCommitments].commitments
+ val previousCommitment = bobCommitments.active.find(_.fundingTxIndex == 0).get
+ val bobCommitTx = previousCommitment.fullySignedLocalCommitTx(bobCommitments.channelParams, bob.underlyingActor.channelKeys)
+ alice ! WatchFundingSpentTriggered(bobCommitTx)
+ // We act on it as soon as it confirms.
+ assert(alice2blockchain.fishForMessage() {
+ case w: WatchAlternativeCommitTxConfirmed => w.txId == bobCommitTx.txid
+ case _ => false
+ }.asInstanceOf[WatchAlternativeCommitTxConfirmed].minDepth == 1)
+ awaitCond(alice.stateName == CLOSING)
+
+ // Bob's commit tx confirms: it may still be reorged out, so we keep our commitments, but we immediately claim its
+ // htlc outputs, because Bob may be able to claim them as well with htlc-success transactions.
+ alice ! WatchAlternativeCommitTxConfirmedTriggered(alice.underlyingActor.nodeParams.currentBlockHeight, 42, bobCommitTx)
+ assert(alice2blockchain.fishForMessage() {
+ case w: WatchAlternativeCommitTxConfirmed => w.txId == bobCommitTx.txid
+ case _ => false
+ }.asInstanceOf[WatchAlternativeCommitTxConfirmed].minDepth == alice.underlyingActor.nodeParams.channelConf.minDepth)
+ val htlcTimeoutTxs = htlcs.aliceToBob.map(_ => alice2blockchain.fishForMessage() {
+ case p: PublishReplaceableTx => p.txInfo.isInstanceOf[ClaimHtlcTimeoutTx]
+ case _ => false
+ }.asInstanceOf[PublishReplaceableTx])
+ htlcTimeoutTxs.foreach(p => assert(p.input.txid == bobCommitTx.txid))
+ assert(alice.stateData.asInstanceOf[DATA_CLOSING].remoteCommitPublished.map(_.commitTx.txid).contains(bobCommitTx.txid))
+ assert(alice.stateData.asInstanceOf[DATA_CLOSING].commitments.active.map(_.fundingTxId).toSet == Set(spliceTx.txid, previousCommitment.fundingTxId))
+
+ // Once Bob's commit tx is deeply confirmed, we forget the splice commitment.
+ alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 42, bobCommitTx)
+ awaitCond(alice.stateData.asInstanceOf[DATA_CLOSING].commitments.active.map(_.fundingTxId) == Seq(previousCommitment.fundingTxId))
+ }
+
test("force-close with unsigned splice (tx_signatures not received)") { f =>
import f._
@@ -4003,7 +4230,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(bob.stateData.asInstanceOf[DATA_CLOSING].commitmentFor(commitTx2.txid).fundingTxId == rbfTx.txid)
}
- test("force-close with multiple splices (previous active remote)", Tag(ChannelStateTestsTags.OptionSimpleTaproot), Tag(ChannelStateTestsTags.ZeroConf)) { f =>
+ test("force-close with multiple splices (previous active remote)", Tag(ChannelStateTestsTags.OptionSimpleTaproot), Tag(ChannelStateTestsTags.ZeroConf), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val htlcs = setupHtlcs(f)
@@ -4051,7 +4278,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(alice2blockchain.expectMsgType[WatchAlternativeCommitTxConfirmed].txId == bobCommitTx1.txid)
alice2blockchain.expectNoMessage(100 millis)
// Bob's commit tx confirms.
- alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(400000), 42, bobCommitTx1)
+ alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 42, bobCommitTx1)
// We're back to the normal handling of remote commit.
val remoteAnchor = alice2blockchain.expectReplaceableTxPublished[ClaimRemoteAnchorTx]
@@ -4085,7 +4312,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(alice.stateData.asInstanceOf[DATA_CLOSED].fundingTxId == fundingTx1.txid)
}
- test("force-close with multiple splices (previous active revoked)") { f =>
+ test("force-close with multiple splices (previous active revoked)", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val htlcs = setupHtlcs(f)
@@ -4139,7 +4366,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
(htlcs.bobToAlice.map(_._2) ++ Seq(htlcIn)).map(_ => alice2blockchain.expectMsgType[WatchOutputSpent])
// Bob's revoked commit tx wins.
- alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(400000), 42, bobRevokedCommitTx)
+ alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 42, bobRevokedCommitTx)
// Alice reacts by punishing bob.
val remoteMain = alice2blockchain.expectFinalTxPublished("remote-main")
val mainPenalty = alice2blockchain.expectFinalTxPublished("main-penalty")
@@ -4242,7 +4469,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
alice2blockchain.expectNoMessage(100 millis)
// bob's remote tx wins
- alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(400000), 42, bobCommitTx1)
+ alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 42, bobCommitTx1)
// we're back to the normal handling of remote commit
val remoteAnchor = alice2blockchain.expectReplaceableTxPublished[ClaimRemoteAnchorTx]
val remoteMain = alice2blockchain.expectFinalTxPublished("remote-main")
@@ -4343,7 +4570,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
alice2blockchain.expectNoMessage(100 millis)
// bob's revoked tx wins
- alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(400000), 42, bobRevokedCommitTx)
+ alice ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 42, bobRevokedCommitTx)
// alice reacts by punishing bob
val remoteMain = alice2blockchain.expectFinalTxPublished("remote-main")
val mainPenalty = alice2blockchain.expectFinalTxPublished("main-penalty")
@@ -4370,7 +4597,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(alice.stateData.asInstanceOf[DATA_CLOSED].closingTxId == bobRevokedCommitTx.txid)
}
- test("force-close after channel type upgrade (latest active)", Tag(ChannelStateTestsTags.AnchorOutputsPhoenix)) { f =>
+ test("force-close after channel type upgrade (latest active)", Tag(ChannelStateTestsTags.AnchorOutputsPhoenix), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val htlcs = setupHtlcs(f)
@@ -4499,7 +4726,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
bob2blockchain.expectNoMessage(100 millis)
// Alice's commit tx confirms.
- bob ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(450_000), 5, aliceCommitTx)
+ bob ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 5, aliceCommitTx)
val anchorTx = bob2blockchain.expectReplaceableTxPublished[ClaimRemoteAnchorTx]
val mainTx = bob2blockchain.expectFinalTxPublished("remote-main")
Transaction.correctlySpends(mainTx.tx, Seq(aliceCommitTx), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS)
@@ -4543,7 +4770,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
bob2blockchain.expectNoMessage(100 millis)
// Alice's commit tx confirms.
- bob ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(450_000), 5, aliceCommitTx)
+ bob ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 5, aliceCommitTx)
val mainTx = bob2blockchain.expectFinalTxPublished("remote-main")
Transaction.correctlySpends(mainTx.tx, Seq(aliceCommitTx), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS)
val penaltyTx = bob2blockchain.expectFinalTxPublished("main-penalty")
@@ -4649,7 +4876,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
bob2blockchain.expectNoMessage(100 millis)
// Alice's revoked commit tx confirms.
- bob ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(450_000), 5, aliceCommitTx)
+ bob ! WatchAlternativeCommitTxConfirmedTriggered(BlockHeight(399_000), 5, aliceCommitTx)
val mainTx = bob2blockchain.expectFinalTxPublished("remote-main")
Transaction.correctlySpends(mainTx.tx, Seq(aliceCommitTx), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS)
val penaltyTx = bob2blockchain.expectFinalTxPublished("main-penalty")
@@ -4670,7 +4897,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
assert(bob.stateData.asInstanceOf[DATA_CLOSED].closingTxId == aliceCommitTx.txid)
}
- test("put back watches after restart") { f =>
+ test("put back watches after restart", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val fundingTxId0 = alice.stateData.asInstanceOf[DATA_NORMAL].commitments.latest.fundingTxId
@@ -4719,7 +4946,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
bob2blockchain.expectNoMessage(100 millis)
}
- test("put back watches after restart (inactive)", Tag(ChannelStateTestsTags.ZeroConf)) { f =>
+ test("put back watches after restart (inactive)", Tag(ChannelStateTestsTags.ZeroConf), Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
val fundingTx0 = alice.stateData.asInstanceOf[DATA_NORMAL].commitments.latest.localFundingStatus.signedTx_opt.get
@@ -4846,7 +5073,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
resolveHtlcs(f, htlcs)
}
- test("recv multiple CMD_SPLICE (splice-in, splice-out)") { f =>
+ test("recv multiple CMD_SPLICE (splice-in, splice-out)", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
// Add some HTLCs before splicing in and out.
@@ -4864,7 +5091,7 @@ class NormalSplicesStateSpec extends TestKitBaseClass with FixtureAnyFunSuiteLik
resolveHtlcs(f, htlcs, spliceOutFee = spliceOutFee(f, capacity = 1_900_000.sat))
}
- test("recv CMD_BUMP_FUNDING_FEE with pre and post rbf htlcs") { f =>
+ test("recv CMD_BUMP_FUNDING_FEE with pre and post rbf htlcs", Tag(DontRequireConfirmedInputsForSplicing)) { f =>
import f._
// We create two unconfirmed splice transactions spending each other:Why this scored 72/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.