What changed, and why it matters
This commit fixes a set of vulnerabilities in Eclair's Lightning channel splicing protocol that could let a malicious peer trick the victim into signing a splice transaction that can never be published on the Bitcoin network. Because the victim's latest commitment transaction depends on that splice transaction confirming, the victim would be unable to recover their funds through a normal force-close, while the attacker could still broadcast an older commitment and steal HTLCs (pending routed payments). The fixes reject future lock times, relative time locks on inputs, non-standard witnesses, and too-low feerates when the victim does not contribute to the splice.
Treat this as a security patch and include it in the next release. Operators running nodes that accept splice-in/splice-out or RBF should upgrade promptly. Review any channels where a splice was attempted but rejected around the time of upgrade, and consider monitoring for peers that previously sent future lockTimes, relative nSequences, or non-standard witnesses.
Security signals we found
Commit title and message explicitly describe preventing a malicious peer from making us sign an unpublishable splice transaction
Adds validation of absolute lockTime against current block height to prevent indefinite publication delay
Adds rejection of BIP 68 relative lock time on all interactive-tx inputs, including shared splice input
Adds witness standardness and standard weight checks before accepting tx_signatures
Extends feerate validation to splices where local node contributes nothing
Closes four audit issues from project-loupe/audit-eclair
Adds unit tests covering each new restriction
Evidence from the diff
The patch hardens InteractiveTxBuilder and InteractiveTxSigningSession against four peer-controlled splice parameters: (1) absolute lockTime more than 6 blocks ahead of the local block height, (2) nSequence values enabling BIP 68 relative lock time on any input including the shared splice input, (3) signed splice feerate below 95% of target when the local node did not contribute (because a splice still funds the local commitment), and (4) non-standard witnesses or total weight above Bitcoin Core’s standard limit in tx_signatures. A new isWitnessStandard() helper mirrors Bitcoin Core’s policy for P2WSH, P2TR key-path/script-path, and pay-to-anchor inputs. The commit message explicitly describes the attack outcome: victim force-closes with a commitment that cannot confirm while the peer publishes a prior commitment to steal HTLCs.
Changed components
eclair-core/src/main/scala/fr/acinq/eclair/channel/fund/InteractiveTxBuilder.scalaeclair-core/src/main/scala/fr/acinq/eclair/transactions/Transactions.scalaeclair-core/src/main/scala/fr/acinq/eclair/channel/ChannelExceptions.scalaInspect captured patch +235 / −3
### eclair-core/src/main/scala/fr/acinq/eclair/channel/ChannelExceptions.scala
@@ -67,6 +67,7 @@ case class UnknownSerialId (override val channelId: Byte
case class DuplicateInput (override val channelId: ByteVector32, serialId: UInt64, previousTxId: TxId, previousTxOutput: Long) extends ChannelException(channelId, s"duplicate input $previousTxId:$previousTxOutput (serial_id=${serialId.toByteVector.toHex})")
case class InputOutOfBounds (override val channelId: ByteVector32, serialId: UInt64, previousTxId: TxId, previousTxOutput: Long) extends ChannelException(channelId, s"invalid input $previousTxId:$previousTxOutput (serial_id=${serialId.toByteVector.toHex})")
case class NonReplaceableInput (override val channelId: ByteVector32, serialId: UInt64, previousTxId: TxId, previousTxOutput: Long, sequence: Long) extends ChannelException(channelId, s"$previousTxId:$previousTxOutput is not replaceable (serial_id=${serialId.toByteVector.toHex}, nSequence=$sequence)")
+case class RelativeLockTimeInput (override val channelId: ByteVector32, serialId: UInt64, sequence: Long) extends ChannelException(channelId, s"input must not use a relative lock time (serial_id=${serialId.toByteVector.toHex}, nSequence=$sequence)")
case class NonSegwitInput (override val channelId: ByteVector32, serialId: UInt64, previousTxId: TxId, previousTxOutput: Long) extends ChannelException(channelId, s"$previousTxId:$previousTxOutput is not a native segwit input (serial_id=${serialId.toByteVector.toHex})")
case class PreviousTxMissing (override val channelId: ByteVector32, serialId: UInt64) extends ChannelException(channelId, s"previous tx missing from tx_add_input (serial_id=${serialId.toByteVector.toHex})")
case class InvalidSharedInput (override val channelId: ByteVector32, serialId: UInt64) extends ChannelException(channelId, s"invalid shared tx_add_input (serial_id=${serialId.toByteVector.toHex})")
### eclair-core/src/main/scala/fr/acinq/eclair/channel/fund/InteractiveTxBuilder.scala
@@ -457,6 +457,15 @@ 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
+ // 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.
+ val MAX_LOCKTIME_AHEAD_BLOCKS = 6
+
+ /** A relative lock time on one of its inputs (see BIP 68) would let our peer delay the publication of the transaction. */
+ def hasRelativeLockTime(sequence: Long): Boolean = {
+ (sequence & fr.acinq.bitcoin.TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0 && (sequence & fr.acinq.bitcoin.TxIn.SEQUENCE_LOCKTIME_MASK) != 0
+ }
+
}
private class InteractiveTxBuilder(replyTo: ActorRef[InteractiveTxBuilder.Response],
@@ -595,6 +604,11 @@ private class InteractiveTxBuilder(replyTo: ActorRef[InteractiveTxBuilder.Respon
if (session.remoteInputs.exists(_.serialId == addInput.serialId)) {
return Left(DuplicateSerialId(fundingParams.channelId, addInput.serialId))
}
+ // This applies to every input, including the shared input whose nSequence is chosen by the initiator.
+ if (hasRelativeLockTime(addInput.sequence)) {
+ return Left(RelativeLockTimeInput(fundingParams.channelId, addInput.serialId, addInput.sequence))
+ }
+
// We check whether this is the shared input or a remote input, and validate input details if it is not the shared input.
// The remote input details are usually provided by sending the entire previous transaction.
// But when splicing a taproot channel, it is possible to only send the previous txOut (which saves bandwidth and
@@ -782,6 +796,10 @@ 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.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"))
+ }
val sharedInputs = session.localInputs.collect { case i: Input.Shared => i } ++ session.remoteInputs.collect { case i: Input.Shared => i }
val localInputs = session.localInputs.collect { case i: Input.Local => i }
@@ -1181,12 +1199,25 @@ object InteractiveTxSigningSession {
log.info("invalid tx_signatures: txId mismatch (expected={}, got={})", txWithSigs.signedTx.txid, remoteSigs.txId)
return Left(InvalidFundingSignature(fundingParams.channelId, Some(partiallySignedTx.txId)))
}
+ // Our peer could otherwise create a valid transaction that cannot be relayed, which would prevent us from publishing
+ // our commitment if it spends that transaction.
+ if (!Transactions.isWitnessStandard(txWithSigs.signedTx, partiallySignedTx.tx.inputDetails)) {
+ log.info("invalid tx_signatures: non-standard witness")
+ return Left(InvalidFundingSignature(fundingParams.channelId, Some(partiallySignedTx.txId)))
+ }
+ if (txWithSigs.signedTx.weight() > Transactions.MAX_STANDARD_TX_WEIGHT) {
+ log.info("invalid tx_signatures: exceeds standard weight (weight={})", txWithSigs.signedTx.weight())
+ return Left(InvalidFundingSignature(fundingParams.channelId, Some(partiallySignedTx.txId)))
+ }
// We allow a 5% error margin since witness size prediction could be inaccurate.
// If they didn't contribute to the transaction, they're not responsible, so we don't check the feerate.
- // If we didn't contribute to the transaction, we don't care if they use a lower feerate than expected.
+ // If we didn't contribute to a dual-funded channel open, we don't care if they use a lower feerate than expected.
+ // But a splice transaction funds our latest commitment, so it must be able to confirm even if we didn't contribute:
+ // otherwise our peer could use large witnesses to make the transaction impossible to relay.
val localContributed = txWithSigs.tx.localInputs.nonEmpty || txWithSigs.tx.localOutputs.nonEmpty
val remoteContributed = txWithSigs.tx.remoteInputs.nonEmpty || txWithSigs.tx.remoteOutputs.nonEmpty
- if (localContributed && remoteContributed && txWithSigs.feerate < fundingParams.targetFeerate * 0.95) {
+ val isSplice = fundingParams.sharedInput_opt.nonEmpty
+ if ((localContributed || isSplice) && remoteContributed && txWithSigs.feerate < fundingParams.targetFeerate * 0.95) {
return Left(InvalidFundingFeerate(fundingParams.channelId, fundingParams.targetFeerate, txWithSigs.feerate))
}
val previousOutputs = {
### eclair-core/src/main/scala/fr/acinq/eclair/transactions/Transactions.scala
@@ -44,6 +44,46 @@ import scala.util.Try
object Transactions {
val MAX_STANDARD_TX_WEIGHT = 400_000
+ // Witness standardness limits from Bitcoin Core's policy.
+ val MAX_STANDARD_P2WSH_SCRIPT_SIZE = 3600
+ val MAX_STANDARD_P2WSH_STACK_ITEMS = 100
+ val MAX_STANDARD_P2WSH_STACK_ITEM_SIZE = 80
+ val MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE = 80
+
+ /**
+ * Bitcoin Core doesn't relay transactions with non-standard witnesses, even if they are valid: this mirrors the
+ * IsWitnessStandard policy check from Bitcoin Core, assuming that all inputs are native segwit inputs.
+ *
+ * @param inputs previous outputs spent by the transaction.
+ */
+ def isWitnessStandard(tx: Transaction, inputs: Map[OutPoint, TxOut]): Boolean = tx.txIn.forall { txIn =>
+ val stack = txIn.witness.stack
+ val pubkeyScript = inputs.get(txIn.outPoint).map(_.publicKeyScript)
+ val isPay2anchor = pubkeyScript.contains(Script.write(Script.pay2anchor))
+ val isPay2wsh = pubkeyScript.exists(s => s.length == 34 && s(0) == 0x00 && s(1) == 0x20)
+ val isPay2tr = pubkeyScript.exists(s => s.length == 34 && s(0) == 0x51 && s(1) == 0x20)
+ if (stack.isEmpty) {
+ true
+ } else if (!pubkeyScript.exists(s => Script.isNativeWitnessScript(s)) || isPay2anchor) {
+ false
+ } else if (isPay2wsh) {
+ stack.last.length <= MAX_STANDARD_P2WSH_SCRIPT_SIZE && stack.length - 1 <= MAX_STANDARD_P2WSH_STACK_ITEMS && stack.init.forall(_.length <= MAX_STANDARD_P2WSH_STACK_ITEM_SIZE)
+ } else if (isPay2tr) {
+ val hasAnnex = stack.length >= 2 && stack.last.nonEmpty && stack.last.head == 0x50
+ if (hasAnnex) {
+ false
+ } else if (stack.length >= 2) {
+ // This is a script path spend: the last two items are the script and the control block.
+ val controlBlock = stack.last
+ val isTapscript = controlBlock.nonEmpty && (controlBlock.head & 0xfe) == 0xc0
+ controlBlock.nonEmpty && (!isTapscript || stack.dropRight(2).forall(_.length <= MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE))
+ } else {
+ true
+ }
+ } else {
+ true
+ }
+ }
/** Weight of a fully signed p2wpkh input (using a 73 bytes signature). */
val p2wpkhInputWeight = 273
### eclair-core/src/test/scala/fr/acinq/eclair/channel/InteractiveTxBuilderSpec.scala
@@ -1262,6 +1262,66 @@ class InteractiveTxBuilderSpec extends TestKitBaseClass with AnyFunSuiteLike wit
}
}
+ test("signed splice feerate too low when only remote contributes") {
+ val targetFeerate = FeeratePerKw(2500 sat)
+ withFixture(ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), 100_000 sat, Seq(150_000 sat), 0 sat, Nil, targetFeerate, 330 sat, 0, RequireConfirmedInputs(forLocal = false, forRemote = false)) { f =>
+ import f._
+
+ val probe = TestProbe()
+ alice ! Start(alice2bob.ref)
+ bob ! Start(bob2alice.ref)
+ val (successA1, successB1) = runInteractiveTx(alice, bob, alice2bob, bob2alice)
+ val (txA1, commitmentA1, _, commitmentB1) = fixtureParams.exchangeSigsBobFirst(bobParams, successA1, successB1)
+ walletA.publishTransaction(txA1.signedTx).pipeTo(probe.ref)
+ probe.expectMsg(txA1.txId)
+
+ // Alice splices funds in, while Bob doesn't contribute. Bob expects a slightly higher feerate than what Alice
+ // actually pays for: the unsigned transaction satisfies Bob's target, but the signed transaction doesn't, because
+ // Alice's witnesses are larger than expected. A malicious peer could use this to make splice transactions that
+ // cannot be relayed, so Bob must reject it even though he doesn't contribute.
+ val (sharedInputA, sharedInputB) = fixtureParams.sharedInputs(commitmentA1, commitmentB1)
+ val spliceFixtureParams = fixtureParams.createSpliceFixtureParams(fundingTxIndex = 1, fundingAmountA = 20_000 sat, fundingAmountB = 0 sat, targetFeerate, aliceParams.dustLimit, aliceParams.lockTime, sharedInputA = sharedInputA, sharedInputB = sharedInputB, requireConfirmedInputs = aliceParams.requireConfirmedInputs)
+ val fundingParamsB = spliceFixtureParams.fundingParamsB.copy(targetFeerate = targetFeerate * 1.1)
+ val aliceSplice = fixtureParams.spawnTxBuilderSpliceAlice(spliceFixtureParams.fundingParamsA, commitmentA1, walletA)
+ val bobSplice = fixtureParams.spawnTxBuilderSpliceBob(fundingParamsB, commitmentB1, walletB)
+ aliceSplice ! Start(alice2bob.ref)
+ bobSplice ! Start(bob2alice.ref)
+ val (successA2, successB2) = runInteractiveTx(aliceSplice, bobSplice, alice2bob, bob2alice)
+ assert(successB2.signingSession.fundingTx.tx.localInputs.isEmpty && successB2.signingSession.fundingTx.tx.localOutputs.isEmpty)
+ assert(successB2.signingSession.fundingTx.tx.remoteInputs.nonEmpty)
+
+ implicit val log: akka.event.LoggingAdapter = akka.event.NoLogging
+ // Alice <-- commit_sig --- Bob
+ val Right(signingSessionA: InteractiveTxSigningSession.WaitingForSigs) = successA2.signingSession.receiveCommitSig(fixtureParams.channelParamsA, fixtureParams.channelKeysA, successB2.commitSig, fixtureParams.nodeParamsA.currentBlockHeight)
+ // Alice --- commit_sig --> Bob
+ val Right(sigsB: InteractiveTxSigningSession.SendingSigs) = successB2.signingSession.receiveCommitSig(fixtureParams.channelParamsB, fixtureParams.channelKeysB, successA2.commitSig, fixtureParams.nodeParamsB.currentBlockHeight)
+ // Alice <-- tx_signatures --- Bob
+ val Right(sigsA) = signingSessionA.receiveTxSigs(fixtureParams.channelKeysA, sigsB.localSigs, fixtureParams.nodeParamsA.currentBlockHeight)
+ val spliceTxA = sigsA.fundingTx.sharedTx.asInstanceOf[FullySignedSharedTransaction]
+ assert(spliceTxA.feerate < fundingParamsB.targetFeerate * 0.95)
+ // Alice --- tx_signatures --> Bob
+ val Left(error) = InteractiveTxSigningSession.addRemoteSigs(fixtureParams.channelKeysB, fundingParamsB, sigsB.fundingTx.sharedTx.asInstanceOf[PartiallySignedSharedTransaction], sigsA.localSigs)
+ assert(error.isInstanceOf[InvalidFundingFeerate])
+ }
+ }
+
+ /** Forward interactive-tx messages between Alice and Bob until the protocol completes. */
+ private def runInteractiveTx(alice: ActorRef[InteractiveTxBuilder.Command], bob: ActorRef[InteractiveTxBuilder.Command], alice2bob: TestProbe, bob2alice: TestProbe): (Succeeded, Succeeded) = {
+ var successA_opt = Option.empty[Succeeded]
+ var successB_opt = Option.empty[Succeeded]
+ while (successA_opt.isEmpty || successB_opt.isEmpty) {
+ Seq((alice2bob, bob, (s: Succeeded) => successA_opt = Some(s), successA_opt.isEmpty), (bob2alice, alice, (s: Succeeded) => successB_opt = Some(s), successB_opt.isEmpty)).foreach {
+ case (probe, receiver, onSuccess, pending) if pending => probe.expectMsgType[Response] match {
+ case SendMessage(_, msg: InteractiveTxConstructionMessage) => receiver ! ReceiveMessage(msg)
+ case s: Succeeded => onSuccess(s)
+ case r => fail(s"unexpected response: $r")
+ }
+ case _ => ()
+ }
+ }
+ (successA_opt.get, successB_opt.get)
+ }
+
test("not enough funds (unconfirmed utxos not allowed)") {
withFixture(ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), 100_000 sat, Seq(250_000 sat), 0 sat, Nil, FeeratePerKw(2500 sat), 660 sat, 0, RequireConfirmedInputs(forLocal = true, forRemote = true)) { f =>
import f._
@@ -2673,6 +2733,9 @@ class InteractiveTxBuilderSpec extends TestKitBaseClass with AnyFunSuiteLike wit
TxAddInput(params.channelId, UInt64(7), Some(previousTx), 1, 0) -> NonSegwitInput(params.channelId, UInt64(7), previousTx.txid, 1),
TxAddInput(params.channelId, UInt64(9), Some(previousTx), 2, 0xfffffffeL) -> NonReplaceableInput(params.channelId, UInt64(9), previousTx.txid, 2, 0xfffffffeL),
TxAddInput(params.channelId, UInt64(9), Some(previousTx), 2, 0xffffffffL) -> NonReplaceableInput(params.channelId, UInt64(9), previousTx.txid, 2, 0xffffffffL),
+ // Inputs must not use a relative lock time, which would let our peer delay the publication of the transaction.
+ TxAddInput(params.channelId, UInt64(11), Some(previousTx), 2, 0x0000ffffL) -> RelativeLockTimeInput(params.channelId, UInt64(11), 0x0000ffffL),
+ TxAddInput(params.channelId, UInt64(11), Some(previousTx), 2, 0x00400001L) -> RelativeLockTimeInput(params.channelId, UInt64(11), 0x00400001L),
// Replacing the previousTx field with previousTxOut is only allowed for splices on taproot channels.
TxAddInput(params.channelId, UInt64(5), None, 0, 0, TlvStream(TxAddInputTlv.PrevTxOut(previousTx.txid, previousOutputs(0).amount, previousOutputs(0).publicKeyScript))) -> PreviousTxMissing(params.channelId, UInt64(5))
)
@@ -2938,6 +3001,21 @@ class InteractiveTxBuilderSpec extends TestKitBaseClass with AnyFunSuiteLike wit
assert(probe.expectMsgType[RemoteFailure].cause == InvalidSharedInput(params.channelId, UInt64(0)))
}
+ test("shared input with relative lock time") {
+ val probe = TestProbe()
+ val wallet = new SingleKeyOnChainWallet()
+ val params = createFixtureParams(ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), 100_000 sat, 0 sat, FeeratePerKw(5000 sat), 330 sat, 0)
+ val previousCommitment = CommitmentsSpec.makeCommitments(25_000_000 msat, 50_000_000 msat).active.head
+ val fundingTx = Transaction(2, Nil, Seq(TxOut(50_000 sat, Script.pay2wpkh(randomKey().publicKey)), TxOut(20_000 sat, Script.pay2wpkh(randomKey().publicKey))), 0)
+ val sharedInput = SharedFundingInput(InputInfo(OutPoint(fundingTx, 0), fundingTx.txOut.head), 0, randomKey().publicKey, previousCommitment.commitmentFormat)
+ val bob = params.spawnTxBuilderSpliceBob(params.fundingParamsB.copy(sharedInput_opt = Some(sharedInput)), previousCommitment, wallet)
+ bob ! Start(probe.ref)
+ // Alice --- tx_add_input --> Bob
+ // The initiator chooses the nSequence of the shared input: it must not use a relative lock time.
+ bob ! ReceiveMessage(TxAddInput(params.channelId, UInt64(0), sharedInput.info.outPoint, 0x0000ffffL))
+ assert(probe.expectMsgType[RemoteFailure].cause == RelativeLockTimeInput(params.channelId, UInt64(0), 0x0000ffffL))
+ }
+
test("total input amount too low") {
val probe = TestProbe()
val wallet = new SingleKeyOnChainWallet()
@@ -2986,6 +3064,44 @@ class InteractiveTxBuilderSpec extends TestKitBaseClass with AnyFunSuiteLike wit
assert(probe.expectMsgType[RemoteFailure].cause.isInstanceOf[InvalidSpliceFeerate])
}
+ test("lock time too far in the future") {
+ val currentBlockHeight = TestConstants.Bob.nodeParams.currentBlockHeight.toLong
+ val testCases = Seq(
+ currentBlockHeight + InteractiveTxBuilder.MAX_LOCKTIME_AHEAD_BLOCKS -> true,
+ currentBlockHeight + InteractiveTxBuilder.MAX_LOCKTIME_AHEAD_BLOCKS + 1 -> false,
+ 499_999_999L -> false,
+ // Timestamp-based lock times are never accepted.
+ 1_800_000_000L -> false,
+ )
+ testCases.foreach { case (lockTime, isValid) =>
+ val probe = TestProbe()
+ val wallet = new SingleKeyOnChainWallet()
+ val params = createFixtureParams(ChannelTypes.AnchorOutputsZeroFeeHtlcTx(), 100_000 sat, 0 sat, FeeratePerKw(5000 sat), 330 sat, lockTime)
+ val validScript = Script.write(Script.pay2wpkh(randomKey().publicKey))
+ val bob = params.spawnTxBuilderBob(wallet)
+ bob ! Start(probe.ref)
+ // Alice --- tx_add_input --> Bob
+ bob ! ReceiveMessage(createInput(params.channelId, UInt64(0), 150_000 sat))
+ // Alice <-- tx_complete --- Bob
+ probe.expectMsgType[SendMessage]
+ // Alice --- tx_add_output --> Bob
+ bob ! ReceiveMessage(TxAddOutput(params.channelId, UInt64(2), 100_000 sat, params.fundingPubkeyScript))
+ // Alice <-- tx_complete --- Bob
+ probe.expectMsgType[SendMessage]
+ // Alice --- tx_add_output --> Bob
+ bob ! ReceiveMessage(TxAddOutput(params.channelId, UInt64(4), 45_000 sat, validScript))
+ // Alice <-- tx_complete --- Bob
+ probe.expectMsgType[SendMessage]
+ // Alice --- tx_complete --> Bob
+ bob ! ReceiveMessage(TxComplete(params.channelId))
+ if (isValid) {
+ probe.expectMsgType[Succeeded]
+ } else {
+ assert(probe.expectMsgType[RemoteFailure].cause == InvalidCompleteInteractiveTx(params.channelId, "lock time too far in the future"))
+ }
+ }
+ }
+
test("previous attempts not double-spent") {
val targetFeerate = FeeratePerKw(7500 sat)
val fundingA = 85_000 sat
### eclair-core/src/test/scala/fr/acinq/eclair/transactions/TransactionsSpec.scala
@@ -19,7 +19,7 @@ package fr.acinq.eclair.transactions
import fr.acinq.bitcoin.SigHash._
import fr.acinq.bitcoin.scalacompat.Crypto.TaprootTweak.KeyPathTweak
import fr.acinq.bitcoin.scalacompat.Crypto._
-import fr.acinq.bitcoin.scalacompat.{Btc, ByteVector32, ByteVector64, Crypto, MilliBtc, MilliBtcDouble, Musig2, OP_2, OP_CHECKMULTISIG, OP_PUSHDATA, OP_RETURN, OutPoint, Satoshi, SatoshiLong, Script, Transaction, TxIn, TxOut}
+import fr.acinq.bitcoin.scalacompat.{Btc, ByteVector32, ByteVector64, Crypto, MilliBtc, MilliBtcDouble, Musig2, OP_1, OP_2, OP_2DROP, OP_CHECKMULTISIG, OP_PUSHDATA, OP_RETURN, OutPoint, Satoshi, SatoshiLong, Script, ScriptWitness, Transaction, TxIn, TxOut}
import fr.acinq.bitcoin.{ScriptFlags, SigVersion}
import fr.acinq.eclair.TestUtils.randomTxId
import fr.acinq.eclair._
@@ -113,6 +113,50 @@ class TransactionsSpec extends AnyFunSuite with Logging {
}
}
+ test("check witness standardness") {
+ val p2wpkh = TxOut(50_000 sat, Script.pay2wpkh(randomKey().publicKey))
+ val p2wsh = TxOut(50_000 sat, Script.pay2wsh(Seq(OP_2DROP, OP_1)))
+ val p2tr = TxOut(50_000 sat, Script.pay2tr(randomKey().xOnlyPublicKey(), KeyPathTweak))
+ val p2a = TxOut(240 sat, Script.pay2anchor)
+ val p2pkh = TxOut(50_000 sat, Script.pay2pkh(randomKey().publicKey))
+ val witnessScript = Script.write(Seq(OP_2DROP, OP_1))
+ val tapscriptControlBlock = ByteVector(0xc0) ++ randomBytes(32)
+ val testCases = Seq(
+ (p2wpkh, ScriptWitness.empty, true),
+ (p2wpkh, ScriptWitness(Seq(ByteVector.fill(72)(1), randomKey().publicKey.value)), true),
+ (p2wsh, ScriptWitness(Seq(ByteVector.fill(80)(1), ByteVector.fill(80)(1), witnessScript)), true),
+ // P2WSH stack items are limited to 80 bytes.
+ (p2wsh, ScriptWitness(Seq(ByteVector.fill(81)(1), ByteVector.fill(80)(1), witnessScript)), false),
+ // P2WSH stacks are limited to 100 items (excluding the witness script).
+ (p2wsh, ScriptWitness(Seq.fill(100)(ByteVector.fill(1)(1)) :+ witnessScript), true),
+ (p2wsh, ScriptWitness(Seq.fill(101)(ByteVector.fill(1)(1)) :+ witnessScript), false),
+ // P2WSH scripts are limited to 3600 bytes.
+ (p2wsh, ScriptWitness(Seq(ByteVector.fill(3600)(0x51))), true),
+ (p2wsh, ScriptWitness(Seq(ByteVector.fill(3601)(0x51))), false),
+ // Taproot key path spend.
+ (p2tr, ScriptWitness(Seq(randomBytes(64))), true),
+ // Taproot annexes are not standard.
+ (p2tr, ScriptWitness(Seq(randomBytes(64), ByteVector(0x50) ++ ByteVector.fill(500)(0))), false),
+ // Tapscript stack items are limited to 80 bytes.
+ (p2tr, ScriptWitness(Seq(ByteVector.fill(80)(1), witnessScript, tapscriptControlBlock)), true),
+ (p2tr, ScriptWitness(Seq(ByteVector.fill(81)(1), witnessScript, tapscriptControlBlock)), false),
+ // Unknown leaf versions are not restricted.
+ (p2tr, ScriptWitness(Seq(ByteVector.fill(81)(1), witnessScript, ByteVector(0xc2) ++ randomBytes(32))), true),
+ // An empty control block is invalid.
+ (p2tr, ScriptWitness(Seq(ByteVector.fill(32)(1), witnessScript, ByteVector.empty)), false),
+ // Pay-to-anchor outputs must be spent with an empty witness.
+ (p2a, ScriptWitness.empty, true),
+ (p2a, ScriptWitness(Seq(ByteVector.fill(1)(1))), false),
+ // Non-segwit inputs must not have a witness.
+ (p2pkh, ScriptWitness(Seq(ByteVector.fill(1)(1))), false),
+ )
+ testCases.foreach { case (previousOutput, witness, expected) =>
+ val outPoint = OutPoint(randomTxId(), 0)
+ val tx = Transaction(2, Seq(TxIn(outPoint, ByteVector.empty, 0xfffffffdL, witness)), Seq(TxOut(10_000 sat, Script.pay2wpkh(randomKey().publicKey))), 0)
+ assert(isWitnessStandard(tx, Map(outPoint -> previousOutput)) == expected, s"previousOutput=$previousOutput witness=$witness")
+ }
+ }
+
test("compute fees") {
val htlcs = Set[DirectedHtlc](
OutgoingHtlc(UpdateAddHtlc(ByteVector32.Zeroes, 0, 5000000 msat, ByteVector32.Zeroes, CltvExpiry(552), TestConstants.emptyOnionPacket, None, accountable = false, None)),Why this scored 89/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.