From fe06ac0a377128003a0d6f18a21b592c2c047a67 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:05 +0300 Subject: [PATCH 01/17] lnwallet: populate resolution blob for htlc retribution --- lnwallet/channel.go | 87 +++++++++++++++++++++++++++++++++++----- lnwallet/channel_test.go | 3 ++ 2 files changed, 81 insertions(+), 9 deletions(-) diff --git a/lnwallet/channel.go b/lnwallet/channel.go index ea243dd863d..88a6499afa4 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2195,6 +2195,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, br, ourAmt, theirAmt, err = createBreachRetribution( revokedLog, spendTx, chanState, keyRing, commitmentSecret, leaseExpiry, auxResult.AuxLeaves, + auxResolver, ) if err != nil { return nil, err @@ -2209,7 +2210,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, // are confident that no legacy format is in use. br, ourAmt, theirAmt, err = createBreachRetributionLegacy( revokedLogLegacy, chanState, keyRing, commitmentSecret, - ourScript, theirScript, leaseExpiry, + ourScript, theirScript, leaseExpiry, auxResolver, ) if err != nil { return nil, err @@ -2399,8 +2400,9 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, func createHtlcRetribution(chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitHash chainhash.Hash, commitmentSecret *btcec.PrivateKey, leaseExpiry uint32, - htlc *channeldb.HTLCEntry, - auxLeaves fn.Option[CommitAuxLeaves]) (HtlcRetribution, error) { + htlc *channeldb.HTLCEntry, auxLeaves fn.Option[CommitAuxLeaves], + spendTx *wire.MsgTx, auxResolver fn.Option[AuxContractResolver], + revokedLog *channeldb.RevocationLog) (HtlcRetribution, error) { var emptyRetribution HtlcRetribution @@ -2503,6 +2505,69 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, copy(secondLevelTapTweak[:], scriptTree.TapTweak()) } + // Determine the witness type for this HTLC revocation based on the + // channel type and whether it's incoming or outgoing. + var htlcWitnessType input.StandardWitnessType + isTaproot := chanState.ChanType.IsTaproot() + switch { + case isTaproot && htlc.Incoming.Val: + htlcWitnessType = input.TaprootHtlcAcceptedRevoke + + case isTaproot && !htlc.Incoming.Val: + htlcWitnessType = input.TaprootHtlcOfferedRevoke + + case !isTaproot && htlc.Incoming.Val: + htlcWitnessType = input.HtlcAcceptedRevoke + + case !isTaproot && !htlc.Incoming.Val: + htlcWitnessType = input.HtlcOfferedRevoke + } + + // Only taproot channels can be modified by aux channels, so we + // only need to resolve the aux blob for taproot channel types. + var resolutionBlob fn.Option[tlv.Blob] + if isTaproot { + htlcIDOpt := fn.MapOption( + func(v tlv.BigSizeT[uint64]) input.HtlcIndex { + return v.Int() + }, + )(htlc.HtlcIndex.ValOpt()) + + resolveReq := ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanState.ChanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + FundingBlob: chanState.CustomBlob, + Type: htlcWitnessType, + CloseType: Breach, + CommitTx: spendTx, + SignDesc: signDesc, + KeyRing: keyRing, + CsvDelay: theirDelay, + CommitFee: chanState.RemoteCommitment.CommitFee, + PayHash: fn.Some([32]byte(htlc.RHash.Val)), + HtlcID: htlcIDOpt, + CltvDelay: fn.Some(htlc.RefundTimeout.Val), + } + if revokedLog != nil { + resolveReq.CommitBlob = revokedLog.CustomBlob.ValOpt() + } + + resolveBlob := fn.MapOptionZ( + auxResolver, + func(a AuxContractResolver) fn.Result[tlv.Blob] { + return a.ResolveContract(resolveReq) + }, + ) + if err := resolveBlob.Err(); err != nil { + return emptyRetribution, fmt.Errorf("unable to "+ + "aux resolve HTLC: %w", err) + } + + resolutionBlob = resolveBlob.OkToSome() + } + return HtlcRetribution{ SignDesc: signDesc, OutPoint: wire.OutPoint{ @@ -2512,6 +2577,7 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, SecondLevelWitnessScript: secondLevelWitnessScript, IsIncoming: htlc.Incoming.Val, SecondLevelTapTweak: secondLevelTapTweak, + ResolutionBlob: resolutionBlob, }, nil } @@ -2525,9 +2591,9 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, func createBreachRetribution(revokedLog *channeldb.RevocationLog, spendTx *wire.MsgTx, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, - leaseExpiry uint32, - auxLeaves fn.Option[CommitAuxLeaves]) (*BreachRetribution, int64, int64, - error) { + leaseExpiry uint32, auxLeaves fn.Option[CommitAuxLeaves], + auxResolver fn.Option[AuxContractResolver]) (*BreachRetribution, + int64, int64, error) { commitHash := revokedLog.CommitTxHash @@ -2536,7 +2602,8 @@ func createBreachRetribution(revokedLog *channeldb.RevocationLog, for i, htlc := range revokedLog.HTLCEntries { hr, err := createHtlcRetribution( chanState, keyRing, commitHash.Val, - commitmentSecret, leaseExpiry, htlc, auxLeaves, + commitmentSecret, leaseExpiry, htlc, auxLeaves, spendTx, + auxResolver, revokedLog, ) if err != nil { return nil, 0, 0, err @@ -2642,8 +2709,9 @@ func createBreachRetribution(revokedLog *channeldb.RevocationLog, func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, - ourScript, theirScript input.ScriptDescriptor, - leaseExpiry uint32) (*BreachRetribution, int64, int64, error) { + ourScript, theirScript input.ScriptDescriptor, leaseExpiry uint32, + auxResolver fn.Option[AuxContractResolver]) (*BreachRetribution, + int64, int64, error) { commitHash := revokedLog.CommitTx.TxHash() ourOutpoint := wire.OutPoint{ @@ -2690,6 +2758,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState, keyRing, commitHash, commitmentSecret, leaseExpiry, entry, fn.None[CommitAuxLeaves](), + revokedLog.CommitTx, auxResolver, nil, ) if err != nil { return nil, 0, 0, err diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 5fd8cc08e61..5a41dfd5614 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -10108,6 +10108,7 @@ func TestCreateHtlcRetribution(t *testing.T) { hr, err := createHtlcRetribution( aliceChannel.channelState, keyRing, commitHash, dummyPrivate, leaseExpiry, htlc, fn.None[CommitAuxLeaves](), + nil, fn.None[AuxContractResolver](), nil, ) // Expect no error. require.NoError(t, err) @@ -10313,6 +10314,7 @@ func TestCreateBreachRetribution(t *testing.T) { aliceChannel.channelState, keyRing, dummyPrivate, leaseExpiry, fn.None[CommitAuxLeaves](), + fn.None[AuxContractResolver](), ) // Check the error if expected. @@ -10371,6 +10373,7 @@ func TestCreateBreachRetributionLegacy(t *testing.T) { br, ourAmt, theirAmt, err := createBreachRetributionLegacy( &revokedLog, aliceChannel.channelState, keyRing, dummyPrivate, ourScript, theirScript, leaseExpiry, + fn.None[AuxContractResolver](), ) require.NoError(t, err) From 82966fcb54b62bf6ddbaabf667faa1efbcc6afc5 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:06 +0300 Subject: [PATCH 02/17] sweep+contractcourt: notify aux sweeper only on confirmed sweeps Previously the breach arbiter called NotifyBroadcast on the aux sweeper when each justice tx was first broadcast. That fires too early: the aux sweeper imports proofs on broadcast, but a re-org or pinned-by-low-fee HTLC scenario can prevent that broadcast from ever confirming, leaving the aux sweeper with stale proofs for txids that never made it on-chain. Move the NotifyBroadcast call into a new notifyConfirmedJusticeTx helper that runs from the spend-detection loop and only fires once a confirmed spending tx matches one of our justice tx variants (current or historic across rebuild cycles). The same dedup state is now batch-local to the helper since within a single batch waitForSpendEvent can produce multiple spend entries for the same SpenderTxHash; across loop iterations each outpoint fires exactly once. This also lets us drop the long-lived notifiedJusticeTxs map from exactRetribution. --- contractcourt/breach_arbitrator.go | 107 ++++++++++++++++++++++++----- sweep/fee_bumper.go | 2 + sweep/interface.go | 6 +- sweep/mock_test.go | 2 +- 4 files changed, 97 insertions(+), 20 deletions(-) diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 7b839e67e2d..9bc6b7231f3 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -689,6 +689,88 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( return totalFunds, revokedFunds } +// notifyConfirmedJusticeTx checks if any of the spend details match one of our +// justice transactions. If a confirmed justice transaction is detected and we +// haven't already notified about it, we call NotifyBroadcast on the aux sweeper +// to generate asset-level proofs. +func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, + justiceTxs *justiceTxVariants) { + + // waitForSpendEvent can produce multiple spend entries that point at + // the same SpenderTxHash (one justice tx may sweep several breached + // outputs, and each output has its own SpendNtfn subscription that + // races to commit before the exit channel closes). Dedup within this + // batch so we notify the aux sweeper at most once per confirmed + // justice tx. The set is intentionally batch-local: across Loop + // iterations each SpendEvent fires exactly once per outpoint, and + // the chain notifier handles re-orgs of depth N-1, so no long-lived + // dedup state is needed. + notifiedTxs := make(map[chainhash.Hash]bool) + + // Check each spend to see if it's from one of our justice txs. + for _, s := range spends { + spendingTxHash := *s.detail.SpenderTxHash + + // Skip if we've already notified about this transaction in + // this batch. + if notifiedTxs[spendingTxHash] { + continue + } + + // Helper to check if a justice tx matches the spending tx. + matchesJusticeTx := func(jtx *justiceTxCtx) bool { + if jtx == nil { + return false + } + hash := jtx.justiceTx.TxHash() + + return spendingTxHash.IsEqual(&hash) + } + + var justiceCtx *justiceTxCtx + switch { + case matchesJusticeTx(justiceTxs.spendAll): + justiceCtx = justiceTxs.spendAll + + case matchesJusticeTx(justiceTxs.spendCommitOuts): + justiceCtx = justiceTxs.spendCommitOuts + + case matchesJusticeTx(justiceTxs.spendHTLCs): + justiceCtx = justiceTxs.spendHTLCs + } + + // If this is one of our justice txs, notify the aux sweeper. + if justiceCtx != nil { + bumpReq := sweep.BumpRequest{ + Inputs: justiceCtx.inputs, + DeliveryAddress: justiceCtx.sweepAddr, + ExtraTxOut: justiceCtx.extraTxOut, + } + + err := fn.MapOptionZ( + b.cfg.AuxSweeper, + func(aux sweep.AuxSweeper) error { + // The transaction is already confirmed, + // so we pass skipBroadcast=true. + return aux.NotifyBroadcast( + &bumpReq, s.detail.SpendingTx, + justiceCtx.fee, nil, true, + ) + }, + ) + if err != nil { + brarLog.Errorf("Failed to notify aux sweeper "+ + "of confirmed justice tx %v: %v", + spendingTxHash, err) + } else { + // Mark this transaction as notified to avoid + // duplicate calls. + notifiedTxs[spendingTxHash] = true + } + } + } +} + // exactRetribution is a goroutine which is executed once a contract breach has // been detected by a breachObserver. This function is responsible for // punishing a counterparty for violating the channel contract by sweeping ALL @@ -743,24 +825,6 @@ justiceTxBroadcast: brarLog.Debugf("Broadcasting justice tx: %v", lnutils.SpewLogClosure( finalTx)) - // As we're about to broadcast our breach transaction, we'll notify the - // aux sweeper of our broadcast attempt first. - err = fn.MapOptionZ(b.cfg.AuxSweeper, func(aux sweep.AuxSweeper) error { - bumpReq := sweep.BumpRequest{ - Inputs: finalTx.inputs, - DeliveryAddress: finalTx.sweepAddr, - ExtraTxOut: finalTx.extraTxOut, - } - - return aux.NotifyBroadcast( - &bumpReq, finalTx.justiceTx, finalTx.fee, nil, - ) - }) - if err != nil { - brarLog.Errorf("unable to notify broadcast: %w", err) - return - } - // We'll now attempt to broadcast the transaction which finalized the // channel's retribution against the cheating counter party. label := labels.MakeLabel(labels.LabelTypeJusticeTransaction, nil) @@ -805,6 +869,13 @@ Loop: for { select { case spends := <-spendChan: + // Check if any of the spends represent a confirmed + // justice transaction, and if so, notify the aux + // sweeper. + b.notifyConfirmedJusticeTx( + spends, justiceTxs, + ) + // Update the breach info with the new spends. t, r := updateBreachInfo(breachInfo, spends) totalFunds += t diff --git a/sweep/fee_bumper.go b/sweep/fee_bumper.go index 6088094ffe8..e36c439ef71 100644 --- a/sweep/fee_bumper.go +++ b/sweep/fee_bumper.go @@ -738,8 +738,10 @@ func (t *TxPublisher) broadcast(record *monitorRecord) (*BumpResult, error) { // Before we go to broadcast, we'll notify the aux sweeper, if it's // present of this new broadcast attempt. err := fn.MapOptionZ(t.cfg.AuxSweeper, func(aux AuxSweeper) error { + const skipBroadcast = false return aux.NotifyBroadcast( record.req, tx, record.fee, record.outpointToTxIndex, + skipBroadcast, ) }) if err != nil { diff --git a/sweep/interface.go b/sweep/interface.go index 98863e2e115..21f489be929 100644 --- a/sweep/interface.go +++ b/sweep/interface.go @@ -99,7 +99,11 @@ type AuxSweeper interface { // NotifyBroadcast is used to notify external callers of the broadcast // of a sweep transaction, generated by the passed BumpRequest. + // The skipBroadcast parameter indicates whether the transaction is + // already confirmed on-chain (true for breach sweeps) or needs to be + // broadcast (false for normal sweeps). NotifyBroadcast(req *BumpRequest, tx *wire.MsgTx, totalFees btcutil.Amount, - outpointToTxIndex map[wire.OutPoint]int) error + outpointToTxIndex map[wire.OutPoint]int, + skipBroadcast bool) error } diff --git a/sweep/mock_test.go b/sweep/mock_test.go index 88d63ef6e6f..606ff3163ef 100644 --- a/sweep/mock_test.go +++ b/sweep/mock_test.go @@ -359,7 +359,7 @@ func (m *MockAuxSweeper) ExtraBudgetForInputs( // NotifyBroadcast is used to notify external callers of the broadcast // of a sweep transaction, generated by the passed BumpRequest. func (*MockAuxSweeper) NotifyBroadcast(_ *BumpRequest, _ *wire.MsgTx, - _ btcutil.Amount, _ map[wire.OutPoint]int) error { + _ btcutil.Amount, _ map[wire.OutPoint]int, _ bool) error { return nil } From e846294317cfec6bd06105f582bbed343e9f6c91 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:07 +0300 Subject: [PATCH 03/17] lnwallet: pass breach height to HTLC resolution requests Pass the breach height through the call chain from NewBreachRetribution to createHtlcRetribution, and include it in the ResolutionReq for HTLC outputs via CommitTxBlockHeight. This is required for taproot-assets to properly reanchor asset proofs when sweeping revoked HTLCs. The reanchorAssetOutputs function needs the block height to fetch the block containing the breach commitment transaction and construct valid proofs for the sweep. Without this, the CommitTxBlockHeight defaults to 0, causing tapd to look for the commitment tx in the genesis block and fail with: "commit tx not found in block". See: lightninglabs/taproot-assets@815021fd (tapchannel: add reanchorAssetOutputs for proof reanchoring) --- lnwallet/channel.go | 52 ++++++++++++++++++++++------------------ lnwallet/channel_test.go | 6 ++--- 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 88a6499afa4..51286fb5f02 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2195,7 +2195,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, br, ourAmt, theirAmt, err = createBreachRetribution( revokedLog, spendTx, chanState, keyRing, commitmentSecret, leaseExpiry, auxResult.AuxLeaves, - auxResolver, + auxResolver, breachHeight, ) if err != nil { return nil, err @@ -2211,6 +2211,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, br, ourAmt, theirAmt, err = createBreachRetributionLegacy( revokedLogLegacy, chanState, keyRing, commitmentSecret, ourScript, theirScript, leaseExpiry, auxResolver, + breachHeight, ) if err != nil { return nil, err @@ -2402,7 +2403,8 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, commitmentSecret *btcec.PrivateKey, leaseExpiry uint32, htlc *channeldb.HTLCEntry, auxLeaves fn.Option[CommitAuxLeaves], spendTx *wire.MsgTx, auxResolver fn.Option[AuxContractResolver], - revokedLog *channeldb.RevocationLog) (HtlcRetribution, error) { + revokedLog *channeldb.RevocationLog, + breachHeight uint32) (HtlcRetribution, error) { var emptyRetribution HtlcRetribution @@ -2533,22 +2535,26 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, }, )(htlc.HtlcIndex.ValOpt()) + cs := chanState resolveReq := ResolutionReq{ - ChanPoint: chanState.FundingOutpoint, - ChanType: chanState.ChanType, - ShortChanID: chanState.ShortChanID(), - Initiator: chanState.IsInitiator, - FundingBlob: chanState.CustomBlob, - Type: htlcWitnessType, - CloseType: Breach, - CommitTx: spendTx, - SignDesc: signDesc, - KeyRing: keyRing, - CsvDelay: theirDelay, - CommitFee: chanState.RemoteCommitment.CommitFee, - PayHash: fn.Some([32]byte(htlc.RHash.Val)), - HtlcID: htlcIDOpt, - CltvDelay: fn.Some(htlc.RefundTimeout.Val), + ChanPoint: cs.FundingOutpoint, + ChanType: cs.ChanType, + ShortChanID: cs.ShortChanID(), + Initiator: cs.IsInitiator, + FundingBlob: cs.CustomBlob, + Type: htlcWitnessType, + CloseType: Breach, + CommitTx: spendTx, + CommitTxBlockHeight: breachHeight, + SignDesc: signDesc, + KeyRing: keyRing, + CsvDelay: theirDelay, + CommitFee: cs.RemoteCommitment.CommitFee, + PayHash: fn.Some( + [32]byte(htlc.RHash.Val), + ), + HtlcID: htlcIDOpt, + CltvDelay: fn.Some(htlc.RefundTimeout.Val), } if revokedLog != nil { resolveReq.CommitBlob = revokedLog.CustomBlob.ValOpt() @@ -2592,8 +2598,8 @@ func createBreachRetribution(revokedLog *channeldb.RevocationLog, spendTx *wire.MsgTx, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, leaseExpiry uint32, auxLeaves fn.Option[CommitAuxLeaves], - auxResolver fn.Option[AuxContractResolver]) (*BreachRetribution, - int64, int64, error) { + auxResolver fn.Option[AuxContractResolver], + breachHeight uint32) (*BreachRetribution, int64, int64, error) { commitHash := revokedLog.CommitTxHash @@ -2603,7 +2609,7 @@ func createBreachRetribution(revokedLog *channeldb.RevocationLog, hr, err := createHtlcRetribution( chanState, keyRing, commitHash.Val, commitmentSecret, leaseExpiry, htlc, auxLeaves, spendTx, - auxResolver, revokedLog, + auxResolver, revokedLog, breachHeight, ) if err != nil { return nil, 0, 0, err @@ -2710,8 +2716,8 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, ourScript, theirScript input.ScriptDescriptor, leaseExpiry uint32, - auxResolver fn.Option[AuxContractResolver]) (*BreachRetribution, - int64, int64, error) { + auxResolver fn.Option[AuxContractResolver], + breachHeight uint32) (*BreachRetribution, int64, int64, error) { commitHash := revokedLog.CommitTx.TxHash() ourOutpoint := wire.OutPoint{ @@ -2758,7 +2764,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState, keyRing, commitHash, commitmentSecret, leaseExpiry, entry, fn.None[CommitAuxLeaves](), - revokedLog.CommitTx, auxResolver, nil, + revokedLog.CommitTx, auxResolver, nil, breachHeight, ) if err != nil { return nil, 0, 0, err diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 5a41dfd5614..820932ac4ee 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -10108,7 +10108,7 @@ func TestCreateHtlcRetribution(t *testing.T) { hr, err := createHtlcRetribution( aliceChannel.channelState, keyRing, commitHash, dummyPrivate, leaseExpiry, htlc, fn.None[CommitAuxLeaves](), - nil, fn.None[AuxContractResolver](), nil, + nil, fn.None[AuxContractResolver](), nil, 0, ) // Expect no error. require.NoError(t, err) @@ -10314,7 +10314,7 @@ func TestCreateBreachRetribution(t *testing.T) { aliceChannel.channelState, keyRing, dummyPrivate, leaseExpiry, fn.None[CommitAuxLeaves](), - fn.None[AuxContractResolver](), + fn.None[AuxContractResolver](), 0, ) // Check the error if expected. @@ -10373,7 +10373,7 @@ func TestCreateBreachRetributionLegacy(t *testing.T) { br, ourAmt, theirAmt, err := createBreachRetributionLegacy( &revokedLog, aliceChannel.channelState, keyRing, dummyPrivate, ourScript, theirScript, leaseExpiry, - fn.None[AuxContractResolver](), + fn.None[AuxContractResolver](), 0, ) require.NoError(t, err) From e0eed799a5f1fab05f20700f57925602043da8b7 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:08 +0300 Subject: [PATCH 04/17] contractcourt: add tests for notifyConfirmedJusticeTx Add unit tests for the notifyConfirmedJusticeTx function to verify correct behavior when detecting confirmed justice transactions and notifying the aux sweeper. Test cases cover: - Detection of each justice tx variant (spendAll, spendCommitOuts, spendHTLCs) - Skipping already-notified transactions via notifiedTxs map - No notification for unrelated transactions - Multiple spends with mixed matching/non-matching - Graceful handling of nil justice tx contexts - Operation without an aux sweeper configured --- contractcourt/breach_arbitrator_test.go | 295 ++++++++++++++++++++++++ 1 file changed, 295 insertions(+) diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index fd0997990e1..f4b7d43f2cf 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -33,6 +33,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/shachain" + "github.com/lightningnetwork/lnd/sweep" "github.com/lightningnetwork/lnd/tlv" "github.com/stretchr/testify/require" ) @@ -2632,3 +2633,297 @@ func TestUpdateBreachInfoCountsFinalTaprootRevokedFunds(t *testing.T) { require.Equal(t, revokedAmt, revoked) require.Empty(t, breachInfo.breachedOutputs) } + +// mockAuxSweeperNotify is a mock implementation of sweep.AuxSweeper that tracks +// calls to NotifyBroadcast for testing purposes. +type mockAuxSweeperNotify struct { + notifyCalls []notifyCall + notifyErr error +} + +// notifyCall records the parameters of a NotifyBroadcast call. +type notifyCall struct { + req *sweep.BumpRequest + tx *wire.MsgTx + fee btcutil.Amount + skipBroadcast bool +} + +// DeriveSweepAddr implements sweep.AuxSweeper. +func (m *mockAuxSweeperNotify) DeriveSweepAddr(_ []input.Input, + _ lnwallet.AddrWithKey) fn.Result[sweep.SweepOutput] { + + return fn.Ok(sweep.SweepOutput{}) +} + +// ExtraBudgetForInputs implements sweep.AuxSweeper. +func (m *mockAuxSweeperNotify) ExtraBudgetForInputs( + _ []input.Input) fn.Result[btcutil.Amount] { + + return fn.Ok(btcutil.Amount(0)) +} + +// NotifyBroadcast implements sweep.AuxSweeper and records the call. +func (m *mockAuxSweeperNotify) NotifyBroadcast(req *sweep.BumpRequest, + tx *wire.MsgTx, fee btcutil.Amount, + _ map[wire.OutPoint]int, skipBroadcast bool) error { + + m.notifyCalls = append(m.notifyCalls, notifyCall{ + req: req, + tx: tx, + fee: fee, + skipBroadcast: skipBroadcast, + }) + + return m.notifyErr +} + +// TestNotifyConfirmedJusticeTx tests that notifyConfirmedJusticeTx correctly +// identifies confirmed justice transactions and notifies the aux sweeper. +func TestNotifyConfirmedJusticeTx(t *testing.T) { + t.Parallel() + + // Create test transactions for each justice tx variant. + spendAllTx := &wire.MsgTx{Version: 1} + spendCommitOutsTx := &wire.MsgTx{Version: 2} + spendHTLCsTx := &wire.MsgTx{Version: 3} + unrelatedTx := &wire.MsgTx{Version: 4} + + spendAllHash := spendAllTx.TxHash() + spendCommitOutsHash := spendCommitOutsTx.TxHash() + spendHTLCsHash := spendHTLCsTx.TxHash() + unrelatedHash := unrelatedTx.TxHash() + + // Create justice tx contexts. + spendAllCtx := &justiceTxCtx{ + justiceTx: spendAllTx, + fee: btcutil.Amount(1000), + } + spendCommitOutsCtx := &justiceTxCtx{ + justiceTx: spendCommitOutsTx, + fee: btcutil.Amount(2000), + } + spendHTLCsCtx := &justiceTxCtx{ + justiceTx: spendHTLCsTx, + fee: btcutil.Amount(3000), + } + + tests := []struct { + name string + spends []spend + justiceTxs *justiceTxVariants + expectedCalls int + expectedFees []btcutil.Amount + expectedSkipFlag bool + }{ + { + name: "spendAll variant detected", + spends: []spend{{ + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendAllHash, + SpendingTx: spendAllTx, + SpendingHeight: 100, + }, + }}, + justiceTxs: &justiceTxVariants{ + spendAll: spendAllCtx, + }, + expectedCalls: 1, + expectedFees: []btcutil.Amount{1000}, + expectedSkipFlag: true, + }, + { + name: "spendCommitOuts variant detected", + spends: []spend{{ + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendCommitOutsHash, + SpendingTx: spendCommitOutsTx, + SpendingHeight: 100, + }, + }}, + justiceTxs: &justiceTxVariants{ + spendCommitOuts: spendCommitOutsCtx, + }, + expectedCalls: 1, + expectedFees: []btcutil.Amount{2000}, + expectedSkipFlag: true, + }, + { + name: "spendHTLCs variant detected", + spends: []spend{{ + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendHTLCsHash, + SpendingTx: spendHTLCsTx, + SpendingHeight: 100, + }, + }}, + justiceTxs: &justiceTxVariants{ + spendHTLCs: spendHTLCsCtx, + }, + expectedCalls: 1, + expectedFees: []btcutil.Amount{3000}, + expectedSkipFlag: true, + }, + { + name: "within-batch dedup - same tx referenced twice", + spends: []spend{ + { + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendAllHash, + SpendingTx: spendAllTx, + SpendingHeight: 100, + }, + }, + { + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendAllHash, + SpendingTx: spendAllTx, + SpendingHeight: 100, + }, + }, + }, + justiceTxs: &justiceTxVariants{ + spendAll: spendAllCtx, + }, + expectedCalls: 1, + expectedFees: []btcutil.Amount{1000}, + expectedSkipFlag: true, + }, + { + name: "no match - unrelated transaction", + spends: []spend{{ + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &unrelatedHash, + SpendingTx: unrelatedTx, + SpendingHeight: 100, + }, + }}, + justiceTxs: &justiceTxVariants{ + spendAll: spendAllCtx, + spendCommitOuts: spendCommitOutsCtx, + spendHTLCs: spendHTLCsCtx, + }, + expectedCalls: 0, + }, + { + name: "multiple spends - only matching ones notified", + spends: []spend{ + { + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendAllHash, + SpendingTx: spendAllTx, + SpendingHeight: 100, + }, + }, + { + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &unrelatedHash, + SpendingTx: unrelatedTx, + SpendingHeight: 100, + }, + }, + { + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendHTLCsHash, + SpendingTx: spendHTLCsTx, + SpendingHeight: 100, + }, + }, + }, + justiceTxs: &justiceTxVariants{ + spendAll: spendAllCtx, + spendHTLCs: spendHTLCsCtx, + }, + expectedCalls: 2, + expectedFees: []btcutil.Amount{1000, 3000}, + expectedSkipFlag: true, + }, + { + name: "nil justice txs - no panic", + spends: []spend{}, + justiceTxs: &justiceTxVariants{ + spendAll: nil, + spendCommitOuts: nil, + spendHTLCs: nil, + }, + expectedCalls: 0, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // Create mock aux sweeper. + mockSweeper := &mockAuxSweeperNotify{} + + // Create a minimal BreachArbitrator with the mock. + brar := &BreachArbitrator{ + cfg: &BreachConfig{ + AuxSweeper: fn.Some[sweep.AuxSweeper]( + mockSweeper, + ), + }, + } + + // Call the function under test. + brar.notifyConfirmedJusticeTx( + tc.spends, tc.justiceTxs, + ) + + // Verify the number of NotifyBroadcast calls. + require.Len(t, mockSweeper.notifyCalls, + tc.expectedCalls, "unexpected number of "+ + "NotifyBroadcast calls") + + // Verify the fees if we expected calls. + for i, call := range mockSweeper.notifyCalls { + if i < len(tc.expectedFees) { + require.Equal(t, tc.expectedFees[i], + call.fee, + "unexpected fee for call %d", i) + } + + // Verify skipBroadcast is always true for + // confirmed justice txs. + require.Equal(t, tc.expectedSkipFlag, + call.skipBroadcast, + "skipBroadcast should be true") + } + }) + } +} + +// TestNotifyConfirmedJusticeTxNoAuxSweeper verifies that the function handles +// the case where no aux sweeper is configured. +func TestNotifyConfirmedJusticeTxNoAuxSweeper(t *testing.T) { + t.Parallel() + + spendAllTx := &wire.MsgTx{Version: 1} + spendAllHash := spendAllTx.TxHash() + + spends := []spend{{ + detail: &chainntnfs.SpendDetail{ + SpenderTxHash: &spendAllHash, + SpendingTx: spendAllTx, + SpendingHeight: 100, + }, + }} + + justiceTxs := &justiceTxVariants{ + spendAll: &justiceTxCtx{ + justiceTx: spendAllTx, + fee: btcutil.Amount(1000), + }, + } + + // Create BreachArbitrator with no aux sweeper. + brar := &BreachArbitrator{ + cfg: &BreachConfig{ + AuxSweeper: fn.None[sweep.AuxSweeper](), + }, + } + + // Should not panic when there's no aux sweeper to notify. + brar.notifyConfirmedJusticeTx( + spends, justiceTxs, + ) +} From 684d28dd8a2f1d6cff7a491a4479d67f96e5224c Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:09 +0300 Subject: [PATCH 05/17] lnwallet: extend FetchLeavesFromRevocation with channel state params Second-level HTLC auxiliary leaves need to be computed at runtime from the channel state, key ring, and commitment transaction, rather than being stored in the commitment blob. Extend the FetchLeavesFromRevocation interface method to accept these additional parameters so that implementers can derive the leaves on the fly. --- lnwallet/aux_leaf_store.go | 24 +++++++++++++++++++++++- lnwallet/channel.go | 9 ++++++++- lnwallet/mock.go | 2 +- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/lnwallet/aux_leaf_store.go b/lnwallet/aux_leaf_store.go index e4c22335f93..97329443dcc 100644 --- a/lnwallet/aux_leaf_store.go +++ b/lnwallet/aux_leaf_store.go @@ -191,8 +191,11 @@ type AuxLeafStore interface { // FetchLeavesFromRevocation attempts to fetch the auxiliary leaves // from a channel revocation that stores balance + blob information. + // The chanState, keys, and commitTx fields on the request are needed + // to compute second-level HTLC auxiliary leaves at runtime, since + // these are not stored in the commitment blob. FetchLeavesFromRevocation( - r *channeldb.RevocationLog) fn.Result[CommitDiffAuxResult] + req RevocationLeavesReq) fn.Result[CommitDiffAuxResult] // ApplyHtlcView serves as the state transition function for the custom // channel's blob. Given the old blob, and an HTLC view, then a new @@ -200,6 +203,25 @@ type AuxLeafStore interface { ApplyHtlcView(in CommitDiffAuxInput) fn.Result[fn.Option[tlv.Blob]] } +// RevocationLeavesReq packages the inputs needed to derive aux leaves +// from a channel revocation. ChanState, Keys, and CommitTx are required +// to recompute second-level HTLC leaves that aren't stored in the +// commitment blob. +type RevocationLeavesReq struct { + // Revocation is the revocation log entry whose aux leaves are being + // fetched. + Revocation *channeldb.RevocationLog + + // ChanState is the channel state at the revoked commitment height. + ChanState AuxChanState + + // Keys is the key ring for the revoked commitment. + Keys CommitmentKeyRing + + // CommitTx is the revoked commitment transaction. + CommitTx *wire.MsgTx +} + // auxLeavesFromView is used to derive the set of commit aux leaves (if any), // that are needed to create a new commitment transaction using the original // (unfiltered) htlc view. diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 51286fb5f02..57c02ea2cad 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2145,7 +2145,14 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, auxResult, err := fn.MapOptionZ( leafStore, func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { - return s.FetchLeavesFromRevocation(revokedLog) + return s.FetchLeavesFromRevocation( + RevocationLeavesReq{ + Revocation: revokedLog, + ChanState: NewAuxChanState(chanState), + Keys: *keyRing, + CommitTx: spendTx, + }, + ) }, ).Unpack() if err != nil { diff --git a/lnwallet/mock.go b/lnwallet/mock.go index 5583073e6c4..a8982ef90fc 100644 --- a/lnwallet/mock.go +++ b/lnwallet/mock.go @@ -445,7 +445,7 @@ func (*MockAuxLeafStore) FetchLeavesFromCommit(_ AuxChanState, // FetchLeavesFromRevocation attempts to fetch the auxiliary leaves // from a channel revocation that stores balance + blob information. func (*MockAuxLeafStore) FetchLeavesFromRevocation( - _ *channeldb.RevocationLog) fn.Result[CommitDiffAuxResult] { + _ RevocationLeavesReq) fn.Result[CommitDiffAuxResult] { return fn.Ok(CommitDiffAuxResult{}) } From 70ba95627834b0d75712b6df80a8207cc77b5045 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:09 +0300 Subject: [PATCH 06/17] lnwallet: preserve resolution request for HTLC resolutions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an HTLC is taken to the second level — whether during a breach or during a regular force close — the aux contract resolver needs to re-resolve the contract with the actual second-level transaction once it confirms. Preserve the original ResolutionReq as a template: - in HtlcRetribution, so the breach arbiter can re-resolve with a different witness type - on IncomingHtlcResolution / OutgoingHtlcResolution, so the htlc success and timeout resolvers can do the same once their pre-signed second-level tx confirms Also add SecondLevelTx and SecondLevelTxBlockHeight fields to ResolutionReq so the resolver can re-anchor proofs to the second-level transaction rather than the commitment transaction. Populate HtlcAmt in the resolution request so the resolver has the HTLC value available. Add a NewSecondLevelResolveReq helper that reconstructs the ResolutionReq at re-resolve time, re-deriving the commitment key ring from RevocationProducer.AtIndex(LocalCommitment.CommitHeight) so the plumbing does not have to round-trip the key ring through the briefcase. --- lnwallet/aux_resolutions.go | 17 +++ lnwallet/channel.go | 267 +++++++++++++++++++++++++++--------- 2 files changed, 222 insertions(+), 62 deletions(-) diff --git a/lnwallet/aux_resolutions.go b/lnwallet/aux_resolutions.go index 8891da7d633..a2fa4f234c1 100644 --- a/lnwallet/aux_resolutions.go +++ b/lnwallet/aux_resolutions.go @@ -117,6 +117,23 @@ type ResolutionReq struct { // AuxSigDesc is an optional field that contains additional information // needed to sweep second level HTLCs. AuxSigDesc fn.Option[AuxSigDesc] + + // SecondLevel carries the on-chain context for a just-confirmed + // second-level HTLC tx. It is set only when resolving a + // TaprootHtlcSecondLevelRevoke so the resolver can re-anchor proofs + // to the second-level tx rather than the commitment tx. + SecondLevel fn.Option[SecondLevelInfo] +} + +// SecondLevelInfo carries the on-chain context for a second-level HTLC +// transaction. The fields are derived from the on-chain confirmation of +// the second-level tx and travel together as one inter-related unit. +type SecondLevelInfo struct { + // Tx is the confirmed second-level HTLC transaction. + Tx *wire.MsgTx + + // BlockHeight is the block height at which Tx was confirmed. + BlockHeight uint32 } // AuxContractResolver is an interface that is used to resolve contracts that diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 57c02ea2cad..d0c1169808e 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2003,6 +2003,12 @@ type HtlcRetribution struct { // ResolutionBlob is a blob used for aux channels that permits a // spender of this output to claim all funds. ResolutionBlob fn.Option[tlv.Blob] + + // ResolveReq is the resolution request template used to generate + // the ResolutionBlob. It is preserved so the breach arbiter can + // re-resolve with a different witness type when an HTLC is taken + // to the second level. + ResolveReq *ResolutionReq } // BreachRetribution contains all the data necessary to bring a channel @@ -2535,6 +2541,7 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, // Only taproot channels can be modified by aux channels, so we // only need to resolve the aux blob for taproot channel types. var resolutionBlob fn.Option[tlv.Blob] + var savedResolveReq *ResolutionReq if isTaproot { htlcIDOpt := fn.MapOption( func(v tlv.BigSizeT[uint64]) input.HtlcIndex { @@ -2557,6 +2564,7 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, KeyRing: keyRing, CsvDelay: theirDelay, CommitFee: cs.RemoteCommitment.CommitFee, + HtlcAmt: htlc.Amt.Val.Int(), PayHash: fn.Some( [32]byte(htlc.RHash.Val), ), @@ -2579,6 +2587,15 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, } resolutionBlob = resolveBlob.OkToSome() + + // Save the resolve request template so the breach arbiter + // can re-resolve when an HTLC is taken to second level. + // We deep-copy the key ring to prevent any potential + // mutation from affecting the saved request. + keyRingCopy := *keyRing + resolveReqCopy := resolveReq + resolveReqCopy.KeyRing = &keyRingCopy + savedResolveReq = &resolveReqCopy } return HtlcRetribution{ @@ -2591,6 +2608,7 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, IsIncoming: htlc.Incoming.Val, SecondLevelTapTweak: secondLevelTapTweak, ResolutionBlob: resolutionBlob, + ResolveReq: savedResolveReq, }, nil } @@ -7417,6 +7435,15 @@ type IncomingHtlcResolution struct { // spender of the output to properly resolve it in the case of a force // close. ResolutionBlob fn.Option[tlv.Blob] + + // ResolveReq is the resolution request template used to generate the + // ResolutionBlob. It is preserved so the htlc success resolver can + // re-resolve with a second-level witness type once the pre-signed + // second-level HTLC tx confirms (under DeterministicHTLCs the + // resolver publishes the second-level tx directly via PublishTx, + // bypassing the sweeper's NotifyBroadcast, so tapd must import the + // second-level proof retroactively before the output sweep runs). + ResolveReq *ResolutionReq } // OutgoingHtlcResolution houses the information necessary to sweep any @@ -7471,6 +7498,10 @@ type OutgoingHtlcResolution struct { // spender of the output to properly resolve it in the case of a force // close. ResolutionBlob fn.Option[tlv.Blob] + + // ResolveReq is the resolution request template used to generate the + // ResolutionBlob. See IncomingHtlcResolution.ResolveReq for details. + ResolveReq *ResolutionReq } // HtlcResolutions contains the items necessary to sweep HTLC's on chain @@ -7802,39 +7833,37 @@ func newOutgoingHtlcResolution(signer input.Signer, // This might be an aux channel, so we'll go ahead and attempt to // generate the resolution blob for the channel so we can pass along to // the sweeping sub-system. + resReq := ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + CommitBlob: chanState.LocalCommitment.CustomBlob, + FundingBlob: chanState.CustomBlob, + Type: input.TaprootHtlcLocalOfferedTimeout, + CloseType: LocalForceClose, + CommitTx: commitTx, + CommitTxBlockHeight: commitTxHeight, + ContractPoint: op, + SignDesc: sweepSignDesc, + KeyRing: keyRing, + CsvDelay: htlcCsvDelay, + HtlcAmt: btcutil.Amount(txOut.Value), + CommitCsvDelay: csvDelay, + CltvDelay: fn.Some(htlc.RefundTimeout), + CommitFee: chanState.LocalCommitment.CommitFee, + HtlcID: fn.Some(htlc.HtlcIndex), + PayHash: fn.Some(htlc.RHash), + AuxSigDesc: fn.Some(AuxSigDesc{ + SignDetails: *txSignDetails, + AuxSig: func() []byte { + tlvType := htlcCustomSigType.TypeVal() + return htlc.CustomRecords[uint64(tlvType)] + }(), + }), + } resolveRes := fn.MapOptionZ( auxResolver, func(a AuxContractResolver) fn.Result[tlv.Blob] { - //nolint:ll - resReq := ResolutionReq{ - ChanPoint: chanState.FundingOutpoint, - ChanType: chanType, - ShortChanID: chanState.ShortChanID(), - Initiator: chanState.IsInitiator, - CommitBlob: chanState.LocalCommitment.CustomBlob, - FundingBlob: chanState.CustomBlob, - Type: input.TaprootHtlcLocalOfferedTimeout, - CloseType: LocalForceClose, - CommitTx: commitTx, - CommitTxBlockHeight: commitTxHeight, - ContractPoint: op, - SignDesc: sweepSignDesc, - KeyRing: keyRing, - CsvDelay: htlcCsvDelay, - HtlcAmt: btcutil.Amount(txOut.Value), - CommitCsvDelay: csvDelay, - CltvDelay: fn.Some(htlc.RefundTimeout), - CommitFee: chanState.LocalCommitment.CommitFee, - HtlcID: fn.Some(htlc.HtlcIndex), - PayHash: fn.Some(htlc.RHash), - AuxSigDesc: fn.Some(AuxSigDesc{ - SignDetails: *txSignDetails, - AuxSig: func() []byte { - tlvType := htlcCustomSigType.TypeVal() - return htlc.CustomRecords[uint64(tlvType)] - }(), - }), - } - return a.ResolveContract(resReq) }, ) @@ -7843,12 +7872,15 @@ func newOutgoingHtlcResolution(signer input.Signer, } resolutionBlob := resolveRes.OkToSome() + resReqCopy := resReq + return &OutgoingHtlcResolution{ Expiry: htlc.RefundTimeout, SignedTimeoutTx: timeoutTx, SignDetails: txSignDetails, CsvDelay: csvDelay, ResolutionBlob: resolutionBlob, + ResolveReq: &resReqCopy, ClaimOutpoint: wire.OutPoint{ Hash: timeoutTx.TxHash(), Index: 0, @@ -8166,39 +8198,37 @@ func newIncomingHtlcResolution(signer input.Signer, }, nil } + resReq := ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + CommitBlob: chanState.LocalCommitment.CustomBlob, + Type: input.TaprootHtlcAcceptedLocalSuccess, + FundingBlob: chanState.CustomBlob, + CloseType: LocalForceClose, + CommitTx: commitTx, + CommitTxBlockHeight: commitTxHeight, + ContractPoint: op, + SignDesc: sweepSignDesc, + KeyRing: keyRing, + HtlcID: fn.Some(htlc.HtlcIndex), + CsvDelay: htlcCsvDelay, + CommitFee: chanState.LocalCommitment.CommitFee, + PayHash: fn.Some(htlc.RHash), + AuxSigDesc: fn.Some(AuxSigDesc{ + SignDetails: *txSignDetails, + AuxSig: func() []byte { + tlvType := htlcCustomSigType.TypeVal() + return htlc.CustomRecords[uint64(tlvType)] + }(), + }), + CommitCsvDelay: csvDelay, + HtlcAmt: btcutil.Amount(txOut.Value), + CltvDelay: fn.Some(htlc.RefundTimeout), + } resolveRes := fn.MapOptionZ( auxResolver, func(a AuxContractResolver) fn.Result[tlv.Blob] { - //nolint:ll - resReq := ResolutionReq{ - ChanPoint: chanState.FundingOutpoint, - ChanType: chanType, - ShortChanID: chanState.ShortChanID(), - Initiator: chanState.IsInitiator, - CommitBlob: chanState.LocalCommitment.CustomBlob, - Type: input.TaprootHtlcAcceptedLocalSuccess, - FundingBlob: chanState.CustomBlob, - CloseType: LocalForceClose, - CommitTx: commitTx, - CommitTxBlockHeight: commitTxHeight, - ContractPoint: op, - SignDesc: sweepSignDesc, - KeyRing: keyRing, - HtlcID: fn.Some(htlc.HtlcIndex), - CsvDelay: htlcCsvDelay, - CommitFee: chanState.LocalCommitment.CommitFee, - PayHash: fn.Some(htlc.RHash), - AuxSigDesc: fn.Some(AuxSigDesc{ - SignDetails: *txSignDetails, - AuxSig: func() []byte { - tlvType := htlcCustomSigType.TypeVal() - return htlc.CustomRecords[uint64(tlvType)] - }(), - }), - CommitCsvDelay: csvDelay, - HtlcAmt: btcutil.Amount(txOut.Value), - CltvDelay: fn.Some(htlc.RefundTimeout), - } - return a.ResolveContract(resReq) }, ) @@ -8208,11 +8238,14 @@ func newIncomingHtlcResolution(signer input.Signer, resolutionBlob := resolveRes.OkToSome() + resReqCopy := resReq + return &IncomingHtlcResolution{ SignedSuccessTx: successTx, SignDetails: txSignDetails, CsvDelay: csvDelay, ResolutionBlob: resolutionBlob, + ResolveReq: &resReqCopy, ClaimOutpoint: wire.OutPoint{ Hash: successTx.TxHash(), Index: 0, @@ -8245,6 +8278,116 @@ func (r *OutgoingHtlcResolution) HtlcPoint() wire.OutPoint { return r.ClaimOutpoint } +// NewSecondLevelResolveReq reconstructs a ResolutionReq for re-resolving a +// second-level HTLC sweep after the pre-signed second-level tx has confirmed +// on chain. It is intended to be called from the htlc success / timeout +// resolvers when, under DeterministicHTLCs, the resolver published the +// pre-signed second-level tx directly via PublishTx (bypassing the aux +// sweeper's NotifyBroadcast) and the upcoming second-level output sweep +// would otherwise fail to fetch its input proof from the aux sweeper's +// archive. +// +// The ResolveReq returned mirrors the live request that +// newIncomingHtlcResolution / newOutgoingHtlcResolution built at +// force-close time. We rebuild it here from the persisted channel state +// because IncomingHtlcResolution / OutgoingHtlcResolution don't currently +// round-trip the original ResolveReq through the briefcase log. +// +// chanState must be the historical channel state (e.g. via +// FetchHistoricalChannel). htlc is the HTLC entry whose second-level +// sweep we're about to perform. signDetails is the SignDetails captured +// on the resolution at force-close time. htlcCsvDelay is the CSV delay +// for the second-level output (taken from +// IncomingHtlcResolution.CsvDelay / OutgoingHtlcResolution.CsvDelay). +// commitTxBlockHeight is the height at which the force-close commitment +// confirmed. secondLevelTx and secondLevelTxBlockHeight describe the +// just-confirmed second-level tx. witType is the second-level output +// witness type LND is about to offer to the sweeper +// (TaprootHtlcAcceptedSuccessSecondLevel for the success path or +// TaprootHtlcOfferedTimeoutSecondLevel for the timeout path). +// +// We always treat this as the local commitment because the success / +// timeout resolvers only run for HTLCs on our local force-close +// commitment. +func NewSecondLevelResolveReq(chanState *channeldb.OpenChannel, + htlc *channeldb.HTLC, signDetails *input.SignDetails, + sweepSignDesc input.SignDescriptor, htlcCsvDelay, + commitTxBlockHeight uint32, secondLevelTx *wire.MsgTx, + secondLevelTxBlockHeight uint32, + witType input.WitnessType) (*ResolutionReq, error) { + + if chanState == nil { + return nil, fmt.Errorf("chanState is nil") + } + if secondLevelTx == nil || len(secondLevelTx.TxIn) == 0 { + return nil, fmt.Errorf("invalid second-level tx") + } + + revocation, err := chanState.RevocationProducer.AtIndex( + chanState.LocalCommitment.CommitHeight, + ) + if err != nil { + return nil, fmt.Errorf("derive revocation: %w", err) + } + commitPoint := input.ComputeCommitmentPoint(revocation[:]) + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Local, chanState.ChanType, + &chanState.LocalChanCfg, &chanState.RemoteChanCfg, + ) + keyRingCopy := *keyRing + + htlcAmt := htlc.Amt.ToSatoshis() + commitCsvDelay := uint32(chanState.LocalChanCfg.CsvDelay) + contractPoint := secondLevelTx.TxIn[0].PreviousOutPoint + + // AuxSigDesc is populated when we have both the SignDetails captured + // on the resolution and the remote party's aux sig in the HTLC's + // custom records. signSecondLevelImport uses the breach-style + // 2-of-2 witness construction when AuxSigDesc is present, producing + // a fully verifiable proof transition; the placeholder-witness + // fallback is reserved for the breach path where we don't have the + // remote sig. + var auxSigDesc fn.Option[AuxSigDesc] + if signDetails != nil { + sigType := htlcCustomSigType.TypeVal() + auxSig := htlc.CustomRecords[uint64(sigType)] + if len(auxSig) > 0 { + auxSigDesc = fn.Some(AuxSigDesc{ + SignDetails: *signDetails, + AuxSig: auxSig, + }) + } + } + + return &ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanState.ChanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + CommitBlob: chanState.LocalCommitment.CustomBlob, + FundingBlob: chanState.CustomBlob, + HtlcID: fn.Some(htlc.HtlcIndex), + HtlcAmt: htlcAmt, + Type: witType, + CloseType: LocalForceClose, + CommitTx: chanState.LocalCommitment.CommitTx, + CommitTxBlockHeight: commitTxBlockHeight, + CommitFee: chanState.LocalCommitment.CommitFee, + ContractPoint: contractPoint, + SignDesc: sweepSignDesc, + KeyRing: &keyRingCopy, + CsvDelay: htlcCsvDelay, + CommitCsvDelay: commitCsvDelay, + CltvDelay: fn.Some(htlc.RefundTimeout), + PayHash: fn.Some(htlc.RHash), + AuxSigDesc: auxSigDesc, + SecondLevel: fn.Some(SecondLevelInfo{ + Tx: secondLevelTx, + BlockHeight: secondLevelTxBlockHeight, + }), + }, nil +} + // extractHtlcResolutions creates a series of outgoing HTLC resolutions, and // the local key used when generating the HTLC scrips. This function is to be // used in two cases: force close, or a unilateral close. From 9ab4f2febbdfc65139686736d4d6c1f7d467e767 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:10 +0300 Subject: [PATCH 07/17] contractcourt: enhance breach arbiter for second-level HTLC revocation Support revoking second-level HTLC outputs in custom (asset) channels: - Add findSecondLevelOutputIndex to locate second-level outputs by script match rather than relying on SpenderInputIndex, which can diverge from the output index when the spending tx has additional inputs (e.g., wallet UTXOs for fees). - Re-resolve contract blobs at morph time via AuxContractResolver when an HTLC is taken to the second level, using the preserved ResolutionReq template with an updated witness type and the actual second-level spending transaction. - Handle non-positive BTC sweep amounts when an aux output carries the real value, allowing all input BTC to go toward fees. - Wire AuxResolver into BreachConfig from server.go. --- contractcourt/breach_arbitrator.go | 227 ++++++++++++++- contractcourt/breach_arbitrator_test.go | 355 +++++++++++++++++++++++- server.go | 3 +- 3 files changed, 568 insertions(+), 17 deletions(-) diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 9bc6b7231f3..9d9568276b8 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -179,6 +179,11 @@ type BreachConfig struct { // AuxSweeper is an optional interface that can be used to modify the // way sweep transaction are generated. AuxSweeper fn.Option[sweep.AuxSweeper] + + // AuxResolver is an optional interface for resolving auxiliary + // contract data. Used to generate resolution blobs for second-level + // HTLC revocations at morph time. + AuxResolver fn.Option[lnwallet.AuxContractResolver] } // BreachArbitrator is a special subsystem which is responsible for watching and @@ -539,13 +544,72 @@ func (b *BreachArbitrator) waitForSpendEvent(breachInfo *retributionInfo, } } +// findSecondLevelOutputIndex searches the spending (second-level) transaction's +// outputs for the one that matches the expected second-level HTLC output +// script. This is necessary because SpenderInputIndex (which identifies the +// input that spent our output) does NOT necessarily correspond to the output +// index — the second-level tx may contain additional inputs (e.g. wallet UTXOs +// for fees) that shift the input indices. +func findSecondLevelOutputIndex(bo *breachedOutput, + spendingTx *wire.MsgTx) (uint32, error) { + + isTaproot := txscript.IsPayToTaproot(bo.signDesc.Output.PkScript) + if !isTaproot || bo.signDesc.DoubleTweak == nil { + return 0, fmt.Errorf("cannot derive expected pkScript: " + + "non-taproot or missing DoubleTweak") + } + + // For taproot outputs we derive the expected pkScript from the + // revocation key and the second-level tap tweak. + // + // Derive the revocation public key from the revocation base point + // and the commitment secret (DoubleTweak). + commitPoint := bo.signDesc.DoubleTweak.PubKey() + revokeKey := input.DeriveRevocationPubkey( + bo.signDesc.KeyDesc.PubKey, commitPoint, + ) + + // Compute the expected taproot output key using the revocation key + // as internal key and the second-level tap tweak. + expectedOutputKey := txscript.ComputeTaprootOutputKey( + revokeKey, bo.secondLevelTapTweak[:], + ) + expectedPkScript, err := input.PayToTaprootScript(expectedOutputKey) + if err != nil { + return 0, fmt.Errorf("unable to compute expected pkScript: %w", + err) + } + + // Search the spending tx outputs for the matching pkScript. + for i, txOut := range spendingTx.TxOut { + if bytes.Equal(txOut.PkScript, expectedPkScript) { + return uint32(i), nil + } + } + + // Log details to help diagnose why no match was found. + brarLog.Warnf("Expected second-level pkScript %x (revokeKey=%x, "+ + "tapTweak=%x) not found among %d outputs of tx %s", + expectedPkScript, revokeKey.SerializeCompressed(), + bo.secondLevelTapTweak[:], len(spendingTx.TxOut), + spendingTx.TxHash()) + for i, txOut := range spendingTx.TxOut { + brarLog.Warnf(" output %d: pkScript=%x value=%d", + i, txOut.PkScript, txOut.Value) + } + + return 0, fmt.Errorf("no output matching expected second-level "+ + "taproot pkScript found in tx %s", spendingTx.TxHash()) +} + // convertToSecondLevelRevoke takes a breached output, and a transaction that // spends it to the second level, and mutates the breach output into one that // is able to properly sweep that second level output. We'll use this function // when we go to sweep a breached commitment transaction, but the cheating // party has already attempted to take it to the second level. func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo, - spendDetails *chainntnfs.SpendDetail) { + spendDetails *chainntnfs.SpendDetail, + auxResolver fn.Option[lnwallet.AuxContractResolver]) { // In this case, we'll modify the witness type of this output to // actually prepare for a second level revoke. @@ -556,24 +620,49 @@ func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo, bo.witnessType = input.HtlcSecondLevelRevoke } - // We'll also redirect the outpoint to this second level output, so the - // spending transaction updates it inputs accordingly. + // Find the correct output index in the spending (second-level) tx. + // + // On aux (taproot-asset) channels the second-level tx may bundle + // multiple HTLCs and/or wallet UTXOs for fees, so input index no + // longer matches output index. We script-match our expected + // second-level pkScript to locate the right output. + // + // On non-aux channels (regular legacy/anchor/taproot) we keep the + // legacy behavior of using SpenderInputIndex directly. The + // script-matching code path only runs for aux channels so we don't + // regress sweep behavior on normal channels. spendingTx := spendDetails.SpendingTx - spendInputIndex := spendDetails.SpenderInputIndex + isAuxChannel := bo.resolveReq != nil + + var outputIndex uint32 + if isAuxChannel { + idx, err := findSecondLevelOutputIndex(bo, spendingTx) + if err != nil { + brarLog.Errorf("BUG: cannot locate second-level "+ + "taproot output by script match for "+ + "aux-channel breach %v: %v", bo.outpoint, err) + + return + } + outputIndex = idx + } else { + outputIndex = spendDetails.SpenderInputIndex + } + oldOp := bo.outpoint bo.outpoint = wire.OutPoint{ Hash: spendingTx.TxHash(), - Index: spendInputIndex, + Index: outputIndex, } // Next, we need to update the amount so we can do fee estimation // properly, and also so we can generate a valid signature as we need // to know the new input value (the second level transactions shaves // off some funds to fees). - newAmt := spendingTx.TxOut[spendInputIndex].Value + newAmt := spendingTx.TxOut[outputIndex].Value bo.amt = btcutil.Amount(newAmt) bo.signDesc.Output.Value = newAmt - bo.signDesc.Output.PkScript = spendingTx.TxOut[spendInputIndex].PkScript + bo.signDesc.Output.PkScript = spendingTx.TxOut[outputIndex].PkScript // For taproot outputs, the taptweak also needs to be swapped out. We // do this unconditionally as this field isn't used at all for segwit @@ -584,15 +673,78 @@ func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo, // SignDescriptor. bo.signDesc.WitnessScript = bo.secondLevelWitnessScript + // Re-resolve the aux contract blob for the second-level witness + // type. Aborts the conversion if the re-resolve fails so we don't + // leave bo half-converted with a stale blob. + if err := reresolveAuxBlobForSecondLevel( + bo, spendingTx, spendDetails, auxResolver, + ); err != nil { + return + } + brarLog.Warnf("HTLC(%v) for ChannelPoint(%v) has been spent to the "+ "second-level, adjusting -> %v", oldOp, breachInfo.chanPoint, bo.outpoint) } +// reresolveAuxBlobForSecondLevel re-runs the aux contract resolution against +// the now-known second-level transaction so the breach output's resolution +// blob targets the second-level witness path. No-op for non-aux channels +// (resolveReq is nil). Returns a non-nil error when the caller should bail +// out of the surrounding convertToSecondLevelRevoke (e.g. a resolver error +// would leave bo with a stale blob; better to skip the output entirely). +func reresolveAuxBlobForSecondLevel(bo *breachedOutput, + spendingTx *wire.MsgTx, spendDetails *chainntnfs.SpendDetail, + auxResolver fn.Option[lnwallet.AuxContractResolver]) error { + + if bo.resolveReq == nil { + brarLog.Warnf("No resolve request template available " + + "for second-level HTLC, skipping blob update") + + return nil + } + if bo.resolveReq.KeyRing == nil { + return nil + } + + secondLevelReq := *bo.resolveReq + secondLevelReq.CommitTx = bo.resolveReq.CommitTx.Copy() + secondLevelReq.Type = input.TaprootHtlcSecondLevelRevoke + secondLevelReq.SecondLevel = fn.Some(lnwallet.SecondLevelInfo{ + Tx: spendingTx, + BlockHeight: uint32(spendDetails.SpendingHeight), + }) + + brarLog.Infof("Re-resolving HTLC blob for second-level revoke, "+ + "htlcID=%v, htlcAmt=%v, keyRing=%v, revokeKey=%v", + secondLevelReq.HtlcID, secondLevelReq.HtlcAmt, + secondLevelReq.KeyRing != nil, + secondLevelReq.KeyRing.RevocationKey != nil) + + resolveBlob := fn.MapOptionZ( + auxResolver, + func(a lnwallet.AuxContractResolver) fn.Result[tlv.Blob] { + return a.ResolveContract(secondLevelReq) + }, + ) + if err := resolveBlob.Err(); err != nil { + brarLog.Errorf("Unable to re-resolve second-level HTLC blob "+ + "for %v: %v -- output will be skipped", + bo.outpoint, err) + + return err + } + + bo.resolutionBlob = resolveBlob.OkToSome() + + return nil +} + // updateBreachInfo mutates the passed breachInfo by removing or converting any // outputs among the spends. It also counts the total and revoked funds swept // by our justice spends. -func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( +func updateBreachInfo(breachInfo *retributionInfo, spends []spend, + auxResolver fn.Option[lnwallet.AuxContractResolver]) ( btcutil.Amount, btcutil.Amount) { inputs := breachInfo.breachedOutputs @@ -641,6 +793,7 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( // process. convertToSecondLevelRevoke( breachedOutput, breachInfo, s.detail, + auxResolver, ) continue @@ -739,6 +892,17 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, justiceCtx = justiceTxs.spendHTLCs } + // Also check the individual second-level sweeps. + if justiceCtx == nil { + for _, tx := range justiceTxs.spendSecondLevelHTLCs { + if matchesJusticeTx(tx) { + justiceCtx = tx + + break + } + } + } + // If this is one of our justice txs, notify the aux sweeper. if justiceCtx != nil { bumpReq := sweep.BumpRequest{ @@ -877,7 +1041,9 @@ Loop: ) // Update the breach info with the new spends. - t, r := updateBreachInfo(breachInfo, spends) + t, r := updateBreachInfo( + breachInfo, spends, b.cfg.AuxResolver, + ) totalFunds += t revokedFunds += r @@ -1168,6 +1334,12 @@ type breachedOutput struct { secondLevelWitnessScript []byte secondLevelTapTweak [32]byte + // resolveReq is a template ResolutionReq populated at breach + // detection time. It is used when an HTLC is taken to the second + // level and we need to re-resolve the contract with the updated + // witness type and the actual second-level spending tx. + resolveReq *lnwallet.ResolutionReq + witnessFunc input.WitnessGenerator resolutionBlob fn.Option[tlv.Blob] @@ -1454,9 +1626,10 @@ func newRetributionInfo(chanPoint *wire.OutPoint, ) // For taproot outputs, we also need to hold onto the second - // level tap tweak as well. + // level tap tweak and resolution request template. //nolint:ll htlcOutput.secondLevelTapTweak = breachedHtlc.SecondLevelTapTweak + htlcOutput.resolveReq = breachedHtlc.ResolveReq breachedOutputs = append(breachedOutputs, htlcOutput) } @@ -1573,6 +1746,12 @@ func (b *BreachArbitrator) createJusticeTx( } txs.spendSecondLevelHTLCs = secondLevelSweeps + brarLog.Infof("createJusticeTx: variants summary — spendAll=%v, "+ + "spendCommitOuts=%v, spendHTLCs=%v, "+ + "spendSecondLevelHTLCs=%d", + txs.spendAll != nil, txs.spendCommitOuts != nil, + txs.spendHTLCs != nil, len(txs.spendSecondLevelHTLCs)) + return txs, nil } @@ -1706,19 +1885,37 @@ func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit, // First, we'll add the extra sweep output if it exists, subtracting the // amount from the sweep amt. + var hasAuxOut bool if b.cfg.AuxSweeper.IsSome() { extraChangeOut.WhenOk(func(o sweep.SweepOutput) { sweepAmt -= o.Value txn.AddTxOut(&o.TxOut) + hasAuxOut = true }) } - // Next, we'll add the output to which our funds will be deposited. - txn.AddTxOut(&wire.TxOut{ - PkScript: pkScript.DeliveryAddress, - Value: sweepAmt, - }) + // If the sweep amount is positive, add the regular sweep output as + // usual. If it's non-positive but we have an aux output, we skip + // the BTC sweep output entirely — for custom (asset) channels the + // real value is carried by the aux output and the remaining BTC + // can all go towards fees. + switch { + case sweepAmt > 0: + txn.AddTxOut(&wire.TxOut{ + PkScript: pkScript.DeliveryAddress, + Value: sweepAmt, + }) + + case hasAuxOut: + brarLog.Infof("Dropping BTC sweep output (amount=%d), "+ + "all input BTC (%v) goes to fee + aux output", + sweepAmt, totalAmt) + + default: + return nil, fmt.Errorf("sweep amount is non-positive "+ + "(%d) and no aux output exists", sweepAmt) + } // TODO(roasbeef): add other output change modify sweep amt diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index f4b7d43f2cf..f7daf17e8d3 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -15,8 +15,10 @@ import ( "testing" "time" + "github.com/btcsuite/btcd/address/v2" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chaincfg/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" @@ -2625,7 +2627,7 @@ func TestUpdateBreachInfoCountsFinalTaprootRevokedFunds(t *testing.T) { SpendingTx: &wire.MsgTx{TxIn: []*wire.TxIn{{}}}, SpenderInputIndex: 0, }, - }}) + }}, fn.None[lnwallet.AuxContractResolver]()) // Assert: The amount contributes to both the total and revoked-funds // tallies and is removed from the remaining breach set. @@ -2634,6 +2636,357 @@ func TestUpdateBreachInfoCountsFinalTaprootRevokedFunds(t *testing.T) { require.Empty(t, breachInfo.breachedOutputs) } +// TestFindSecondLevelOutputIndex verifies that findSecondLevelOutputIndex +// correctly identifies the HTLC output in second-level transactions, including +// batched txs with multiple inputs and a wallet change output where input +// indices diverge from output indices. +func TestFindSecondLevelOutputIndex(t *testing.T) { + t.Parallel() + + // Generate a random key pair for the revocation base point. + revokeBasePriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + revokeBasePub := revokeBasePriv.PubKey() + + // Generate a commitment secret (used as DoubleTweak). + commitSecret, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitPoint := commitSecret.PubKey() + + // Derive the revocation public key. + revokeKey := input.DeriveRevocationPubkey( + revokeBasePub, commitPoint, + ) + + // Create a second-level tap tweak (random 32 bytes). + var tapTweak [32]byte + _, err = crand.Read(tapTweak[:]) + require.NoError(t, err) + + // Compute the expected taproot output key and pkScript. + expectedOutputKey := txscript.ComputeTaprootOutputKey( + revokeKey, tapTweak[:], + ) + expectedPkScript, err := input.PayToTaprootScript( + expectedOutputKey, + ) + require.NoError(t, err) + + // Create a random unrelated pkScript for wallet change outputs. + unrelatedKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + unrelatedPkScript, err := input.PayToTaprootScript( + unrelatedKey.PubKey(), + ) + require.NoError(t, err) + + // Build the breachedOutput with taproot signDesc. + bo := &breachedOutput{ + signDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: revokeBasePub, + }, + DoubleTweak: commitSecret, + Output: &wire.TxOut{ + PkScript: expectedPkScript, + }, + }, + secondLevelTapTweak: tapTweak, + } + + tests := []struct { + name string + tx *wire.MsgTx + expectedIndex uint32 + expectErr bool + }{ + { + // Simple 1-input-1-output second-level tx. + name: "single output matches", + tx: &wire.MsgTx{ + TxOut: []*wire.TxOut{ + { + PkScript: expectedPkScript, + Value: 50_000, + }, + }, + }, + expectedIndex: 0, + }, + { + // Batched tx: wallet UTXO input adds a + // change output before the HTLC output. + name: "batched tx - HTLC at index 1", + tx: &wire.MsgTx{ + TxIn: []*wire.TxIn{ + {}, // HTLC input + {}, // wallet UTXO + }, + TxOut: []*wire.TxOut{ + { + PkScript: unrelatedPkScript, + Value: 100_000, + }, + { + PkScript: expectedPkScript, + Value: 50_000, + }, + }, + }, + expectedIndex: 1, + }, + { + // Batched tx: HTLC output first, change + // output second. + name: "batched tx - HTLC at index 0", + tx: &wire.MsgTx{ + TxIn: []*wire.TxIn{ + {}, // wallet UTXO + {}, // HTLC input + }, + TxOut: []*wire.TxOut{ + { + PkScript: expectedPkScript, + Value: 50_000, + }, + { + PkScript: unrelatedPkScript, + Value: 100_000, + }, + }, + }, + expectedIndex: 0, + }, + { + // Batched tx with 3 outputs: HTLC in the + // middle. + name: "batched tx - HTLC at index 1 of 3", + tx: &wire.MsgTx{ + TxIn: []*wire.TxIn{ + {}, {}, {}, + }, + TxOut: []*wire.TxOut{ + { + PkScript: unrelatedPkScript, + Value: 100_000, + }, + { + PkScript: expectedPkScript, + Value: 50_000, + }, + { + PkScript: unrelatedPkScript, + Value: 200_000, + }, + }, + }, + expectedIndex: 1, + }, + { + // No matching output — should error. + name: "no match", + tx: &wire.MsgTx{ + TxOut: []*wire.TxOut{ + { + PkScript: unrelatedPkScript, + Value: 50_000, + }, + }, + }, + expectErr: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + idx, err := findSecondLevelOutputIndex( + bo, tc.tx, + ) + if tc.expectErr { + require.Error(t, err) + return + } + + require.NoError(t, err) + require.Equal(t, tc.expectedIndex, idx) + }) + } +} + +// TestSweepSpendableOutputsAuxOutput tests the three-way output construction +// logic in sweepSpendableOutputsTxn: positive sweep amount, aux-only output +// (BTC sweep dropped), and error when sweep is non-positive without aux. +func TestSweepSpendableOutputsAuxOutput(t *testing.T) { + t.Parallel() + + privKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + + pkScript, err := input.PayToTaprootScript(privKey.PubKey()) + require.NoError(t, err) + + // Build a P2WKH pkScript for the input (WitnessKeyHash needs + // a valid P2WKH output to sign). + p2wkhAddr := address.Hash160( + privKey.PubKey().SerializeCompressed(), + ) + builder := txscript.NewScriptBuilder() + builder.AddOp(txscript.OP_0) + builder.AddData(p2wkhAddr) + p2wkhScript, err := builder.Script() + require.NoError(t, err) + + // Create a breached output with enough value to cover fees. + makeOutput := func(value int64) breachedOutput { + return breachedOutput{ + amt: btcutil.Amount(value), + outpoint: wire.OutPoint{ + Hash: chainhash.Hash{0x01}, + Index: 0, + }, + witnessType: input.WitnessKeyHash, + signDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: privKey.PubKey(), + }, + Output: &wire.TxOut{ + PkScript: p2wkhScript, + Value: value, + }, + }, + } + } + + sweepAddr := lnwallet.AddrWithKey{ + DeliveryAddress: pkScript, + } + + signer := input.NewMockSigner( + []*btcec.PrivateKey{privKey}, + &chaincfg.RegressionNetParams, + ) + + // Common config for the BreachArbitrator. + makeBrar := func( + auxSweeper fn.Option[sweep.AuxSweeper], + ) *BreachArbitrator { + + genScript := func() fn.Result[lnwallet.AddrWithKey] { + return fn.Ok(sweepAddr) + } + + return &BreachArbitrator{ + cfg: &BreachConfig{ + Signer: signer, + GenSweepScript: genScript, + Estimator: chainfee.NewStaticEstimator( + chainfee.FeePerKwFloor, 0, + ), + AuxSweeper: auxSweeper, + }, + } + } + + t.Run("positive sweep no aux", func(t *testing.T) { + brar := makeBrar(fn.None[sweep.AuxSweeper]()) + bo := makeOutput(1_000_000) + + result, err := brar.sweepSpendableOutputsTxn( + 200, &bo, + ) + require.NoError(t, err) + require.NotNil(t, result) + + // Should have exactly 1 output (the BTC sweep). + require.Len(t, result.justiceTx.TxOut, 1) + }) + + t.Run("positive sweep with aux", func(t *testing.T) { + sweeper := &mockAuxSweeperWithOutput{ + outputValue: 10_000, + pkScript: pkScript, + } + brar := makeBrar(fn.Some[sweep.AuxSweeper](sweeper)) + bo := makeOutput(1_000_000) + + result, err := brar.sweepSpendableOutputsTxn( + 200, &bo, + ) + require.NoError(t, err) + require.NotNil(t, result) + + // Should have 2 outputs: aux + BTC sweep. + require.Len(t, result.justiceTx.TxOut, 2) + }) + + t.Run("non-positive sweep with aux", func(t *testing.T) { + // Value so low that after fee the sweep amount is + // non-positive, but aux output saves it. + sweeper := &mockAuxSweeperWithOutput{ + outputValue: 100, + pkScript: pkScript, + } + brar := makeBrar(fn.Some[sweep.AuxSweeper](sweeper)) + + // Use a very high weight so fee exceeds input value. + bo := makeOutput(500) + + result, err := brar.sweepSpendableOutputsTxn( + 100_000, &bo, + ) + require.NoError(t, err) + require.NotNil(t, result) + + // Should have only 1 output (aux only, BTC sweep + // dropped). + require.Len(t, result.justiceTx.TxOut, 1) + }) + + t.Run("non-positive sweep no aux errors", func(t *testing.T) { + brar := makeBrar(fn.None[sweep.AuxSweeper]()) + bo := makeOutput(500) + + _, err := brar.sweepSpendableOutputsTxn( + 100_000, &bo, + ) + require.Error(t, err) + require.Contains(t, err.Error(), "non-positive") + }) +} + +// mockAuxSweeperWithOutput is a mock AuxSweeper that returns a configurable +// sweep output from DeriveSweepAddr. +type mockAuxSweeperWithOutput struct { + outputValue int64 + pkScript []byte +} + +func (m *mockAuxSweeperWithOutput) DeriveSweepAddr( + _ []input.Input, + _ lnwallet.AddrWithKey) fn.Result[sweep.SweepOutput] { + + return fn.Ok(sweep.SweepOutput{ + TxOut: wire.TxOut{ + PkScript: m.pkScript, + Value: m.outputValue, + }, + }) +} + +func (m *mockAuxSweeperWithOutput) ExtraBudgetForInputs( + _ []input.Input) fn.Result[btcutil.Amount] { + + return fn.Ok(btcutil.Amount(0)) +} + +func (m *mockAuxSweeperWithOutput) NotifyBroadcast( + _ *sweep.BumpRequest, _ *wire.MsgTx, + _ btcutil.Amount, _ map[wire.OutPoint]int, + _ bool) error { + + return nil +} + // mockAuxSweeperNotify is a mock implementation of sweep.AuxSweeper that tracks // calls to NotifyBroadcast for testing purposes. type mockAuxSweeperNotify struct { diff --git a/server.go b/server.go index a0312bb0146..5e915ee88f1 100644 --- a/server.go +++ b/server.go @@ -1355,7 +1355,8 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr, Store: contractcourt.NewRetributionStore( dbs.ChanStateDB, ), - AuxSweeper: s.implCfg.AuxSweeper, + AuxSweeper: s.implCfg.AuxSweeper, + AuxResolver: s.implCfg.AuxContractResolver, }, ) From 089ded93ecd73c33a4d6eb0d8ce8fb563c66dee8 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:11 +0300 Subject: [PATCH 08/17] lnwallet+contractcourt: gate HTLC sighash on negotiated feature bit Replace the backwards-incompatible CustomBlob.IsSome() check for choosing SigHashDefault with a feature-bit negotiation approach via a new AuxSigner.HtlcSigHashType hook. Add ResolveHtlcSigHashType helper that queries the aux signer for a channel-specific sighash override based on negotiated features, falling back to the default HtlcSigHashType when no aux signer is present or the feature isn't negotiated. Thread the auxSigner through all HTLC second-level transaction signing and validation call sites. This ensures both channel parties agree on the sighash type through explicit feature negotiation rather than an implicit check that could cause sighash disagreement and forced channel closure when only one party has upgraded. --- contractcourt/chain_arbitrator.go | 2 ++ contractcourt/chain_watcher.go | 7 +++- input/size_test.go | 4 ++- lnwallet/aux_signer.go | 46 +++++++++++++++++++++++++ lnwallet/channel.go | 56 +++++++++++++++++++++++-------- lnwallet/channel_test.go | 3 ++ lnwallet/commitment.go | 7 ++-- lnwallet/mock.go | 8 +++++ 8 files changed, 115 insertions(+), 18 deletions(-) diff --git a/contractcourt/chain_arbitrator.go b/contractcourt/chain_arbitrator.go index e31b5a9bd4e..da3649ef51a 100644 --- a/contractcourt/chain_arbitrator.go +++ b/contractcourt/chain_arbitrator.go @@ -1205,6 +1205,7 @@ func (c *ChainArbitrator) WatchNewChannel( extractStateNumHint: lnwallet.GetStateNumHint, auxLeafStore: c.cfg.AuxLeafStore, auxResolver: c.cfg.AuxResolver, + auxSigner: c.cfg.AuxSigner, auxCloser: c.cfg.AuxCloser, chanCloseConfs: c.cfg.ChannelCloseConfs, notifyEarlyCoopClose: c.cfg.NotifyEarlyClosedChannel, @@ -1385,6 +1386,7 @@ func (c *ChainArbitrator) loadOpenChannels() error { extractStateNumHint: lnwallet.GetStateNumHint, auxLeafStore: c.cfg.AuxLeafStore, auxResolver: c.cfg.AuxResolver, + auxSigner: c.cfg.AuxSigner, auxCloser: c.cfg.AuxCloser, chanCloseConfs: c.cfg.ChannelCloseConfs, notifyEarlyCoopClose: notifyEarlyClose, diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index ee8f870ed6d..ca4af9d0841 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -273,6 +273,10 @@ type chainWatcherConfig struct { // auxResolver is used to supplement contract resolution. auxResolver fn.Option[lnwallet.AuxContractResolver] + // auxSigner is an optional signer that can be used to determine + // channel-specific HTLC sighash types based on negotiated features. + auxSigner fn.Option[lnwallet.AuxSigner] + // auxCloser is used to finalize cooperative closes. auxCloser fn.Option[AuxChanCloser] @@ -1574,7 +1578,7 @@ func (c *chainWatcher) dispatchLocalForceClose( forceClose, err := lnwallet.NewLocalForceCloseSummary( c.cfg.chanState, c.cfg.signer, commitSpend.SpendingTx, uint32(commitSpend.SpendingHeight), stateNum, - c.cfg.auxLeafStore, c.cfg.auxResolver, + c.cfg.auxLeafStore, c.cfg.auxResolver, c.cfg.auxSigner, ) if err != nil { return err @@ -1681,6 +1685,7 @@ func (c *chainWatcher) dispatchRemoteForceClose( uniClose, err := lnwallet.NewUnilateralCloseSummary( c.cfg.chanState, c.cfg.signer, commitSpend, remoteCommit, commitPoint, c.cfg.auxLeafStore, c.cfg.auxResolver, + c.cfg.auxSigner, ) if err != nil { return err diff --git a/input/size_test.go b/input/size_test.go index 7b193640703..1ef9f3186ad 100644 --- a/input/size_test.go +++ b/input/size_test.go @@ -1704,7 +1704,9 @@ func genSuccessTx(t *testing.T, chanType channeldb.ChannelType) *wire.MsgTx { }, } - sigHashType := lnwallet.HtlcSigHashType(channeldb.SingleFunderBit) + sigHashType := lnwallet.HtlcSigHashType( + channeldb.SingleFunderBit, + ) var successWitness [][]byte diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index 38f540454f5..75eae355db6 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -1,7 +1,9 @@ package lnwallet import ( + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/lntypes" @@ -305,4 +307,48 @@ type AuxSigner interface { // sig jobs. VerifySecondLevelSigs(chanState AuxChanState, commitTx *wire.MsgTx, verifyJob []AuxVerifyJob) error + + // HtlcSigHashType returns the sighash type to use for HTLC + // second-level transactions for the given channel. The caller + // populates HtlcSigHashReq with either a ChanID (for live + // feature-negotiation lookups on new commitments) or a CommitBlob + // (for existing commitments where the blob is the source of truth), + // or both. The implementation decides the lookup strategy. + HtlcSigHashType( + req HtlcSigHashReq, + ) fn.Option[txscript.SigHashType] +} + +// HtlcSigHashReq is the request passed to AuxSigner.HtlcSigHashType. +// Callers populate either ChanID (for next-commitment signing/verification +// where live feature negotiation is authoritative) or CommitBlob (for +// existing commitments where the blob records what was actually used), or +// both. +type HtlcSigHashReq struct { + // ChanID identifies the channel for live feature-negotiation lookups. + // Set when determining the sighash for a new commitment being + // signed or verified. + ChanID fn.Option[lnwire.ChannelID] + + // CommitBlob is the commitment custom blob that may contain a cached + // SigHashDefault flag. Set when resolving the sighash for an + // already-persisted commitment (breach, resolution). + CommitBlob fn.Option[tlv.Blob] +} + +// ResolveHtlcSigHashType determines the sighash type to use for HTLC +// second-level transactions. It queries the aux signer (if present) with the +// given request. If the aux signer returns None (or is not present), it falls +// back to the default HtlcSigHashType based on channel type. +func ResolveHtlcSigHashType(chanType channeldb.ChannelType, + auxSigner fn.Option[AuxSigner], + req HtlcSigHashReq) txscript.SigHashType { + + sigHash := fn.FlatMapOption( + func(s AuxSigner) fn.Option[txscript.SigHashType] { + return s.HtlcSigHashType(req) + }, + )(auxSigner) + + return sigHash.UnwrapOr(HtlcSigHashType(chanType)) } diff --git a/lnwallet/channel.go b/lnwallet/channel.go index d0c1169808e..f50f1f35b52 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -3440,7 +3440,8 @@ func (lc *LightningChannel) evaluateNoOpHtlc(entry *paymentDescriptor, func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, chanState *chanstate.OpenChannel, leaseExpiry uint32, remoteCommitView *commitment, - leafStore fn.Option[AuxLeafStore]) ([]SignJob, []AuxSigJob, + leafStore fn.Option[AuxLeafStore], + auxSigner fn.Option[AuxSigner]) ([]SignJob, []AuxSigJob, chan struct{}, error) { var ( @@ -3453,7 +3454,14 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, txHash := remoteCommitView.txn.TxHash() dustLimit := remoteChanCfg.DustLimit feePerKw := remoteCommitView.feePerKw - sigHashType := HtlcSigHashType(chanType) + sigHashType := ResolveHtlcSigHashType( + chanType, auxSigner, HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + chanState.FundingOutpoint, + )), + CommitBlob: remoteCommitView.customBlob, + }, + ) // With the keys generated, we'll make a slice with enough capacity to // hold potentially all the HTLCs. The actual slice may be a bit @@ -4316,7 +4324,7 @@ func (lc *LightningChannel) SignNextCommitment( } sigBatch, auxSigBatch, cancelChan, err := genRemoteHtlcSigJobs( keyRing, lc.channelState, leaseExpiry, newCommitView, - lc.leafStore, + lc.leafStore, lc.auxSigner, ) if err != nil { return nil, err @@ -5082,7 +5090,14 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, txHash := localCommitmentView.txn.TxHash() feePerKw := localCommitmentView.feePerKw - sigHashType := HtlcSigHashType(chanType) + sigHashType := ResolveHtlcSigHashType( + chanType, auxSigner, HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + chanState.FundingOutpoint, + )), + CommitBlob: localCommitmentView.customBlob, + }, + ) // With the required state generated, we'll create a slice with large // enough capacity to hold verification jobs for all HTLC's in this @@ -7176,7 +7191,8 @@ func NewUnilateralCloseSummary(chanState *chanstate.OpenChannel, signer input.Signer, commitSpend *chainntnfs.SpendDetail, remoteCommit channeldb.ChannelCommitment, commitPoint *btcec.PublicKey, leafStore fn.Option[AuxLeafStore], - auxResolver fn.Option[AuxContractResolver]) (*UnilateralCloseSummary, + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*UnilateralCloseSummary, error) { // First, we'll generate the commitment point and the revocation point @@ -7219,7 +7235,7 @@ func NewUnilateralCloseSummary(chanState *chanstate.OpenChannel, &chanState.RemoteChanCfg, commitSpend.SpendingTx, commitTxHeight, chanState.ChanType, isRemoteInitiator, leaseExpiry, chanState, auxResult.AuxLeaves, - auxResolver, + auxResolver, auxSigner, ) if err != nil { return nil, fmt.Errorf("unable to create htlc resolutions: %w", @@ -7529,6 +7545,7 @@ func newOutgoingHtlcResolution(signer input.Signer, chanType channeldb.ChannelType, chanState *chanstate.OpenChannel, auxLeaves fn.Option[CommitAuxLeaves], auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner], ) (*OutgoingHtlcResolution, error) { op := wire.OutPoint{ @@ -7693,7 +7710,11 @@ func newOutgoingHtlcResolution(signer input.Signer, // With the sign desc created, we can now construct the full witness // for the timeout transaction, and populate it as well. - sigHashType := HtlcSigHashType(chanType) + sigHashType := ResolveHtlcSigHashType( + chanType, auxSigner, HtlcSigHashReq{ + CommitBlob: chanState.LocalCommitment.CustomBlob, + }, + ) var timeoutWitness wire.TxWitness if scriptTree, ok := htlcScriptInfo.(input.TapscriptDescriptor); ok { timeoutSignDesc.SignMethod = input.TaprootScriptSpendSignMethod @@ -7904,6 +7925,7 @@ func newIncomingHtlcResolution(signer input.Signer, chanType channeldb.ChannelType, chanState *chanstate.OpenChannel, auxLeaves fn.Option[CommitAuxLeaves], auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner], ) (*IncomingHtlcResolution, error) { op := wire.OutPoint{ @@ -8066,7 +8088,11 @@ func newIncomingHtlcResolution(signer input.Signer, // will be supplied by the contract resolver, either directly or when it // becomes known. var successWitness wire.TxWitness - sigHashType := HtlcSigHashType(chanType) + sigHashType := ResolveHtlcSigHashType( + chanType, auxSigner, HtlcSigHashReq{ + CommitBlob: chanState.LocalCommitment.CustomBlob, + }, + ) if scriptTree, ok := scriptInfo.(input.TapscriptDescriptor); ok { successSignDesc.SignMethod = input.TaprootScriptSpendSignMethod @@ -8399,7 +8425,8 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, chanType channeldb.ChannelType, isCommitFromInitiator bool, leaseExpiry uint32, chanState *chanstate.OpenChannel, auxLeaves fn.Option[CommitAuxLeaves], - auxResolver fn.Option[AuxContractResolver]) (*HtlcResolutions, error) { + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*HtlcResolutions, error) { // TODO(roasbeef): don't need to swap csv delay? dustLimit := remoteChanCfg.DustLimit @@ -8434,6 +8461,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, &htlc, keyRing, feePerKw, uint32(csvDelay), leaseExpiry, whoseCommit, isCommitFromInitiator, chanType, chanState, auxLeaves, auxResolver, + auxSigner, ) if err != nil { return nil, fmt.Errorf("incoming resolution "+ @@ -8448,7 +8476,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, signer, localChanCfg, commitTx, commitTxHeight, &htlc, keyRing, feePerKw, uint32(csvDelay), leaseExpiry, whoseCommit, isCommitFromInitiator, chanType, chanState, - auxLeaves, auxResolver, + auxLeaves, auxResolver, auxSigner, ) if err != nil { return nil, fmt.Errorf("outgoing resolution "+ @@ -8595,7 +8623,7 @@ func (lc *LightningChannel) ForceClose(opts ...ForceCloseOpt) ( summary, err := NewLocalForceCloseSummary( lc.channelState, lc.Signer, commitTx, 0, localCommitment.CommitHeight, lc.leafStore, - lc.auxResolver, + lc.auxResolver, lc.auxSigner, ) if err != nil { return nil, fmt.Errorf("unable to gen force close "+ @@ -8614,8 +8642,8 @@ func (lc *LightningChannel) ForceClose(opts ...ForceCloseOpt) ( func NewLocalForceCloseSummary(chanState *chanstate.OpenChannel, signer input.Signer, commitTx *wire.MsgTx, commitTxHeight uint32, stateNum uint64, leafStore fn.Option[AuxLeafStore], - auxResolver fn.Option[AuxContractResolver]) (*LocalForceCloseSummary, - error) { + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*LocalForceCloseSummary, error) { // Re-derive the original pkScript for to-self output within the // commitment transaction. We'll need this to find the corresponding @@ -8784,7 +8812,7 @@ func NewLocalForceCloseSummary(chanState *chanstate.OpenChannel, signer, localCommit.Htlcs, keyRing, &chanState.LocalChanCfg, &chanState.RemoteChanCfg, commitTx, commitTxHeight, chanState.ChanType, chanState.IsInitiator, leaseExpiry, - chanState, auxResult.AuxLeaves, auxResolver, + chanState, auxResult.AuxLeaves, auxResolver, auxSigner, ) if err != nil { return nil, fmt.Errorf("unable to gen htlc resolution: %w", err) diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 820932ac4ee..59e409cb4ca 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -6483,6 +6483,7 @@ func TestChannelUnilateralCloseHtlcResolution(t *testing.T) { aliceChannel.channelState.RemoteCurrentRevocation, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create alice close summary") @@ -6629,6 +6630,7 @@ func TestChannelUnilateralClosePendingCommit(t *testing.T) { aliceChannel.channelState.RemoteCurrentRevocation, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create alice close summary") @@ -6648,6 +6650,7 @@ func TestChannelUnilateralClosePendingCommit(t *testing.T) { aliceChannel.channelState.RemoteNextRevocation, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create alice close summary") diff --git a/lnwallet/commitment.go b/lnwallet/commitment.go index 78b82125b6e..c8fb778d156 100644 --- a/lnwallet/commitment.go +++ b/lnwallet/commitment.go @@ -376,8 +376,11 @@ func CommitScriptToRemote(chanType channeldb.ChannelType, initiator bool, } } -// HtlcSigHashType returns the sighash type to use for HTLC success and timeout -// transactions given the channel type. +// HtlcSigHashType returns the default sighash type to use for HTLC success +// and timeout transactions given the channel type. For channels where an +// AuxSigner is available, use ResolveHtlcSigHashType instead, which queries +// the aux signer for a channel-specific override based on negotiated feature +// bits. func HtlcSigHashType(chanType channeldb.ChannelType) txscript.SigHashType { if chanType.HasAnchors() { return txscript.SigHashSingle | txscript.SigHashAnyOneCanPay diff --git a/lnwallet/mock.go b/lnwallet/mock.go index a8982ef90fc..1af8e233a92 100644 --- a/lnwallet/mock.go +++ b/lnwallet/mock.go @@ -13,6 +13,7 @@ import ( "github.com/btcsuite/btcd/chaincfg/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/btcsuite/btcwallet/waddrmgr" base "github.com/btcsuite/btcwallet/wallet" @@ -525,6 +526,13 @@ func (a *MockAuxSigner) VerifySecondLevelSigs(chanState AuxChanState, return args.Error(0) } +// HtlcSigHashType returns None, deferring to the default sighash behavior. +func (a *MockAuxSigner) HtlcSigHashType( + _ HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + return fn.None[txscript.SigHashType]() +} + type MockAuxContractResolver struct{} // ResolveContract is called to resolve a contract that needs From f9c7158f89a1ed753d0528577bb2e37bb146b95c Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:12 +0300 Subject: [PATCH 09/17] lnwallet: bake fees into second-level HTLCs under SigHashDefault When the channel uses SigHashDefault for HTLC second-level transactions, the sweeper cannot add wallet inputs to pay fees (that would invalidate the peer's signature). Instead, the fee must be baked into the pre-signed transaction at commitment signing time. Add sigHashDefaultFeeRate (3x FeePerKwFloor = 759 sat/kw) and thread a sigHashDefault bool through HtlcTimeoutFee, HtlcSuccessFee, HtlcIsDust, CommitmentBuilder, and all call sites in channel.go, htlcswitch/link.go, and the HTLC resolution construction paths. This results in: - Timeout tx fee: 759 * 645 / 1000 = 489 sat - Success tx fee: 759 * 705 / 1000 = 535 sat The 3x multiplier ensures the pre-signed tx clears the mempool minimum even when nodes compute fee rate against raw serialized size rather than virtual size. Add an IsSigHashDefault convenience helper and IsChanSigHashDefault / isSigHashDefault methods on LightningChannel. For next-commitment call sites (genRemoteHtlcSigJobs, genHtlcSigValidationJobs), extract the sigHashReq into a local variable so it can be shared between ResolveHtlcSigHashType and IsSigHashDefault. Use chanState.LocalCommitment.CustomBlob as the CommitBlob source (instead of the in-memory commitment view blob) since the persisted commitment already carries the SigHashDefault flag. NewBreachRetribution now takes an AuxSigner option so it can resolve the sighash type when computing dust thresholds for HTLC retribution data. --- contractcourt/breach_arbitrator_test.go | 2 + contractcourt/chain_watcher.go | 1 + htlcswitch/link.go | 7 +- htlcswitch/mailbox_test.go | 2 +- htlcswitch/mock.go | 1 + lnwallet/aux_signer.go | 13 +++ lnwallet/channel.go | 137 ++++++++++++++++++------ lnwallet/channel_test.go | 103 ++++++++++++++++-- lnwallet/commitment.go | 57 ++++++++-- server.go | 1 + 10 files changed, 272 insertions(+), 52 deletions(-) diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index f7daf17e8d3..96216f76bda 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -1590,6 +1590,7 @@ func testBreachSpends(t *testing.T, test breachTest) { fn.Some[lnwallet.AuxContractResolver]( &lnwallet.MockAuxContractResolver{}, ), + fn.None[lnwallet.AuxSigner](), ) require.NoError(t, err, "unable to create breach retribution") @@ -1805,6 +1806,7 @@ func TestBreachDelayedJusticeConfirmation(t *testing.T) { fn.Some[lnwallet.AuxContractResolver]( &lnwallet.MockAuxContractResolver{}, ), + fn.None[lnwallet.AuxSigner](), ) require.NoError(t, err, "unable to create breach retribution") diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index ca4af9d0841..6fb9fbb068a 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -1164,6 +1164,7 @@ func (c *chainWatcher) handlePossibleBreach(commitSpend *chainntnfs.SpendDetail, retribution, err := lnwallet.NewBreachRetribution( c.cfg.chanState, broadcastStateNum, spendHeight, commitSpend.SpendingTx, c.cfg.auxLeafStore, c.cfg.auxResolver, + c.cfg.auxSigner, ) switch { diff --git a/htlcswitch/link.go b/htlcswitch/link.go index 9e3adf0bbc2..5976f2d0f8e 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -2206,7 +2206,8 @@ func (l *channelLink) getDustClosure() dustClosure { remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit chanType := l.channel.State().ChanType - return dustHelper(chanType, localDustLimit, remoteDustLimit) + return dustHelper(chanType, localDustLimit, remoteDustLimit, + l.channel.IsChanSigHashDefault()) } // getCommitFee returns either the local or remote CommitFee in satoshis. This @@ -2374,7 +2375,7 @@ type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool, // dustHelper is used to construct the dustClosure. func dustHelper(chantype chanstate.ChannelType, localDustLimit, - remoteDustLimit btcutil.Amount) dustClosure { + remoteDustLimit btcutil.Amount, sigHashDefault bool) dustClosure { isDust := func(feerate chainfee.SatPerKWeight, incoming bool, whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool { @@ -2388,7 +2389,7 @@ func dustHelper(chantype chanstate.ChannelType, localDustLimit, return lnwallet.HtlcIsDust( chantype, incoming, whoseCommit, feerate, amt, - dustLimit, + dustLimit, sigHashDefault, ) } diff --git a/htlcswitch/mailbox_test.go b/htlcswitch/mailbox_test.go index b732694a6c4..061af337ac9 100644 --- a/htlcswitch/mailbox_test.go +++ b/htlcswitch/mailbox_test.go @@ -604,7 +604,7 @@ func testMailBoxDust(t *testing.T, chantype chanstate.ChannelType) { localDustLimit := btcutil.Amount(400) remoteDustLimit := btcutil.Amount(500) - isDust := dustHelper(chantype, localDustLimit, remoteDustLimit) + isDust := dustHelper(chantype, localDustLimit, remoteDustLimit, false) ctx.mailbox.SetDustClosure(isDust) // The first packet will be dust according to the remote dust limit, diff --git a/htlcswitch/mock.go b/htlcswitch/mock.go index a3079e69628..849e77a10e7 100644 --- a/htlcswitch/mock.go +++ b/htlcswitch/mock.go @@ -835,6 +835,7 @@ func (f *mockChannelLink) getDustClosure() dustClosure { dustLimit := btcutil.Amount(400) return dustHelper( channeldb.SingleFunderTweaklessBit, dustLimit, dustLimit, + false, ) } diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index 75eae355db6..1f6d9cc0018 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -352,3 +352,16 @@ func ResolveHtlcSigHashType(chanType channeldb.ChannelType, return sigHash.UnwrapOr(HtlcSigHashType(chanType)) } + +// IsSigHashDefault returns true if the resolved HTLC sighash type for the +// given channel is SigHashDefault. This is used to determine whether +// second-level HTLC transactions must carry their own fee (since the sweeper +// cannot add wallet inputs under SigHashDefault). +func IsSigHashDefault(chanType channeldb.ChannelType, + auxSigner fn.Option[AuxSigner], + req HtlcSigHashReq) bool { + + return ResolveHtlcSigHashType( + chanType, auxSigner, req, + ) == txscript.SigHashDefault +} diff --git a/lnwallet/channel.go b/lnwallet/channel.go index f50f1f35b52..23056361b6c 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -311,7 +311,7 @@ func locateOutputIndex(p *paymentDescriptor, tx *wire.MsgTx, // the current state to disk, and also to locate the paymentDescriptor // corresponding to HTLC outputs in the commitment transaction. func (c *commitment) populateHtlcIndexes(chanType channeldb.ChannelType, - cltvs []uint32) error { + cltvs []uint32, sigHashDefault bool) error { // First, we'll set up some state to allow us to locate the output // index of the all the HTLCs within the commitment transaction. We @@ -327,6 +327,7 @@ func (c *commitment) populateHtlcIndexes(chanType channeldb.ChannelType, isDust := HtlcIsDust( chanType, incoming, c.whoseCommit, c.feePerKw, htlc.Amount.ToSatoshis(), c.dustLimit, + sigHashDefault, ) var err error @@ -479,6 +480,23 @@ func (c *commitment) toDiskCommit( return commit } +// IsChanSigHashDefault returns whether HTLC second-level transactions for +// this channel use SigHashDefault. +func (lc *LightningChannel) IsChanSigHashDefault() bool { + chanID := lnwire.NewChanIDFromOutPoint( + lc.channelState.FundingOutpoint, + ) + + return IsSigHashDefault( + lc.channelState.ChanType, + lc.auxSigner, + HtlcSigHashReq{ + ChanID: fn.Some(chanID), + CommitBlob: lc.channelState.LocalCommitment.CustomBlob, + }, + ) +} + // diskHtlcToPayDesc converts an HTLC previously written to disk within a // commitment state to the form required to manipulate in memory within the // commitment struct and updateLog. This function is used when we need to @@ -507,6 +525,7 @@ func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight, isDustLocal := HtlcIsDust( chanType, htlc.Incoming, lntypes.Local, feeRate, htlc.Amt.ToSatoshis(), lc.channelState.LocalChanCfg.DustLimit, + lc.IsChanSigHashDefault(), ) localCommitKeys := commitKeys.GetForParty(lntypes.Local) if !isDustLocal && localCommitKeys != nil { @@ -524,6 +543,7 @@ func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight, isDustRemote := HtlcIsDust( chanType, htlc.Incoming, lntypes.Remote, feeRate, htlc.Amt.ToSatoshis(), lc.channelState.RemoteChanCfg.DustLimit, + lc.IsChanSigHashDefault(), ) remoteCommitKeys := commitKeys.GetForParty(lntypes.Remote) if !isDustRemote && remoteCommitKeys != nil { @@ -1000,7 +1020,19 @@ func NewLightningChannel(signer input.Signer, commitChains: commitChains, channelState: state, commitBuilder: NewCommitmentBuilder( - state, opts.leafStore, + state, opts.leafStore, IsSigHashDefault( + state.ChanType, opts.auxSigner, + HtlcSigHashReq{ + ChanID: fn.Some( + lnwire.NewChanIDFromOutPoint( + state.FundingOutpoint, + ), + ), + CommitBlob: state. + LocalCommitment. + CustomBlob, + }, + ), ), updateLogs: updateLogs, Capacity: state.Capacity, @@ -1159,6 +1191,7 @@ func (lc *LightningChannel) logUpdateToPayDesc(logUpdate *channeldb.LogUpdate, isDustRemote := HtlcIsDust( lc.channelState.ChanType, false, lntypes.Remote, feeRate, wireMsg.Amount.ToSatoshis(), remoteDustLimit, + lc.IsChanSigHashDefault(), ) if !isDustRemote { auxLeaf := fn.FlatMapOption( @@ -2105,7 +2138,8 @@ type BreachRetribution struct { func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, breachHeight uint32, spendTx *wire.MsgTx, leafStore fn.Option[AuxLeafStore], - auxResolver fn.Option[AuxContractResolver]) (*BreachRetribution, + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*BreachRetribution, error) { // Query the on-disk revocation log for the snapshot which was recorded @@ -2224,7 +2258,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, br, ourAmt, theirAmt, err = createBreachRetributionLegacy( revokedLogLegacy, chanState, keyRing, commitmentSecret, ourScript, theirScript, leaseExpiry, auxResolver, - breachHeight, + auxSigner, breachHeight, ) if err != nil { return nil, err @@ -2742,6 +2776,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, commitmentSecret *btcec.PrivateKey, ourScript, theirScript input.ScriptDescriptor, leaseExpiry uint32, auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner], breachHeight uint32) (*BreachRetribution, int64, int64, error) { commitHash := revokedLog.CommitTx.TxHash() @@ -2775,6 +2810,14 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chainfee.SatPerKWeight(revokedLog.FeePerKw), htlc.Amt.ToSatoshis(), chanState.RemoteChanCfg.DustLimit, + IsSigHashDefault( + chanState.ChanType, + auxSigner, + HtlcSigHashReq{ + CommitBlob: chanState. + LocalCommitment.CustomBlob, + }, + ), ) { continue @@ -2821,6 +2864,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, func HtlcIsDust(chanType channeldb.ChannelType, incoming bool, whoseCommit lntypes.ChannelParty, feePerKw chainfee.SatPerKWeight, htlcAmt, dustLimit btcutil.Amount, + sigHashDefault bool, ) bool { // First we'll determine the fee required for this HTLC based on if this is @@ -2832,25 +2876,25 @@ func HtlcIsDust(chanType channeldb.ChannelType, // If this is an incoming HTLC on our commitment transaction, then the // second-level transaction will be a success transaction. case incoming && whoseCommit.IsLocal(): - htlcFee = HtlcSuccessFee(chanType, feePerKw) + htlcFee = HtlcSuccessFee(chanType, feePerKw, sigHashDefault) // If this is an incoming HTLC on their commitment transaction, then // we'll be using a second-level timeout transaction as they've added // this HTLC. case incoming && whoseCommit.IsRemote(): - htlcFee = HtlcTimeoutFee(chanType, feePerKw) + htlcFee = HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) // If this is an outgoing HTLC on our commitment transaction, then // we'll be using a timeout transaction as we're the sender of the // HTLC. case !incoming && whoseCommit.IsLocal(): - htlcFee = HtlcTimeoutFee(chanType, feePerKw) + htlcFee = HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) // If this is an outgoing HTLC on their commitment transaction, then // we'll be using an HTLC success transaction as they're the receiver // of this HTLC. case !incoming && whoseCommit.IsRemote(): - htlcFee = HtlcSuccessFee(chanType, feePerKw) + htlcFee = HtlcSuccessFee(chanType, feePerKw, sigHashDefault) } return (htlcAmt - htlcFee) < dustLimit @@ -3082,7 +3126,8 @@ func (lc *LightningChannel) fetchCommitmentView( // locations of each HTLC in the commitment state. We pass in the sorted // slice of CLTV deltas in order to properly locate HTLCs that otherwise // have the same payment hash and amount. - err = c.populateHtlcIndexes(lc.channelState.ChanType, commitTx.cltvs) + err = c.populateHtlcIndexes(lc.channelState.ChanType, commitTx.cltvs, + lc.IsChanSigHashDefault()) if err != nil { return nil, err } @@ -3454,13 +3499,14 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, txHash := remoteCommitView.txn.TxHash() dustLimit := remoteChanCfg.DustLimit feePerKw := remoteCommitView.feePerKw + sigHashReq := HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + chanState.FundingOutpoint, + )), + CommitBlob: chanState.LocalCommitment.CustomBlob, + } sigHashType := ResolveHtlcSigHashType( - chanType, auxSigner, HtlcSigHashReq{ - ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( - chanState.FundingOutpoint, - )), - CommitBlob: remoteCommitView.customBlob, - }, + chanType, auxSigner, sigHashReq, ) // With the keys generated, we'll make a slice with enough capacity to @@ -3491,10 +3537,14 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // For each outgoing and incoming HTLC, if the HTLC isn't considered a // dust output after taking into account second-level HTLC fees, then a // sigJob will be generated and appended to the current batch. + sigHashDefault := IsSigHashDefault( + chanType, auxSigner, sigHashReq, + ) for _, htlc := range remoteCommitView.incomingHTLCs { if HtlcIsDust( chanType, true, lntypes.Remote, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -3511,7 +3561,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // HTLC timeout transaction for them. The output of the timeout // transaction needs to account for fees, so we'll compute the // required fee and output now. - htlcFee := HtlcTimeoutFee(chanType, feePerKw) + htlcFee := HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption( @@ -3578,6 +3628,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, if HtlcIsDust( chanType, false, lntypes.Remote, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -3592,7 +3643,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // HTLC success transaction for them. The output of the timeout // transaction needs to account for fees, so we'll compute the // required fee and output now. - htlcFee := HtlcSuccessFee(chanType, feePerKw) + htlcFee := HtlcSuccessFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption( @@ -5034,6 +5085,7 @@ func (lc *LightningChannel) computeView(view *HtlcView, if HtlcIsDust( lc.channelState.ChanType, false, whoseCommitChain, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + lc.IsChanSigHashDefault(), ) { continue @@ -5045,6 +5097,7 @@ func (lc *LightningChannel) computeView(view *HtlcView, if HtlcIsDust( lc.channelState.ChanType, true, whoseCommitChain, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + lc.IsChanSigHashDefault(), ) { continue @@ -5090,13 +5143,17 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, txHash := localCommitmentView.txn.TxHash() feePerKw := localCommitmentView.feePerKw + sigHashReq := HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + chanState.FundingOutpoint, + )), + CommitBlob: chanState.LocalCommitment.CustomBlob, + } sigHashType := ResolveHtlcSigHashType( - chanType, auxSigner, HtlcSigHashReq{ - ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( - chanState.FundingOutpoint, - )), - CommitBlob: localCommitmentView.customBlob, - }, + chanType, auxSigner, sigHashReq, + ) + sigHashDefault := IsSigHashDefault( + chanType, auxSigner, sigHashReq, ) // With the required state generated, we'll create a slice with large @@ -5169,7 +5226,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, Index: uint32(htlc.localOutputIndex), } - htlcFee := HtlcSuccessFee(chanType, feePerKw) + htlcFee := HtlcSuccessFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption(func( @@ -5262,7 +5319,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, Index: uint32(htlc.localOutputIndex), } - htlcFee := HtlcTimeoutFee(chanType, feePerKw) + htlcFee := HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption(func( @@ -6407,6 +6464,7 @@ func (lc *LightningChannel) GetDustSum(whoseCommit lntypes.ChannelParty, // amount to the dust sum. if HtlcIsDust( chanType, false, whoseCommit, feeRate, amt, dustLimit, + lc.IsChanSigHashDefault(), ) { dustSum += pd.Amount @@ -6426,7 +6484,7 @@ func (lc *LightningChannel) GetDustSum(whoseCommit lntypes.ChannelParty, // amount to the dust sum. if HtlcIsDust( chanType, true, whoseCommit, feeRate, - amt, dustLimit, + amt, dustLimit, lc.IsChanSigHashDefault(), ) { dustSum += pd.Amount @@ -7664,7 +7722,12 @@ func newOutgoingHtlcResolution(signer input.Signer, // In order to properly reconstruct the HTLC transaction, we'll need to // re-calculate the fee required at this state, so we can add the // correct output value amount to the transaction. - htlcFee := HtlcTimeoutFee(chanType, feePerKw) + htlcFee := HtlcTimeoutFee(chanType, feePerKw, IsSigHashDefault( + chanType, auxSigner, + HtlcSigHashReq{ + CommitBlob: chanState.LocalCommitment.CustomBlob, + }, + )) secondLevelOutputAmt := htlc.Amt.ToSatoshis() - htlcFee // With the fee calculated, re-construct the second level timeout @@ -8049,7 +8112,12 @@ func newIncomingHtlcResolution(signer input.Signer, // // First, we'll reconstruct the original HTLC success transaction, // taking into account the fee rate used. - htlcFee := HtlcSuccessFee(chanType, feePerKw) + htlcFee := HtlcSuccessFee(chanType, feePerKw, IsSigHashDefault( + chanType, auxSigner, + HtlcSigHashReq{ + CommitBlob: chanState.LocalCommitment.CustomBlob, + }, + )) secondLevelOutputAmt := htlc.Amt.ToSatoshis() - htlcFee successTx, err := CreateHtlcSuccessTx( chanType, isCommitFromInitiator, op, secondLevelOutputAmt, @@ -8446,6 +8514,13 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, if HtlcIsDust( chanType, htlc.Incoming, whoseCommit, feePerKw, htlc.Amt.ToSatoshis(), dustLimit, + IsSigHashDefault( + chanType, auxSigner, + HtlcSigHashReq{ + CommitBlob: chanState. + LocalCommitment.CustomBlob, + }, + ), ) { continue @@ -9569,7 +9644,8 @@ func (lc *LightningChannel) availableCommitmentBalance(view *HtlcView, // For an extra HTLC fee to be paid on our commitment, the HTLC must be // large enough to make a non-dust HTLC timeout transaction. htlcFee := lnwire.NewMSatFromSatoshis( - HtlcTimeoutFee(lc.channelState.ChanType, feePerKw), + HtlcTimeoutFee(lc.channelState.ChanType, feePerKw, + lc.IsChanSigHashDefault()), ) // If we are looking at the remote commitment, we must use the remote @@ -9579,7 +9655,8 @@ func (lc *LightningChannel) availableCommitmentBalance(view *HtlcView, lc.channelState.RemoteChanCfg.DustLimit, ) htlcFee = lnwire.NewMSatFromSatoshis( - HtlcSuccessFee(lc.channelState.ChanType, feePerKw), + HtlcSuccessFee(lc.channelState.ChanType, feePerKw, + lc.IsChanSigHashDefault()), ) } diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 59e409cb4ca..c7a3d9635a5 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -1561,6 +1561,7 @@ func TestHTLCDustLimit(t *testing.T) { chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ), + false, )) htlcAmount := lnwire.NewMSatFromSatoshis(htlcSat) @@ -1655,10 +1656,10 @@ func TestHTLCSigNumber(t *testing.T) { require.NoError(t, err, "unable to get fee") belowDust := btcutil.Amount(500) + HtlcTimeoutFee( - channeldb.SingleFunderTweaklessBit, feePerKw, + channeldb.SingleFunderTweaklessBit, feePerKw, false, ) aboveDust := btcutil.Amount(1400) + HtlcSuccessFee( - channeldb.SingleFunderTweaklessBit, feePerKw, + channeldb.SingleFunderTweaklessBit, feePerKw, false, ) // =================================================================== @@ -1806,6 +1807,7 @@ func TestChannelBalanceDustLimit(t *testing.T) { chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ), + false, ) htlcAmount := lnwire.NewMSatFromSatoshis(htlcSat) @@ -5780,11 +5782,12 @@ func TestChanAvailableBalanceNearHtlcFee(t *testing.T) { commitFee := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalCommitment.CommitFee, ) + chanType := aliceChannel.channelState.ChanType htlcTimeoutFee := lnwire.NewMSatFromSatoshis( - HtlcTimeoutFee(aliceChannel.channelState.ChanType, feeRate), + HtlcTimeoutFee(chanType, feeRate, false), ) htlcSuccessFee := lnwire.NewMSatFromSatoshis( - HtlcSuccessFee(aliceChannel.channelState.ChanType, feeRate), + HtlcSuccessFee(chanType, feeRate, false), ) // Helper method to check the current reported balance. @@ -5951,11 +5954,12 @@ func TestChanCommitWeightDustHtlcs(t *testing.T) { feeRate := chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) + chanType := aliceChannel.channelState.ChanType htlcTimeoutFee := lnwire.NewMSatFromSatoshis( - HtlcTimeoutFee(aliceChannel.channelState.ChanType, feeRate), + HtlcTimeoutFee(chanType, feeRate, false), ) htlcSuccessFee := lnwire.NewMSatFromSatoshis( - HtlcSuccessFee(aliceChannel.channelState.ChanType, feeRate), + HtlcSuccessFee(chanType, feeRate, false), ) // Helper method to add an HTLC from Alice to Bob. @@ -7298,6 +7302,7 @@ func TestChanReserveLocalInitiatorDustHtlc(t *testing.T) { chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ), + false, ) // Set Alice's channel reserve to be low enough to carry the value of @@ -7477,6 +7482,7 @@ func TestNewBreachRetributionSkipsDustHtlcs(t *testing.T) { aliceChannel.channelState, revokedStateNum, 100, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create breach retribution") @@ -10376,7 +10382,7 @@ func TestCreateBreachRetributionLegacy(t *testing.T) { br, ourAmt, theirAmt, err := createBreachRetributionLegacy( &revokedLog, aliceChannel.channelState, keyRing, dummyPrivate, ourScript, theirScript, leaseExpiry, - fn.None[AuxContractResolver](), 0, + fn.None[AuxContractResolver](), fn.None[AuxSigner](), 0, ) require.NoError(t, err) @@ -10439,6 +10445,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrNoPastDeltas) @@ -10448,6 +10455,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, nil, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrNoPastDeltas) @@ -10495,6 +10503,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err) @@ -10508,6 +10517,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, nil, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err) assertRetribution(br, 1, 0) @@ -10518,6 +10528,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum+1, breachHeight, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrLogEntryNotFound) @@ -10527,6 +10538,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum+1, breachHeight, nil, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrLogEntryNotFound) } @@ -10821,7 +10833,9 @@ func TestAsynchronousSendingContraint(t *testing.T) { // |<----add------- // make sure this htlc is non-dust for alice. - htlcFee := HtlcSuccessFee(channeldb.SingleFunderTweaklessBit, feePerKw) + htlcFee := HtlcSuccessFee( + channeldb.SingleFunderTweaklessBit, feePerKw, false, + ) // We need to take the remote dustlimit amount, because it the greater // one. htlcAmt2 := lnwire.NewMSatFromSatoshis( @@ -10955,7 +10969,9 @@ func TestAsynchronousSendingWithFeeBuffer(t *testing.T) { // commitment as well. // |<----add------- // make sure this htlc is non-dust for alice. - htlcFee := HtlcSuccessFee(channeldb.SingleFunderTweaklessBit, feePerKw) + htlcFee := HtlcSuccessFee( + channeldb.SingleFunderTweaklessBit, feePerKw, false, + ) htlcAmt2 := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalChanCfg.DustLimit + htlcFee, ) @@ -11039,7 +11055,9 @@ func TestAsynchronousSendingWithFeeBuffer(t *testing.T) { // --------------- |-----sig------> // <----rev------- |--------------- // Update the non-dust amount because we updated the fee by 100%. - htlcFee = HtlcSuccessFee(channeldb.SingleFunderTweaklessBit, feePerKw*2) + htlcFee = HtlcSuccessFee( + channeldb.SingleFunderTweaklessBit, feePerKw*2, false, + ) htlcAmt3 := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalChanCfg.DustLimit + htlcFee, ) @@ -11961,3 +11979,68 @@ func TestEvaluateNoOpHtlc(t *testing.T) { require.Equal(t, tc.expectedDeltas, tc.balanceDeltas) } } + +// TestHtlcFeesSigHashDefault verifies that HtlcTimeoutFee and +// HtlcSuccessFee return non-zero baked-in fees for taproot channels +// with sigHashDefault=true, using the fixed sigHashDefaultFeeRate. +func TestHtlcFeesSigHashDefault(t *testing.T) { + t.Parallel() + + taprootChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + + // With sigHashDefault=false, taproot channels have zero + // second-level fees (zero-fee HTLC path). + timeoutFeeOff := HtlcTimeoutFee(taprootChanType, 0, false) + successFeeOff := HtlcSuccessFee(taprootChanType, 0, false) + require.Zero(t, timeoutFeeOff, + "taproot timeout fee should be zero without sigHashDefault") + require.Zero(t, successFeeOff, + "taproot success fee should be zero without sigHashDefault") + + // With sigHashDefault=true, taproot channels use baked-in fees + // at sigHashDefaultFeeRate regardless of the passed feePerKw. + timeoutFeeOn := HtlcTimeoutFee(taprootChanType, 0, true) + successFeeOn := HtlcSuccessFee(taprootChanType, 0, true) + require.NotZero(t, timeoutFeeOn, + "taproot timeout fee should be non-zero with sigHashDefault") + require.NotZero(t, successFeeOn, + "taproot success fee should be non-zero with sigHashDefault") + + // The fee should be deterministic and match the expected weight + // calculation. + expectedTimeout := sigHashDefaultFeeRate.FeeForWeight( + input.TaprootHtlcTimeoutWeight, + ) + expectedSuccess := sigHashDefaultFeeRate.FeeForWeight( + input.TaprootHtlcSuccessWeight, + ) + require.Equal(t, expectedTimeout, timeoutFeeOn) + require.Equal(t, expectedSuccess, successFeeOn) + + // The fee should be independent of the passed feePerKw. + highFeeRate := chainfee.SatPerKWeight(50_000) + timeoutFeeHigh := HtlcTimeoutFee( + taprootChanType, highFeeRate, true, + ) + successFeeHigh := HtlcSuccessFee( + taprootChanType, highFeeRate, true, + ) + require.Equal(t, timeoutFeeOn, timeoutFeeHigh, + "sigHashDefault fee should not depend on feePerKw") + require.Equal(t, successFeeOn, successFeeHigh, + "sigHashDefault fee should not depend on feePerKw") + + // Non-taproot channel types should not be affected by + // sigHashDefault flag. + anchorChanType := channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + anchorTimeoutFee := HtlcTimeoutFee( + anchorChanType, highFeeRate, true, + ) + require.Zero(t, anchorTimeoutFee, + "non-taproot zero-fee channel should still have zero fee") +} diff --git a/lnwallet/commitment.go b/lnwallet/commitment.go index c8fb778d156..999ee396e5c 100644 --- a/lnwallet/commitment.go +++ b/lnwallet/commitment.go @@ -509,12 +509,31 @@ func CommitWeight(chanType channeldb.ChannelType) lntypes.WeightUnit { } } +// sigHashDefaultFeeRate is the fee rate used for baked-in second-level HTLC +// transaction fees when SigHashDefault is active. We use 3x the floor relay +// rate to ensure the pre-signed transaction clears the mempool minimum fee +// even when nodes compute fee rate using the full serialized size (including +// witness data) rather than the virtual size. +const sigHashDefaultFeeRate = 3 * chainfee.FeePerKwFloor + // HtlcTimeoutFee returns the fee in satoshis required for an HTLC timeout -// transaction based on the current fee rate. +// transaction based on the current fee rate. When sigHashDefault is true and +// the channel is taproot, a fixed fee rate is used because the pre-signed +// second-level tx must carry its own fee (the sweeper cannot add wallet +// inputs under SigHashDefault). func HtlcTimeoutFee(chanType channeldb.ChannelType, - feePerKw chainfee.SatPerKWeight) btcutil.Amount { + feePerKw chainfee.SatPerKWeight, + sigHashDefault bool) btcutil.Amount { switch { + // For taproot channels with SigHashDefault, the second-level tx must + // pay its own fee. We use a rate well above the floor to account for + // nodes that check fee rate against the raw serialized size. + case chanType.IsTaproot() && sigHashDefault: + return sigHashDefaultFeeRate.FeeForWeight( + input.TaprootHtlcTimeoutWeight, + ) + // For zero-fee HTLC channels, this will always be zero, regardless of // feerate. case chanType.ZeroHtlcTxFee() || chanType.IsTaproot(): @@ -529,11 +548,23 @@ func HtlcTimeoutFee(chanType channeldb.ChannelType, } // HtlcSuccessFee returns the fee in satoshis required for an HTLC success -// transaction based on the current fee rate. +// transaction based on the current fee rate. When sigHashDefault is true and +// the channel is taproot, a fixed fee rate is used because the pre-signed +// second-level tx must carry its own fee (the sweeper cannot add wallet +// inputs under SigHashDefault). func HtlcSuccessFee(chanType channeldb.ChannelType, - feePerKw chainfee.SatPerKWeight) btcutil.Amount { + feePerKw chainfee.SatPerKWeight, + sigHashDefault bool) btcutil.Amount { switch { + // For taproot channels with SigHashDefault, the second-level tx must + // pay its own fee. We use a rate well above the floor to account for + // nodes that check fee rate against the raw serialized size. + case chanType.IsTaproot() && sigHashDefault: + return sigHashDefaultFeeRate.FeeForWeight( + input.TaprootHtlcSuccessWeight, + ) + // For zero-fee HTLC channels, this will always be zero, regardless of // feerate. case chanType.ZeroHtlcTxFee() || chanType.IsTaproot(): @@ -648,11 +679,16 @@ type CommitmentBuilder struct { // auxLeafStore is an interface that allows us to fetch auxiliary // tapscript leaves for the commitment output. auxLeafStore fn.Option[AuxLeafStore] + + // sigHashDefault indicates whether HTLC second-level transactions + // for this channel use SigHashDefault. + sigHashDefault bool } // NewCommitmentBuilder creates a new CommitmentBuilder from chanState. func NewCommitmentBuilder(chanState *chanstate.OpenChannel, - leafStore fn.Option[AuxLeafStore]) *CommitmentBuilder { + leafStore fn.Option[AuxLeafStore], + sigHashDefault bool) *CommitmentBuilder { // The anchor channel type MUST be tweakless. if chanState.ChanType.HasAnchors() && !chanState.ChanType.IsTweakless() { @@ -660,9 +696,10 @@ func NewCommitmentBuilder(chanState *chanstate.OpenChannel, } return &CommitmentBuilder{ - chanState: chanState, - obfuscator: createStateHintObfuscator(chanState), - auxLeafStore: leafStore, + chanState: chanState, + obfuscator: createStateHintObfuscator(chanState), + auxLeafStore: leafStore, + sigHashDefault: sigHashDefault, } } @@ -731,6 +768,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, false, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + cb.sigHashDefault, ) { continue @@ -742,6 +780,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, true, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + cb.sigHashDefault, ) { continue @@ -856,6 +895,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, false, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + cb.sigHashDefault, ) { continue @@ -884,6 +924,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, true, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + cb.sigHashDefault, ) { continue diff --git a/server.go b/server.go index 5e915ee88f1..e5959e31176 100644 --- a/server.go +++ b/server.go @@ -1832,6 +1832,7 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr, channel, commitHeight, 0, nil, implCfg.AuxLeafStore, implCfg.AuxContractResolver, + implCfg.AuxSigner, ) if err != nil { return nil, 0, err From d04c9b9c90d568bd09ac6c5d67873e10d7df1b64 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:13 +0300 Subject: [PATCH 10/17] contractcourt: publish pre-signed second-level HTLCs under SigHashDefault When the second-level HTLC transaction was signed with SigHashDefault (baked-in fees), the sweeper's normal tx-rebuilding flow would invalidate the peer's signature. Add isSigHashDefault() and publishTimeoutTx() / publishSuccessTx() to both the timeout and success resolvers, which bypass the sweeper and broadcast the pre-signed transaction directly. The Launch() method now checks isSigHashDefault() before falling through to the sweeper-based sweepTimeoutTx / sweepSuccessTx paths. Because the resolver publishes the second-level tx directly via PublishTx, the aux sweeper's NotifyBroadcast hook never fires for it and the aux resolver never gets a chance to import the second-level proof. To compensate, sweepSuccessTxOutput and sweepTimeoutTxOutput now call AuxResolver.ResolveContract once the pre-signed tx confirms (mirroring the breach arbiter's re-resolve pattern), using the new lnwallet.NewSecondLevelResolveReq helper to rebuild the resolution request with the actual second-level transaction. The resulting blob carries the imported 2nd-level proof, so the upcoming output sweep can find its input proof when the sweeper later offers it. --- contractcourt/contract_resolver.go | 21 +++++ contractcourt/htlc_success_resolver.go | 115 ++++++++++++++++++++++++- contractcourt/htlc_timeout_resolver.go | 114 +++++++++++++++++++++++- 3 files changed, 248 insertions(+), 2 deletions(-) diff --git a/contractcourt/contract_resolver.go b/contractcourt/contract_resolver.go index 66926b0415b..2a9b2ea1e8d 100644 --- a/contractcourt/contract_resolver.go +++ b/contractcourt/contract_resolver.go @@ -7,11 +7,13 @@ import ( "io" "sync/atomic" + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/btcsuite/btclog/v2" "github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/chanstate" "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/sweep" ) @@ -184,3 +186,22 @@ var ( // progressing because it received the quit signal. errResolverShuttingDown = errors.New("resolver shutting down") ) + +// isSecondLevelSigHashDefault returns true when a pre-signed second-level +// HTLC transaction was signed with SigHashDefault. In this case the tx +// has baked-in fees and must be broadcast as-is — the sweeper cannot add +// wallet inputs or change outputs without invalidating the peer's +// signature. +// +// The channel type is the authoritative gate: only aux (taproot-assets) +// channels — identified by TapscriptRootBit — use SigHashDefault for +// second-level HTLCs. Without this gate, the zero-value SigHashType +// (0x00 == SigHashDefault) would accidentally match on regular lnd +// channels that never explicitly populate SignDetails.SigHashType. +func isSecondLevelSigHashDefault(signDetails *input.SignDetails, + chanType channeldb.ChannelType) bool { + + return signDetails != nil && + signDetails.SigHashType == txscript.SigHashDefault && + chanType.HasTapscriptRoot() +} diff --git a/contractcourt/htlc_success_resolver.go b/contractcourt/htlc_success_resolver.go index 467641280a8..9f715c93593 100644 --- a/contractcourt/htlc_success_resolver.go +++ b/contractcourt/htlc_success_resolver.go @@ -419,6 +419,64 @@ func (h *htlcSuccessResolver) isZeroFeeOutput() bool { h.htlcResolution.SignDetails != nil } +// isSigHashDefault returns true when the second-level HTLC transaction +// was signed with SigHashDefault. See isSecondLevelSigHashDefault. +func (h *htlcSuccessResolver) isSigHashDefault() bool { + return isSecondLevelSigHashDefault( + h.htlcResolution.SignDetails, h.chanType, + ) +} + +// buildSecondLevelResolveReq returns a ResolutionReq targeting the +// just-confirmed second-level HTLC tx. The fast path clones the +// ResolveReq preserved on htlcResolution at force-close time and updates +// only the fields that differ for a second-level sweep. The slow path +// (used when the resolver was recovered from the briefcase and the +// in-memory ResolveReq is gone) reconstructs the request from historical +// channel state. +func (h *htlcSuccessResolver) buildSecondLevelResolveReq( + witType input.WitnessType, secondLevelTx *wire.MsgTx, + spendingHeight uint32) (*lnwallet.ResolutionReq, error) { + + if h.htlcResolution.ResolveReq != nil { + req := *h.htlcResolution.ResolveReq + req.Type = witType + req.SecondLevel = fn.Some(lnwallet.SecondLevelInfo{ + Tx: secondLevelTx, + BlockHeight: spendingHeight, + }) + + return &req, nil + } + + chanState, err := h.FetchHistoricalChannel() + if err != nil { + return nil, fmt.Errorf("fetch historical channel: %w", err) + } + + return lnwallet.NewSecondLevelResolveReq( + chanState, &h.htlc, h.htlcResolution.SignDetails, + h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, + h.broadcastHeight, secondLevelTx, spendingHeight, witType, + ) +} + +// publishSuccessTx directly broadcasts the pre-signed second-level HTLC +// success transaction. This is used when the transaction was signed with +// SigHashDefault (baked-in fees), where the sweeper's normal tx-rebuilding +// flow would invalidate the peer's signature. +func (h *htlcSuccessResolver) publishSuccessTx() error { + h.log.Infof("publishing pre-signed 2nd-level HTLC success tx=%v "+ + "(SigHashDefault, baked-in fees)", + h.htlcResolution.SignedSuccessTx.TxHash()) + + label := labels.MakeLabel( + labels.LabelTypeChannelClose, &h.ShortChanID, + ) + + return h.PublishTx(h.htlcResolution.SignedSuccessTx, label) +} + // isTaproot returns true if the resolver is for a taproot output. func (h *htlcSuccessResolver) isTaproot() bool { return txscript.IsPayToTaproot( @@ -605,12 +663,59 @@ func (h *htlcSuccessResolver) sweepSuccessTxOutput() error { default: witType = input.HtlcAcceptedSuccessSecondLevel } + + // Under DeterministicHTLCs the pre-signed second-level HTLC tx was + // published directly via PublishTx, bypassing the sweeper's + // NotifyBroadcast hook. As a result the aux sweeper never imported + // the second-level proof transition into its archive, and the + // upcoming output sweep would fail to fetch its input proof. Give + // the aux resolver a chance to import the second-level tx into its + // proof archive before we offer the output sweep to the sweeper. + // + // We prefer the ResolveReq preserved on htlcResolution at force-close + // time and only fall back to reconstructing it from historical + // channel state when that field is unavailable — the briefcase + // encoder doesn't currently round-trip ResolveReq, so resolvers + // recovered from a checkpoint have it nil. + resolutionBlob := h.htlcResolution.ResolutionBlob + h.AuxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { + secondLevelReq, err := h.buildSecondLevelResolveReq( + witType, h.htlcResolution.SignedSuccessTx, + uint32(commitSpend.SpendingHeight), + ) + if err != nil { + h.log.Errorf("Unable to build second-level success "+ + "ResolveReq (htlcID=%v): %v — falling back "+ + "to original blob", h.htlc.HtlcIndex, err) + + return + } + + resolveBlob := a.ResolveContract(*secondLevelReq) + if err := resolveBlob.Err(); err != nil { + h.log.Errorf("Unable to re-resolve aux blob for "+ + "second-level success output sweep "+ + "(htlcID=%v): %v — falling back to original "+ + "blob; output sweep may fail aux proof "+ + "verification", + h.htlc.HtlcIndex, err) + + return + } + h.log.Infof("sweepSuccessTxOutput: re-resolved aux blob "+ + "for second-level success output sweep "+ + "(htlcID=%v, secondLevelTxid=%v)", + h.htlc.HtlcIndex, + h.htlcResolution.SignedSuccessTx.TxHash()) + resolutionBlob = resolveBlob.OkToSome() + }) + inp := h.makeSweepInput( op, witType, input.LeaseHtlcAcceptedSuccessSecondLevel, &h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, uint32(commitSpend.SpendingHeight), - h.htlc.RHash, h.htlcResolution.ResolutionBlob, + h.htlc.RHash, resolutionBlob, ) // Calculate the budget for this sweep. @@ -798,6 +903,14 @@ func (h *htlcSuccessResolver) Launch() error { return h.sweepSuccessTxOutput() } + // When the peer signed with SigHashDefault the pre-signed + // second-level tx has baked-in fees and cannot be modified + // (adding wallet inputs would invalidate the signature). + // Publish it directly instead of going through the sweeper. + if h.isSigHashDefault() { + return h.publishSuccessTx() + } + // Otherwise, sweep the second level tx. return h.sweepSuccessTx() diff --git a/contractcourt/htlc_timeout_resolver.go b/contractcourt/htlc_timeout_resolver.go index e6d20bf0978..dd6d6bf51cb 100644 --- a/contractcourt/htlc_timeout_resolver.go +++ b/contractcourt/htlc_timeout_resolver.go @@ -15,6 +15,7 @@ import ( "github.com/lightningnetwork/lnd/chanstate" "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/labels" "github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/lnutils" "github.com/lightningnetwork/lnd/lnwallet" @@ -973,6 +974,64 @@ func (h *htlcTimeoutResolver) isZeroFeeOutput() bool { h.htlcResolution.SignDetails != nil } +// isSigHashDefault returns true when the second-level HTLC transaction +// was signed with SigHashDefault. See isSecondLevelSigHashDefault. +func (h *htlcTimeoutResolver) isSigHashDefault() bool { + return isSecondLevelSigHashDefault( + h.htlcResolution.SignDetails, h.chanType, + ) +} + +// buildSecondLevelResolveReq returns a ResolutionReq targeting the +// just-confirmed second-level HTLC tx. The fast path clones the +// ResolveReq preserved on htlcResolution at force-close time and updates +// only the fields that differ for a second-level sweep. The slow path +// (used when the resolver was recovered from the briefcase and the +// in-memory ResolveReq is gone) reconstructs the request from historical +// channel state. +func (h *htlcTimeoutResolver) buildSecondLevelResolveReq( + witType input.WitnessType, secondLevelTx *wire.MsgTx, + spendingHeight uint32) (*lnwallet.ResolutionReq, error) { + + if h.htlcResolution.ResolveReq != nil { + req := *h.htlcResolution.ResolveReq + req.Type = witType + req.SecondLevel = fn.Some(lnwallet.SecondLevelInfo{ + Tx: secondLevelTx, + BlockHeight: spendingHeight, + }) + + return &req, nil + } + + chanState, err := h.FetchHistoricalChannel() + if err != nil { + return nil, fmt.Errorf("fetch historical channel: %w", err) + } + + return lnwallet.NewSecondLevelResolveReq( + chanState, &h.htlc, h.htlcResolution.SignDetails, + h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, + h.broadcastHeight, secondLevelTx, spendingHeight, witType, + ) +} + +// publishTimeoutTx directly broadcasts the pre-signed second-level HTLC +// timeout transaction. This is used when the transaction was signed with +// SigHashDefault (baked-in fees), where the sweeper's normal tx-rebuilding +// flow would invalidate the peer's signature. +func (h *htlcTimeoutResolver) publishTimeoutTx() error { + h.log.Infof("publishing pre-signed 2nd-level HTLC timeout tx=%v "+ + "(SigHashDefault, baked-in fees)", + h.htlcResolution.SignedTimeoutTx.TxHash()) + + label := labels.MakeLabel( + labels.LabelTypeChannelClose, &h.ShortChanID, + ) + + return h.PublishTx(h.htlcResolution.SignedTimeoutTx, label) +} + // waitHtlcSpendAndCheckPreimage waits for the htlc output to be spent and // checks whether the spending reveals the preimage. If the preimage is found, // it will be added to the preimage beacon to settle the incoming link, and a @@ -1065,6 +1124,51 @@ func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error { witType = input.HtlcOfferedTimeoutSecondLevel } + // Under DeterministicHTLCs the pre-signed second-level HTLC tx was + // published directly via PublishTx, bypassing the sweeper's + // NotifyBroadcast hook. As a result the aux sweeper never imported + // the second-level proof transition into its archive, and the + // upcoming output sweep would fail to fetch its input proof. Give + // the aux resolver a chance to import the second-level tx into its + // proof archive before we offer the output sweep to the sweeper. + // + // We prefer the ResolveReq preserved on htlcResolution at force-close + // time and only fall back to reconstructing it from historical + // channel state when that field is unavailable — the briefcase + // encoder doesn't currently round-trip ResolveReq, so resolvers + // recovered from a checkpoint have it nil. + resolutionBlob := h.htlcResolution.ResolutionBlob + h.AuxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { + secondLevelReq, err := h.buildSecondLevelResolveReq( + witType, h.htlcResolution.SignedTimeoutTx, + uint32(commitSpend.SpendingHeight), + ) + if err != nil { + h.log.Errorf("Unable to build second-level timeout "+ + "ResolveReq (htlcID=%v): %v — falling back "+ + "to original blob", h.htlc.HtlcIndex, err) + + return + } + + resolveBlob := a.ResolveContract(*secondLevelReq) + if err := resolveBlob.Err(); err != nil { + h.log.Errorf("Unable to re-resolve aux blob for "+ + "second-level timeout output sweep "+ + "(htlcID=%v): %v — falling back to original "+ + "blob; output sweep may fail aux proof "+ + "verification", + h.htlc.HtlcIndex, err) + + return + } + h.log.Infof("re-resolved aux blob for second-level timeout "+ + "output sweep (htlcID=%v, secondLevelTxid=%v)", + h.htlc.HtlcIndex, + h.htlcResolution.SignedTimeoutTx.TxHash()) + resolutionBlob = resolveBlob.OkToSome() + }) + // Let the sweeper sweep the second-level output now that the CSV/CLTV // locks have expired. inp := h.makeSweepInput( @@ -1072,7 +1176,7 @@ func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error { input.LeaseHtlcOfferedTimeoutSecondLevel, &h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, uint32(commitSpend.SpendingHeight), - h.htlc.RHash, h.htlcResolution.ResolutionBlob, + h.htlc.RHash, resolutionBlob, ) // Calculate the budget for this sweep. @@ -1321,6 +1425,14 @@ func (h *htlcTimeoutResolver) Launch() error { return h.sweepTimeoutTxOutput() } + // When the peer signed with SigHashDefault the pre-signed + // second-level tx has baked-in fees and cannot be modified + // (adding wallet inputs would invalidate the signature). + // Publish it directly instead of going through the sweeper. + if h.isSigHashDefault() { + return h.publishTimeoutTx() + } + // Otherwise, sweep the second level tx. return h.sweepTimeoutTx() From 36960b29868ea83cb5e7e69f334b9625512a864f Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:13 +0300 Subject: [PATCH 11/17] contractcourt: track historic justice tx variants across rebuild cycles The breach arbiter rebuilds justice tx variants after each spend detection (e.g. when an HTLC transitions to second-level). The tx that ultimately confirms may have been created in an earlier rebuild cycle and is no longer present in the current justiceTxVariants struct. Add a historicJusticeTxs map that records every justice tx variant ever created (keyed by txid) via recordJusticeTxVariants(). The notifyConfirmedJusticeTx function now falls back to this map when the confirmed spend doesn't match any current variant, ensuring the aux sweeper receives NotifyBroadcast for asset proof generation. Also improve the split-broadcast path: rebuild justice tx variants from the updated breach info before splitting, and re-attempt the spendAll variant first (which may now succeed after second-level spends have been incorporated). Add logging to createJusticeTx for input counts and variant creation. --- contractcourt/breach_arbitrator.go | 104 +++++++++++++++++++++++- contractcourt/breach_arbitrator_test.go | 17 +++- 2 files changed, 114 insertions(+), 7 deletions(-) diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 9d9568276b8..d5baa294c5c 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -847,7 +847,8 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend, // haven't already notified about it, we call NotifyBroadcast on the aux sweeper // to generate asset-level proofs. func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, - justiceTxs *justiceTxVariants) { + justiceTxs *justiceTxVariants, + historicJusticeTxs map[chainhash.Hash]*justiceTxCtx) { // waitForSpendEvent can produce multiple spend entries that point at // the same SpenderTxHash (one justice tx may sweep several breached @@ -903,6 +904,19 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, } } + // If none of the current variants matched, check the historic + // map. The current justiceTxs reflect only the LATEST rebuild + // cycle — when a second-level HTLC spend morphs a breached + // output (see convertToSecondLevelRevoke), we rebuild the + // variants with the morphed input set, and the originally + // broadcast txids drop out of `justiceTxs`. Without this + // fallback, a confirmed pre-rebuild justice tx (broadcast by + // us earlier in this loop) would no longer match anything we + // recognize, and we'd skip the aux-sweeper notification. + if justiceCtx == nil { + justiceCtx = historicJusticeTxs[spendingTxHash] + } + // If this is one of our justice txs, notify the aux sweeper. if justiceCtx != nil { bumpReq := sweep.BumpRequest{ @@ -935,6 +949,28 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, } } +// recordJusticeTxVariants records all non-nil justice tx variants into the +// historic map keyed by their txid. This allows notifyConfirmedJusticeTx to +// match confirmed spends against justice txs from previous rebuild cycles. +func recordJusticeTxVariants(variants *justiceTxVariants, + history map[chainhash.Hash]*justiceTxCtx) { + + record := func(jtx *justiceTxCtx) { + if jtx == nil { + return + } + hash := jtx.justiceTx.TxHash() + history[hash] = jtx + } + + record(variants.spendAll) + record(variants.spendCommitOuts) + record(variants.spendHTLCs) + for _, tx := range variants.spendSecondLevelHTLCs { + record(tx) + } +} + // exactRetribution is a goroutine which is executed once a contract breach has // been detected by a breachObserver. This function is responsible for // punishing a counterparty for violating the channel contract by sweeping ALL @@ -971,6 +1007,13 @@ func (b *BreachArbitrator) exactRetribution( // SpendEvents between each attempt to not re-register unnecessarily. spendNtfns := make(map[wire.OutPoint]*chainntnfs.SpendEvent) + // Track all historically created justice tx contexts by their txid. + // This is needed because justiceTxs is rebuilt after each spend + // detection, and the tx that actually confirmed may have been from + // an earlier rebuild cycle. Without this history, we can't match + // the confirmed tx to call NotifyBroadcast on the aux sweeper. + historicJusticeTxs := make(map[chainhash.Hash]*justiceTxCtx) + // Compute both the total value of funds being swept and the // amount of funds that were revoked from the counter party. var totalFunds, revokedFunds btcutil.Amount @@ -984,6 +1027,7 @@ justiceTxBroadcast: brarLog.Errorf("Unable to create justice tx: %v", err) return } + recordJusticeTxVariants(justiceTxs, historicJusticeTxs) finalTx := justiceTxs.spendAll brarLog.Debugf("Broadcasting justice tx: %v", lnutils.SpewLogClosure( @@ -1038,6 +1082,7 @@ Loop: // sweeper. b.notifyConfirmedJusticeTx( spends, justiceTxs, + historicJusticeTxs, ) // Update the breach info with the new spends. @@ -1105,6 +1150,44 @@ Loop: "height %v), splitting justice tx.", epoch.Height, breachInfo.breachHeight) + // Rebuild justice tx variants from the current + // breach info, which may have been updated by + // spend detection (e.g. second-level HTLC spends + // replacing commit-level outputs). + justiceTxs, err = b.createJusticeTx( + breachInfo.breachedOutputs, + ) + if err != nil { + brarLog.Errorf("Unable to recreate "+ + "justice tx for split: %v", err) + continue Loop + } + recordJusticeTxVariants( + justiceTxs, historicJusticeTxs, + ) + + // Re-attempt the spendAll variant first, in + // case the breach info was updated since the + // initial broadcast. This avoids splitting into + // small txs that can't pay fees when a combined + // tx would work. + if justiceTxs.spendAll != nil { + label := labels.MakeLabel( + labels.LabelTypeJusticeTransaction, + nil, + ) + err = b.cfg.PublishTransaction( + justiceTxs.spendAll.justiceTx, + label, + ) + if err != nil { + brarLog.Warnf("Unable to "+ + "broadcast updated "+ + "spendAll justice "+ + "tx: %v", err) + } + } + // Otherwise we'll attempt to publish the two separate // justice transactions that sweeps the commitment // outputs and the HTLC outputs separately. This is to @@ -1707,6 +1790,10 @@ func (b *BreachArbitrator) createJusticeTx( } } + brarLog.Infof("createJusticeTx: %d total inputs (%d commit, "+ + "%d htlc, %d second-level)", len(allInputs), + len(commitInputs), len(htlcInputs), len(secondLevelInputs)) + var ( txs = &justiceTxVariants{} err error @@ -1717,31 +1804,42 @@ func (b *BreachArbitrator) createJusticeTx( if err != nil { return nil, err } + brarLog.Infof("createJusticeTx: spendAll created successfully "+ + "(%d inputs, txid=%v)", len(allInputs), + txs.spendAll.justiceTx.TxHash()) txs.spendCommitOuts, err = b.createSweepTx(commitInputs...) if err != nil { brarLog.Errorf("could not create sweep tx for commitment "+ "outputs: %v", err) + } else if txs.spendCommitOuts != nil { + brarLog.Infof("createJusticeTx: spendCommitOuts created "+ + "successfully (%d inputs)", len(commitInputs)) } txs.spendHTLCs, err = b.createSweepTx(htlcInputs...) if err != nil { brarLog.Errorf("could not create sweep tx for HTLC outputs: %v", err) + } else if txs.spendHTLCs != nil { + brarLog.Infof("createJusticeTx: spendHTLCs created "+ + "successfully (%d inputs)", len(htlcInputs)) } // TODO(roasbeef): only register one of them? secondLevelSweeps := make([]*justiceTxCtx, 0, len(secondLevelInputs)) - for _, input := range secondLevelInputs { + for i, input := range secondLevelInputs { sweepTx, err := b.createSweepTx(input) if err != nil { brarLog.Errorf("could not create sweep tx for "+ - "second-level HTLC output: %v", err) + "second-level HTLC output %d: %v", i, err) continue } + brarLog.Infof("createJusticeTx: individual second-level "+ + "sweep %d created successfully", i) secondLevelSweeps = append(secondLevelSweeps, sweepTx) } txs.spendSecondLevelHTLCs = secondLevelSweeps diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index 96216f76bda..d03ba190429 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -1905,12 +1905,19 @@ func TestBreachDelayedJusticeConfirmation(t *testing.T) { } // Now mine another block without the justice tx confirming. This - // should lead to the BreachArbitrator publishing the split justice tx - // variants. + // should lead to the BreachArbitrator re-broadcasting the spendAll + // variant and then publishing the split justice tx variants. notifier.EpochChan <- &chainntnfs.BlockEpoch{ Height: blockHeight + 4, } + // First, drain the re-broadcast of the spendAll variant. + select { + case <-publTx: + case <-time.After(defaultTimeout): + t.Fatalf("spendAll re-broadcast not published") + } + var ( splits []*wire.MsgTx spending = make(map[wire.OutPoint]struct{}) @@ -3220,8 +3227,9 @@ func TestNotifyConfirmedJusticeTx(t *testing.T) { } // Call the function under test. + historicTxs := make(map[chainhash.Hash]*justiceTxCtx) brar.notifyConfirmedJusticeTx( - tc.spends, tc.justiceTxs, + tc.spends, tc.justiceTxs, historicTxs, ) // Verify the number of NotifyBroadcast calls. @@ -3278,7 +3286,8 @@ func TestNotifyConfirmedJusticeTxNoAuxSweeper(t *testing.T) { } // Should not panic when there's no aux sweeper to notify. + historicTxs := make(map[chainhash.Hash]*justiceTxCtx) brar.notifyConfirmedJusticeTx( - spends, justiceTxs, + spends, justiceTxs, historicTxs, ) } From e9983721b9c99b287601d823deb1111f1ccafea1 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:14 +0300 Subject: [PATCH 12/17] input: remove ErrTweakOverdose check from SignDescriptor.Decode The ErrTweakOverdose check rejected SignDescriptors with both SingleTweak and DoubleTweak set during deserialization. This was a placeholder guard that no caller ever checked for or handled. With taproot asset channels, the combined tweak path (DoubleTweak for revocation + SingleTweak for HTLC index) is exercised during asset-level signing. While the current code only sets both tweaks on transient copies that are never persisted, removing the check eliminates a latent footgun if a future change were to persist such descriptors. --- input/signdescriptor.go | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/input/signdescriptor.go b/input/signdescriptor.go index 7e77326b4a1..95548dccacc 100644 --- a/input/signdescriptor.go +++ b/input/signdescriptor.go @@ -2,7 +2,6 @@ package input import ( "encoding/binary" - "errors" "fmt" "io" @@ -12,11 +11,6 @@ import ( "github.com/lightningnetwork/lnd/keychain" ) -var ( - // ErrTweakOverdose signals a SignDescriptor is invalid because both of its - // SingleTweak and DoubleTweak are non-nil. - ErrTweakOverdose = errors.New("sign descriptor should only have one tweak") -) // SignDescriptor houses the necessary information required to successfully // sign a given segwit output. This struct is used by the Signer interface in @@ -289,11 +283,6 @@ func ReadSignDescriptor(r io.Reader, sd *SignDescriptor) error { sd.DoubleTweak, _ = btcec.PrivKeyFromBytes(doubleTweakBytes) } - // Only one tweak should ever be set, fail if both are present. - if sd.SingleTweak != nil && sd.DoubleTweak != nil { - return ErrTweakOverdose - } - witnessScript, err := wire.ReadVarBytes(r, 0, 500, "witnessScript") if err != nil { return err From 3771d02b7b2074b367bebea60d729f441e628ec2 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:15 +0300 Subject: [PATCH 13/17] sweep+contractcourt: replace skipBroadcast bool with AuxNotifyOpts Introduce AuxNotifyOpts struct with SkipBroadcast and SkipProofVerify fields, replacing the bare boolean skipBroadcast parameter on the AuxSweeper.NotifyBroadcast interface. This decouples broadcast control (transport) from proof verification skip (security), allowing callers to set each independently. --- contractcourt/breach_arbitrator.go | 11 +++++++--- contractcourt/breach_arbitrator_test.go | 29 ++++++++++++++----------- sweep/fee_bumper.go | 3 +-- sweep/interface.go | 21 ++++++++++++++---- sweep/mock_test.go | 2 +- 5 files changed, 43 insertions(+), 23 deletions(-) diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index d5baa294c5c..24f7155d05b 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -928,11 +928,16 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, err := fn.MapOptionZ( b.cfg.AuxSweeper, func(aux sweep.AuxSweeper) error { - // The transaction is already confirmed, - // so we pass skipBroadcast=true. + // The tx is already confirmed, so + // skip broadcast and proof verify + // (placeholder witnesses). return aux.NotifyBroadcast( &bumpReq, s.detail.SpendingTx, - justiceCtx.fee, nil, true, + justiceCtx.fee, nil, + sweep.AuxNotifyOpts{ + SkipBroadcast: true, + SkipProofVerify: true, + }, ) }, ) diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index d03ba190429..6269a34361f 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -2991,7 +2991,7 @@ func (m *mockAuxSweeperWithOutput) ExtraBudgetForInputs( func (m *mockAuxSweeperWithOutput) NotifyBroadcast( _ *sweep.BumpRequest, _ *wire.MsgTx, _ btcutil.Amount, _ map[wire.OutPoint]int, - _ bool) error { + _ sweep.AuxNotifyOpts) error { return nil } @@ -3005,10 +3005,10 @@ type mockAuxSweeperNotify struct { // notifyCall records the parameters of a NotifyBroadcast call. type notifyCall struct { - req *sweep.BumpRequest - tx *wire.MsgTx - fee btcutil.Amount - skipBroadcast bool + req *sweep.BumpRequest + tx *wire.MsgTx + fee btcutil.Amount + opts sweep.AuxNotifyOpts } // DeriveSweepAddr implements sweep.AuxSweeper. @@ -3028,13 +3028,13 @@ func (m *mockAuxSweeperNotify) ExtraBudgetForInputs( // NotifyBroadcast implements sweep.AuxSweeper and records the call. func (m *mockAuxSweeperNotify) NotifyBroadcast(req *sweep.BumpRequest, tx *wire.MsgTx, fee btcutil.Amount, - _ map[wire.OutPoint]int, skipBroadcast bool) error { + _ map[wire.OutPoint]int, opts sweep.AuxNotifyOpts) error { m.notifyCalls = append(m.notifyCalls, notifyCall{ - req: req, - tx: tx, - fee: fee, - skipBroadcast: skipBroadcast, + req: req, + tx: tx, + fee: fee, + opts: opts, }) return m.notifyErr @@ -3245,11 +3245,14 @@ func TestNotifyConfirmedJusticeTx(t *testing.T) { "unexpected fee for call %d", i) } - // Verify skipBroadcast is always true for + // Verify skip flags are set for // confirmed justice txs. require.Equal(t, tc.expectedSkipFlag, - call.skipBroadcast, - "skipBroadcast should be true") + call.opts.SkipBroadcast, + "SkipBroadcast should be true") + require.Equal(t, tc.expectedSkipFlag, + call.opts.SkipProofVerify, + "SkipProofVerify should be true") } }) } diff --git a/sweep/fee_bumper.go b/sweep/fee_bumper.go index e36c439ef71..294621124b4 100644 --- a/sweep/fee_bumper.go +++ b/sweep/fee_bumper.go @@ -738,10 +738,9 @@ func (t *TxPublisher) broadcast(record *monitorRecord) (*BumpResult, error) { // Before we go to broadcast, we'll notify the aux sweeper, if it's // present of this new broadcast attempt. err := fn.MapOptionZ(t.cfg.AuxSweeper, func(aux AuxSweeper) error { - const skipBroadcast = false return aux.NotifyBroadcast( record.req, tx, record.fee, record.outpointToTxIndex, - skipBroadcast, + AuxNotifyOpts{}, ) }) if err != nil { diff --git a/sweep/interface.go b/sweep/interface.go index 21f489be929..d593a5e8a35 100644 --- a/sweep/interface.go +++ b/sweep/interface.go @@ -75,6 +75,22 @@ type SweepOutput struct { //nolint:revive InternalKey fn.Option[keychain.KeyDescriptor] } +// AuxNotifyOpts contains options for the NotifyBroadcast call on the +// AuxSweeper interface. +type AuxNotifyOpts struct { + // SkipBroadcast indicates whether the transaction is already + // confirmed on-chain (true for breach sweeps, force close + // commitments) and should not be broadcast again. + SkipBroadcast bool + + // SkipProofVerify indicates whether asset-level proof + // verification should be skipped. This is used when the input + // proofs contain placeholder witnesses (e.g. second-level HTLC + // outputs) that cannot pass VM-level validation, and the + // on-chain confirmation serves as proof of validity instead. + SkipProofVerify bool +} + // AuxSweeper is used to enable a 3rd party to further shape the sweeping // transaction by adding a set of extra outputs to the sweeping transaction. type AuxSweeper interface { @@ -99,11 +115,8 @@ type AuxSweeper interface { // NotifyBroadcast is used to notify external callers of the broadcast // of a sweep transaction, generated by the passed BumpRequest. - // The skipBroadcast parameter indicates whether the transaction is - // already confirmed on-chain (true for breach sweeps) or needs to be - // broadcast (false for normal sweeps). NotifyBroadcast(req *BumpRequest, tx *wire.MsgTx, totalFees btcutil.Amount, outpointToTxIndex map[wire.OutPoint]int, - skipBroadcast bool) error + opts AuxNotifyOpts) error } diff --git a/sweep/mock_test.go b/sweep/mock_test.go index 606ff3163ef..3bb3975f1f8 100644 --- a/sweep/mock_test.go +++ b/sweep/mock_test.go @@ -359,7 +359,7 @@ func (m *MockAuxSweeper) ExtraBudgetForInputs( // NotifyBroadcast is used to notify external callers of the broadcast // of a sweep transaction, generated by the passed BumpRequest. func (*MockAuxSweeper) NotifyBroadcast(_ *BumpRequest, _ *wire.MsgTx, - _ btcutil.Amount, _ map[wire.OutPoint]int, _ bool) error { + _ btcutil.Amount, _ map[wire.OutPoint]int, _ AuxNotifyOpts) error { return nil } From 15e050101ed22443ca5d1eb133b4bc455d769672 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:16 +0300 Subject: [PATCH 14/17] lnwallet: populate AuxSigDesc for breach HTLC retribution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When constructing HtlcRetribution for a breached commitment, extract the remote party's asset-level HTLC signature from the revocation log's CustomBlob and populate AuxSigDesc on the ResolutionReq. This allows the aux subsystem to construct valid asset witnesses for the commitment → second-level proof transition, making breach-recovered assets fully spendable. --- lnwallet/channel.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 23056361b6c..02f20d66865 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2605,6 +2605,48 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, HtlcID: htlcIDOpt, CltvDelay: fn.Some(htlc.RefundTimeout.Val), } + + // Populate the AuxSigDesc if the HTLC has custom + // records (containing the remote's asset-level + // sig for the second-level tx). This allows the + // aux subsystem to construct a valid proof with + // real witnesses instead of placeholders. + htlc.CustomBlob.WhenSome( + func(r tlv.RecordT[tlv.TlvType5, tlv.Blob]) { + customRecords, err := lnwire. + ParseCustomRecords(r.Val) + if err != nil { + return + } + + sigType := htlcCustomSigType.TypeVal() + auxSig := customRecords[uint64(sigType)] + if len(auxSig) > 0 { + // Construct the HTLC sign + // descriptor that the aux + // subsystem needs to sign the + // second-level transition proof. + htlcSignDesc := input.SignDescriptor{ + KeyDesc: chanState. + LocalChanCfg. + HtlcBasePoint, + SingleTweak: keyRing. + LocalHtlcKeyTweak, + SignMethod: input. + TaprootScriptSpendSignMethod, + } + + resolveReq.AuxSigDesc = fn.Some( + AuxSigDesc{ + AuxSig: auxSig, + SignDetails: input.SignDetails{ + SignDesc: htlcSignDesc, + }, + }, + ) + } + }, + ) if revokedLog != nil { resolveReq.CommitBlob = revokedLog.CustomBlob.ValOpt() } From d6d8d43f9b6befd4577e4120f961bf1e7cbf4c74 Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:16 +0300 Subject: [PATCH 15/17] contractcourt: use dust limit for justice tx sweep output check When the justice tx has an aux (asset) output, the remaining BTC change after fees can be below the dust limit but still positive. Check against the dust limit instead of zero to prevent btcd from rejecting the transaction as non-standard. --- contractcourt/breach_arbitrator.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 24f7155d05b..79c9df6c555 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -1998,13 +1998,15 @@ func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit, }) } - // If the sweep amount is positive, add the regular sweep output as - // usual. If it's non-positive but we have an aux output, we skip - // the BTC sweep output entirely — for custom (asset) channels the - // real value is carried by the aux output and the remaining BTC - // can all go towards fees. + // If the sweep amount exceeds the dust limit, add the regular sweep + // output. If it's at or below dust but we have an aux output, we + // skip the BTC sweep output entirely — for custom (asset) channels + // the real value is carried by the aux output and the remaining BTC + // can all go towards fees. Using the dust limit instead of zero + // prevents the mempool from rejecting the transaction. + dustLimit := int64(lnwallet.DustLimitForSize(input.UnknownWitnessSize)) switch { - case sweepAmt > 0: + case sweepAmt > dustLimit: txn.AddTxOut(&wire.TxOut{ PkScript: pkScript.DeliveryAddress, Value: sweepAmt, From 7952e88f04e74c2d9fbc9a44e6a36b0024e2e8ed Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Tue, 14 Apr 2026 18:39:17 +0300 Subject: [PATCH 16/17] multi: add revocation AuxSig signing and verification When revoking a commitment via RevokeAndAck, sign both spending paths (success and timeout) for each in-flight HTLC's second-level virtual transaction. The signatures are packed into an HTLC-index-tagged blob that the receiver can match to HTLCs unambiguously, regardless of ordering differences between local and remote commitment views. On the receiving side, verify all signatures against the breach-time key ring before accepting the revocation. Store both primary and alternate path signatures in the revocation log so the honest party can reconstruct valid proofs for whichever spending path the breaching party used on-chain. Both signing and verification are gated by IsDeterministicHTLCs (formerly IsSigHashDefault), ensuring backward compatibility with peers that have not negotiated the feature. Key changes: - Add signLocalHtlcAuxSigs to produce dual-path AuxSigs per HTLC - Add verifyRevocationAuxSigs to validate sigs at ReceiveRevocation - Add injectRevocationAuxSigs to store sigs in the revocation log - Add HTLC-index-tagged pack/unpack format for revocation sig blobs - Add AuxSigAlt field to AuxSigDesc for alternate spending path - Add IncomingHTLCLookup to BaseAuxJob for correct aux output lookup when Incoming is flipped for alternate spending path generation - Add WhoseCommit, HtlcTimeout fields to BaseAuxJob - Add CustomRecords field to RevokeAndAck for carrying aux sig blobs - Rename IsSigHashDefault to IsDeterministicHTLCs - Use ResolveHtlcSigHashType instead of hardcoded SigHashAll - Add ConfirmHeight to AuxNotifyOpts for porter height hints --- contractcourt/breach_arbitrator.go | 145 +++- contractcourt/breach_arbitrator_test.go | 12 +- input/signdescriptor.go | 1 - lnwallet/aux_resolutions.go | 12 +- lnwallet/aux_signer.go | 54 +- lnwallet/channel.go | 1055 +++++++++++++++++++++-- lnwallet/revocation_aux_sig_test.go | 101 +++ lnwire/revoke_and_ack.go | 48 +- sweep/interface.go | 19 +- 9 files changed, 1328 insertions(+), 119 deletions(-) create mode 100644 lnwallet/revocation_aux_sig_test.go diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 79c9df6c555..8e008600f59 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -845,10 +845,11 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend, // notifyConfirmedJusticeTx checks if any of the spend details match one of our // justice transactions. If a confirmed justice transaction is detected and we // haven't already notified about it, we call NotifyBroadcast on the aux sweeper -// to generate asset-level proofs. +// to generate aux-level proofs. func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, justiceTxs *justiceTxVariants, - historicJusticeTxs map[chainhash.Hash]*justiceTxCtx) { + historicJusticeTxs map[chainhash.Hash]*justiceTxCtx, + breachedOutputs []breachedOutput) { // waitForSpendEvent can produce multiple spend entries that point at // the same SpenderTxHash (one justice tx may sweep several breached @@ -882,22 +883,29 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, } var justiceCtx *justiceTxCtx + var matchSource string switch { case matchesJusticeTx(justiceTxs.spendAll): justiceCtx = justiceTxs.spendAll + matchSource = "spendAll" case matchesJusticeTx(justiceTxs.spendCommitOuts): justiceCtx = justiceTxs.spendCommitOuts + matchSource = "spendCommitOuts" case matchesJusticeTx(justiceTxs.spendHTLCs): justiceCtx = justiceTxs.spendHTLCs + matchSource = "spendHTLCs" } // Also check the individual second-level sweeps. if justiceCtx == nil { - for _, tx := range justiceTxs.spendSecondLevelHTLCs { + for i, tx := range justiceTxs.spendSecondLevelHTLCs { if matchesJusticeTx(tx) { justiceCtx = tx + matchSource = fmt.Sprintf( + "secondLevel[%d]", i, + ) break } @@ -915,12 +923,76 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, // recognize, and we'd skip the aux-sweeper notification. if justiceCtx == nil { justiceCtx = historicJusticeTxs[spendingTxHash] + if justiceCtx != nil { + matchSource = "historic" + } } // If this is one of our justice txs, notify the aux sweeper. if justiceCtx != nil { + brarLog.Debugf("Matched spend txid=%v to justice tx "+ + "via %s (numInputs=%d), notifying aux sweeper", + spendingTxHash, matchSource, + len(justiceCtx.inputs)) + for i, inp := range justiceCtx.inputs { + brarLog.Debugf(" input[%d]: outpoint=%v "+ + "witnessType=%v", i, inp.OutPoint(), + inp.WitnessType()) + } + } else { + brarLog.Debugf("Spend txid=%v did NOT match any "+ + "justice tx", spendingTxHash) + } + if justiceCtx != nil { + // Build a fresh input list by matching the + // confirmed tx's BTC inputs against the + // current breachedOutputs. This avoids using + // stale pointers from historic variants + // whose data may have been mutated by + // second-level morphing or slice compaction. + spendingTx := s.detail.SpendingTx + boByOutpoint := make( + map[wire.OutPoint]*breachedOutput, + ) + for i := range breachedOutputs { + bo := &breachedOutputs[i] + boByOutpoint[bo.outpoint] = bo + } + + var freshInputs []input.Input + hasSecondLevel := false + + // Preserve second-level awareness from the justice + // tx context snapshot. The current breachedOutputs + // view can lag after morphing/rebuilds, and if we + // lose this bit for a mixed justice tx we stop + // looking up refreshed input proofs for the + // second-level spends on aux channels. + hasSecondLevel = justiceCtx.hasSecondLevel + + for _, txIn := range spendingTx.TxIn { + op := txIn.PreviousOutPoint + bo, ok := boByOutpoint[op] + if !ok { + continue + } + freshInputs = append(freshInputs, bo) + + wt := bo.WitnessType() + switch wt { + case input.HtlcSecondLevelRevoke, + input.TaprootHtlcSecondLevelRevoke: + + hasSecondLevel = true + } + } + + brarLog.Debugf("Built fresh input list: %d inputs "+ + "(hasSecondLevel=%v)", len(freshInputs), + hasSecondLevel) + bumpReq := sweep.BumpRequest{ - Inputs: justiceCtx.inputs, + Inputs: freshInputs, DeliveryAddress: justiceCtx.sweepAddr, ExtraTxOut: justiceCtx.extraTxOut, } @@ -929,14 +1001,17 @@ func (b *BreachArbitrator) notifyConfirmedJusticeTx(spends []spend, b.cfg.AuxSweeper, func(aux sweep.AuxSweeper) error { // The tx is already confirmed, so - // skip broadcast and proof verify - // (placeholder witnesses). + // skip broadcast. Proof verification + // must run to ensure valid anchor + // metadata for spending. + h := uint32(s.detail.SpendingHeight) return aux.NotifyBroadcast( &bumpReq, s.detail.SpendingTx, justiceCtx.fee, nil, sweep.AuxNotifyOpts{ - SkipBroadcast: true, - SkipProofVerify: true, + SkipBroadcast: true, + ConfirmHeight: h, + LookupInputProofs: hasSecondLevel, //nolint:ll }, ) }, @@ -964,8 +1039,22 @@ func recordJusticeTxVariants(variants *justiceTxVariants, if jtx == nil { return } - hash := jtx.justiceTx.TxHash() - history[hash] = jtx + + snapshot := *jtx + if jtx.justiceTx != nil { + snapshot.justiceTx = jtx.justiceTx.Copy() + } + + // The historic map is only used to match later confirmed + // spends against the justice variants that were published + // at the time. Store an immutable snapshot so later rebuilds + // can't mutate the metadata associated with an older txid + // and retroactively change whether that tx should be + // treated as carrying second-level inputs. + snapshot.inputs = nil + + hash := snapshot.justiceTx.TxHash() + history[hash] = &snapshot } record(variants.spendAll) @@ -1035,15 +1124,13 @@ justiceTxBroadcast: recordJusticeTxVariants(justiceTxs, historicJusticeTxs) finalTx := justiceTxs.spendAll - brarLog.Debugf("Broadcasting justice tx: %v", lnutils.SpewLogClosure( - finalTx)) - // We'll now attempt to broadcast the transaction which finalized the // channel's retribution against the cheating counter party. label := labels.MakeLabel(labels.LabelTypeJusticeTransaction, nil) err = b.cfg.PublishTransaction(finalTx.justiceTx, label) if err != nil { - brarLog.Errorf("Unable to broadcast justice tx: %v", err) + brarLog.Errorf("Unable to broadcast initial spendAll "+ + "justice tx: %v", err) } // Regardless of publication succeeded or not, we now wait for any of @@ -1088,12 +1175,14 @@ Loop: b.notifyConfirmedJusticeTx( spends, justiceTxs, historicJusticeTxs, + breachInfo.breachedOutputs, ) // Update the breach info with the new spends. t, r := updateBreachInfo( breachInfo, spends, b.cfg.AuxResolver, ) + totalFunds += t revokedFunds += r @@ -1171,24 +1260,19 @@ Loop: justiceTxs, historicJusticeTxs, ) - // Re-attempt the spendAll variant first, in - // case the breach info was updated since the - // initial broadcast. This avoids splitting into - // small txs that can't pay fees when a combined - // tx would work. + // Re-attempt the spendAll variant first. if justiceTxs.spendAll != nil { + sa := justiceTxs.spendAll label := labels.MakeLabel( labels.LabelTypeJusticeTransaction, nil, ) err = b.cfg.PublishTransaction( - justiceTxs.spendAll.justiceTx, - label, + sa.justiceTx, label, ) if err != nil { - brarLog.Warnf("Unable to "+ - "broadcast updated "+ - "spendAll justice "+ + brarLog.Warnf("Unable to broadcast "+ + "rebuild spendAll justice "+ "tx: %v", err) } } @@ -1869,6 +1953,12 @@ type justiceTxCtx struct { fee btcutil.Amount + // hasSecondLevel records whether this concrete justice tx spends any + // second-level revoke inputs. We keep it on the tx context because the + // live breachedOutputs slice may later be rebuilt into a view that no + // longer faithfully reflects the confirmed tx we need to notify about. + hasSecondLevel bool + inputs []input.Input } @@ -2084,7 +2174,12 @@ func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit, sweepAddr: pkScript, extraTxOut: extraChangeOut.OkToSome(), fee: txFee, - inputs: inputs, + hasSecondLevel: fn.Any(inputs, func(inp input.Input) bool { + wt := inp.WitnessType() + return wt == input.HtlcSecondLevelRevoke || + wt == input.TaprootHtlcSecondLevelRevoke + }), + inputs: inputs, }, nil } diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index 6269a34361f..f8ef6287a74 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -3229,7 +3229,8 @@ func TestNotifyConfirmedJusticeTx(t *testing.T) { // Call the function under test. historicTxs := make(map[chainhash.Hash]*justiceTxCtx) brar.notifyConfirmedJusticeTx( - tc.spends, tc.justiceTxs, historicTxs, + tc.spends, tc.justiceTxs, + historicTxs, nil, ) // Verify the number of NotifyBroadcast calls. @@ -3250,9 +3251,12 @@ func TestNotifyConfirmedJusticeTx(t *testing.T) { require.Equal(t, tc.expectedSkipFlag, call.opts.SkipBroadcast, "SkipBroadcast should be true") - require.Equal(t, tc.expectedSkipFlag, + // SkipProofVerify is NOT set — + // proof verification must run to + // ensure valid anchor metadata. + require.False(t, call.opts.SkipProofVerify, - "SkipProofVerify should be true") + "SkipProofVerify should be false") } }) } @@ -3291,6 +3295,6 @@ func TestNotifyConfirmedJusticeTxNoAuxSweeper(t *testing.T) { // Should not panic when there's no aux sweeper to notify. historicTxs := make(map[chainhash.Hash]*justiceTxCtx) brar.notifyConfirmedJusticeTx( - spends, justiceTxs, historicTxs, + spends, justiceTxs, historicTxs, nil, ) } diff --git a/input/signdescriptor.go b/input/signdescriptor.go index 95548dccacc..ff3983b6b14 100644 --- a/input/signdescriptor.go +++ b/input/signdescriptor.go @@ -11,7 +11,6 @@ import ( "github.com/lightningnetwork/lnd/keychain" ) - // SignDescriptor houses the necessary information required to successfully // sign a given segwit output. This struct is used by the Signer interface in // order to gain access to critical data needed to generate a valid signature. diff --git a/lnwallet/aux_resolutions.go b/lnwallet/aux_resolutions.go index a2fa4f234c1..2f3dabf2140 100644 --- a/lnwallet/aux_resolutions.go +++ b/lnwallet/aux_resolutions.go @@ -28,11 +28,17 @@ const ( // AuxSigDesc stores optional information related to 2nd level HTLCs for aux // channels. type AuxSigDesc struct { - // AuxSig is the second-level signature for the HTLC that we are trying - // to resolve. This is only present if this is a resolution request for - // an HTLC on our commitment transaction. + // AuxSig is the second-level signature for the HTLC's primary + // spending path (success for incoming, timeout for outgoing). AuxSig []byte + // AuxSigAlt is the second-level signature for the HTLC's + // alternate spending path (timeout for incoming, success for + // outgoing). At breach time, the honest party uses the BTC-level + // witness to determine which path was used and selects the + // matching sig. + AuxSigAlt []byte + // SignDetails is the sign details for the second-level HTLC. This may // be used to generate the second signature needed for broadcast. SignDetails input.SignDetails diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index 1f6d9cc0018..e8ddf9dc4ce 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -194,9 +194,20 @@ type BaseAuxJob struct { HTLC AuxHtlcDescriptor // Incoming is a boolean that indicates if the HTLC is incoming or - // outgoing. + // outgoing from the LOCAL party's perspective. This is used with + // WhoseCommit to determine the correct HTLC script variant + // (sender vs receiver). Incoming bool + // IncomingHTLCLookup controls which HTLC aux output list in the + // commitment blob the signer uses to find the aux outputs. + // When true, the signer looks in IncomingHtlcAssets; when false, + // in OutgoingHtlcAssets. This is normally the same as Incoming, + // but differs for revocation self-signing where the Incoming + // flag is flipped for script generation but the aux output lookup + // must still use the original direction. + IncomingHTLCLookup bool + // CommitBlob is the commitment transaction blob that contains the aux // information for this channel. CommitBlob fn.Option[tlv.Blob] @@ -204,6 +215,16 @@ type BaseAuxJob struct { // HtlcLeaf is the aux tap leaf that corresponds to the HTLC being // signed/verified. HtlcLeaf input.AuxTapLeaf + + // WhoseCommit indicates which party's commitment transaction the + // second-level HTLC belongs to. + WhoseCommit lntypes.ChannelParty + + // HtlcTimeout, if set, overrides the timeout logic in + // generateHtlcSignature and verifyHtlcSignature. When nil, + // the timeout is derived from Incoming (the normal CommitSig + // convention). When set, it is used directly. + HtlcTimeout fn.Option[uint32] } // AuxSigJob is a struct that contains all the information needed to sign an @@ -224,20 +245,24 @@ type AuxSigJob struct { Cancel <-chan struct{} } -// NewAuxSigJob creates a new AuxSigJob. +// NewAuxSigJob creates a new AuxSigJob. The whoseCommit parameter indicates +// which party's commitment the HTLC belongs to. func NewAuxSigJob(sigJob SignJob, keyRing CommitmentKeyRing, incoming bool, htlc AuxHtlcDescriptor, commitBlob fn.Option[tlv.Blob], - htlcLeaf input.AuxTapLeaf, cancelChan <-chan struct{}) AuxSigJob { + htlcLeaf input.AuxTapLeaf, whoseCommit lntypes.ChannelParty, + cancelChan <-chan struct{}) AuxSigJob { return AuxSigJob{ SignDesc: sigJob.SignDesc, BaseAuxJob: BaseAuxJob{ - OutputIndex: sigJob.OutputIndex, - KeyRing: keyRing, - HTLC: htlc, - Incoming: incoming, - CommitBlob: commitBlob, - HtlcLeaf: htlcLeaf, + OutputIndex: sigJob.OutputIndex, + KeyRing: keyRing, + HTLC: htlc, + Incoming: incoming, + IncomingHTLCLookup: incoming, + CommitBlob: commitBlob, + HtlcLeaf: htlcLeaf, + WhoseCommit: whoseCommit, }, Resp: make(chan AuxSigJobResp, 1), Cancel: cancelChan, @@ -353,11 +378,12 @@ func ResolveHtlcSigHashType(chanType channeldb.ChannelType, return sigHash.UnwrapOr(HtlcSigHashType(chanType)) } -// IsSigHashDefault returns true if the resolved HTLC sighash type for the -// given channel is SigHashDefault. This is used to determine whether -// second-level HTLC transactions must carry their own fee (since the sweeper -// cannot add wallet inputs under SigHashDefault). -func IsSigHashDefault(chanType channeldb.ChannelType, +// IsDeterministicHTLCs returns true if the DeterministicHTLCs feature is +// active for the given channel. When true, second-level HTLC transactions +// use SigHashDefault (making them fully deterministic), must carry their +// own fees, and the revoking party includes dual-path AuxSigs in +// RevokeAndAck for breach proof reconstruction. +func IsDeterministicHTLCs(chanType channeldb.ChannelType, auxSigner fn.Option[AuxSigner], req HtlcSigHashReq) bool { diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 02f20d66865..34741e59ae9 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -487,7 +487,7 @@ func (lc *LightningChannel) IsChanSigHashDefault() bool { lc.channelState.FundingOutpoint, ) - return IsSigHashDefault( + return IsDeterministicHTLCs( lc.channelState.ChanType, lc.auxSigner, HtlcSigHashReq{ @@ -1020,7 +1020,7 @@ func NewLightningChannel(signer input.Signer, commitChains: commitChains, channelState: state, commitBuilder: NewCommitmentBuilder( - state, opts.leafStore, IsSigHashDefault( + state, opts.leafStore, IsDeterministicHTLCs( state.ChanType, opts.auxSigner, HtlcSigHashReq{ ChanID: fn.Some( @@ -2445,6 +2445,55 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, // createHtlcRetribution is a helper function to construct an HtlcRetribution // based on the passed params. +// auxSigDescFromHTLCBlob extracts the AuxSigDesc for a breached HTLC from its +// custom-records blob, if present. It prefers the remote party's +// revocation-path aux sig (revocationAuxSigType, sent in RevokeAndAck, which +// is the correct sig for reconstructing the breach proof chain) plus its +// alternate, falling back to the CommitSig aux sig (htlcCustomSigType) for +// backward compatibility. Returns None when no aux sig is present. +func auxSigDescFromHTLCBlob(htlc *channeldb.HTLCEntry, + chanState *chanstate.OpenChannel, + keyRing *CommitmentKeyRing) fn.Option[AuxSigDesc] { + + var auxSigDesc fn.Option[AuxSigDesc] + htlc.CustomBlob.WhenSome(func(r tlv.RecordT[tlv.TlvType5, tlv.Blob]) { + customRecords, err := lnwire.ParseCustomRecords(r.Val) + if err != nil { + return + } + + // Extract both the primary and alternate revocation aux sigs. + revSigType := revocationAuxSigType.TypeVal() + auxSig := customRecords[uint64(revSigType)] + altSigType := revocationAuxSigAltType.TypeVal() + auxSigAlt := customRecords[uint64(altSigType)] + + // Fall back to the CommitSig aux sig. + if len(auxSig) == 0 { + sigType := htlcCustomSigType.TypeVal() + auxSig = customRecords[uint64(sigType)] + } + + if len(auxSig) == 0 { + return + } + + // Construct the sign desc for the second-level tx proof. + sd := input.SignDescriptor{ + KeyDesc: chanState.LocalChanCfg.HtlcBasePoint, + SingleTweak: keyRing.LocalHtlcKeyTweak, + SignMethod: input.TaprootScriptSpendSignMethod, + } + auxSigDesc = fn.Some(AuxSigDesc{ + AuxSig: auxSig, + AuxSigAlt: auxSigAlt, + SignDetails: input.SignDetails{SignDesc: sd}, + }) + }) + + return auxSigDesc +} + func createHtlcRetribution(chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitHash chainhash.Hash, commitmentSecret *btcec.PrivateKey, leaseExpiry uint32, @@ -2606,46 +2655,8 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, CltvDelay: fn.Some(htlc.RefundTimeout.Val), } - // Populate the AuxSigDesc if the HTLC has custom - // records (containing the remote's asset-level - // sig for the second-level tx). This allows the - // aux subsystem to construct a valid proof with - // real witnesses instead of placeholders. - htlc.CustomBlob.WhenSome( - func(r tlv.RecordT[tlv.TlvType5, tlv.Blob]) { - customRecords, err := lnwire. - ParseCustomRecords(r.Val) - if err != nil { - return - } - - sigType := htlcCustomSigType.TypeVal() - auxSig := customRecords[uint64(sigType)] - if len(auxSig) > 0 { - // Construct the HTLC sign - // descriptor that the aux - // subsystem needs to sign the - // second-level transition proof. - htlcSignDesc := input.SignDescriptor{ - KeyDesc: chanState. - LocalChanCfg. - HtlcBasePoint, - SingleTweak: keyRing. - LocalHtlcKeyTweak, - SignMethod: input. - TaprootScriptSpendSignMethod, - } - - resolveReq.AuxSigDesc = fn.Some( - AuxSigDesc{ - AuxSig: auxSig, - SignDetails: input.SignDetails{ - SignDesc: htlcSignDesc, - }, - }, - ) - } - }, + resolveReq.AuxSigDesc = auxSigDescFromHTLCBlob( + htlc, chanState, keyRing, ) if revokedLog != nil { resolveReq.CommitBlob = revokedLog.CustomBlob.ValOpt() @@ -2852,7 +2863,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chainfee.SatPerKWeight(revokedLog.FeePerKw), htlc.Amt.ToSatoshis(), chanState.RemoteChanCfg.DustLimit, - IsSigHashDefault( + IsDeterministicHTLCs( chanState.ChanType, auxSigner, HtlcSigHashReq{ @@ -3579,7 +3590,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // For each outgoing and incoming HTLC, if the HTLC isn't considered a // dust output after taking into account second-level HTLC fees, then a // sigJob will be generated and appended to the current batch. - sigHashDefault := IsSigHashDefault( + sigHashDefault := IsDeterministicHTLCs( chanType, auxSigner, sigHashReq, ) for _, htlc := range remoteCommitView.incomingHTLCs { @@ -3663,7 +3674,8 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, auxSigBatch = append(auxSigBatch, NewAuxSigJob( sigJob, *keyRing, true, newAuxHtlcDescriptor(&htlc), - remoteCommitView.customBlob, auxLeaf, cancelChan, + remoteCommitView.customBlob, auxLeaf, + lntypes.Remote, cancelChan, )) } for _, htlc := range remoteCommitView.outgoingHTLCs { @@ -3746,13 +3758,889 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, auxSigBatch = append(auxSigBatch, NewAuxSigJob( sigJob, *keyRing, false, newAuxHtlcDescriptor(&htlc), - remoteCommitView.customBlob, auxLeaf, cancelChan, + remoteCommitView.customBlob, auxLeaf, + lntypes.Remote, cancelChan, )) } return sigBatch, auxSigBatch, cancelChan, nil } +// revocationAuxSigType is the TLV type used to store the remote party's +// aux signatures for their own second-level HTLCs in the HTLC +// CustomRecords within the revocation log. We use a different type than +// htlcCustomSigType to avoid collisions with the sigs the remote sent +// for OUR local commitment (stored during genHtlcSigValidationJobs). +var revocationAuxSigType tlv.TlvType65637 + +// revocationAuxSigAltType stores the alternate spending path's AuxSig. +// For incoming HTLCs, the primary is success and alt is timeout. +// For outgoing HTLCs, the primary is timeout and alt is success. +var revocationAuxSigAltType tlv.TlvType65639 + +// revocationAuxSigEntry holds a single HTLC's revocation AuxSigs tagged with +// its HTLC index, so the receiver can match sigs to HTLCs unambiguously +// regardless of HTLC ordering differences between local and remote views. +// +// On the wire, each entry is encoded as a TLV stream with three records +// (HtlcIndex / PrimarySig / AltSig). The full blob is a BigSize-prefixed +// count followed by length-prefixed entry streams — TLV streams aren't +// natively self-delimiting at the list level, so we wrap each entry with +// its byte length so the decoder can frame the next entry. +type revocationAuxSigEntry struct { + htlcIndex uint64 + primarySig []byte + altSig []byte +} + +// encode writes the entry as a TLV stream. +func (e *revocationAuxSigEntry) encode(w io.Writer) error { + htlcIdx := e.htlcIndex + primary := e.primarySig + alt := e.altSig + + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(0, &htlcIdx), + tlv.MakePrimitiveRecord(1, &primary), + tlv.MakePrimitiveRecord(2, &alt), + ) + if err != nil { + return err + } + + return stream.Encode(w) +} + +// decode reads the entry from a TLV stream. +func (e *revocationAuxSigEntry) decode(r io.Reader) error { + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(0, &e.htlcIndex), + tlv.MakePrimitiveRecord(1, &e.primarySig), + tlv.MakePrimitiveRecord(2, &e.altSig), + ) + if err != nil { + return err + } + + return stream.Decode(r) +} + +// packRevocationAuxSigs encodes a list of HTLC-index-tagged sig pairs into a +// single blob. Format: BigSize count + repeated [BigSize entryLen + +// entry-TLV-stream] records. Each entry's TLV stream carries records 0 +// (HtlcIndex), 1 (PrimarySig), 2 (AltSig). +func packRevocationAuxSigs(entries []revocationAuxSigEntry) ([]byte, error) { + var ( + buf bytes.Buffer + scratch [8]byte + ) + + if err := tlv.WriteVarInt( + &buf, uint64(len(entries)), &scratch, + ); err != nil { + return nil, fmt.Errorf("write entry count: %w", err) + } + + for i := range entries { + var inner bytes.Buffer + if err := entries[i].encode(&inner); err != nil { + return nil, fmt.Errorf("encode entry %d: %w", i, err) + } + + if err := tlv.WriteVarInt( + &buf, uint64(inner.Len()), &scratch, + ); err != nil { + return nil, fmt.Errorf("write entry %d length: %w", + i, err) + } + if _, err := buf.Write(inner.Bytes()); err != nil { + return nil, fmt.Errorf("write entry %d bytes: %w", + i, err) + } + } + + return buf.Bytes(), nil +} + +// unpackRevocationAuxSigs decodes a blob produced by packRevocationAuxSigs +// into a map of HTLC index → (primarySig, altSig). +func unpackRevocationAuxSigs( + blob []byte) (map[uint64]revocationAuxSigEntry, error) { + + r := bytes.NewReader(blob) + var scratch [8]byte + + count, err := tlv.ReadVarInt(r, &scratch) + if err != nil { + return nil, fmt.Errorf("read entry count: %w", err) + } + + result := make(map[uint64]revocationAuxSigEntry, count) + for i := uint64(0); i < count; i++ { + entryLen, err := tlv.ReadVarInt(r, &scratch) + if err != nil { + return nil, fmt.Errorf("read entry %d length: %w", + i, err) + } + + inner := io.LimitReader(r, int64(entryLen)) + var entry revocationAuxSigEntry + if err := entry.decode(inner); err != nil { + return nil, fmt.Errorf("decode entry %d: %w", i, err) + } + + result[entry.htlcIndex] = entry + } + + return result, nil +} + +// injectRevocationAuxSigs takes the packed aux sig blob from a RevokeAndAck +// and injects individual HTLC sigs into the remote commitment's HTLC entries. +// This must be called before AdvanceCommitChainTail so the sigs are persisted +// in the revocation log. +func (lc *LightningChannel) injectRevocationAuxSigs(auxSigBlob []byte) { + sigMap, err := unpackRevocationAuxSigs(auxSigBlob) + if err != nil { + lc.log.Warnf("Unable to unpack revocation aux sigs: %v", err) + return + } + + if len(sigMap) == 0 { + return + } + + primaryType := revocationAuxSigType.TypeVal() + altType := revocationAuxSigAltType.TypeVal() + htlcs := lc.channelState.RemoteCommitment.Htlcs + // Match sigs to HTLCs by HTLC index. + for i := range htlcs { + entry, ok := sigMap[htlcs[i].HtlcIndex] + if !ok { + continue + } + + if htlcs[i].CustomRecords == nil { + htlcs[i].CustomRecords = make(lnwire.CustomRecords) + } + if len(entry.primarySig) > 0 { + htlcs[i].CustomRecords[uint64(primaryType)] = + entry.primarySig + } + if len(entry.altSig) > 0 { + htlcs[i].CustomRecords[uint64(altType)] = + entry.altSig + } + } +} + +// verifyRevocationAuxSigs verifies the aux sigs received in a RevokeAndAck +// message. It derives the same key ring that the breach-time code will use +// (DeriveCommitmentKeys with whoseCommit=Remote and our local configs) and +// verifies the signatures against the remote commitment's HTLCs. If the +// signatures don't verify now, they won't work at breach time either. +// +// The commitPoint must be the RemoteCurrentRevocation BEFORE it is rotated. +func (lc *LightningChannel) verifyRevocationAuxSigs( + auxSigBlob []byte, commitPoint *btcec.PublicKey) error { + + // If there's no aux signer, nothing to verify. + if lc.auxSigner.IsNone() { + return nil + } + + auxSigner, _ := lc.auxSigner.UnwrapOrErr( + fmt.Errorf("no aux signer"), + ) + + // Unpack the HTLC-index-tagged blob. + sigMap, err := unpackRevocationAuxSigs(auxSigBlob) + if err != nil { + return fmt.Errorf("unable to unpack revocation aux sigs "+ + "for verification: %w", err) + } + + if len(sigMap) == 0 { + return nil + } + + // Get the remote commitment view (about to be revoked). + remoteCommitView := lc.commitChains.Remote.tail() + if remoteCommitView == nil { + return nil + } + + numHTLCs := len(remoteCommitView.incomingHTLCs) + + len(remoteCommitView.outgoingHTLCs) + if numHTLCs == 0 { + return nil + } + + // Derive the key ring the same way the breach code does. + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Remote, + lc.channelState.ChanType, + &lc.channelState.LocalChanCfg, + &lc.channelState.RemoteChanCfg, + ) + + chanState := lc.channelState + chanType := chanState.ChanType + remoteChanCfg := chanState.RemoteChanCfg + feePerKw := remoteCommitView.feePerKw + dustLimit := remoteChanCfg.DustLimit + + sigHashReq := HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + chanState.FundingOutpoint, + )), + CommitBlob: chanState.RemoteCommitment.CustomBlob, + } + sigHashDefault := IsDeterministicHTLCs( + chanType, lc.auxSigner, sigHashReq, + ) + + // Fetch aux leaves for the remote commitment. + diskCommit := remoteCommitView.toDiskCommit(lntypes.Remote) + auxResult, err := fn.MapOptionZ( + lc.leafStore, + func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { + return s.FetchLeavesFromCommit( + NewAuxChanState(chanState), *diskCommit, + *keyRing, lntypes.Remote, + ) + }, + ).Unpack() + if err != nil { + return fmt.Errorf("unable to fetch aux leaves for "+ + "revocation verification: %w", err) + } + + // Build verify jobs for both spending paths of each non-dust + // HTLC, matched by HTLC index from the unpacked sig map. + type htlcEntry struct { + htlc *paymentDescriptor + incoming bool + } + var htlcList []htlcEntry + for i := range remoteCommitView.incomingHTLCs { + htlcList = append(htlcList, htlcEntry{ + htlc: &remoteCommitView.incomingHTLCs[i], + incoming: true, + }) + } + for i := range remoteCommitView.outgoingHTLCs { + htlcList = append(htlcList, htlcEntry{ + htlc: &remoteCommitView.outgoingHTLCs[i], + incoming: false, + }) + } + + auxVerifyJobs := make([]AuxVerifyJob, 0, numHTLCs*2) + commitBlob := remoteCommitView.customBlob + + for _, entry := range htlcList { + htlc := entry.htlc + incoming := entry.incoming + + if HtlcIsDust( + chanType, incoming, lntypes.Remote, feePerKw, + htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, + ) { + + continue + } + + sigEntry, ok := sigMap[htlc.HtlcIndex] + if !ok { + return fmt.Errorf("no revocation aux sig for "+ + "HTLC index %d", htlc.HtlcIndex) + } + + // Determine the aux leaf for this HTLC. + var auxLeaf input.AuxTapLeaf + if incoming { + auxLeaf = fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.IncomingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(auxResult.AuxLeaves) + } else { + auxLeaf = fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.OutgoingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(auxResult.AuxLeaves) + } + + // Verify the PRIMARY sig against its natural spending + // path: incoming→success, outgoing→timeout. From OUR + // perspective, the remote's incoming is our outgoing + // and vice versa. The signer signs from their local + // perspective where their incoming=success. Our + // "incoming" here means "incoming to the remote + // commitment" = the signer's outgoing = timeout. + // + // So: our incoming → signer's outgoing → timeout path + // our outgoing → signer's incoming → success path + if len(sigEntry.primarySig) > 0 { + primaryJob := AuxVerifyJob{ + SigBlob: fn.Some(sigEntry.primarySig), + BaseAuxJob: BaseAuxJob{ + OutputIndex: htlc. + remoteOutputIndex, + KeyRing: *keyRing, + HTLC: newAuxHtlcDescriptor( + htlc, + ), + Incoming: incoming, + IncomingHTLCLookup: incoming, + CommitBlob: commitBlob, + HtlcLeaf: auxLeaf, + WhoseCommit: lntypes.Remote, + }, + } + // The primary path for the signer: + // signer's incoming=success (no timeout needed), + // signer's outgoing=timeout (needs timeout). + // Our incoming = signer's outgoing → timeout. + if incoming { + primaryJob.HtlcTimeout = fn.Some(htlc.Timeout) + } + auxVerifyJobs = append(auxVerifyJobs, primaryJob) + } + + // Verify the ALT sig against the alternate spending + // path: incoming→timeout, outgoing→success. + if len(sigEntry.altSig) > 0 { + altJob := AuxVerifyJob{ + SigBlob: fn.Some(sigEntry.altSig), + BaseAuxJob: BaseAuxJob{ + OutputIndex: htlc.remoteOutputIndex, + KeyRing: *keyRing, + HTLC: newAuxHtlcDescriptor(htlc), + // Flip incoming for the alt + // path script generation. + Incoming: !incoming, + IncomingHTLCLookup: incoming, + CommitBlob: commitBlob, + HtlcLeaf: auxLeaf, + WhoseCommit: lntypes.Remote, + }, + } + // Alt path is the opposite: if our incoming + // (signer's outgoing) primary=timeout, then + // alt=success (no timeout needed). And vice versa. + if !incoming { + altJob.HtlcTimeout = fn.Some(htlc.Timeout) + } + auxVerifyJobs = append(auxVerifyJobs, altJob) + } + } + + if len(auxVerifyJobs) == 0 { + return nil + } + + lc.log.Infof("Verifying %d revocation aux sigs (%d HTLCs, "+ + "2 paths each) against breach-time key ring", + len(auxVerifyJobs), len(sigMap)) + + err = auxSigner.VerifySecondLevelSigs( + NewAuxChanState(lc.channelState), + remoteCommitView.txn, auxVerifyJobs, + ) + if err != nil { + return fmt.Errorf("revocation aux sig verification "+ + "failed: %w", err) + } + + lc.log.Infof("Revocation aux sig verification passed") + + return nil +} + +// htlcAuxSigParams bundles the parameters shared across both the incoming +// and outgoing HTLC aux-signing loops. +type htlcAuxSigParams struct { + chanType channeldb.ChannelType + isRemoteInitiator bool + localChanCfg channeldb.ChannelConfig + localHtlcKeyTweak []byte + feePerKw chainfee.SatPerKWeight + dustLimit btcutil.Amount + txHash chainhash.Hash + ourDelay uint32 + leaseExpiry uint32 + sigHashDefault bool + sigHashType txscript.SigHashType + keyRing *CommitmentKeyRing + auxResult CommitDiffAuxResult + commitView *commitment + cancelChan chan struct{} +} + +// signIncomingHTLCAuxSigs signs both spending paths (success + timeout) +// for each non-dust incoming HTLC on the local commitment. +func (p *htlcAuxSigParams) signIncomingHTLCAuxSigs( + htlcs []paymentDescriptor, +) ([]AuxSigJob, error) { + + var jobs []AuxSigJob + for _, htlc := range htlcs { + if HtlcIsDust( + p.chanType, true, lntypes.Local, + p.feePerKw, htlc.Amount.ToSatoshis(), + p.dustLimit, p.sigHashDefault, + ) { + + continue + } + + primary, alt, err := p.signHTLCBothPaths( + &htlc, true, + ) + if err != nil { + return nil, err + } + + jobs = append(jobs, primary, alt) + } + + return jobs, nil +} + +// signOutgoingHTLCAuxSigs signs both spending paths (timeout + success) +// for each non-dust outgoing HTLC on the local commitment. +func (p *htlcAuxSigParams) signOutgoingHTLCAuxSigs( + htlcs []paymentDescriptor, +) ([]AuxSigJob, error) { + + var jobs []AuxSigJob + for _, htlc := range htlcs { + if HtlcIsDust( + p.chanType, false, lntypes.Local, + p.feePerKw, htlc.Amount.ToSatoshis(), + p.dustLimit, p.sigHashDefault, + ) { + + continue + } + + primary, alt, err := p.signHTLCBothPaths( + &htlc, false, + ) + if err != nil { + return nil, err + } + + jobs = append(jobs, primary, alt) + } + + return jobs, nil +} + +// signHTLCBothPaths creates AuxSigJobs for both the primary and +// alternate spending paths of an HTLC. For incoming HTLCs the +// primary path is success and the alternate is timeout; for +// outgoing HTLCs the primary is timeout and the alternate is +// success. +func (p *htlcAuxSigParams) signHTLCBothPaths( + htlc *paymentDescriptor, incoming bool, +) (AuxSigJob, AuxSigJob, error) { + + auxLeaf := p.getAuxLeaf(htlc, incoming) + op := wire.OutPoint{ + Hash: p.txHash, + Index: uint32(htlc.localOutputIndex), + } + + // Build the primary second-level tx. + primaryTx, _, err := p.createSecondLevelTx( + op, htlc, incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, AuxSigJob{}, err + } + + amt := htlc.Amount.ToSatoshis() + txOut := p.commitView.txn.TxOut[htlc.localOutputIndex] + prevFetcher := txscript.NewCannedPrevOutputFetcher( + txOut.PkScript, int64(amt), + ) + + primaryJob, err := p.buildSigJob( + primaryTx, txOut, prevFetcher, htlc, + incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, AuxSigJob{}, err + } + + // Build the alternate second-level tx (opposite path). + altTx, _, err := p.createSecondLevelTx( + op, htlc, !incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, AuxSigJob{}, err + } + + altJob, err := p.buildSigJob( + altTx, txOut, prevFetcher, htlc, + !incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, AuxSigJob{}, err + } + + // The alt job flips Incoming for script generation, but the + // asset lookup must still use the original HTLC direction. + altJob.IncomingHTLCLookup = incoming + + // Set timeout fields. The primary path for incoming is + // success (no timeout), alt is timeout. Vice versa for + // outgoing. + if incoming { + primaryJob.HtlcTimeout = fn.None[uint32]() + altJob.HtlcTimeout = fn.Some(htlc.Timeout) + } else { + primaryJob.HtlcTimeout = fn.Some(htlc.Timeout) + altJob.HtlcTimeout = fn.None[uint32]() + } + + return primaryJob, altJob, nil +} + +// createSecondLevelTx creates the second-level HTLC transaction for +// the given path. When incoming is true a success-tx is created; +// when false a timeout-tx is created. Returns the tx and its fee. +func (p *htlcAuxSigParams) createSecondLevelTx( + op wire.OutPoint, htlc *paymentDescriptor, + incoming bool, auxLeaf input.AuxTapLeaf, +) (*wire.MsgTx, btcutil.Amount, error) { + + if incoming { + fee := HtlcSuccessFee( + p.chanType, p.feePerKw, p.sigHashDefault, + ) + amt := htlc.Amount.ToSatoshis() - fee + tx, err := CreateHtlcSuccessTx( + p.chanType, p.isRemoteInitiator, op, + amt, p.ourDelay, p.leaseExpiry, + p.keyRing.RevocationKey, + p.keyRing.ToLocalKey, auxLeaf, + ) + + return tx, fee, err + } + + fee := HtlcTimeoutFee( + p.chanType, p.feePerKw, p.sigHashDefault, + ) + amt := htlc.Amount.ToSatoshis() - fee + tx, err := CreateHtlcTimeoutTx( + p.chanType, p.isRemoteInitiator, op, amt, + htlc.Timeout, p.ourDelay, p.leaseExpiry, + p.keyRing.RevocationKey, + p.keyRing.ToLocalKey, auxLeaf, + ) + + return tx, fee, err +} + +// buildSigJob creates an AuxSigJob for a second-level HTLC +// transaction, wrapping the sign descriptor and script generation. +func (p *htlcAuxSigParams) buildSigJob( + tx *wire.MsgTx, txOut *wire.TxOut, + prevFetcher txscript.PrevOutputFetcher, + htlc *paymentDescriptor, incoming bool, + auxLeaf input.AuxTapLeaf, +) (AuxSigJob, error) { + + hashCache := txscript.NewTxSigHashes(tx, prevFetcher) + htlcScript, err := genHtlcScript( + p.chanType, incoming, lntypes.Local, + htlc.Timeout, htlc.RHash, p.keyRing, + fn.None[txscript.TapLeaf](), + ) + if err != nil { + return AuxSigJob{}, err + } + + ws := htlcScript.WitnessScriptToSign() + sigJob := SignJob{ + SignDesc: input.SignDescriptor{ + KeyDesc: p.localChanCfg.HtlcBasePoint, + SingleTweak: p.localHtlcKeyTweak, + WitnessScript: ws, + Output: txOut, + PrevOutputFetcher: prevFetcher, + HashType: p.sigHashType, + SigHashes: hashCache, + InputIndex: 0, + }, + Tx: tx, + OutputIndex: htlc.localOutputIndex, + } + if p.chanType.IsTaproot() { + sigJob.SignDesc.SignMethod = input.TaprootScriptSpendSignMethod + } + + auxJob := NewAuxSigJob( + sigJob, *p.keyRing, incoming, + newAuxHtlcDescriptor(htlc), + p.commitView.customBlob, auxLeaf, + lntypes.Local, p.cancelChan, + ) + + return auxJob, nil +} + +// getAuxLeaf returns the aux tap leaf for the given HTLC. +func (p *htlcAuxSigParams) getAuxLeaf( + htlc *paymentDescriptor, incoming bool, +) input.AuxTapLeaf { + + if incoming { + return fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.IncomingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(p.auxResult.AuxLeaves) + } + + return fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.OutgoingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(p.auxResult.AuxLeaves) +} + +// signLocalHtlcAuxSigs signs the second-level HTLC virtual packets for the +// current local commitment (the one being revoked). These signatures allow +// the remote party to reconstruct valid aux proofs for the +// commitment-to-second-level transition if a breach occurs. The returned +// blob is packed in the same format as CommitSig aux sigs and can be +// attached to RevokeAndAck.CustomRecords. +// +// This method must be called BEFORE advanceTail() since it needs access to the +// current local commitment view and the commitment secret at currentHeight. +func (lc *LightningChannel) signLocalHtlcAuxSigs() ([]byte, error) { + // If there's no aux signer, nothing to do. + if lc.auxSigner.IsNone() { + return nil, nil + } + + // Get the current local commitment view (about to be revoked). + localCommitView := lc.commitChains.Local.tail() + if localCommitView == nil { + return nil, nil + } + + // Check if there are any HTLCs to sign. + numHTLCs := len(localCommitView.incomingHTLCs) + + len(localCommitView.outgoingHTLCs) + if numHTLCs == 0 { + return nil, nil + } + + // Derive the key ring for our local commitment using the + // standard perspective (whoseCommit=Local, standard config + // order). This matches how the commitment was originally + // built, so the AuxSig will be over the actual on-chain + // second-level HTLC outputs. + commitSecret, err := lc.channelState.RevocationProducer.AtIndex( + lc.currentHeight, + ) + if err != nil { + return nil, err + } + commitPoint := input.ComputeCommitmentPoint(commitSecret[:]) + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Local, + lc.channelState.ChanType, + &lc.channelState.LocalChanCfg, + &lc.channelState.RemoteChanCfg, + ) + + chanState := lc.channelState + chanType := chanState.ChanType + + var leaseExpiry uint32 + if chanType.HasLeaseExpiration() { + leaseExpiry = chanState.ThawHeight + } + + sigHashReq := HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + chanState.FundingOutpoint, + )), + CommitBlob: chanState.LocalCommitment.CustomBlob, + } + sigHashDefault := IsDeterministicHTLCs( + chanType, lc.auxSigner, sigHashReq, + ) + sigHashType := ResolveHtlcSigHashType( + chanType, lc.auxSigner, sigHashReq, + ) + + // Fetch aux leaves for our local commitment, matching how + // the commitment was originally constructed. + diskCommit := localCommitView.toDiskCommit(lntypes.Local) + auxResult, err := fn.MapOptionZ( + lc.leafStore, + func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { + return s.FetchLeavesFromCommit( + NewAuxChanState(chanState), *diskCommit, + *keyRing, lntypes.Local, + ) + }, + ).Unpack() + if err != nil { + return nil, fmt.Errorf("unable to fetch aux leaves: %w", err) + } + + cancelChan := make(chan struct{}) + + localChanCfg := chanState.LocalChanCfg + params := htlcAuxSigParams{ + chanType: chanType, + isRemoteInitiator: !chanState.IsInitiator, + localChanCfg: localChanCfg, + localHtlcKeyTweak: keyRing.LocalHtlcKeyTweak, + feePerKw: localCommitView.feePerKw, + dustLimit: chanState.LocalChanCfg.DustLimit, + txHash: localCommitView.txn.TxHash(), + ourDelay: uint32(localChanCfg.CsvDelay), + leaseExpiry: leaseExpiry, + sigHashDefault: sigHashDefault, + sigHashType: sigHashType, + keyRing: keyRing, + auxResult: auxResult, + commitView: localCommitView, + cancelChan: cancelChan, + } + + // Sign incoming HTLCs (both success + timeout paths). + inJobs, err := params.signIncomingHTLCAuxSigs( + localCommitView.incomingHTLCs, + ) + if err != nil { + return nil, err + } + + // Sign outgoing HTLCs (both timeout + success paths). + outJobs, err := params.signOutgoingHTLCAuxSigs( + localCommitView.outgoingHTLCs, + ) + if err != nil { + return nil, err + } + + auxSigBatch := append(inJobs, outJobs...) //nolint:gocritic + + if len(auxSigBatch) == 0 { + return nil, nil + } + + // Sort by output index to match the order the verify side and + // inject code expect (same as genRemoteHtlcSigJobs). + slices.SortFunc(auxSigBatch, func(i, j AuxSigJob) int { + return cmp.Compare(i.OutputIndex, j.OutputIndex) + }) + + // Submit the signing batch using the standard chanState + // (matching the commitment construction perspective). + auxSigner, _ := lc.auxSigner.UnwrapOrErr( + fmt.Errorf("no aux signer"), + ) + err = auxSigner.SubmitSecondLevelSigBatch( + NewAuxChanState(lc.channelState), + localCommitView.txn, auxSigBatch, + ) + if err != nil { + return nil, fmt.Errorf("unable to submit aux sig batch: %w", + err) + } + + // Collect the signatures from the batch. + auxSigs := make([]fn.Option[tlv.Blob], len(auxSigBatch)) + for i, sigJob := range auxSigBatch { + resp := <-sigJob.Resp + if resp.Err != nil { + close(cancelChan) + return nil, fmt.Errorf("aux sig job %d "+ + "failed: %w", i, resp.Err) + } + auxSigs[i] = resp.SigBlob + } + + // Pack sigs into a blob tagged by HTLC index. We can't rely on the + // two jobs for a given HTLC remaining adjacent after the global + // output-index sort above. Once multiple HTLCs are present, an + // adjacent-pair assumption can mix primary/alt sigs across HTLCs and + // produce an invalid RevokeAndAck aux-sig blob. Group by HTLC index and + // path type explicitly before packing. + entryByHtlc := make(map[uint64]revocationAuxSigEntry) + for i, sigOpt := range auxSigs { + htlcIdx := auxSigBatch[i].HTLC.HtlcIndex + entry := entryByHtlc[htlcIdx] + entry.htlcIndex = htlcIdx + + // The natural path keeps Incoming equal to the original + // HTLC direction used for aux-output lookup. The alternate + // path flips Incoming for script generation but preserves + // IncomingHTLCLookup. + if auxSigBatch[i].Incoming == + auxSigBatch[i].IncomingHTLCLookup { + + entry.primarySig = sigOpt.UnwrapOr(nil) + } else { + entry.altSig = sigOpt.UnwrapOr(nil) + } + + entryByHtlc[htlcIdx] = entry + } + + entries := make([]revocationAuxSigEntry, 0, len(entryByHtlc)) + for _, entry := range entryByHtlc { + entries = append(entries, entry) + } + slices.SortFunc(entries, func(i, j revocationAuxSigEntry) int { + return cmp.Compare(i.htlcIndex, j.htlcIndex) + }) + + // If no entry has any actual sig data, return nil to avoid + // attaching an empty blob to the RevokeAndAck. + hasSigs := false + for _, e := range entries { + if len(e.primarySig) > 0 || len(e.altSig) > 0 { + hasSigs = true + + break + } + } + if !hasSigs { + return nil, nil + } + + packed, err := packRevocationAuxSigs(entries) + if err != nil { + return nil, fmt.Errorf("pack revocation aux sigs: %w", err) + } + + return packed, nil +} + // createCommitDiff will create a commit diff given a new pending commitment // for the remote party and the necessary signatures for the remote party to // validate this new state. This function is called right before sending the @@ -5194,7 +6082,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, sigHashType := ResolveHtlcSigHashType( chanType, auxSigner, sigHashReq, ) - sigHashDefault := IsSigHashDefault( + sigHashDefault := IsDeterministicHTLCs( chanType, auxSigner, sigHashReq, ) @@ -6010,6 +6898,36 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, lc.commitChains.Local.tail().height, lc.currentHeight+1) + // Sign second-level HTLC virtual packets for the commitment + // being revoked, but only if the DeterministicHTLCs feature is + // negotiated. Without the feature the remote party has no use + // for the signatures (and wouldn't know how to parse them). + sigHashReq := HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + lc.channelState.FundingOutpoint, + )), + CommitBlob: lc.channelState.LocalCommitment.CustomBlob, + } + + if IsDeterministicHTLCs( + lc.channelState.ChanType, lc.auxSigner, sigHashReq, + ) { + + auxSigBlob, err := lc.signLocalHtlcAuxSigs() + if err != nil { + lc.log.Errorf("Unable to sign local HTLC aux "+ + "sigs for revocation: %v", err) + } + if auxSigBlob != nil { + revocationMsg.CustomRecords = + make(lnwire.CustomRecords) + + recType := uint64(lnwire.MinCustomRecordsTlvType) + revocationMsg.CustomRecords[recType] = + auxSigBlob + } + } + // Advance our tail, as we've revoked our previous state. lc.commitChains.Local.advanceTail() lc.currentHeight++ @@ -6288,6 +7206,43 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) ( lc.musigSessions.RemoteSession = session } + // When the DeterministicHTLCs feature is negotiated, the + // RevokeAndAck must contain aux sigs for the remote party's + // second-level HTLCs. Verify all signatures against the + // breach-time key ring before accepting the revocation, then + // store them in the revocation log for breach recovery. + // + // When the feature is NOT negotiated, skip verification + // entirely — the remote party does not include aux sigs. + revSigHashReq := HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + lc.channelState.FundingOutpoint, + )), + CommitBlob: lc.channelState.RemoteCommitment. + CustomBlob, + } + deterministicHTLCs := IsDeterministicHTLCs( + lc.channelState.ChanType, lc.auxSigner, + revSigHashReq, + ) + if deterministicHTLCs { + recType := uint64(lnwire.MinCustomRecordsTlvType) + auxSigBlob := revMsg.CustomRecords[recType] + + if len(auxSigBlob) > 0 { + err = lc.verifyRevocationAuxSigs( + auxSigBlob, currentCommitPoint, + ) + if err != nil { + return nil, nil, fmt.Errorf("invalid "+ + "revocation aux sigs: %w", + err) + } + + lc.injectRevocationAuxSigs(auxSigBlob) + } + } + // At this point, the revocation has been accepted, and we've rotated // the current revocation key+hash for the remote party. Therefore we // sync now to ensure the revocation producer state is consistent with @@ -7764,7 +8719,7 @@ func newOutgoingHtlcResolution(signer input.Signer, // In order to properly reconstruct the HTLC transaction, we'll need to // re-calculate the fee required at this state, so we can add the // correct output value amount to the transaction. - htlcFee := HtlcTimeoutFee(chanType, feePerKw, IsSigHashDefault( + htlcFee := HtlcTimeoutFee(chanType, feePerKw, IsDeterministicHTLCs( chanType, auxSigner, HtlcSigHashReq{ CommitBlob: chanState.LocalCommitment.CustomBlob, @@ -8154,7 +9109,7 @@ func newIncomingHtlcResolution(signer input.Signer, // // First, we'll reconstruct the original HTLC success transaction, // taking into account the fee rate used. - htlcFee := HtlcSuccessFee(chanType, feePerKw, IsSigHashDefault( + htlcFee := HtlcSuccessFee(chanType, feePerKw, IsDeterministicHTLCs( chanType, auxSigner, HtlcSigHashReq{ CommitBlob: chanState.LocalCommitment.CustomBlob, @@ -8556,7 +9511,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, if HtlcIsDust( chanType, htlc.Incoming, whoseCommit, feePerKw, htlc.Amt.ToSatoshis(), dustLimit, - IsSigHashDefault( + IsDeterministicHTLCs( chanType, auxSigner, HtlcSigHashReq{ CommitBlob: chanState. diff --git a/lnwallet/revocation_aux_sig_test.go b/lnwallet/revocation_aux_sig_test.go new file mode 100644 index 00000000000..deda52ecc34 --- /dev/null +++ b/lnwallet/revocation_aux_sig_test.go @@ -0,0 +1,101 @@ +package lnwallet + +import ( + "math" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestPackUnpackRevocationAuxSigs tests the round-trip encoding and decoding +// of revocation aux sig entries. +func TestPackUnpackRevocationAuxSigs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + entries []revocationAuxSigEntry + }{ + { + name: "empty entries", + entries: []revocationAuxSigEntry{}, + }, + { + name: "single entry with one HTLC", + entries: []revocationAuxSigEntry{ + { + htlcIndex: 42, + primarySig: []byte{0xaa, 0xbb, 0xcc}, + altSig: []byte{0xdd, 0xee, 0xff}, + }, + }, + }, + { + name: "multiple entries with various HTLC indices", + entries: []revocationAuxSigEntry{ + { + htlcIndex: 0, + primarySig: []byte{0x01}, + altSig: []byte{0x02, 0x03}, + }, + { + htlcIndex: 100, + primarySig: []byte{0x04, 0x05, 0x06}, + altSig: []byte{0x07}, + }, + { + htlcIndex: 999, + primarySig: []byte{0x08, 0x09}, + altSig: []byte{ + 0x0a, 0x0b, 0x0c, 0x0d, + }, + }, + }, + }, + { + name: "entry with empty primary and alt sigs", + entries: []revocationAuxSigEntry{ + { + htlcIndex: 7, + primarySig: []byte{}, + altSig: []byte{}, + }, + }, + }, + { + name: "max uint64 HTLC index", + entries: []revocationAuxSigEntry{ + { + htlcIndex: math.MaxUint64, + primarySig: []byte{0xde, 0xad}, + altSig: []byte{0xbe, 0xef}, + }, + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + packed, err := packRevocationAuxSigs(tc.entries) + require.NoError(t, err) + + sigMap, err := unpackRevocationAuxSigs(packed) + require.NoError(t, err) + + require.Len(t, sigMap, len(tc.entries)) + + for _, entry := range tc.entries { + got, ok := sigMap[entry.htlcIndex] + require.True(t, ok, "missing HTLC index %d", + entry.htlcIndex) + + require.Equal(t, entry.htlcIndex, got.htlcIndex) + require.Equal( + t, entry.primarySig, + got.primarySig, + ) + require.Equal(t, entry.altSig, got.altSig) + } + }) + } +} diff --git a/lnwire/revoke_and_ack.go b/lnwire/revoke_and_ack.go index e2a4c930798..222ef35e13e 100644 --- a/lnwire/revoke_and_ack.go +++ b/lnwire/revoke_and_ack.go @@ -42,6 +42,13 @@ type RevokeAndAck struct { // nonces, keyed by TXID. This is used for splice nonce coordination. LocalNonces OptLocalNonces + // CustomRecords is a set of custom TLV records that can be used to + // attach auxiliary data to the revocation message. For custom + // channels, this carries the revoking party's aux signatures for + // the second-level HTLC transactions on the commitment being + // revoked. + CustomRecords CustomRecords + // ExtraData is the set of data that was appended to this message to // fill out the full maximum transport message size. These fields can // be used to specify optional data such as custom TLV fields. @@ -50,9 +57,7 @@ type RevokeAndAck struct { // NewRevokeAndAck creates a new RevokeAndAck message. func NewRevokeAndAck() *RevokeAndAck { - return &RevokeAndAck{ - ExtraData: make([]byte, 0), - } + return &RevokeAndAck{} } // A compile time check to ensure RevokeAndAck implements the lnwire.Message @@ -68,43 +73,41 @@ var _ SizeableMessage = (*RevokeAndAck)(nil) // // This is part of the lnwire.Message interface. func (c *RevokeAndAck) Decode(r io.Reader, pver uint32) error { + // msgExtraData is a temporary variable used to read the message extra + // data field from the reader. + var msgExtraData ExtraOpaqueData + err := ReadElements(r, &c.ChanID, c.Revocation[:], &c.NextRevocationKey, + &msgExtraData, ) if err != nil { return err } - var tlvRecords ExtraOpaqueData - if err := ReadElements(r, &tlvRecords); err != nil { - return err - } - - var ( - localNonce = c.LocalNonce.Zero() - localNoncesData LocalNoncesData - ) + // Extract TLV records from the extra data field. + localNonce := c.LocalNonce.Zero() + var localNoncesData LocalNoncesData - typeMap, err := tlvRecords.ExtractRecords( - &localNonce, &localNoncesData, + customRecords, parsed, extraData, err := ParseAndExtractCustomRecords( + msgExtraData, &localNonce, &localNoncesData, ) if err != nil { return err } // Set the corresponding TLV types if they were included in the stream. - if val, ok := typeMap[c.LocalNonce.TlvType()]; ok && val == nil { + if _, ok := parsed[localNonce.TlvType()]; ok { c.LocalNonce = tlv.SomeRecordT(localNonce) } - if val, ok := typeMap[(LocalNoncesRecordTypeDef)(nil).TypeVal()]; ok && val == nil { //nolint:ll + if _, ok := parsed[(LocalNoncesRecordTypeDef)(nil).TypeVal()]; ok { c.LocalNonces = SomeLocalNonces(localNoncesData) } - if len(tlvRecords) != 0 { - c.ExtraData = tlvRecords - } + c.CustomRecords = customRecords + c.ExtraData = extraData return nil } @@ -121,7 +124,10 @@ func (c *RevokeAndAck) Encode(w *bytes.Buffer, pver uint32) error { c.LocalNonces.WhenSome(func(ln LocalNoncesData) { recordProducers = append(recordProducers, &ln) }) - err := EncodeMessageExtraData(&c.ExtraData, recordProducers...) + + extraData, err := MergeAndEncode( + recordProducers, c.ExtraData, c.CustomRecords, + ) if err != nil { return err } @@ -138,7 +144,7 @@ func (c *RevokeAndAck) Encode(w *bytes.Buffer, pver uint32) error { return err } - return WriteBytes(w, c.ExtraData) + return WriteBytes(w, extraData) } // MsgType returns the integer uniquely identifying this message type on the diff --git a/sweep/interface.go b/sweep/interface.go index d593a5e8a35..53cd647c4bf 100644 --- a/sweep/interface.go +++ b/sweep/interface.go @@ -83,12 +83,29 @@ type AuxNotifyOpts struct { // commitments) and should not be broadcast again. SkipBroadcast bool - // SkipProofVerify indicates whether asset-level proof + // SkipProofVerify indicates whether aux-level proof // verification should be skipped. This is used when the input // proofs contain placeholder witnesses (e.g. second-level HTLC // outputs) that cannot pass VM-level validation, and the // on-chain confirmation serves as proof of validity instead. SkipProofVerify bool + + // ConfirmHeight is an optional confirmation height hint for the + // transaction. When set, the porter uses this as the height hint + // when scanning for the on-chain confirmation instead of the + // current chain tip. This is critical for breach justice sweeps + // where NotifyBroadcast is called after the tx has already been + // confirmed and the chain has advanced past the confirmation + // block. + ConfirmHeight uint32 + + // LookupInputProofs indicates that the aux sweeper should look + // up the input proofs from its proof archive rather than using + // the proofs embedded in the resolution blob. This is needed + // when the resolution blob carries a stale proof (e.g. the + // commit-level proof for a second-level HTLC output that has + // since been imported with a proper second-level proof). + LookupInputProofs bool } // AuxSweeper is used to enable a 3rd party to further shape the sweeping From 275ea444b24b870039134003367744f6bdd5c73f Mon Sep 17 00:00:00 2001 From: George Tsagkarelis Date: Wed, 22 Jul 2026 09:13:58 +0000 Subject: [PATCH 17/17] squash-fixup: gate aux revocation paths on custom-channel type TO BE FOLDED before merge: this commit is kept separate purely for reviewability of the isolation change. Squash each hunk into its respective aux-revocation commit: - IsDeterministicHTLCs HasTapscriptRoot guard (lnwallet/aux_signer.go) -> "lnwallet+contractcourt: gate HTLC sighash on negotiated feature bit" - createHtlcRetribution HasTapscriptRoot gate (lnwallet/channel.go) -> "lnwallet: preserve resolution request for HTLC resolutions" - RevokeAndAck AuxSig sign/verify comments (lnwallet/channel.go) -> "multi: add revocation AuxSig signing and verification" - resolver isAuxChannel() + gated re-resolve (contractcourt/htlc_*_resolver.go) -> "contractcourt: publish pre-signed second-level HTLCs under SigHashDefault" - breach arbiter resolveReq discriminator comment (contractcourt/breach_arbitrator.go) -> "contractcourt: enhance breach arbiter for second-level HTLC revocation" Makes it unmistakable that every aux (taproot asset) revocation action runs only for custom channels, which are exactly the channels carrying a tapscript root. No behavior change for custom channels; non-custom channels provably skip these paths. --- contractcourt/breach_arbitrator.go | 14 ++++++--- contractcourt/htlc_success_resolver.go | 21 ++++++++++++- contractcourt/htlc_timeout_resolver.go | 21 ++++++++++++- lnwallet/aux_signer.go | 11 +++++++ lnwallet/channel.go | 42 +++++++++++++++++--------- 5 files changed, 88 insertions(+), 21 deletions(-) diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 8e008600f59..2579a5a5cf3 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -627,10 +627,16 @@ func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo, // longer matches output index. We script-match our expected // second-level pkScript to locate the right output. // - // On non-aux channels (regular legacy/anchor/taproot) we keep the - // legacy behavior of using SpenderInputIndex directly. The - // script-matching code path only runs for aux channels so we don't - // regress sweep behavior on normal channels. + // On non-aux channels (regular legacy/anchor/taproot, including + // non-custom simple taproot) we keep the legacy behavior of using + // SpenderInputIndex directly, so we don't regress sweep behavior on + // normal channels. + // + // resolveReq is a reliable aux-channel discriminator here: it is + // populated in createHtlcRetribution only for channels with a + // tapscript root (aux/custom channels), so a nil resolveReq + // unambiguously means "not a custom channel" and takes the legacy + // path below. spendingTx := spendDetails.SpendingTx isAuxChannel := bo.resolveReq != nil diff --git a/contractcourt/htlc_success_resolver.go b/contractcourt/htlc_success_resolver.go index 9f715c93593..eb21ee13d43 100644 --- a/contractcourt/htlc_success_resolver.go +++ b/contractcourt/htlc_success_resolver.go @@ -427,6 +427,15 @@ func (h *htlcSuccessResolver) isSigHashDefault() bool { ) } +// isAuxChannel reports whether this resolver is running for an aux/custom +// (taproot asset) channel. Only such channels carry a tapscript root, so +// this is the authoritative, self-contained predicate used to keep every +// aux-specific code path in this resolver from running on non-custom +// channels. +func (h *htlcSuccessResolver) isAuxChannel() bool { + return h.chanType.HasTapscriptRoot() +} + // buildSecondLevelResolveReq returns a ResolutionReq targeting the // just-confirmed second-level HTLC tx. The fast path clones the // ResolveReq preserved on htlcResolution at force-close time and updates @@ -678,7 +687,17 @@ func (h *htlcSuccessResolver) sweepSuccessTxOutput() error { // encoder doesn't currently round-trip ResolveReq, so resolvers // recovered from a checkpoint have it nil. resolutionBlob := h.htlcResolution.ResolutionBlob - h.AuxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { + + // The aux blob re-resolution below is an aux/custom (taproot asset) + // channel concern only. The AuxResolver is a daemon-global option + // (present on every resolver whenever tapd is attached, regardless of + // channel type), so we additionally gate on the channel type here to + // guarantee this path never executes for a non-custom channel. + auxResolver := fn.None[lnwallet.AuxContractResolver]() + if h.isAuxChannel() { + auxResolver = h.AuxResolver + } + auxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { secondLevelReq, err := h.buildSecondLevelResolveReq( witType, h.htlcResolution.SignedSuccessTx, uint32(commitSpend.SpendingHeight), diff --git a/contractcourt/htlc_timeout_resolver.go b/contractcourt/htlc_timeout_resolver.go index dd6d6bf51cb..ba1d48e12e9 100644 --- a/contractcourt/htlc_timeout_resolver.go +++ b/contractcourt/htlc_timeout_resolver.go @@ -982,6 +982,15 @@ func (h *htlcTimeoutResolver) isSigHashDefault() bool { ) } +// isAuxChannel reports whether this resolver is running for an aux/custom +// (taproot asset) channel. Only such channels carry a tapscript root, so +// this is the authoritative, self-contained predicate used to keep every +// aux-specific code path in this resolver from running on non-custom +// channels. +func (h *htlcTimeoutResolver) isAuxChannel() bool { + return h.chanType.HasTapscriptRoot() +} + // buildSecondLevelResolveReq returns a ResolutionReq targeting the // just-confirmed second-level HTLC tx. The fast path clones the // ResolveReq preserved on htlcResolution at force-close time and updates @@ -1138,7 +1147,17 @@ func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error { // encoder doesn't currently round-trip ResolveReq, so resolvers // recovered from a checkpoint have it nil. resolutionBlob := h.htlcResolution.ResolutionBlob - h.AuxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { + + // The aux blob re-resolution below is an aux/custom (taproot asset) + // channel concern only. The AuxResolver is a daemon-global option + // (present on every resolver whenever tapd is attached, regardless of + // channel type), so we additionally gate on the channel type here to + // guarantee this path never executes for a non-custom channel. + auxResolver := fn.None[lnwallet.AuxContractResolver]() + if h.isAuxChannel() { + auxResolver = h.AuxResolver + } + auxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { secondLevelReq, err := h.buildSecondLevelResolveReq( witType, h.htlcResolution.SignedTimeoutTx, uint32(commitSpend.SpendingHeight), diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index e8ddf9dc4ce..f5dc0053e79 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -387,6 +387,17 @@ func IsDeterministicHTLCs(chanType channeldb.ChannelType, auxSigner fn.Option[AuxSigner], req HtlcSigHashReq) bool { + // DeterministicHTLCs is exclusively an aux/custom (taproot asset) + // channel feature. Such channels are the only ones that carry a + // tapscript root, so we gate on the channel type first: no + // non-custom channel can ever take a DeterministicHTLCs code path, + // regardless of aux signer state. This keeps every downstream call + // site (dust/fee calc, commitment building, revocation AuxSigs, + // breach retribution) confined to custom channels. + if !chanType.HasTapscriptRoot() { + return false + } + return ResolveHtlcSigHashType( chanType, auxSigner, req, ) == txscript.SigHashDefault diff --git a/lnwallet/channel.go b/lnwallet/channel.go index 34741e59ae9..f3b8bf87e85 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2621,11 +2621,18 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, htlcWitnessType = input.HtlcOfferedRevoke } - // Only taproot channels can be modified by aux channels, so we - // only need to resolve the aux blob for taproot channel types. + // Aux resolution data (the resolution blob and the preserved + // ResolveReq template used by the breach arbiter for second-level + // re-resolution) is exclusively an aux/custom channel concern. + // Custom channels are precisely the taproot channels that carry a + // tapscript root, so we gate on that here rather than on plain + // IsTaproot(): this guarantees non-custom taproot channels (e.g. + // simple taproot) get a nil ResolveReq and empty blob, leaving + // their breach handling byte-for-byte unchanged. var resolutionBlob fn.Option[tlv.Blob] var savedResolveReq *ResolutionReq - if isTaproot { + isAuxChannel := chanState.ChanType.HasTapscriptRoot() + if isAuxChannel { htlcIDOpt := fn.MapOption( func(v tlv.BigSizeT[uint64]) input.HtlcIndex { return v.Int() @@ -6898,10 +6905,15 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, lc.commitChains.Local.tail().height, lc.currentHeight+1) - // Sign second-level HTLC virtual packets for the commitment - // being revoked, but only if the DeterministicHTLCs feature is - // negotiated. Without the feature the remote party has no use - // for the signatures (and wouldn't know how to parse them). + // Attach revocation AuxSigs to the RevokeAndAck, but ONLY for + // aux/custom (taproot asset) channels. This is a custom-channel-only + // addition to the message: IsDeterministicHTLCs is false for every + // non-custom channel (it requires a tapscript root, see + // IsDeterministicHTLCs), so a vanilla lnd channel never signs or + // appends these records and its RevokeAndAck is byte-identical to + // before this feature. Without DeterministicHTLCs the remote party + // has no use for the signatures (and wouldn't know how to parse + // them). sigHashReq := HtlcSigHashReq{ ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( lc.channelState.FundingOutpoint, @@ -7206,14 +7218,14 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) ( lc.musigSessions.RemoteSession = session } - // When the DeterministicHTLCs feature is negotiated, the - // RevokeAndAck must contain aux sigs for the remote party's - // second-level HTLCs. Verify all signatures against the - // breach-time key ring before accepting the revocation, then - // store them in the revocation log for breach recovery. - // - // When the feature is NOT negotiated, skip verification - // entirely — the remote party does not include aux sigs. + // Revocation AuxSigs are a custom-channel-only concern. On aux/custom + // (taproot asset) channels with DeterministicHTLCs negotiated, the + // RevokeAndAck carries aux sigs for the remote party's second-level + // HTLCs; we verify them against the breach-time key ring before + // accepting the revocation, then store them in the revocation log for + // breach recovery. For every non-custom channel IsDeterministicHTLCs + // is false (it requires a tapscript root, see IsDeterministicHTLCs), + // so we skip this block entirely and never inspect CustomRecords. revSigHashReq := HtlcSigHashReq{ ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( lc.channelState.FundingOutpoint,