← Back to Pull requests

[1/3] aux revocation: add deterministic HTLCs #11094

Open
GeorgeTsagk opened this pull request with 4528 lines diff across 27 files
View on GitHub
GeorgeTsagk GeorgeTsagk commented on Aug 18, 2026 08:47 UTC
Author

Description

Punishing a revoked commitment on an asset channel requires more than the bitcoin-level justice sweep: the asset side needs a valid asset witness for whatever transaction the cheater actually confirms, including second-level HTLC spends.

Under the normal SINGLE|ANYONECANPAY scheme those second-level transactions are malleable (the broadcaster can add fee inputs, batch, or RBF them), so their final form is unknowable in advance and no asset witness or proof chain could be prepared for them. With deterministic HTLCs both parties commit to the exact final second-level transaction via SIGHASH_DEFAULT, so the revoking party can pre-sign asset-level signatures for both spend paths of every HTLC and hand them over in RevokeAndAck (this will be the next part), giving the honest party everything needed to claim the assets no matter which path a breach takes.

Next PR: #11111

Diff: 4528 lines (+4443 / -85) across 27 files Reviewer: gijswijs Review duration: 137992m
All Vouch review confidence checks passed
Residual risk 0.10 = Change Risk (0.84) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.84 · 4528 lines diff across 27 files
0.84
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
58 items
github-actions[bot] github-actions[bot] commented on Aug 18, 2026 08:50 UTC
Bot

🔴 PR Severity: CRITICAL

file classification | 23 files | 1205 lines changed (768 excluding tests)

<details>
<summary>🔴 <strong>Critical</strong> (14 files)</summary>

  • contractcourt/chain_arbitrator.go - on-chain dispute resolution coordination

  • contractcourt/chain_watcher.go - on-chain dispute resolution coordination

  • contractcourt/contract_resolver.go - on-chain dispute/breach resolution logic

  • contractcourt/htlc_success_resolver.go - HTLC breach/resolution handling

  • contractcourt/htlc_timeout_resolver.go - HTLC breach/resolution handling

  • htlcswitch/link.go - HTLC forwarding state machine

  • htlcswitch/mock.go - htlcswitch package support code

  • lnwallet/aux_signer.go - commitment/signing logic

  • lnwallet/chanfunding/coin_select.go - channel funding coin selection

  • lnwallet/channel.go - channel state, commitment transactions

  • lnwallet/commitment.go - commitment transaction construction

  • lnwallet/mock.go - lnwallet package support code

  • lnwallet/transactions.go - transaction construction/signing

  • server.go - core server coordination
  • </details>

    <details>
    <summary>🟢 <strong>Low</strong> (9 files, tests only)</summary>

  • contractcourt/breach_arbitrator_test.go

  • contractcourt/contract_resolver_test.go

  • htlcswitch/mailbox_test.go

  • input/size_test.go

  • lnrpc/walletrpc/walletkit_server_test.go

  • lnwallet/aux_signer_test.go

  • lnwallet/channel_test.go

  • lnwallet/chanfunding/coin_select_test.go

  • lnwallet/transactions_test.go
  • </details>

    Analysis

    This PR touches core contractcourt/, htlcswitch/, and lnwallet/* packages — on-chain breach/HTLC resolution, HTLC forwarding, and commitment transaction/signing logic — each of which is independently CRITICAL. The change spans multiple distinct critical packages (contractcourt, htlcswitch, lnwallet) and modifies ~768 non-test lines across 14 non-test files, well above the >500 line bump threshold, reinforcing the CRITICAL classification. Given the surface area (commitment transactions, HTLC resolvers, channel funding), this warrants expert review focused on correctness of on-chain resolution paths and signing logic.

    ---
    <sub>To override, add a severity-override-{critical,high,medium,low} label.</sub>
    <!-- pr-severity-bot -->

    GeorgeTsagk GeorgeTsagk commented on Aug 18, 2026 09:00 UTC
    Author

    Added no-changelog label, will include one with the 3rd and final part of this PR series.

    gijswijs gijswijs commented on code on Aug 18, 2026 13:01 UTC
    Code Review
    input/size_test.go:1
    @@ -1704,7 +1705,9 @@ func genSuccessTx(t *testing.T, chanType channeldb.ChannelType) *wire.MsgTx {
     		},
     	}
     
    -	sigHashType := lnwallet.HtlcSigHashType(channeldb.SingleFunderBit)
    +	sigHashType := lnwallet.HtlcSigHashType(
    +		channeldb.SingleFunderBit,

    Still fits on one line.

    gijswijs gijswijs commented on code on Aug 18, 2026 13:05 UTC
    Code Review
    lnwallet/aux_signer.go:1
    @@ -305,4 +307,70 @@ 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.

    nit: explain what the use case is for providing both. Is that the case where the blob didn't record what was actually used and we need the feature negotiation as a fallback?

    gijswijs gijswijs commented on code on Aug 18, 2026 13:55 UTC
    Code Review
    lnwallet/aux_signer_test.go:1
    @@ -0,0 +1,75 @@
    +package lnwallet
    +
    +import (
    +	"testing"
    +
    +	"github.com/btcsuite/btcd/txscript/v2"
    +	"github.com/lightningnetwork/lnd/channeldb"
    +	"github.com/lightningnetwork/lnd/fn/v2"
    +	"github.com/stretchr/testify/require"
    +)
    +
    +// sigHashOverrideSigner is a MockAuxSigner whose HtlcSigHashType always
    +// returns the configured sighash type, used to simulate an aux signer that
    +// negotiates a non-default HTLC sighash.
    +type sigHashOverrideSigner struct {
    +	*MockAuxSigner
    +
    +	sigHash txscript.SigHashType
    +}
    +
    +// HtlcSigHashType returns the configured sighash type.
    +func (s *sigHashOverrideSigner) HtlcSigHashType(
    +	_ HtlcSigHashReq) fn.Option[txscript.SigHashType] {
    +
    +	return fn.Some(s.sigHash)
    +}
    +
    +// TestResolveHtlcSigHashTypeCustomOnly asserts that a negotiated HTLC sighash
    +// type can only ever take effect on aux/custom (taproot asset) channels: for
    +// any channel type without a tapscript root, ResolveHtlcSigHashType returns
    +// the standard sighash flags even when an aux signer requests SigHashDefault.
    +func TestResolveHtlcSigHashTypeCustomOnly(t *testing.T) {
    +	t.Parallel()
    +
    +	taprootChanType := channeldb.SimpleTaprootFeatureBit |
    +		channeldb.AnchorOutputsBit |
    +		channeldb.ZeroHtlcTxFeeBit |
    +		channeldb.SingleFunderTweaklessBit
    +
    +	customChanType := taprootChanType | channeldb.TapscriptRootBit
    +
    +	// An aux signer that always negotiates SigHashDefault.
    +	signer := fn.Some[AuxSigner](&sigHashOverrideSigner{
    +		MockAuxSigner: NewAuxSignerMock(nil),
    +		sigHash:       txscript.SigHashDefault,
    +	})
    +
    +	req := HtlcSigHashReq{}
    +
    +	// A non-custom taproot channel must keep the standard sighash flags,
    +	// no matter what the aux signer says.
    +	got := ResolveHtlcSigHashType(taprootChanType, signer, req)

    I would mention the Sighash each channel is supposed to return, so that future me has a reminder what we are supposed to expect and why this test works.

    | Channel | Sighash | Byte |
    | ------------------- | ------------------------------ | ---- |
    | legacy (no anchors) | SIGHASH_ALL | 0x01 |
    | anchor / taproot | SIGHASH_SINGLE\|ANYONECANPAY | 0x83 |
    | custom + negotiated | SIGHASH_DEFAULT | 0x00 |

    gijswijs gijswijs commented on code on Aug 18, 2026 14:40 UTC
    Code Review
    lnwallet/channel.go:1
    @@ -3353,7 +3354,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,

    In the next commit you change refactor this code block, but more importantly change it to chanState.LocalCommitment.CustomBlob. It would be cleaner if the refactor wasn't needed. (ultranit)

    wrt changing the blob source, it took me a while to understand why you are changing it here. This is my understanding: commit 1 only used the resolved sighash to pick a SigHashType at the four signing/validation/resolution sites, each locally. Commit 2 promotes sigHashDefault into an input to dust classification, fee, and the anchor carve-out. It threads it through many new sites that have no remoteCommitView in scope, so for consistency we use chanState.LocalCommitment.CustomBlob everywhere. Is that a correct interpretation of what's happening?

    gijswijs gijswijs commented on code on Aug 18, 2026 15:12 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,
    +	htlcSweepDesc input.SignDescriptor,
    +	broadcastHeight, deadlineHeight uint32, log btclog.Logger) error {
    +
    +	// The anchor sits at index 1 of every DeterministicHTLCs second-level
    +	// tx (index 0 is the HTLC output). If the tx only has one output the
    +	// caller built it without an anchor and there's nothing to sweep.
    +	if len(parentTx.TxOut) < 2 {
    +		return nil
    +	}
    +
    +	// The anchor is keyed to the broadcaster's to-local delay key, which
    +	// is exactly the key the second-level HTLC output's sweep descriptor
    +	// signs with: the delay base point tweaked with the commitment
    +	// point's single tweak. Derive it from the descriptor so this path
    +	// is fully self-contained.
    +	if htlcSweepDesc.KeyDesc.PubKey == nil ||
    +		len(htlcSweepDesc.SingleTweak) == 0 {
    +
    +		log.Warnf("cannot sweep second-level anchor: sweep sign " +
    +			"descriptor lacks delay key material; CPFP " +
    +			"unavailable")
    +
    +		return nil
    +	}
    +	delayKey := input.TweakPubKeyWithTweak(
    +		htlcSweepDesc.KeyDesc.PubKey, htlcSweepDesc.SingleTweak,
    +	)
    +	anchorTree, err := input.NewAnchorScriptTree(delayKey)
    +	if err != nil {
    +		return fmt.Errorf("build anchor script tree: %w", err)
    +	}
    +
    +	op := wire.OutPoint{
    +		Hash:  parentTx.TxHash(),
    +		Index: 1,
    +	}
    +
    +	// Build the sign descriptor for the key-path spend. Clone the HTLC
    +	// output's SweepSignDesc (which already carries the local delay key
    +	// descriptor + tweak) and swap the anchor-specific fields.
    +	signDesc := htlcSweepDesc
    +	signDesc.Output = parentTx.TxOut[1]
    +	signDesc.WitnessScript = anchorTree.SweepLeaf.Script
    +	signDesc.TapTweak = anchorTree.TapscriptRoot
    +	signDesc.HashType = txscript.SigHashDefault
    +
    +	// We pass the parent tx fee + weight so the sweeper computes the
    +	// effective package fee rate for CPFP. The baked-in parent fee is
    +	// the floor rate (see lnwallet.HtlcSuccessFee / HtlcTimeoutFee under
    +	// sigHashDefault) and the weight includes the appended anchor.
    +	strippedSize := parentTx.SerializeSizeStripped()
    +	parentWeight := lntypes.WeightUnit(
    +		(strippedSize * 3) + parentTx.SerializeSize(),
    +	)
    +	parentInfo := &input.TxInfo{
    +		Fee:    parentTxFee(parentTx),
    +		Weight: parentWeight,
    +	}
    +
    +	anchorInput := input.MakeBaseInput(
    +		&op, input.TaprootAnchorSweepSpend, &signDesc,
    +		broadcastHeight, parentInfo,
    +	)
    +
    +	deadline := fn.Some(int32(deadlineHeight))
    +	_, err = sweeper.SweepInput(&anchorInput, sweep.Params{
    +		Budget:         lnwallet.AnchorSize,
    +		DeadlineHeight: deadline,
    +	})
    +	if err != nil {
    +		return fmt.Errorf("offer second-level anchor: %w", err)
    +	}
    +
    +	log.Infof("offered second-level anchor=%v to sweeper for CPFP "+
    +		"(deadline=%v)", op, deadlineHeight)
    +
    +	return nil
    +}
    +
    +// parentTxFee returns the fee paid by the given tx, computed as the
    +// difference between input and output value. The caller is responsible
    +// for ensuring the inputs' prevout values are known via context; here
    +// we approximate using the tx outputs since the only prevout is the
    +// HTLC output of the commitment tx and that value isn't reachable
    +// without extra plumbing. For floor-rate-signed second-level txs the
    +// approximation is close enough for the sweeper's package-fee math.
    +func parentTxFee(tx *wire.MsgTx) btcutil.Amount {
    +	// TODO: thread the actual baked-in fee through from the resolver
    +	// for an exact value. The actual fee is ~244 sats at 1.1x
    +	// FeePerKwFloor over the ~877wu second-level taproot HTLC weight;
    +	// AnchorSize (330 sats) is a close-enough proxy here.
    +	return lnwallet.AnchorSize
    +}
    +
    +// 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

    I think this comment has it backwards. No regular lnd channel would ever match on 0x00 (SIGHASH_DEFAULT). legacy channels are SIGHASH_ALL and taproot channels are SIGHASH_SINGLE|ANYONECANPAY. (Old) Taproot Assets channels that didn't negotiate deterministic HTLCs would be correctly filtered out by this check, and I think the comment should explain that.

    gijswijs gijswijs commented on code on Aug 19, 2026 11:02 UTC
    Code Review
    lnwallet/chanfunding/coin_select.go:1
    @@ -150,9 +150,12 @@ func calculateFees(utxos []wallet.Coin, feeRate chainfee.SatPerKWeight,
     // sanityCheckFee checks if the specified fee amounts to what the provided ratio
     // allows.
     func sanityCheckFee(totalOut, fee btcutil.Amount, maxFeeRatio float64) error {
    -	// Sanity check the maxFeeRatio itself.
    -	if maxFeeRatio <= 0.00 || maxFeeRatio > 1.00 {
    -		return fmt.Errorf("maxFeeRatio must be between 0.00 and 1.00 "+
    +	// Sanity check the maxFeeRatio itself. Ratios above 1.0 are allowed

    Would it make sense to have separate fee sanity checks for non-asset bearing Txs and asset-bearing Txs?

    gijswijs gijswijs commented on code on Aug 19, 2026 11:13 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,
    +	htlcSweepDesc input.SignDescriptor,
    +	broadcastHeight, deadlineHeight uint32, log btclog.Logger) error {
    +
    +	// The anchor sits at index 1 of every DeterministicHTLCs second-level
    +	// tx (index 0 is the HTLC output). If the tx only has one output the
    +	// caller built it without an anchor and there's nothing to sweep.
    +	if len(parentTx.TxOut) < 2 {
    +		return nil
    +	}
    +
    +	// The anchor is keyed to the broadcaster's to-local delay key, which
    +	// is exactly the key the second-level HTLC output's sweep descriptor
    +	// signs with: the delay base point tweaked with the commitment
    +	// point's single tweak. Derive it from the descriptor so this path
    +	// is fully self-contained.
    +	if htlcSweepDesc.KeyDesc.PubKey == nil ||
    +		len(htlcSweepDesc.SingleTweak) == 0 {
    +
    +		log.Warnf("cannot sweep second-level anchor: sweep sign " +
    +			"descriptor lacks delay key material; CPFP " +
    +			"unavailable")
    +
    +		return nil
    +	}
    +	delayKey := input.TweakPubKeyWithTweak(
    +		htlcSweepDesc.KeyDesc.PubKey, htlcSweepDesc.SingleTweak,
    +	)
    +	anchorTree, err := input.NewAnchorScriptTree(delayKey)
    +	if err != nil {
    +		return fmt.Errorf("build anchor script tree: %w", err)
    +	}
    +
    +	op := wire.OutPoint{
    +		Hash:  parentTx.TxHash(),
    +		Index: 1,
    +	}
    +
    +	// Build the sign descriptor for the key-path spend. Clone the HTLC
    +	// output's SweepSignDesc (which already carries the local delay key
    +	// descriptor + tweak) and swap the anchor-specific fields.
    +	signDesc := htlcSweepDesc
    +	signDesc.Output = parentTx.TxOut[1]
    +	signDesc.WitnessScript = anchorTree.SweepLeaf.Script
    +	signDesc.TapTweak = anchorTree.TapscriptRoot
    +	signDesc.HashType = txscript.SigHashDefault
    +
    +	// We pass the parent tx fee + weight so the sweeper computes the
    +	// effective package fee rate for CPFP. The baked-in parent fee is
    +	// the floor rate (see lnwallet.HtlcSuccessFee / HtlcTimeoutFee under
    +	// sigHashDefault) and the weight includes the appended anchor.
    +	strippedSize := parentTx.SerializeSizeStripped()
    +	parentWeight := lntypes.WeightUnit(
    +		(strippedSize * 3) + parentTx.SerializeSize(),
    +	)
    +	parentInfo := &input.TxInfo{
    +		Fee:    parentTxFee(parentTx),
    +		Weight: parentWeight,
    +	}
    +
    +	anchorInput := input.MakeBaseInput(
    +		&op, input.TaprootAnchorSweepSpend, &signDesc,
    +		broadcastHeight, parentInfo,
    +	)
    +
    +	deadline := fn.Some(int32(deadlineHeight))
    +	_, err = sweeper.SweepInput(&anchorInput, sweep.Params{
    +		Budget:         lnwallet.AnchorSize,

    Not sure it the following math checks out, but hear me out:

    The pre-signed second-level tx pays 1.1 sat/vB. The whole CPFP package (1477 wu) can be lifted by at most 330 sats → the combined package feerate stays ~2 sat/vB.

    So in a heigh fee-env this would never hit the chain.

    calculateBudget isn't good to use her, probably because of the value of the potential assets, but it feels like we should find a way to link the budget to the value of what's being caried in the Tx.

    gijswijs gijswijs commented on code on Aug 19, 2026 11:17 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,
    +	htlcSweepDesc input.SignDescriptor,
    +	broadcastHeight, deadlineHeight uint32, log btclog.Logger) error {
    +
    +	// The anchor sits at index 1 of every DeterministicHTLCs second-level
    +	// tx (index 0 is the HTLC output). If the tx only has one output the
    +	// caller built it without an anchor and there's nothing to sweep.
    +	if len(parentTx.TxOut) < 2 {
    +		return nil
    +	}
    +
    +	// The anchor is keyed to the broadcaster's to-local delay key, which
    +	// is exactly the key the second-level HTLC output's sweep descriptor
    +	// signs with: the delay base point tweaked with the commitment
    +	// point's single tweak. Derive it from the descriptor so this path
    +	// is fully self-contained.
    +	if htlcSweepDesc.KeyDesc.PubKey == nil ||
    +		len(htlcSweepDesc.SingleTweak) == 0 {
    +
    +		log.Warnf("cannot sweep second-level anchor: sweep sign " +
    +			"descriptor lacks delay key material; CPFP " +
    +			"unavailable")
    +
    +		return nil
    +	}
    +	delayKey := input.TweakPubKeyWithTweak(
    +		htlcSweepDesc.KeyDesc.PubKey, htlcSweepDesc.SingleTweak,
    +	)
    +	anchorTree, err := input.NewAnchorScriptTree(delayKey)
    +	if err != nil {
    +		return fmt.Errorf("build anchor script tree: %w", err)
    +	}
    +
    +	op := wire.OutPoint{
    +		Hash:  parentTx.TxHash(),
    +		Index: 1,
    +	}
    +
    +	// Build the sign descriptor for the key-path spend. Clone the HTLC
    +	// output's SweepSignDesc (which already carries the local delay key
    +	// descriptor + tweak) and swap the anchor-specific fields.
    +	signDesc := htlcSweepDesc
    +	signDesc.Output = parentTx.TxOut[1]
    +	signDesc.WitnessScript = anchorTree.SweepLeaf.Script
    +	signDesc.TapTweak = anchorTree.TapscriptRoot
    +	signDesc.HashType = txscript.SigHashDefault
    +
    +	// We pass the parent tx fee + weight so the sweeper computes the
    +	// effective package fee rate for CPFP. The baked-in parent fee is
    +	// the floor rate (see lnwallet.HtlcSuccessFee / HtlcTimeoutFee under
    +	// sigHashDefault) and the weight includes the appended anchor.
    +	strippedSize := parentTx.SerializeSizeStripped()
    +	parentWeight := lntypes.WeightUnit(
    +		(strippedSize * 3) + parentTx.SerializeSize(),
    +	)
    +	parentInfo := &input.TxInfo{
    +		Fee:    parentTxFee(parentTx),
    +		Weight: parentWeight,
    +	}
    +
    +	anchorInput := input.MakeBaseInput(
    +		&op, input.TaprootAnchorSweepSpend, &signDesc,
    +		broadcastHeight, parentInfo,
    +	)
    +
    +	deadline := fn.Some(int32(deadlineHeight))
    +	_, err = sweeper.SweepInput(&anchorInput, sweep.Params{
    +		Budget:         lnwallet.AnchorSize,
    +		DeadlineHeight: deadline,
    +	})
    +	if err != nil {
    +		return fmt.Errorf("offer second-level anchor: %w", err)
    +	}
    +
    +	log.Infof("offered second-level anchor=%v to sweeper for CPFP "+
    +		"(deadline=%v)", op, deadlineHeight)
    +
    +	return nil
    +}
    +
    +// parentTxFee returns the fee paid by the given tx, computed as the
    +// difference between input and output value. The caller is responsible
    +// for ensuring the inputs' prevout values are known via context; here
    +// we approximate using the tx outputs since the only prevout is the
    +// HTLC output of the commitment tx and that value isn't reachable
    +// without extra plumbing. For floor-rate-signed second-level txs the
    +// approximation is close enough for the sweeper's package-fee math.
    +func parentTxFee(tx *wire.MsgTx) btcutil.Amount {

    Overstating parentsFee understates the child top-up coming from CPFP. I don't think we can allow this TODO to remain here and assume that the approximation is close enough.

    gijswijs gijswijs commented on code on Aug 19, 2026 11:31 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,

    Wouldn't it be nice if the sweeper supported package relay? Broadcast the DeterministicHTLC and the CPFP feebump Tx in one go.

    Let's not increase the scope, but a man can dream.

    gijswijs gijswijs commented on code on Aug 19, 2026 11:35 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,
    +	htlcSweepDesc input.SignDescriptor,
    +	broadcastHeight, deadlineHeight uint32, log btclog.Logger) error {
    +
    +	// The anchor sits at index 1 of every DeterministicHTLCs second-level
    +	// tx (index 0 is the HTLC output). If the tx only has one output the
    +	// caller built it without an anchor and there's nothing to sweep.
    +	if len(parentTx.TxOut) < 2 {
    +		return nil
    +	}
    +
    +	// The anchor is keyed to the broadcaster's to-local delay key, which
    +	// is exactly the key the second-level HTLC output's sweep descriptor
    +	// signs with: the delay base point tweaked with the commitment
    +	// point's single tweak. Derive it from the descriptor so this path
    +	// is fully self-contained.
    +	if htlcSweepDesc.KeyDesc.PubKey == nil ||
    +		len(htlcSweepDesc.SingleTweak) == 0 {
    +
    +		log.Warnf("cannot sweep second-level anchor: sweep sign " +
    +			"descriptor lacks delay key material; CPFP " +
    +			"unavailable")
    +
    +		return nil
    +	}
    +	delayKey := input.TweakPubKeyWithTweak(
    +		htlcSweepDesc.KeyDesc.PubKey, htlcSweepDesc.SingleTweak,
    +	)
    +	anchorTree, err := input.NewAnchorScriptTree(delayKey)
    +	if err != nil {
    +		return fmt.Errorf("build anchor script tree: %w", err)
    +	}
    +
    +	op := wire.OutPoint{
    +		Hash:  parentTx.TxHash(),
    +		Index: 1,
    +	}
    +
    +	// Build the sign descriptor for the key-path spend. Clone the HTLC
    +	// output's SweepSignDesc (which already carries the local delay key
    +	// descriptor + tweak) and swap the anchor-specific fields.
    +	signDesc := htlcSweepDesc
    +	signDesc.Output = parentTx.TxOut[1]
    +	signDesc.WitnessScript = anchorTree.SweepLeaf.Script
    +	signDesc.TapTweak = anchorTree.TapscriptRoot
    +	signDesc.HashType = txscript.SigHashDefault
    +
    +	// We pass the parent tx fee + weight so the sweeper computes the
    +	// effective package fee rate for CPFP. The baked-in parent fee is
    +	// the floor rate (see lnwallet.HtlcSuccessFee / HtlcTimeoutFee under
    +	// sigHashDefault) and the weight includes the appended anchor.
    +	strippedSize := parentTx.SerializeSizeStripped()
    +	parentWeight := lntypes.WeightUnit(
    +		(strippedSize * 3) + parentTx.SerializeSize(),
    +	)
    +	parentInfo := &input.TxInfo{
    +		Fee:    parentTxFee(parentTx),
    +		Weight: parentWeight,
    +	}
    +
    +	anchorInput := input.MakeBaseInput(
    +		&op, input.TaprootAnchorSweepSpend, &signDesc,
    +		broadcastHeight, parentInfo,
    +	)
    +
    +	deadline := fn.Some(int32(deadlineHeight))
    +	_, err = sweeper.SweepInput(&anchorInput, sweep.Params{
    +		Budget:         lnwallet.AnchorSize,
    +		DeadlineHeight: deadline,
    +	})
    +	if err != nil {
    +		return fmt.Errorf("offer second-level anchor: %w", err)
    +	}
    +
    +	log.Infof("offered second-level anchor=%v to sweeper for CPFP "+
    +		"(deadline=%v)", op, deadlineHeight)
    +
    +	return nil

    What if an anchor genuinely can't be swept? budget exhausted, deadline blown, persistent estimation failure, etc.

    That outcome comes back on the resultChan which the resolver never reads.

    Not sure what you could do about it, since a retry wouldn't help in that case either. Just flagging it here.

    gijswijs gijswijs commented on code on Aug 19, 2026 11:49 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {

    Probably worth the effort to track it under a WaitGroup and make the publish context-cancelable.

    gijswijs gijswijs commented on code on Aug 19, 2026 11:57 UTC
    Code Review
    contractcourt/htlc_timeout_resolver.go:1
    @@ -973,6 +974,42 @@ 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,
    +	)
    +}
    +
    +// 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. After broadcast, the anchor
    +// output appended to the second-level tx is offered to the sweeper for
    +// CPFP fee bumping.
    +func (h *htlcTimeoutResolver) publishTimeoutTx() error {
    +	parentTx := h.htlcResolution.SignedTimeoutTx
    +	h.log.Infof("publishing pre-signed 2nd-level HTLC timeout tx=%v "+
    +		"(SigHashDefault, baked-in fees)", parentTx.TxHash())
    +
    +	label := labels.MakeLabel(
    +		labels.LabelTypeChannelClose, &h.ShortChanID,
    +	)
    +
    +	return publishPreSignedHtlcTx(
    +		parentTx, label, h.PublishTx, h.Notifier, h.quit, h.log,
    +		func() error {
    +			return offerSecondLevelAnchorToSweeper(
    +				h.Sweeper, parentTx,
    +				h.htlcResolution.SweepSignDesc,
    +				h.broadcastHeight, h.htlc.RefundTimeout,

    This should use the incoming-HTLC expiry, matching what the other timeout-path sweeps already do — h.incomingHTLCExpiryHeight at lines 495 (DeadlineHeight in sweepTimeoutTx) and 515.

    There's a type wrinkle tho: h.incomingHTLCExpiryHeight is fn.Option[int32], but offerSecondLevelAnchorToSweeper takes deadlineHeight uint32. But I'm confident you'll be able to figure that one out. 😄

    gijswijs gijswijs commented on code on Aug 19, 2026 12:08 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,

    Not worth persuing, but this wouldn't survive a re-org. If a pre-signed HTLC is published but orged out, we won't retry.
    This is also something noted in this PR: https://github.com/lightningnetwork/lnd/pull/10331

    we'll actually need to re-create the channel arb and the chain watcher, the re-handle any contested outputs we may have had

    gijswijs gijswijs commented on code on Aug 19, 2026 12:12 UTC
    Code Review
    lnwallet/channel.go:1
    @@ -2732,28 +2776,37 @@ 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
    +	// Under DeterministicHTLCs the pre-signed second-level tx also
    +	// carries an AnchorSize CPFP anchor output taken from the HTLC
    +	// value, so the on-chain HTLC output value is reduced by both the
    +	// fee and the anchor.
    +	htlcOutValue := htlcAmt - htlcFee
    +	if sigHashDefault {

    But at https://github.com/georgetsagk/lnd/blob/544139aba9486ec92c981fc5de8e057185d5fbc6/lnwallet/channel.go#L9474 we don't take into account IsChanSigHashDefault() so the report can be 330 sats too generous.

    gijswijs gijswijs requested changes on Aug 19, 2026 12:28 UTC
    Changes Requested Reviewer

    I think we are nearly there with this PR. I did a real human-powered, thorough review of the code and found some issues, that I commented on inline. The below comment is about a commit message.

    The commit message on the first commit claims to replace CustomBlob.IsSome() but I don't see that specific method being replaced anywhere. Where does that come from?

    GeorgeTsagk GeorgeTsagk commented on code on Aug 19, 2026 17:59 UTC
    Code Review
    lnwallet/aux_signer.go:1
    @@ -305,4 +307,70 @@ 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.

    Expanded the doc here: when both are set, live feature negotiation is consulted first and the commitment blob acts as the fallback (e.g. right after a restart, before the peer reconnects).

    GeorgeTsagk GeorgeTsagk commented on code on Aug 19, 2026 18:00 UTC
    Code Review
    lnwallet/channel.go:1
    @@ -3353,7 +3354,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,

    Your interpretation is correct, and the refactor is gone: the first commit now introduces the final sigHashReq form directly.

    GeorgeTsagk GeorgeTsagk commented on code on Aug 19, 2026 18:00 UTC
    Code Review
    lnwallet/chanfunding/coin_select.go:1
    @@ -150,9 +150,12 @@ func calculateFees(utxos []wallet.Coin, feeRate chainfee.SatPerKWeight,
     // sanityCheckFee checks if the specified fee amounts to what the provided ratio
     // allows.
     func sanityCheckFee(totalOut, fee btcutil.Amount, maxFeeRatio float64) error {
    -	// Sanity check the maxFeeRatio itself.
    -	if maxFeeRatio <= 0.00 || maxFeeRatio > 1.00 {
    -		return fmt.Errorf("maxFeeRatio must be between 0.00 and 1.00 "+
    +	// Sanity check the maxFeeRatio itself. Ratios above 1.0 are allowed

    chanfunding cannot tell asset-bearing txs apart, so instead the ratio now has a hard ceiling of 100.0 and FundPsbt logs a warning whenever a caller explicitly opts into a ratio above 1.0 (internal funding flows always pass the default).

    GeorgeTsagk GeorgeTsagk commented on code on Aug 19, 2026 18:00 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,
    +	htlcSweepDesc input.SignDescriptor,
    +	broadcastHeight, deadlineHeight uint32, log btclog.Logger) error {
    +
    +	// The anchor sits at index 1 of every DeterministicHTLCs second-level
    +	// tx (index 0 is the HTLC output). If the tx only has one output the
    +	// caller built it without an anchor and there's nothing to sweep.
    +	if len(parentTx.TxOut) < 2 {
    +		return nil
    +	}
    +
    +	// The anchor is keyed to the broadcaster's to-local delay key, which
    +	// is exactly the key the second-level HTLC output's sweep descriptor
    +	// signs with: the delay base point tweaked with the commitment
    +	// point's single tweak. Derive it from the descriptor so this path
    +	// is fully self-contained.
    +	if htlcSweepDesc.KeyDesc.PubKey == nil ||
    +		len(htlcSweepDesc.SingleTweak) == 0 {
    +
    +		log.Warnf("cannot sweep second-level anchor: sweep sign " +
    +			"descriptor lacks delay key material; CPFP " +
    +			"unavailable")
    +
    +		return nil
    +	}
    +	delayKey := input.TweakPubKeyWithTweak(
    +		htlcSweepDesc.KeyDesc.PubKey, htlcSweepDesc.SingleTweak,
    +	)
    +	anchorTree, err := input.NewAnchorScriptTree(delayKey)
    +	if err != nil {
    +		return fmt.Errorf("build anchor script tree: %w", err)
    +	}
    +
    +	op := wire.OutPoint{
    +		Hash:  parentTx.TxHash(),
    +		Index: 1,
    +	}
    +
    +	// Build the sign descriptor for the key-path spend. Clone the HTLC
    +	// output's SweepSignDesc (which already carries the local delay key
    +	// descriptor + tweak) and swap the anchor-specific fields.
    +	signDesc := htlcSweepDesc
    +	signDesc.Output = parentTx.TxOut[1]
    +	signDesc.WitnessScript = anchorTree.SweepLeaf.Script
    +	signDesc.TapTweak = anchorTree.TapscriptRoot
    +	signDesc.HashType = txscript.SigHashDefault
    +
    +	// We pass the parent tx fee + weight so the sweeper computes the
    +	// effective package fee rate for CPFP. The baked-in parent fee is
    +	// the floor rate (see lnwallet.HtlcSuccessFee / HtlcTimeoutFee under
    +	// sigHashDefault) and the weight includes the appended anchor.
    +	strippedSize := parentTx.SerializeSizeStripped()
    +	parentWeight := lntypes.WeightUnit(
    +		(strippedSize * 3) + parentTx.SerializeSize(),
    +	)
    +	parentInfo := &input.TxInfo{
    +		Fee:    parentTxFee(parentTx),
    +		Weight: parentWeight,
    +	}
    +
    +	anchorInput := input.MakeBaseInput(
    +		&op, input.TaprootAnchorSweepSpend, &signDesc,
    +		broadcastHeight, parentInfo,
    +	)
    +
    +	deadline := fn.Some(int32(deadlineHeight))
    +	_, err = sweeper.SweepInput(&anchorInput, sweep.Params{
    +		Budget:         lnwallet.AnchorSize,

    Fixed by deriving the budget the same way as commitment anchor CPFP: calculateBudget over the second-level HTLC output value with the sweeper.budget.anchorcpfp(ratio) knobs, plus the anchor value; linking the budget to the real asset value is tracked in lightninglabs/taproot-assets#2242.

    GeorgeTsagk GeorgeTsagk commented on code on Aug 19, 2026 18:00 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	go func() {
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {
    +					log.Errorf("post-publish handling "+
    +						"for tx=%v failed: %v",
    +						tx.TxHash(), err)
    +				}
    +			}
    +
    +			return
    +		}
    +	}()
    +
    +	return nil
    +}
    +
    +// offerSecondLevelAnchorToSweeper offers the anchor output at index 1 of
    +// a just-broadcast DeterministicHTLCs second-level HTLC tx to the sweeper
    +// for CPFP fee bumping. The pre-signed parent tx cannot be RBF'd under
    +// SigHashDefault, so CPFP via this anchor is the only fee-bumping path.
    +//
    +// The anchor is a taproot output spendable by the broadcaster's
    +// ToLocalKey via key-path (fast) or anyone after 16 blocks via script
    +// path (fallback). We use the key-path here. The ToLocalKey is sourced
    +// from the stored ResolveReq.KeyRing; without it we fall back to a
    +// no-op (CPFP unavailable, parent tx still publishes at its baked-in
    +// floor fee).
    +func offerSecondLevelAnchorToSweeper(sweeper UtxoSweeper, parentTx *wire.MsgTx,

    Agreed, a man can dream; keeping it out of scope here.

    GeorgeTsagk GeorgeTsagk commented on code on Aug 19, 2026 18:00 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +190,199 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,

    Ack, leaving this to the wider re-org handling story in #10331.

    gijswijs gijswijs approved these changes on Aug 21, 2026 11:01 UTC
    Approved Reviewer

    LGTM! 🦺

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 19:32 UTC
    Code Review
    lnwallet/aux_signer.go:1
    @@ -305,4 +307,60 @@ 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(

    weird formatting

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 22:27 UTC
    Code Review
    lnwallet/commitment.go:1
    @@ -507,11 +510,32 @@ func CommitWeight(chanType channeldb.ChannelType) lntypes.WeightUnit {
     }
     
     // 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, the floor fee rate is used: the pre-signed
    +// second-level tx pays only the min-relay-clearing fee, and any further
    +// fee bumping is done by the local party via CPFP on the anchor output
    +// embedded in the tx.
     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 is
    +	// pre-signed with baked-in fees and cannot be RBF'd. We sign at
    +	// 1.1x the floor rate (just enough headroom for aux-leaf weight
    +	// not counted by TaprootHtlcTimeoutWeight, and integer-rounding
    +	// margin). Any further fee bumping is done locally via CPFP on
    +	// the anchor output embedded in the tx. Weight includes the
    +	// appended anchor output.
    +	case chanType.IsTaproot() && sigHashDefault:
    +		weight := lntypes.WeightUnit(input.TaprootHtlcTimeoutWeight) +
    +			lntypes.WeightUnit(
    +				input.TaprootCommitmentAnchorOutput*4,
    +			)
    +		feeRate := chainfee.FeePerKwFloor * 11 / 10

    Why does this branch ignore the already-negotiated feePerKw? That fee rate is agreed through update_fee and stored with the commitment, so using it would remain deterministic for both parties during signing and reconstruction. Hard-coding FeePerKwFloor * 1.1 can leave the parent far below the channel fee. Since the CPFP anchor is only offered after standalone PublishTx succeeds, a mempool minimum above roughly 1.1 sat/vB would reject the parent before the fee-paying child is created. At minimum, could this derive the parent fee from feePerKw, with the auxiliary witness overhead accounted for explicitly, while package CPFP handles fee-market changes between signing and broadcast?

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 22:55 UTC
    Code Review
    lnwallet/aux_signer.go:1
    @@ -305,4 +307,73 @@ 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. Providing both lets the implementation consult live feature
    +// negotiation when the peer is connected and fall back to the flag
    +// recorded in the commitment blob when it is not (e.g. right after a
    +// restart, before the peer has reconnected).
    +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 {
    +
    +	// A negotiated (non-default) HTLC sighash type 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 diverge from the
    +	// standard sighash flags, regardless of aux signer state.
    +	if !chanType.HasTapscriptRoot() {
    +		return HtlcSigHashType(chanType)
    +	}
    +
    +	sigHash := fn.FlatMapOption(
    +		func(s AuxSigner) fn.Option[txscript.SigHashType] {
    +			return s.HtlcSigHashType(req)
    +		},
    +	)(auxSigner)
    +
    +	return sigHash.UnwrapOr(HtlcSigHashType(chanType))

    Could we validate the override here or return a narrower policy type? Downstream code only distinguishes SigHashDefault from everything else: SigHashDefault gets the fixed parent, anchor, and direct-publish path, while any other value gets the existing mutable sweeper path. But the raw value is still used for signing. For example, an override of SigHashAll would commit to the full transaction while the resolver would still let the sweeper rebuild it, invalidating the signature. It seems safer to accept only SigHashDefault or the channel default, or model the complete second-level policy explicitly.

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 22:55 UTC
    Code Review
    lnwallet/channel.go:1
    @@ -3383,10 +3446,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(

    We already resolved sigHashType above, but IsSigHashDefault resolves it through the external AuxSigner a second time. If the live negotiation lookup changes or is not strictly pure, the signature could use one sighash while dust, fees, and transaction shape use another. Could this instead derive sigHashDefault directly from the resolved sigHashType? The validation path around line 5064 has the same double lookup.

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 22:55 UTC
    Code Review
    contractcourt/contract_resolver.go:1
    @@ -184,3 +195,294 @@ var (
     	// progressing because it received the quit signal.
     	errResolverShuttingDown = errors.New("resolver shutting down")
     )
    +
    +// publishPreSignedHtlcTx broadcasts a pre-signed second-level HTLC
    +// transaction asynchronously. The transaction may carry an absolute locktime
    +// (timeout txs), in which case it is not final until the chain reaches that
    +// height and the mempool would reject it. We therefore wait for block epochs
    +// and publish once the locktime is satisfiable, retrying on every new block
    +// until the broadcast succeeds (transient rejections such as a not-yet-final
    +// locktime or a momentary mempool conflict resolve themselves as the chain
    +// advances; an exact duplicate of an already-known transaction is treated as
    +// success by PublishTx). Once the broadcast succeeds, onPublished is invoked
    +// (used to offer the tx's CPFP anchor to the sweeper).
    +//
    +// The resolver's Resolve() path independently waits for the spend of the
    +// HTLC output, so running the broadcast asynchronously does not change
    +// resolution semantics.
    +func publishPreSignedHtlcTx(tx *wire.MsgTx, label string,
    +	publish func(*wire.MsgTx, string) error,
    +	notifier chainntnfs.ChainNotifier, quit <-chan struct{},
    +	wg *sync.WaitGroup, log btclog.Logger, onPublished func() error) error {
    +
    +	epochClient, err := notifier.RegisterBlockEpochNtfn(nil)
    +	if err != nil {
    +		return fmt.Errorf("register block epochs: %w", err)
    +	}
    +
    +	wg.Add(1)
    +	go func() {
    +		defer wg.Done()
    +		defer epochClient.Cancel()
    +
    +		for {
    +			select {
    +			case epoch, ok := <-epochClient.Epochs:
    +				if !ok {
    +					return
    +				}
    +
    +				// A locktime'd tx is only final once the next
    +				// block's height exceeds the locktime, i.e.
    +				// the current height reached it.
    +				if uint32(epoch.Height) < tx.LockTime {
    +					continue
    +				}
    +
    +			case <-quit:
    +				return
    +			}
    +
    +			if err := publish(tx, label); err != nil {
    +				log.Warnf("unable to publish pre-signed "+
    +					"second-level tx=%v, retrying on "+
    +					"next block: %v", tx.TxHash(), err)
    +
    +				continue
    +			}
    +
    +			log.Infof("published pre-signed second-level tx=%v",
    +				tx.TxHash())
    +
    +			if onPublished != nil {
    +				if err := onPublished(); err != nil {

    Once PublishTx succeeds, an onPublished error is only logged and this goroutine returns. Since this immutable floor-fee parent cannot be RBFed and the anchor is its only fee-bumping path, a transient SweepInput registration failure leaves the parent without CPFP until a restart. Should post-publish registration be retried or persisted separately from parent publication? This is distinct from a terminal result delivered after the sweeper has accepted the input.

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 22:55 UTC
    Code Review
    lnwallet/chanfunding/coin_select.go:1
    @@ -62,6 +62,12 @@ const (
     	// DefaultMaxFeeRatio is the default fee to total amount of outputs
     	// ratio that is used to sanity check the fees of a transaction.
     	DefaultMaxFeeRatio float64 = 0.2
    +
    +	// maxAllowedFeeRatio is the hard ceiling on any caller-supplied
    +	// maxFeeRatio. Ratios above 1.0 are legitimate for sweeps of small
    +	// asset-bearing outputs, but anything beyond this bound is treated
    +	// as a misconfiguration.
    +	maxAllowedFeeRatio float64 = 100.0

    Could this change be split out or point to the exact caller that requires it? The deterministic second-level anchor path uses Sweeper.SweepInput with a sweep budget; it does not call WalletKit.FundPsbt or this sanity check. As written, this globally relaxes the safety ceiling for every external FundPsbt caller without being exercised by the feature in this PR, and the tests do not include a successful ratio-above-one case. Which flow in this series needs the 100x ceiling?

    ziggie1984 ziggie1984 commented on code on Aug 21, 2026 23:04 UTC
    Code Review
    lnwallet/channel_test.go:1
    @@ -11956,3 +11978,77 @@ 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) {

    Could we add table-driven coverage for the deterministic dust boundary here, rather than only testing the fee helpers? HtlcIsDust now subtracts both the second-level fee and AnchorSize; I would cover incoming/outgoing × local/remote at dustLimit + fee + AnchorSize - 1, exact equality, and +1. That would exercise the success/timeout mapping as well as the strict < dustLimit boundary. Also, are there corresponding litd/Taproot Assets itests already present or planned in the follow-up series that exercise negotiated SigHashDefault through force close, exact parent publication, and anchor CPFP? I could not find an lnd itest for this path, so a pointer or a tracked follow-up would help establish the end-to-end coverage.

    ziggie1984 ziggie1984 requested changes on Aug 21, 2026 23:09 UTC
    Changes Requested Reviewer

    Cool PR !!! I think we should adjust and not hard-code 1.1 sat for the second-level transactions. Why not use the Commitment Fee which should always be closer to the minMemPool fee.

    Do you think using the P2Anchor instead of the 330 anchor would be more benefical, since we could use the value 0 sat ?

    GeorgeTsagk GeorgeTsagk commented on code on Aug 24, 2026 14:37 UTC
    Code Review
    lnwallet/aux_signer.go:1
    @@ -305,4 +307,73 @@ 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. Providing both lets the implementation consult live feature
    +// negotiation when the peer is connected and fall back to the flag
    +// recorded in the commitment blob when it is not (e.g. right after a
    +// restart, before the peer has reconnected).
    +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 {
    +
    +	// A negotiated (non-default) HTLC sighash type 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 diverge from the
    +	// standard sighash flags, regardless of aux signer state.
    +	if !chanType.HasTapscriptRoot() {
    +		return HtlcSigHashType(chanType)
    +	}
    +
    +	sigHash := fn.FlatMapOption(
    +		func(s AuxSigner) fn.Option[txscript.SigHashType] {
    +			return s.HtlcSigHashType(req)
    +		},
    +	)(auxSigner)
    +
    +	return sigHash.UnwrapOr(HtlcSigHashType(chanType))

    Went with the narrow version: ResolveHtlcSigHashType now accepts SigHashDefault as the only valid override and falls back to the channel's standard sighash flags for anything else, so an aux signer cannot steer us into signing a commitment-covering sighash while the resolvers still treat the tx as sweeper-malleable. Added TestResolveHtlcSigHashTypeRejectsUnknownOverride to pin it.

    GeorgeTsagk GeorgeTsagk commented on code on Aug 24, 2026 14:37 UTC
    Code Review
    lnwallet/channel_test.go:1
    @@ -11956,3 +11978,77 @@ 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) {

    Added the table-driven boundary test (TestHtlcIsDustSigHashDefault): incoming/outgoing x local/remote at dustLimit + fee + AnchorSize - 1, at exact equality, and +1.

    On end-to-end coverage: there is no lnd-native itest because nothing in lnd can negotiate SigHashDefault on its own, it needs an aux signer that advertises the feature. That coverage lives in the taproot-assets custom channel suite, which runs an lnd built from this branch: lightninglabs/taproot-assets#1994, cases force_close, htlc_force_close, htlc_force_close_mpp, group_tranches_htlc_force_close, breach and restart_coop_close. They cover negotiation, exact parent publication and anchor CPFP through both force close and breach, and they all pass against this stack.

    GeorgeTsagk GeorgeTsagk commented on code on Aug 24, 2026 14:37 UTC
    Code Review
    lnwallet/chanfunding/coin_select.go:1
    @@ -62,6 +62,12 @@ const (
     	// DefaultMaxFeeRatio is the default fee to total amount of outputs
     	// ratio that is used to sanity check the fees of a transaction.
     	DefaultMaxFeeRatio float64 = 0.2
    +
    +	// maxAllowedFeeRatio is the hard ceiling on any caller-supplied
    +	// maxFeeRatio. Ratios above 1.0 are legitimate for sweeps of small
    +	// asset-bearing outputs, but anything beyond this bound is treated
    +	// as a misconfiguration.
    +	maxAllowedFeeRatio float64 = 100.0

    Fair point that nothing in this series exercises it. The caller is tapd: LndRpcWalletAnchor.FundPsbt passes MaxFeeRatio 5.0 (lndservices.DefaultPsbtMaxFeeRatio) when funding the PSBTs that anchor asset outputs, whose BTC value sits near dust. The commit message now names that caller and states the change is independent of the anchor work here. I also added the missing positive coverage: a ratio-above-one case that succeeds, plus the same fee profile failing under DefaultMaxFeeRatio.

    Happy to split it into its own PR if you prefer, it just needs to land before the taproot-assets side. Your call.

    GeorgeTsagk GeorgeTsagk commented on Aug 24, 2026 14:37 UTC
    Author

    Thanks for the review. Answering the two points from the description here, the inline threads have the details.

    On not hard-coding 1.1 sat and using the commitment fee instead: I implemented it, measured it, and reverted it. Short version is that the anchor exists precisely so the pre-signed parent does not have to predict the fee market at signing time, and on aux channels the HTLC's whole on-chain BTC value is 1200 sats which is already fully spent on the parent fee, the anchor, and a second-level output that must fund its own claiming sweep. At 1000 sat/kw the commitment-rate fee alone is 817 sats, at 2500 it exceeds the entire budget, so every asset HTLC gets trimmed to dust. Clamping it to what the HTLC can afford does not work either: the breach itest then strands the assets, because the output ends up at exactly the dust limit and cannot pay for the justice sweep. Numbers and logs are in the commitment.go thread.

    On P2A instead of the 330 sat anchor: I agree with the direction, and it is the same answer as the fee question, since a 0-value anchor only works inside a TRUC/v3 package where the child pays for both. That also removes the one gap the current design has, a parent below the mempool minimum, and frees the 330 sats plus the parent fee, which would let taproot-assets drop its 1200 sat per-HTLC carrier to roughly 600 and lower the minimum asset payment we quote over RFQ.

    I would rather not pull it into this series though. It changes the pre-signed transaction format, so it is a new negotiated variant rather than a drop-in, it needs machinery lnd does not have yet (no P2A script type, no v3 construction, no TRUC-aware sweeper, only SubmitPackage exists), and it changes the taproot-assets allocation and exclusion-proof layout that the companion series and its itests are built against. On top of that it is currently untestable end to end: both lnd's and taproot-assets' itest frameworks mine with btcd, which has no TRUC or ephemeral dust policy and no server-side submitpackage, so a 0-fee parent with a 0-value output would never be mined. Validating it needs a Core-mined harness, which is its own piece of work.

    Happy to open a tracking issue for the P2A/TRUC variant so it does not get lost, and there is a cheaper intermediate step available: submitting parent plus child as a package with the existing anchor closes the mempool-minimum gap without any format change.

    ziggie1984 ziggie1984 commented on Aug 24, 2026 19:44 UTC
    Reviewer

    Overall, the core design looks good to me now. The fixed floor-fee parent plus CPFP anchor is a reasonable fit for the constrained Taproot Assets carrier, and the analysis in the review threads clarified the main trade-offs.

    I think the PR still needs a small cleanup/rework pass before final approval:

  • Remove the post-publish retry from this PR as discussed. It retries immediate SweepInput call errors, but cannot observe or repair the later sweeper admission/monitoring failures it was intended to handle. A reliable retry belongs in a follow-up with a proper acknowledgement or persistence boundary.

  • Make the SigHashDefault policy consistent across commitment construction, auxiliary leaf creation, signing, and verification. The commitment builder currently snapshots the result while other paths can consult live negotiation; either use one resolved value per commitment transition or demonstrate with a focused test why divergence cannot occur.

  • Open and link the package-relay follow-up for the known case where the standalone floor-fee parent is below the dynamic mempool minimum.

  • Split the independent maxFeeRatio relaxation if possible. Wherever it lands, cap the override at the concrete tapd requirement (5.0) rather than 100.0, and add a focused Taproot Assets test proving the realistic near-dust re-anchor flow needs a ratio above one.
  • Once those points are addressed and the relevant tests are green, I think this should be ready for a final pass.

    ziggie1984 ziggie1984 commented on Aug 27, 2026 16:58 UTC
    Contributor

    One remaining launch-state issue: both HTLC resolvers call markLaunched before publishPreSignedHtlcTx has successfully registered for block epochs. If RegisterBlockEpochNtfn returns an error, no publisher goroutine is started and PublishTx is never called, but the resolver remains marked launched. Every later Launch call then returns early, so the immutable second-level transaction is not retried until the resolver is reconstructed after an lnd restart. This is particularly risky for deadline-sensitive HTLCs because the SIGHASH_DEFAULT transaction cannot fall back to the normal sweeper reconstruction path.

    Could we mark the resolver launched only after publisher setup succeeds, or clear the flag on synchronous setup failure? A focused test should make registration fail once, call Launch again after restoring the notifier, and verify that the transaction is published.

    ziggie1984 ziggie1984 commented on Aug 27, 2026 16:58 UTC
    Contributor

    A separate reliability concern is the CPFP child that spends the second-level anchor. After the parent is published, an immediate SweepInput error and a later sweep-result error are only logged. There is no persistent retry or acknowledgement proving that the CPFP child was accepted into the mempool. Since SIGHASH_DEFAULT prevents rebuilding or RBF-bumping the parent, this anchor spend is its only fee-bumping path.

    Could we add a durable acceptance/retry boundary here? A transient sweeper admission or publication failure should be retried until the child is accepted, the parent confirms, the deadline is reached, or shutdown occurs. The test should inject an initial failure, then verify a later retry publishes a child spending output 1 and that the child is observed in the mempool. If this is intentionally follow-up work, it would be good to link a focused issue that defines the persistence and retry semantics.

    GeorgeTsagk GeorgeTsagk commented on Aug 28, 2026 10:03 UTC
    Author

    Could we mark the resolver launched only after publisher setup succeeds, or clear the flag on synchronous setup failure?

    Done, went with clearing the flag: the SigHashDefault branch in both resolvers clears it when the publish setup fails synchronously, so the next Launch retries instead of no-op'ing until restart. TestHtlcTimeoutResolverLaunchRetry fails registration once, asserts the resolver is not marked launched, and verifies the second Launch publishes the tx.

    Could we add a durable acceptance/retry boundary here?

    Added, in process. The publisher goroutine now supervises the anchor offer instead of firing it once: an immediate SweepInput error is retried on the next block, and a failed sweep result re-offers on the next block. The loop ends when the sweep succeeds, the anchor is spent by someone else (which covers the anyone-can-spend path once the parent confirmed), or the resolver shuts down. A restart re-publishes the parent and re-offers the anchor from scratch, so the boundary survives restarts without new persisted state. TestPublishPreSignedHtlcTxAnchorSupervision covers the initial offer failure, the re-offer after a failed result, and both terminal outcomes.

    litbot-9000 litbot-9000 commented on Sep 04, 2026 10:25 UTC
    Contributor

    @ziggie1984: review reminder

    litbot-9000 litbot-9000 commented on Sep 11, 2026 11:32 UTC
    Contributor

    @ziggie1984: review reminder

    litbot-9000 litbot-9000 commented on Sep 18, 2026 12:52 UTC
    Contributor

    @ziggie1984: review reminder

    litbot-9000 litbot-9000 commented on Sep 25, 2026 12:54 UTC
    Contributor

    @ziggie1984: review reminder

    ziggie1984 ziggie1984 requested changes on Sep 28, 2026 18:23 UTC
    Changes Requested Reviewer

    Re-reviewed the current head (0dca236ae1) and traced the new publisher through SweepInput, handleNewInput, and the sweeper fee-bumper. The focused contractcourt tests pass. To be explicit up front: I am open to a first version that does not implement package relay. Package relay itself is not a blocking requirement for this PR. My blocking concern is that the immutable-parent lifecycle should be owned by the sweeper, with bounded/classified retries, so package publication can be added there as a follow-up without creating another transaction engine in contractcourt.

    1. The CPFP path cannot rescue a parent that fails standalone admission. The parent is fixed near the relay floor and publishPreSignedHtlcTx does not offer output 1 to the sweeper until PublishTx(parent) succeeds. There are no SubmitPackage calls in contractcourt or sweep. If the dynamic mempool minimum is above the parent's ~1.1 sat/vB rate, the parent is rejected, the child is never constructed, and the anchor cannot do the job it was added for. The existing 330-sat anchor and transaction format can remain unchanged; parent+child package submission is sufficient to close this gap. I am fine deferring that package path to the next version

    2. This introduces another long-lived transaction publication engine in contractcourt. publishPreSignedHtlcTx now owns block-driven publication, retries, anchor supervision, and shutdown while sweep.TxPublisher already owns publication, fee bumping, replacement, monitoring, and sweep state. This repeats the split ownership we are trying to remove with the UTXO nursery. Contractcourt should provide the exact immutable parent, anchor input, budget, and deadline; the sweeper should own how that operation reaches confirmation. The first implementation can retain sequential PublishTx(parent) followed by child publication for unsupported backends, with package submission added as the bitcoind strategy, but the lifecycle should live behind one sweeper API rather than becoming a second publisher here.

    3. The retry contract is too broad and the registration boundary is weaker than the helper assumes. SweepInput returns after delivering a message to newInputs; spend-notification registration happens later in handleNewInput. The resolver correctly waits for the returned result rather than issuing concurrent attempts, but once an error arrives it retries every non-ErrRemoteSpend outcome on the next block, including outcomes the sweeper classified as fatal or budget-exhausted. waitBlock also discards the epoch height, so the supervisor cannot apply an explicit deadline termination policy. Please add an acknowledgement/state boundary for successful registration, classify retryable versus terminal results, and add tests showing transient failures retry while deadline/budget/fatal outcomes terminate according to the intended policy.

    I do not think P2A/TRUC or a zero-fee parent belongs in this PR. Keeping the funded anchor and independently relayable parent is a reasonable cross-backend fallback. Again, a sequential first version is acceptable: the sweeper may initially publish the exact parent and then sweep the anchor, while a later bitcoind strategy submits parent+child as a package. The blocking concern is establishing that single sweeper-owned immutable-parent lifecycle now, before package persistence and reorg handling make the contractcourt helper another nursery-like subsystem.

    Separately, the independent maxFeeRatio change should preferably be split. Its implementation now uses the requested 5.0 ceiling, but the commit message still says 100.0.

    ziggie1984 ziggie1984 commented on Oct 05, 2026 17:42 UTC
    Contributor

    Could you clarify why you decided to keep the immutable-parent publication and rebroadcasting logic in contractcourt rather than move the complete lifecycle into the sweeper as suggested?

    GeorgeTsagk GeorgeTsagk commented on Oct 06, 2026 09:00 UTC
    Author

    Could you clarify why you decided to keep the immutable-parent publication and rebroadcasting logic in contractcourt rather than move the complete lifecycle into the sweeper as suggested?

    I misread the last big comment from you, it seemed to me that the points were highlighting the weak points of this approach, in an informative manner. I will address 2 and 3 from above.

    GeorgeTsagk GeorgeTsagk commented on Oct 06, 2026 15:34 UTC
    Author

    Could you clarify why you decided to keep the immutable-parent publication and rebroadcasting logic in contractcourt rather than move the complete lifecycle into the sweeper as suggested?

    Moved now. The sweeper gets PublishPreSignedTx: contractcourt hands over the exact tx, the anchor input with budget and deadline, and the sweeper owns the rest in its collector loop. Locktime gating and re-broadcast run on blockbeats, the anchor is registered inline once the parent is in the mempool, one final result comes back. The old contractcourt publisher is gone, resolvers only build the request. Package submission later slots into that one method.

    On retries: only publication and anchor registration retry, both bounded by the HTLC deadline. A nil from the input handler is the registration ack. Results from the regular sweep machinery are final by construction (it already retries bumps and publication internally), so none of them is retried. Tests in sweep/presigned_test.go cover each step, the deadline, duplicates, shutdown and an end-to-end run through the live collector.

    litbot-9000 litbot-9000 commented on Oct 13, 2026 15:56 UTC
    Contributor

    @ziggie1984: review reminder

    litbot-9000 litbot-9000 commented on Oct 20, 2026 17:12 UTC
    Contributor

    @ziggie1984: review reminder

    litbot-9000 litbot-9000 commented on Oct 27, 2026 17:43 UTC
    Contributor

    @ziggie1984: review reminder

    ziggie1984 ziggie1984 commented on Nov 03, 2026 14:12 UTC
    Contributor

    waiting for a concept ACK from @yyforyongyu here.

    litbot-9000 litbot-9000 commented on Nov 10, 2026 15:14 UTC
    Contributor

    @ziggie1984: review reminder
    @yyforyongyu: review reminder

    litbot-9000 litbot-9000 commented on Nov 11, 2026 11:16 UTC
    Reviewer

    Reviewed as part of the full aux revocation stack (#11094 → #11111 → #11112, plus taproot-assets#1994 pinned at 2069f100d). Each finding is posted on the PR that introduces it.

    The deterministic second-level construction itself holds. I ran a scratch two-party SigHashDefault state machine: both signed second-level txs pass txscript with StandardVerifyFlags (timeout 816 wu, 227 sat; success 876 wu, 243 sat, ≈1.11 sat/vB), and the sweep sign desc value matches TxOut[0]. Most of what's inline is about the sweeper lifecycle around those txs and about where the sighash mode comes from.

    Test gaps (mutation-tested):

  • Removing sweepOutputAmt -= AnchorSize in both resolution builders: all of ./lnwallet/ still passes.

  • Disabling the isSigHashDefault() hand-off in htlcSuccessResolver: all of ./contractcourt/ still passes.

  • No sweeper test covers parent eviction or replacement after the anchor is offered, batching, a conflicting spend before publish, or restart with a confirmed parent. TestPreSignedTxAnchorOutcomes only feeds canned results.
  • Description: the PR description doesn't mention the CPFP anchor, the baked-in floor fee, or the new UtxoSweeper.PublishPreSignedTx API, which together are most of the diff. The PR is labelled no-changelog, but the stack adds a release-notes entry.

    _Posted by claudell (automated review agent) at georgetsagk's request._

    yyforyongyu yyforyongyu requested changes on Nov 12, 2026 13:07 UTC
    Changes Requested Reviewer

    Found a few issues aided by agents. I think this design works with the assumption that the wallet must remain enough utxos.

    I've also started an iteration on whether we could perform an alternative design, maybe a future upgrade, still working on it, but can check https://gist.github.com/yyforyongyu/4547509e21781834fdb41aa2682d98ef#file-01-proposal-md

    There is also an issue here, unless we support bounded CPFP-only batching here.

    With NoInputBatch, each child can tie up a separate confirmed wallet UTXO. If a peer triggers many HTLC resolutions and those children stay unconfirmed, we could run out of funding inputs for urgent sweeps on other channels, even with plenty of BTC sitting in unconfirmed change. This seems to amplify the existing wallet-liquidity risk.

    We'd need to preserve failure isolation: keep ordinary sweeps outside these batches and rebuild the child when one parent disappears. In a focused unit test, the healthy anchor gets reoffered before the deadline, but the same shared failure terminates its lifecycle after the deadline. That needs fixing, and we'd also need to verify wallet-input recovery when rebuilding the child.

    I think we need to track it as follow-up. It should improve wallet funding efficiency without changing the asset proof rules.

    GeorgeTsagk GeorgeTsagk commented on Nov 13, 2026 11:34 UTC
    Author

    The batching concern is real. The anchor keeps NoInputBatch so that a missing parent only fails its own child, and the wallet UTXO it ties up is the cost of that. Filed as #11576. The lifecycle no longer terminates at the deadline, so the shared failure past the deadline you hit in your test now reoffers the anchor like any other block.

    litbot-9000 litbot-9000 commented on Nov 20, 2026 14:16 UTC
    Contributor

    @yyforyongyu: review reminder
    @georgetsagk, remember to re-request review from reviewers when ready

    Reviewers
    Assignees
    GeorgeTsagk GeorgeTsagk
    Labels
    risk: low confidence: 88.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 83.5% (HIGH) · Higher = larger blast radius
    83.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.4% · Lower = rushed or shallow review
    88.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.7% · Safe to merge
    9.7%