diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index 52185e52ce4..ad917a531f0 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -1587,6 +1587,7 @@ func testBreachSpends(t *testing.T, test breachTest) { fn.Some[lnwallet.AuxContractResolver]( &lnwallet.MockAuxContractResolver{}, ), + fn.None[lnwallet.AuxSigner](), ) require.NoError(t, err, "unable to create breach retribution") @@ -1802,6 +1803,7 @@ func TestBreachDelayedJusticeConfirmation(t *testing.T) { fn.Some[lnwallet.AuxContractResolver]( &lnwallet.MockAuxContractResolver{}, ), + fn.None[lnwallet.AuxSigner](), ) require.NoError(t, err, "unable to create breach retribution") diff --git a/contractcourt/chain_arbitrator.go b/contractcourt/chain_arbitrator.go index 9a80bff2c8d..296978c87f3 100644 --- a/contractcourt/chain_arbitrator.go +++ b/contractcourt/chain_arbitrator.go @@ -1205,6 +1205,7 @@ func (c *ChainArbitrator) WatchNewChannel( extractStateNumHint: lnwallet.GetStateNumHint, auxLeafStore: c.cfg.AuxLeafStore, auxResolver: c.cfg.AuxResolver, + auxSigner: c.cfg.AuxSigner, auxCloser: c.cfg.AuxCloser, chanCloseConfs: c.cfg.ChannelCloseConfs, notifyEarlyCoopClose: c.cfg.NotifyEarlyClosedChannel, @@ -1385,6 +1386,7 @@ func (c *ChainArbitrator) loadOpenChannels() error { extractStateNumHint: lnwallet.GetStateNumHint, auxLeafStore: c.cfg.AuxLeafStore, auxResolver: c.cfg.AuxResolver, + auxSigner: c.cfg.AuxSigner, auxCloser: c.cfg.AuxCloser, chanCloseConfs: c.cfg.ChannelCloseConfs, notifyEarlyCoopClose: notifyEarlyClose, diff --git a/contractcourt/chain_watcher.go b/contractcourt/chain_watcher.go index 46c7d8f5578..264ecad4272 100644 --- a/contractcourt/chain_watcher.go +++ b/contractcourt/chain_watcher.go @@ -273,6 +273,10 @@ type chainWatcherConfig struct { // auxResolver is used to supplement contract resolution. auxResolver fn.Option[lnwallet.AuxContractResolver] + // auxSigner is an optional signer that can be used to determine + // channel-specific HTLC sighash types based on negotiated features. + auxSigner fn.Option[lnwallet.AuxSigner] + // auxCloser is used to finalize cooperative closes. auxCloser fn.Option[AuxChanCloser] @@ -1170,6 +1174,7 @@ func (c *chainWatcher) handlePossibleBreach(commitSpend *chainntnfs.SpendDetail, retribution, err := lnwallet.NewBreachRetribution( c.cfg.chanState, broadcastStateNum, spendHeight, commitSpend.SpendingTx, c.cfg.auxLeafStore, c.cfg.auxResolver, + c.cfg.auxSigner, ) switch { @@ -1595,7 +1600,7 @@ func (c *chainWatcher) dispatchLocalForceClose( forceClose, err := lnwallet.NewLocalForceCloseSummary( c.cfg.chanState, c.cfg.signer, commitSpend.SpendingTx, uint32(commitSpend.SpendingHeight), stateNum, - c.cfg.auxLeafStore, c.cfg.auxResolver, + c.cfg.auxLeafStore, c.cfg.auxResolver, c.cfg.auxSigner, ) if err != nil { return err @@ -1702,6 +1707,7 @@ func (c *chainWatcher) dispatchRemoteForceClose( uniClose, err := lnwallet.NewUnilateralCloseSummary( c.cfg.chanState, c.cfg.signer, commitSpend, remoteCommit, commitPoint, c.cfg.auxLeafStore, c.cfg.auxResolver, + c.cfg.auxSigner, ) if err != nil { return err diff --git a/contractcourt/commit_sweep_resolver_test.go b/contractcourt/commit_sweep_resolver_test.go index ef82c39877c..03364c0c02b 100644 --- a/contractcourt/commit_sweep_resolver_test.go +++ b/contractcourt/commit_sweep_resolver_test.go @@ -120,6 +120,14 @@ type mockSweeper struct { createSweepTxChan chan *wire.MsgTx deadlines []int + budgets []btcutil.Amount + + // preSignedReqs records every pre-signed tx handed to the sweeper. + preSignedReqs chan sweep.PreSignedTxRequest + + // preSignedErr, if set, is returned synchronously by + // PublishPreSignedTx. + preSignedErr error } func newMockSweeper() *mockSweeper { @@ -128,10 +136,29 @@ func newMockSweeper() *mockSweeper { updatedInputs: make(chan wire.OutPoint), sweepTx: &wire.MsgTx{}, createSweepTxChan: make(chan *wire.MsgTx), + preSignedReqs: make(chan sweep.PreSignedTxRequest, 3), deadlines: []int{}, } } +func (s *mockSweeper) PublishPreSignedTx( + req sweep.PreSignedTxRequest) (<-chan sweep.Result, error) { + + if s.preSignedErr != nil { + return nil, s.preSignedErr + } + + s.preSignedReqs <- req + + result := make(chan sweep.Result, 1) + result <- sweep.Result{ + Tx: s.sweepTx, + Err: s.sweepErr, + } + + return result, nil +} + func (s *mockSweeper) SweepInput(input input.Input, params sweep.Params) ( chan sweep.Result, error) { @@ -142,6 +169,8 @@ func (s *mockSweeper) SweepInput(input input.Input, params sweep.Params) ( s.deadlines = append(s.deadlines, int(d)) }) + s.budgets = append(s.budgets, params.Budget) + result := make(chan sweep.Result, 1) result <- sweep.Result{ Tx: s.sweepTx, diff --git a/contractcourt/contract_resolver.go b/contractcourt/contract_resolver.go index 66926b0415b..59a00202f62 100644 --- a/contractcourt/contract_resolver.go +++ b/contractcourt/contract_resolver.go @@ -1,17 +1,24 @@ package contractcourt import ( + "bytes" "encoding/binary" "errors" "fmt" "io" + "sync" "sync/atomic" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/btcsuite/btclog/v2" "github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/chanstate" "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/sweep" ) @@ -138,6 +145,11 @@ type contractResolverKit struct { // resolved reflects if the contract has been fully resolved or not. resolved atomic.Bool + + // wg tracks background goroutines spawned by the resolver (the + // consumers of pre-signed tx outcomes reported by the sweeper) so + // Stop can wait for them to exit. + wg sync.WaitGroup } // newContractResolverKit instantiates the mix-in struct. @@ -179,8 +191,228 @@ func (r *contractResolverKit) markLaunched() { r.launched.Store(true) } +// clearLaunched clears the launched flag, allowing a later Launch call to +// retry after a synchronous launch failure. Without this, a resolver whose +// launch failed before anything was handed to the sweeper (or scheduled for +// publish) would no-op every subsequent Launch until a restart. +func (r *contractResolverKit) clearLaunched() { + r.launched.Store(false) +} + +// publishPreSignedHtlcTx hands a pre-signed second-level HTLC transaction +// to the sweeper, which owns its whole lifecycle from here on: publication +// gated on the tx locktime and retried on every block, CPFP of the embedded +// anchor (when present) through the regular sweep machinery, and the final +// outcome. The call returns as soon as the sweeper has accepted the request; +// a tracked goroutine logs the eventual result so failures are visible. +// +// The resolver's Resolve() path independently waits for the spend of the +// HTLC output, so none of this changes resolution semantics; it only +// determines whether the immutable parent gets confirmed in time. +func (r *contractResolverKit) publishPreSignedHtlcTx( + req sweep.PreSignedTxRequest) error { + + resultChan, err := r.Sweeper.PublishPreSignedTx(req) + if err != nil { + return fmt.Errorf("hand pre-signed tx %v to sweeper: %w", + req.Tx.TxHash(), err) + } + + txid := req.Tx.TxHash() + r.log.Infof("handed pre-signed second-level tx=%v to the sweeper "+ + "(locktime=%d, anchor=%v, budget=%v, deadline=%v)", txid, + req.Tx.LockTime, req.Anchor != nil, req.Budget, + req.DeadlineHeight) + + r.wg.Add(1) + go func() { + defer r.wg.Done() + + select { + case result, ok := <-resultChan: + if !ok { + return + } + + switch { + case errors.Is(result.Err, sweep.ErrRemoteSpend): + r.log.Debugf("anchor of pre-signed tx=%v "+ + "spent by a third party", txid) + + case errors.Is( + result.Err, sweep.ErrPreSignedTxConflict, + ): + r.log.Infof("pre-signed tx=%v can no longer "+ + "confirm, its input was spent by "+ + "another tx", txid) + + case result.Err != nil: + r.log.Errorf("pre-signed tx=%v lifecycle "+ + "ended with error: %v", txid, + result.Err) + + case result.Tx != nil: + r.log.Infof("pre-signed tx=%v concluded, "+ + "final tx=%v", txid, + result.Tx.TxHash()) + } + + case <-r.quit: + } + }() + + return nil +} + var ( // errResolverShuttingDown is returned when the resolver stops // progressing because it received the quit signal. errResolverShuttingDown = errors.New("resolver shutting down") + + // errSecondLevelAnchorScript is returned when output 1 of a + // pre-signed second-level HTLC tx does not pay to the anchor script + // the resolver derives, so the anchor could not be spent. + errSecondLevelAnchorScript = errors.New("second-level anchor output " + + "script mismatch") ) + +// secondLevelAnchorInput builds the sweepable input for the CPFP anchor at +// index 1 of a pre-signed DeterministicHTLCs second-level HTLC tx, along +// with the fee budget the sweeper may spend on the child. The pre-signed +// parent cannot be RBF'd under SigHashDefault, so CPFP via this anchor is +// its only fee-bumping path. +// +// The anchor is a taproot output spendable by the broadcaster's ToLocalKey +// via key-path (fast) or by anyone after 16 blocks via script path. We use +// the key-path. The delay key is derived from the second-level HTLC +// output's sweep sign descriptor (delay base point plus the commitment +// point's single tweak), which is exactly the key the anchor is keyed to. +// +// It returns a nil input when the tx carries no anchor or the descriptor +// lacks the key material: the parent then still publishes at its baked-in +// floor fee, CPFP is just unavailable. +func secondLevelAnchorInput(parentTx *wire.MsgTx, + htlcSweepDesc input.SignDescriptor, parentFee btcutil.Amount, + broadcastHeight uint32, budgetCfg BudgetConfig, + log btclog.Logger) (input.Input, btcutil.Amount, 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, 0, nil + } + + 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, 0, nil + } + delayKey := input.TweakPubKeyWithTweak( + htlcSweepDesc.KeyDesc.PubKey, htlcSweepDesc.SingleTweak, + ) + anchorTree, anchorPkScript, err := lnwallet.SecondLevelAnchorScript( + delayKey, + ) + if err != nil { + return nil, 0, fmt.Errorf("build anchor script tree: %w", err) + } + + // Output 1 is assumed to be the anchor. Check that it really pays to + // the script we are about to spend, so a tx built with a different + // key or layout is caught here instead of as an unspendable input. + if !bytes.Equal(parentTx.TxOut[1].PkScript, anchorPkScript) { + return nil, 0, fmt.Errorf("%w: tx %v output 1 pays to %x, "+ + "anchor script is %x", errSecondLevelAnchorScript, + parentTx.TxHash(), parentTx.TxOut[1].PkScript, + anchorPkScript) + } + + 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: parentFee, + Weight: parentWeight, + } + + anchorInput := input.MakeBaseInput( + &op, input.TaprootAnchorSweepSpend, &signDesc, + broadcastHeight, parentInfo, + ) + + // The budget bounds the fees the sweeper may pay for the CPFP child + // (funded from wallet inputs, so it can and usually must exceed the + // anchor's own value). Derive it from the value under protection, + // the second-level HTLC output, with the same configuration used + // for commitment anchor CPFP, plus the anchor value itself. + budget := calculateBudget( + btcutil.Amount(parentTx.TxOut[0].Value), + budgetCfg.AnchorCPFPRatio, budgetCfg.AnchorCPFP, + ) + AnchorOutputValue + + return &anchorInput, budget, nil +} + +// preSignedTxFee returns the exact fee baked into a pre-signed second-level +// HTLC tx: the value of the commitment output it spends (carried by the sign +// details' sign descriptor) minus the sum of its outputs. +func preSignedTxFee(tx *wire.MsgTx, + signDetails *input.SignDetails) btcutil.Amount { + + inputValue := signDetails.SignDesc.Output.Value + + var outputValue int64 + for _, txOut := range tx.TxOut { + outputValue += txOut.Value + } + + return btcutil.Amount(inputValue - outputValue) +} + +// 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 sighash check alone filters every channel that populates sign +// details today: legacy channels sign second levels with SIGHASH_ALL +// (0x01), anchor and taproot channels with SIGHASH_SINGLE|ANYONECANPAY +// (0x83), and taproot asset channels that did not negotiate +// DeterministicHTLCs also carry 0x83. The channel type gate +// (TapscriptRootBit, only ever set for aux/custom channels) is layered +// on top for two reasons: it makes the custom-channel-only isolation of +// this path explicit, and it protects against SigHashDefault being the +// zero value of SigHashType, so no present or future code path that +// leaves the field unset can ever steer a non-custom channel in here. +func isSecondLevelSigHashDefault(signDetails *input.SignDetails, + chanType channeldb.ChannelType) bool { + + return signDetails != nil && + signDetails.SigHashType == txscript.SigHashDefault && + chanType.HasTapscriptRoot() +} diff --git a/contractcourt/contract_resolver_test.go b/contractcourt/contract_resolver_test.go new file mode 100644 index 00000000000..a6c99a06b24 --- /dev/null +++ b/contractcourt/contract_resolver_test.go @@ -0,0 +1,578 @@ +package contractcourt + +import ( + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/sweep" + "github.com/stretchr/testify/require" +) + +// TestIsSecondLevelSigHashDefault asserts that the pre-signed-tx publish path +// can only ever activate for aux/custom (taproot asset) channels: without a +// tapscript root in the channel type, even sign details carrying the +// (zero-value) SigHashDefault flag must not match. +func TestIsSecondLevelSigHashDefault(t *testing.T) { + t.Parallel() + + taprootChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + + customChanType := taprootChanType | channeldb.TapscriptRootBit + + sigHashDefaultDetails := &input.SignDetails{ + SigHashType: txscript.SigHashDefault, + } + standardDetails := &input.SignDetails{ + SigHashType: txscript.SigHashSingle | + txscript.SigHashAnyOneCanPay, + } + + testCases := []struct { + name string + signDetails *input.SignDetails + chanType channeldb.ChannelType + expect bool + }{{ + // No sign details at all (first-level only): never matches. + name: "nil sign details", + signDetails: nil, + chanType: customChanType, + expect: false, + }, { + // The crux: SigHashDefault is the zero value of SigHashType, + // so any non-custom channel that never populates the field + // would false-positively match without the channel-type gate. + name: "sighash default, non-custom taproot", + signDetails: sigHashDefaultDetails, + chanType: taprootChanType, + expect: false, + }, { + name: "sighash default, custom channel", + signDetails: sigHashDefaultDetails, + chanType: customChanType, + expect: true, + }, { + name: "standard sighash, custom channel", + signDetails: standardDetails, + chanType: customChanType, + expect: false, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.expect, isSecondLevelSigHashDefault( + tc.signDetails, tc.chanType, + )) + }) + } +} + +// TestPreSignedTxFee asserts that the exact baked-in fee of a pre-signed +// second-level tx is derived from the spent commitment output value minus +// the tx's own outputs. +func TestPreSignedTxFee(t *testing.T) { + t.Parallel() + + tx := wire.NewMsgTx(2) + tx.AddTxOut(&wire.TxOut{Value: 99_426}) + tx.AddTxOut(&wire.TxOut{Value: int64(lnwallet.AnchorSize)}) + + signDetails := &input.SignDetails{ + SignDesc: input.SignDescriptor{ + Output: &wire.TxOut{Value: 100_000}, + }, + } + + require.Equal( + t, btcutil.Amount(244), preSignedTxFee(tx, signDetails), + ) +} + +// TestSecondLevelAnchorInput asserts the construction of the CPFP anchor +// input for a pre-signed second-level HTLC tx: the anchor outpoint at index +// 1, a key-path (SigHashDefault) sign descriptor for the tweaked delay key's +// anchor tree, the exact baked-in parent fee for package fee-rate math, and +// the budget derived from the protected HTLC value. A parent without an +// anchor or a descriptor without key material yields no input rather than +// an error. +func TestSecondLevelAnchorInput(t *testing.T) { + t.Parallel() + + delayBase, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + singleTweak := input.SingleTweakBytes( + commitPriv.PubKey(), delayBase.PubKey(), + ) + signDesc := input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: delayBase.PubKey(), + }, + SingleTweak: singleTweak, + } + + budgetCfg := BudgetConfig{ + AnchorCPFP: 10_000, + AnchorCPFPRatio: 0.5, + } + const ( + htlcOutValue = int64(100_000) + parentFee = btcutil.Amount(244) + ) + + // A single-output parent (no anchor appended) yields no input. + oneOutTx := wire.NewMsgTx(2) + oneOutTx.AddTxOut(&wire.TxOut{Value: htlcOutValue}) + anchor, budget, err := secondLevelAnchorInput( + oneOutTx, signDesc, parentFee, 100, budgetCfg, log, + ) + require.NoError(t, err) + require.Nil(t, anchor) + require.Zero(t, budget) + + // A parent with an anchor but a descriptor lacking key material also + // yields no input (logged, not an error): CPFP is unavailable but the + // parent still publishes. + twoOutTx := wire.NewMsgTx(2) + twoOutTx.AddTxOut(&wire.TxOut{Value: htlcOutValue}) + twoOutTx.AddTxOut(&wire.TxOut{ + Value: int64(lnwallet.AnchorSize), + PkScript: secondLevelAnchorPkScript( + t, delayBase.PubKey(), commitPriv.PubKey(), + ), + }) + anchor, _, err = secondLevelAnchorInput( + twoOutTx, input.SignDescriptor{}, parentFee, 100, budgetCfg, + log, + ) + require.NoError(t, err) + require.Nil(t, anchor) + + // Output 1 paying to anything but the anchor script derived from the + // descriptor is an error: the input we would build could never be + // spent. A tx built for a different commitment point is such a case. + otherCommit, err := btcec.NewPrivateKey() + require.NoError(t, err) + wrongKeyTx := wire.NewMsgTx(2) + wrongKeyTx.AddTxOut(&wire.TxOut{Value: htlcOutValue}) + wrongKeyTx.AddTxOut(&wire.TxOut{ + Value: int64(lnwallet.AnchorSize), + PkScript: secondLevelAnchorPkScript( + t, delayBase.PubKey(), otherCommit.PubKey(), + ), + }) + anchor, _, err = secondLevelAnchorInput( + wrongKeyTx, signDesc, parentFee, 100, budgetCfg, log, + ) + require.ErrorIs(t, err, errSecondLevelAnchorScript) + require.Nil(t, anchor) + + // The well-formed case. + anchor, budget, err = secondLevelAnchorInput( + twoOutTx, signDesc, parentFee, 100, budgetCfg, log, + ) + require.NoError(t, err) + require.NotNil(t, anchor) + + require.Equal(t, wire.OutPoint{ + Hash: twoOutTx.TxHash(), + Index: 1, + }, anchor.OutPoint()) + require.Equal( + t, input.TaprootAnchorSweepSpend, anchor.WitnessType(), + ) + require.EqualValues(t, 100, anchor.HeightHint()) + + // The budget must be derived from the protected HTLC value via the + // anchor CPFP configuration (50% of 100k, capped at 10k), plus the + // anchor's own value. + require.Equal(t, btcutil.Amount(10_000)+AnchorOutputValue, budget) + + // The parent info must carry the exact baked-in fee for package + // fee-rate calculation. + require.NotNil(t, anchor.UnconfParent()) + require.Equal(t, parentFee, anchor.UnconfParent().Fee) + + // The sign descriptor must target the anchor output with a key-path + // (SigHashDefault) spend of the tweaked delay key's anchor tree. + sd := anchor.SignDesc() + require.Equal(t, twoOutTx.TxOut[1], sd.Output) + require.Equal(t, txscript.SigHashDefault, sd.HashType) + + delayKey := input.TweakPubKeyWithTweak( + delayBase.PubKey(), singleTweak, + ) + anchorTree, anchorPkScript, err := lnwallet.SecondLevelAnchorScript( + delayKey, + ) + require.NoError(t, err) + require.Equal(t, anchorTree.TapscriptRoot, sd.TapTweak) + require.Equal(t, anchorPkScript, sd.Output.PkScript) +} + +// secondLevelAnchorPkScript returns the output script of the anchor of a +// second-level tx whose HTLC output is swept with the given delay base point +// and commitment point. +func secondLevelAnchorPkScript(t *testing.T, delayBase, + commitPoint *btcec.PublicKey) []byte { + + t.Helper() + + delayKey := input.TweakPubKeyWithTweak( + delayBase, input.SingleTweakBytes(commitPoint, delayBase), + ) + _, pkScript, err := lnwallet.SecondLevelAnchorScript(delayKey) + require.NoError(t, err) + + return pkScript +} + +// newPreSignedTestResolver builds a timeout resolver in the SigHashDefault +// state over the given mock sweeper, with a two-output pre-signed timeout tx +// (HTLC output + anchor). +func newPreSignedTestResolver(t *testing.T, + sweeper *mockSweeper) (*htlcTimeoutResolver, *wire.MsgTx) { + + t.Helper() + + customChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + delayBase, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + timeoutTx := wire.NewMsgTx(2) + timeoutTx.LockTime = 500 + timeoutTx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{Hash: [32]byte{1}, Index: 2}, + }) + timeoutTx.AddTxOut(&wire.TxOut{Value: 630}) + timeoutTx.AddTxOut(&wire.TxOut{ + Value: int64(lnwallet.AnchorSize), + PkScript: secondLevelAnchorPkScript( + t, delayBase.PubKey(), commitPriv.PubKey(), + ), + }) + + cfg := ResolverConfig{ + ChannelArbitratorConfig: ChannelArbitratorConfig{ + ChainArbitratorConfig: ChainArbitratorConfig{ + Sweeper: sweeper, + Budget: *DefaultBudgetConfig(), + }, + }, + } + + resolver := &htlcTimeoutResolver{ + contractResolverKit: *newContractResolverKit(cfg), + htlcResolution: lnwallet.OutgoingHtlcResolution{ + SignedTimeoutTx: timeoutTx, + SignDetails: &input.SignDetails{ + SigHashType: txscript.SigHashDefault, + SignDesc: input.SignDescriptor{ + Output: &wire.TxOut{ + Value: 1200, + PkScript: []byte{0x51, 0x20}, + }, + }, + }, + SweepSignDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: delayBase.PubKey(), + }, + SingleTweak: input.SingleTweakBytes( + commitPriv.PubKey(), delayBase.PubKey(), + ), + }, + }, + chanType: customChanType, + incomingHTLCExpiryHeight: fn.Some(int32(600)), + broadcastHeight: 450, + } + resolver.initLogger("test") + + return resolver, timeoutTx +} + +// TestHtlcTimeoutResolverPreSignedHandOff asserts that launching a +// SigHashDefault timeout resolver hands the exact pre-signed tx, its anchor +// input, the CPFP budget and the deadline to the sweeper in a single +// request, and that the resolver does not publish anything itself. +func TestHtlcTimeoutResolverPreSignedHandOff(t *testing.T) { + t.Parallel() + + sweeper := newMockSweeper() + resolver, timeoutTx := newPreSignedTestResolver(t, sweeper) + + require.NoError(t, resolver.Launch()) + require.True(t, resolver.isLaunched()) + + req := <-sweeper.preSignedReqs + require.Equal(t, timeoutTx.TxHash(), req.Tx.TxHash()) + require.NotNil(t, req.Anchor) + require.Equal(t, wire.OutPoint{ + Hash: timeoutTx.TxHash(), + Index: 1, + }, req.Anchor.OutPoint()) + require.Equal(t, fn.Some(int32(600)), req.DeadlineHeight) + require.Equal(t, parentFeeOf(timeoutTx, 1200), + req.Anchor.UnconfParent().Fee) + require.Greater(t, req.Budget, AnchorOutputValue) + + // The sweeper is told which output the tx spends and from which + // height to watch it, so it can tell a confirmation from a conflict. + require.Equal(t, []*wire.TxOut{ + resolver.htlcResolution.SignDetails.SignDesc.Output, + }, req.SpentOutputs) + require.EqualValues(t, 450, req.HeightHint) + + // Nothing was handed to SweepInput directly: the sweeper owns the + // anchor through the pre-signed lifecycle. + require.Empty(t, sweeper.sweptInputs) + + resolver.Stop() + resolver.wg.Wait() +} + +// parentFeeOf returns the baked-in fee of a tx spending a single input of the +// given value. +func parentFeeOf(tx *wire.MsgTx, inputValue int64) btcutil.Amount { + var out int64 + for _, txOut := range tx.TxOut { + out += txOut.Value + } + + return btcutil.Amount(inputValue - out) +} + +// TestHtlcTimeoutResolverLaunchRetry asserts that a synchronous failure to +// hand the pre-signed tx to the sweeper does not leave the resolver +// permanently marked as launched: a later Launch call must retry and +// succeed. +func TestHtlcTimeoutResolverLaunchRetry(t *testing.T) { + t.Parallel() + + sweeper := newMockSweeper() + sweeper.preSignedErr = sweep.ErrSweeperShuttingDown + resolver, timeoutTx := newPreSignedTestResolver(t, sweeper) + + // The first Launch hits the failing hand-off: it must error AND leave + // the resolver un-launched so it can be retried. + err := resolver.Launch() + require.ErrorIs(t, err, sweep.ErrSweeperShuttingDown) + require.False(t, resolver.isLaunched(), + "failed launch must not leave the resolver marked launched") + require.Empty(t, sweeper.preSignedReqs) + + // With the sweeper accepting again, the second Launch hands the tx + // over. + sweeper.preSignedErr = nil + require.NoError(t, resolver.Launch()) + require.True(t, resolver.isLaunched()) + + req := <-sweeper.preSignedReqs + require.Equal(t, timeoutTx.TxHash(), req.Tx.TxHash()) + + // A further Launch is a no-op: the lifecycle is owned by the sweeper + // and must not be submitted twice by the resolver. + require.NoError(t, resolver.Launch()) + require.Empty(t, sweeper.preSignedReqs) + + resolver.Stop() + resolver.wg.Wait() +} + +// newPreSignedSuccessTestResolver builds a success resolver over the given +// mock sweeper, with a two-output pre-signed success tx (HTLC output + +// anchor) whose signature uses the given sighash type. +func newPreSignedSuccessTestResolver(t *testing.T, sweeper *mockSweeper, + sigHashType txscript.SigHashType) (*htlcSuccessResolver, *wire.MsgTx) { + + t.Helper() + + customChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + delayBase, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + sweepPkScript, err := txscript.PayToTaprootScript(delayBase.PubKey()) + require.NoError(t, err) + + successTx := wire.NewMsgTx(2) + successTx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{Hash: [32]byte{1}, Index: 3}, + }) + successTx.AddTxOut(&wire.TxOut{Value: 630}) + successTx.AddTxOut(&wire.TxOut{ + Value: int64(lnwallet.AnchorSize), + PkScript: secondLevelAnchorPkScript( + t, delayBase.PubKey(), commitPriv.PubKey(), + ), + }) + + cfg := ResolverConfig{ + ChannelArbitratorConfig: ChannelArbitratorConfig{ + ChainArbitratorConfig: ChainArbitratorConfig{ + Sweeper: sweeper, + Budget: *DefaultBudgetConfig(), + }, + }, + } + + resolver := &htlcSuccessResolver{ + contractResolverKit: *newContractResolverKit(cfg), + htlcResolution: lnwallet.IncomingHtlcResolution{ + SignedSuccessTx: successTx, + SignDetails: &input.SignDetails{ + SigHashType: sigHashType, + SignDesc: input.SignDescriptor{ + Output: &wire.TxOut{ + Value: 1200, + PkScript: []byte{0x51, 0x20}, + }, + }, + }, + SweepSignDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: delayBase.PubKey(), + }, + Output: &wire.TxOut{ + Value: 630, + PkScript: sweepPkScript, + }, + SingleTweak: input.SingleTweakBytes( + commitPriv.PubKey(), delayBase.PubKey(), + ), + }, + }, + htlc: channeldb.HTLC{ + RefundTimeout: 700, + }, + chanType: customChanType, + broadcastHeight: 450, + } + resolver.initLogger("test") + + return resolver, successTx +} + +// TestHtlcSuccessResolverPreSignedHandOff asserts that launching a +// SigHashDefault success resolver hands the exact pre-signed tx, its anchor +// input, the CPFP budget and the HTLC's refund timeout as the deadline to +// the sweeper in a single request, and that it does not offer the tx to the +// regular sweep flow, which would rebuild it and invalidate the peer's +// signature. +func TestHtlcSuccessResolverPreSignedHandOff(t *testing.T) { + t.Parallel() + + sweeper := newMockSweeper() + resolver, successTx := newPreSignedSuccessTestResolver( + t, sweeper, txscript.SigHashDefault, + ) + + require.True(t, resolver.isSigHashDefault()) + require.NoError(t, resolver.Launch()) + require.True(t, resolver.isLaunched()) + + req := <-sweeper.preSignedReqs + require.Equal(t, successTx.TxHash(), req.Tx.TxHash()) + require.NotNil(t, req.Anchor) + require.Equal(t, wire.OutPoint{ + Hash: successTx.TxHash(), + Index: 1, + }, req.Anchor.OutPoint()) + require.Equal(t, fn.Some(int32(700)), req.DeadlineHeight) + require.Equal(t, parentFeeOf(successTx, 1200), + req.Anchor.UnconfParent().Fee) + require.Greater(t, req.Budget, AnchorOutputValue) + require.Equal(t, []*wire.TxOut{ + resolver.htlcResolution.SignDetails.SignDesc.Output, + }, req.SpentOutputs) + require.EqualValues(t, resolver.broadcastHeight, req.HeightHint) + + // Nothing was handed to SweepInput: the sweeper owns the tx through + // the pre-signed lifecycle only. + require.Empty(t, sweeper.sweptInputs) + + resolver.Stop() + resolver.wg.Wait() +} + +// TestHtlcSuccessResolverLegacySigHashUsesSweeper asserts the other side of +// the hand-off: a success tx signed with SINGLE|ANYONECANPAY is never +// published verbatim, it goes through the regular sweep flow that attaches +// fees to it. +func TestHtlcSuccessResolverLegacySigHashUsesSweeper(t *testing.T) { + t.Parallel() + + sweeper := newMockSweeper() + resolver, _ := newPreSignedSuccessTestResolver( + t, sweeper, + txscript.SigHashSingle|txscript.SigHashAnyOneCanPay, + ) + + require.False(t, resolver.isSigHashDefault()) + require.NoError(t, resolver.Launch()) + + select { + case <-sweeper.sweptInputs: + case <-time.After(5 * time.Second): + t.Fatal("second-level success tx not offered to the sweeper") + } + require.Empty(t, sweeper.preSignedReqs) +} + +// TestHtlcSuccessResolverLaunchRetry asserts that a synchronous failure to +// hand the pre-signed success tx to the sweeper does not leave the resolver +// permanently marked as launched: a later Launch call must retry and +// succeed. +func TestHtlcSuccessResolverLaunchRetry(t *testing.T) { + t.Parallel() + + sweeper := newMockSweeper() + sweeper.preSignedErr = sweep.ErrSweeperShuttingDown + resolver, successTx := newPreSignedSuccessTestResolver( + t, sweeper, txscript.SigHashDefault, + ) + + err := resolver.Launch() + require.ErrorIs(t, err, sweep.ErrSweeperShuttingDown) + require.False(t, resolver.isLaunched(), + "failed launch must not leave the resolver marked launched") + require.Empty(t, sweeper.preSignedReqs) + + sweeper.preSignedErr = nil + require.NoError(t, resolver.Launch()) + require.True(t, resolver.isLaunched()) + + req := <-sweeper.preSignedReqs + require.Equal(t, successTx.TxHash(), req.Tx.TxHash()) + + resolver.Stop() + resolver.wg.Wait() +} diff --git a/contractcourt/htlc_success_resolver.go b/contractcourt/htlc_success_resolver.go index ebe1933bcd3..1bf3b874055 100644 --- a/contractcourt/htlc_success_resolver.go +++ b/contractcourt/htlc_success_resolver.go @@ -410,6 +410,7 @@ func (h *htlcSuccessResolver) Stop() { defer h.log.Debugf("stopped") close(h.quit) + h.wg.Wait() } // report returns a report on the resolution state of the contract. @@ -587,6 +588,55 @@ func (h *htlcSuccessResolver) isZeroFeeOutput() bool { h.htlcResolution.SignDetails != nil } +// isSigHashDefault returns true when the second-level HTLC transaction +// was signed with SigHashDefault. See isSecondLevelSigHashDefault. +func (h *htlcSuccessResolver) isSigHashDefault() bool { + return isSecondLevelSigHashDefault( + h.htlcResolution.SignDetails, h.chanType, + ) +} + +// publishSuccessTx directly broadcasts the pre-signed second-level HTLC +// success transaction. This is used when the transaction was signed with +// SigHashDefault (baked-in fees), where the sweeper's normal tx-rebuilding +// flow would invalidate the peer's signature. The anchor output appended +// to the second-level tx is handed over alongside it so the sweeper can +// CPFP the parent once it is in the mempool. +func (h *htlcSuccessResolver) publishSuccessTx() error { + parentTx := h.htlcResolution.SignedSuccessTx + h.log.Infof("publishing pre-signed 2nd-level HTLC success tx=%v "+ + "(SigHashDefault, baked-in fees)", parentTx.TxHash()) + + // The CPFP anchor at index 1 is the parent's only fee-bumping path. + // The deadline is the HTLC's refund timeout so the sweeper prioritises + // confirmation before the HTLC expires. + anchor, budget, err := secondLevelAnchorInput( + parentTx, h.htlcResolution.SweepSignDesc, + preSignedTxFee(parentTx, h.htlcResolution.SignDetails), + h.broadcastHeight, h.Budget, h.log, + ) + if err != nil { + return err + } + + // The sweeper watches the commitment HTLC output the tx spends: a + // confirmed spend of it is what tells it the tx confirmed, or that + // it never will. + return h.publishPreSignedHtlcTx(sweep.PreSignedTxRequest{ + Tx: parentTx, + SpentOutputs: []*wire.TxOut{ + h.htlcResolution.SignDetails.SignDesc.Output, + }, + HeightHint: h.broadcastHeight, + Label: labels.MakeLabel( + labels.LabelTypeChannelClose, &h.ShortChanID, + ), + Anchor: anchor, + Budget: budget, + DeadlineHeight: fn.Some(int32(h.htlc.RefundTimeout)), + }) +} + // isTaproot returns true if the resolver is for a taproot output. func (h *htlcSuccessResolver) isTaproot() bool { return txscript.IsPayToTaproot( @@ -874,12 +924,15 @@ func (h *htlcSuccessResolver) sweepSuccessTxOutput() error { default: witType = input.HtlcAcceptedSuccessSecondLevel } + + resolutionBlob := h.htlcResolution.ResolutionBlob + inp := h.makeSweepInput( &secondLevelOutpoint, witType, input.LeaseHtlcAcceptedSuccessSecondLevel, &h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, uint32(commitSpend.SpendingHeight), - h.htlc.RHash, h.htlcResolution.ResolutionBlob, + h.htlc.RHash, resolutionBlob, ) // Calculate the budget for this sweep. @@ -1072,6 +1125,24 @@ func (h *htlcSuccessResolver) Launch() error { return h.sweepSuccessTxOutput() } + // When the peer signed with SigHashDefault the pre-signed + // second-level tx has baked-in fees and cannot be modified + // (adding wallet inputs would invalidate the signature). + // Publish it directly instead of going through the sweeper. + if h.isSigHashDefault() { + // A synchronous failure here means the sweeper did + // not accept the request, so nothing is tracking the + // tx and no other component retries. Clear the + // launched flag so the next Launch attempt can retry + // instead of no-op'ing until restart. + err := h.publishSuccessTx() + if err != nil { + h.clearLaunched() + } + + return err + } + // Otherwise, sweep the second level tx. return h.sweepSuccessTx() diff --git a/contractcourt/htlc_timeout_resolver.go b/contractcourt/htlc_timeout_resolver.go index 3d63843bd2f..d7d2bb6577e 100644 --- a/contractcourt/htlc_timeout_resolver.go +++ b/contractcourt/htlc_timeout_resolver.go @@ -16,6 +16,7 @@ import ( "github.com/lightningnetwork/lnd/chanstate" "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/labels" "github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/lnutils" "github.com/lightningnetwork/lnd/lnwallet" @@ -644,6 +645,7 @@ func (h *htlcTimeoutResolver) Stop() { defer h.log.Debugf("stopped") close(h.quit) + h.wg.Wait() } // report returns a report on the resolution state of the contract. @@ -997,6 +999,56 @@ 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. The anchor output appended +// to the second-level tx is handed over alongside it so the sweeper can +// CPFP the parent once it is in the mempool. +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()) + + // The CPFP anchor at index 1 is the parent's only fee-bumping path. + // The deadline is the incoming HTLC's expiry: past that height our + // upstream peer can claw back the funds, matching the deadline the + // other timeout-path sweeps use. + anchor, budget, err := secondLevelAnchorInput( + parentTx, h.htlcResolution.SweepSignDesc, + preSignedTxFee(parentTx, h.htlcResolution.SignDetails), + h.broadcastHeight, h.Budget, h.log, + ) + if err != nil { + return err + } + + // The sweeper watches the commitment HTLC output the tx spends: a + // confirmed spend of it is what tells it the tx confirmed, or that + // it never will. + return h.publishPreSignedHtlcTx(sweep.PreSignedTxRequest{ + Tx: parentTx, + SpentOutputs: []*wire.TxOut{ + h.htlcResolution.SignDetails.SignDesc.Output, + }, + HeightHint: h.broadcastHeight, + Label: labels.MakeLabel( + labels.LabelTypeChannelClose, &h.ShortChanID, + ), + Anchor: anchor, + Budget: budget, + DeadlineHeight: h.incomingHTLCExpiryHeight, + }) +} + // waitHtlcSpendAndCheckPreimage waits for the htlc output to be spent and // checks whether the spending reveals the preimage. If the preimage is found, // it will be added to the preimage beacon to settle the incoming link, and a @@ -1089,6 +1141,8 @@ func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error { witType = input.HtlcOfferedTimeoutSecondLevel } + resolutionBlob := h.htlcResolution.ResolutionBlob + // Let the sweeper sweep the second-level output now that the CSV/CLTV // locks have expired. inp := h.makeSweepInput( @@ -1096,7 +1150,7 @@ func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error { input.LeaseHtlcOfferedTimeoutSecondLevel, &h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, uint32(commitSpend.SpendingHeight), - h.htlc.RHash, h.htlcResolution.ResolutionBlob, + h.htlc.RHash, resolutionBlob, ) // Calculate the budget for this sweep. @@ -1345,6 +1399,22 @@ func (h *htlcTimeoutResolver) Launch() error { return h.sweepTimeoutTxOutput() } + // When the peer signed with SigHashDefault the pre-signed + // second-level tx has baked-in fees and cannot be modified + // (adding wallet inputs would invalidate the signature). + // Publish it directly instead of going through the sweeper. + if h.isSigHashDefault() { + // See the success resolver: a synchronous publish + // setup failure must clear the launched flag so a + // later Launch can retry. + err := h.publishTimeoutTx() + if err != nil { + h.clearLaunched() + } + + return err + } + // Otherwise, sweep the second level tx. return h.sweepTimeoutTx() diff --git a/contractcourt/interfaces.go b/contractcourt/interfaces.go index eb76328cfa8..7d7d247567a 100644 --- a/contractcourt/interfaces.go +++ b/contractcourt/interfaces.go @@ -66,6 +66,15 @@ type UtxoSweeper interface { SweepInput(input input.Input, params sweep.Params) (chan sweep.Result, error) + // PublishPreSignedTx hands a fully signed, immutable transaction to + // the sweeper, which owns its publication (gated on its locktime and + // retried per block) and the CPFP of its anchor output. The returned + // channel receives the single final outcome, which only arrives once + // an input of the transaction is spent on chain, by the transaction + // itself or by a conflicting one, or when the sweeper shuts down. + PublishPreSignedTx(req sweep.PreSignedTxRequest) (<-chan sweep.Result, + error) + // RelayFeePerKW returns the minimum fee rate required for transactions // to be relayed. RelayFeePerKW() chainfee.SatPerKWeight diff --git a/contractcourt/utxonursery_test.go b/contractcourt/utxonursery_test.go index 564bb09e691..7d6d87d2f68 100644 --- a/contractcourt/utxonursery_test.go +++ b/contractcourt/utxonursery_test.go @@ -1073,6 +1073,14 @@ func newMockSweeperFull(t *testing.T) *mockSweeperFull { } } +func (s *mockSweeperFull) PublishPreSignedTx( + sweep.PreSignedTxRequest) (<-chan sweep.Result, error) { + + c := make(chan sweep.Result, 1) + + return c, nil +} + func (s *mockSweeperFull) sweepInput(input input.Input, _ sweep.Params) (chan sweep.Result, error) { diff --git a/htlcswitch/link.go b/htlcswitch/link.go index 45fc0c53697..6406f6a9d6e 100644 --- a/htlcswitch/link.go +++ b/htlcswitch/link.go @@ -1108,6 +1108,12 @@ func (l *channelLink) syncChanStates(ctx context.Context) error { }, ) + // The aux negotiator now knows the features negotiated for + // this channel, which it may not have when the channel state + // machine was created. Pick up the HTLC sighash type that + // follows from them before any new commitment is created. + l.refreshHtlcSigHashType() + var ( openedCircuits []CircuitKey closedCircuits []CircuitKey @@ -2278,6 +2284,17 @@ func (l *channelLink) getFeeRate() chainfee.SatPerKWeight { return l.channel.CommitFeeRate() } +// refreshHtlcSigHashType re-resolves the HTLC sighash type of the channel +// from the live feature negotiation and hands the mailbox a dust closure that +// reflects it. The mailbox captured the closure when it was attached, before +// the channel was reestablished, so without the refresh it would keep +// classifying HTLCs with the old dust threshold while the channel uses the +// new one, and the dust exposure check would mix the two. +func (l *channelLink) refreshHtlcSigHashType() { + l.channel.RefreshHtlcSigHashType() + l.mailBox.SetDustClosure(l.getDustClosure()) +} + // getDustClosure returns a closure that can be used by the switch or mailbox // to evaluate whether a given HTLC is dust. // @@ -2287,7 +2304,8 @@ func (l *channelLink) getDustClosure() dustClosure { remoteDustLimit := l.channel.State().RemoteChanCfg.DustLimit chanType := l.channel.State().ChanType - return dustHelper(chanType, localDustLimit, remoteDustLimit) + return dustHelper(chanType, localDustLimit, remoteDustLimit, + l.channel.IsChanSigHashDefault()) } // getCommitFee returns either the local or remote CommitFee in satoshis. This @@ -2455,7 +2473,7 @@ type dustClosure func(feerate chainfee.SatPerKWeight, incoming bool, // dustHelper is used to construct the dustClosure. func dustHelper(chantype chanstate.ChannelType, localDustLimit, - remoteDustLimit btcutil.Amount) dustClosure { + remoteDustLimit btcutil.Amount, sigHashDefault bool) dustClosure { isDust := func(feerate chainfee.SatPerKWeight, incoming bool, whoseCommit lntypes.ChannelParty, amt btcutil.Amount) bool { @@ -2469,7 +2487,7 @@ func dustHelper(chantype chanstate.ChannelType, localDustLimit, return lnwallet.HtlcIsDust( chantype, incoming, whoseCommit, feerate, amt, - dustLimit, + dustLimit, sigHashDefault, ) } diff --git a/htlcswitch/link_sighash_test.go b/htlcswitch/link_sighash_test.go new file mode 100644 index 00000000000..9d9f9b44729 --- /dev/null +++ b/htlcswitch/link_sighash_test.go @@ -0,0 +1,243 @@ +package htlcswitch + +import ( + "sync" + "testing" + "time" + + "github.com/btcsuite/btcd/txscript/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/clock" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +// negotiatedSigHashSigner is an aux signer whose answer about the HTLC +// sighash type can change over time, the way the real one does once the +// peer has (re)established the channel and the negotiated features are +// known. +type negotiatedSigHashSigner struct { + *lnwallet.MockAuxSigner + + mu sync.Mutex + sigHash fn.Option[txscript.SigHashType] +} + +// negotiate sets the sighash type the signer reports from now on. None +// stands for a peer without the DeterministicHTLCs feature. +func (s *negotiatedSigHashSigner) negotiate( + sigHash fn.Option[txscript.SigHashType]) { + + s.mu.Lock() + defer s.mu.Unlock() + + s.sigHash = sigHash +} + +// HtlcSigHashType returns the currently negotiated sighash type. +func (s *negotiatedSigHashSigner) HtlcSigHashType( + lnwallet.HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + s.mu.Lock() + defer s.mu.Unlock() + + return s.sigHash +} + +// TestLinkRefreshHtlcSigHashTypeMailboxDust asserts that when the channel +// picks up a new HTLC sighash type after a reestablish, the mailbox's dust +// closure is refreshed along with it. The mailbox captures the closure when +// it is attached, which happens before the reestablish, so an HTLC that is +// dust under one sighash type and not under the other must be classified +// the way the channel now classifies it, not the way it did at attach time. +func TestLinkRefreshHtlcSigHashTypeMailboxDust(t *testing.T) { + t.Parallel() + + customChanType := channeldb.SingleFunderTweaklessBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SimpleTaprootFeatureBit | + channeldb.TapscriptRootBit + + aliceChannel, _, err := lnwallet.CreateTestChannels( + t, customChanType, + ) + require.NoError(t, err) + + // At construction the peer has not negotiated anything yet, so the + // channel uses the standard sighash flags. + signer := &negotiatedSigHashSigner{ + MockAuxSigner: lnwallet.NewAuxSignerMock(nil), + sigHash: fn.None[txscript.SigHashType](), + } + channel, err := lnwallet.NewLightningChannel( + aliceChannel.Signer, aliceChannel.State(), + lnwallet.NewSigPool(1, aliceChannel.Signer), + lnwallet.WithAuxSigner(signer), + ) + require.NoError(t, err) + require.False(t, channel.IsChanSigHashDefault()) + + link, ok := NewChannelLink(ChannelLinkConfig{ + DisallowQuiescence: true, + OnChannelFailure: func(lnwire.ChannelID, + lnwire.ShortChannelID, LinkFailureError) { + }, + }, channel).(*channelLink) + require.True(t, ok) + + // The mailbox is attached before the channel is reestablished, so it + // captures the dust closure of the standard sighash flags. + mailbox := newMemoryMailBox(&mailBoxConfig{ + clock: clock.NewTestClock(time.Now()), + expiry: time.Minute, + }) + link.AttachMailBox(mailbox) + + // Pick an HTLC amount that is not dust on either commitment under + // the standard flags but is dust on at least one of them under + // SigHashDefault, where the on-chain value also has to cover the + // baked-in second-level fee and the CPFP anchor. + state := channel.State() + feeRate := channel.CommitFeeRate() + amt := max( + state.LocalChanCfg.DustLimit, state.RemoteChanCfg.DustLimit, + ) + 100 + isDust := func(whoseCommit lntypes.ChannelParty, + sigHashDefault bool) bool { + + dustLimit := state.LocalChanCfg.DustLimit + if whoseCommit.IsRemote() { + dustLimit = state.RemoteChanCfg.DustLimit + } + + return lnwallet.HtlcIsDust( + customChanType, false, whoseCommit, feeRate, amt, + dustLimit, sigHashDefault, + ) + } + require.False(t, isDust(lntypes.Local, false)) + require.False(t, isDust(lntypes.Remote, false)) + require.True(t, + isDust(lntypes.Local, true) || isDust(lntypes.Remote, true), + "the amount must be dust under SigHashDefault somewhere") + + dustSum := func(whoseCommit lntypes.ChannelParty, + sigHashDefault bool) lnwire.MilliSatoshi { + + if isDust(whoseCommit, sigHashDefault) { + return lnwire.NewMSatFromSatoshis(amt) + } + + return 0 + } + + pkt := &htlcPacket{ + incomingChanID: lnwire.NewShortChanIDFromInt(1), + incomingHTLCID: 0, + amount: lnwire.NewMSatFromSatoshis(amt), + htlc: &lnwire.UpdateAddHTLC{}, + } + require.NoError(t, mailbox.AddPacket(pkt)) + + localSum, remoteSum := mailbox.DustPackets() + require.Equal(t, dustSum(lntypes.Local, false), localSum) + require.Equal(t, dustSum(lntypes.Remote, false), remoteSum) + + // The peer reestablishes the channel with DeterministicHTLCs + // negotiated. Refreshing the channel alone moves its own sighash + // type, but leaves the mailbox on the closure it captured: this is + // the mismatch the link has to prevent. + signer.negotiate(fn.Some(txscript.SigHashDefault)) + channel.RefreshHtlcSigHashType() + require.True(t, channel.IsChanSigHashDefault()) + + localSum, remoteSum = mailbox.DustPackets() + require.Equal(t, dustSum(lntypes.Local, false), localSum) + require.Equal(t, dustSum(lntypes.Remote, false), remoteSum) + + // The link's refresh, which is what the reestablish path calls, + // updates both. + link.refreshHtlcSigHashType() + require.True(t, channel.IsChanSigHashDefault()) + + localSum, remoteSum = mailbox.DustPackets() + require.Equal(t, dustSum(lntypes.Local, true), localSum) + require.Equal(t, dustSum(lntypes.Remote, true), remoteSum) + + // A peer that comes back without the feature takes the channel, and + // the mailbox, back to the standard flags. + signer.negotiate(fn.None[txscript.SigHashType]()) + link.refreshHtlcSigHashType() + require.False(t, channel.IsChanSigHashDefault()) + + localSum, remoteSum = mailbox.DustPackets() + require.Equal(t, dustSum(lntypes.Local, false), localSum) + require.Equal(t, dustSum(lntypes.Remote, false), remoteSum) +} + +// TestLinkDustClosureIgnoresSigHashOnVanillaChannel asserts that on a channel +// without a tapscript root the sighash type never influences the dust +// closure: refreshing is a no-op for the mailbox, whatever the aux signer +// answers. +func TestLinkDustClosureIgnoresSigHashOnVanillaChannel(t *testing.T) { + t.Parallel() + + chanType := channeldb.SingleFunderTweaklessBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SimpleTaprootFeatureBit + + aliceChannel, _, err := lnwallet.CreateTestChannels(t, chanType) + require.NoError(t, err) + + signer := &negotiatedSigHashSigner{ + MockAuxSigner: lnwallet.NewAuxSignerMock(nil), + sigHash: fn.Some(txscript.SigHashDefault), + } + channel, err := lnwallet.NewLightningChannel( + aliceChannel.Signer, aliceChannel.State(), + lnwallet.NewSigPool(1, aliceChannel.Signer), + lnwallet.WithAuxSigner(signer), + ) + require.NoError(t, err) + + link, ok := NewChannelLink(ChannelLinkConfig{ + DisallowQuiescence: true, + OnChannelFailure: func(lnwire.ChannelID, + lnwire.ShortChannelID, LinkFailureError) { + }, + }, channel).(*channelLink) + require.True(t, ok) + + mailbox := newMemoryMailBox(&mailBoxConfig{ + clock: clock.NewTestClock(time.Now()), + expiry: time.Minute, + }) + link.AttachMailBox(mailbox) + + state := channel.State() + amt := max( + state.LocalChanCfg.DustLimit, state.RemoteChanCfg.DustLimit, + ) + 100 + require.NoError(t, mailbox.AddPacket(&htlcPacket{ + incomingChanID: lnwire.NewShortChanIDFromInt(1), + amount: lnwire.NewMSatFromSatoshis(amt), + htlc: &lnwire.UpdateAddHTLC{}, + })) + + localSum, remoteSum := mailbox.DustPackets() + require.Zero(t, localSum) + require.Zero(t, remoteSum) + + require.False(t, channel.IsChanSigHashDefault()) + link.refreshHtlcSigHashType() + require.False(t, channel.IsChanSigHashDefault()) + + localSum, remoteSum = mailbox.DustPackets() + require.Zero(t, localSum) + require.Zero(t, remoteSum) +} diff --git a/htlcswitch/mailbox_test.go b/htlcswitch/mailbox_test.go index a640d1334ac..a3ec0bea4eb 100644 --- a/htlcswitch/mailbox_test.go +++ b/htlcswitch/mailbox_test.go @@ -716,7 +716,7 @@ func testMailBoxDust(t *testing.T, chantype chanstate.ChannelType) { localDustLimit := btcutil.Amount(400) remoteDustLimit := btcutil.Amount(500) - isDust := dustHelper(chantype, localDustLimit, remoteDustLimit) + isDust := dustHelper(chantype, localDustLimit, remoteDustLimit, false) ctx.mailbox.SetDustClosure(isDust) // The first packet will be dust according to the remote dust limit, diff --git a/htlcswitch/mock.go b/htlcswitch/mock.go index 7f31747662d..5cdb9d1fc42 100644 --- a/htlcswitch/mock.go +++ b/htlcswitch/mock.go @@ -855,6 +855,7 @@ func (f *mockChannelLink) getDustClosure() dustClosure { dustLimit := btcutil.Amount(400) return dustHelper( channeldb.SingleFunderTweaklessBit, dustLimit, dustLimit, + false, ) } diff --git a/input/size_test.go b/input/size_test.go index 7b193640703..4d5fc1858ce 100644 --- a/input/size_test.go +++ b/input/size_test.go @@ -1603,6 +1603,7 @@ func genTimeoutTx(t *testing.T, timeoutTx, err := lnwallet.CreateHtlcTimeoutTx( chanType, false, testOutPoint, testAmt, testCLTVExpiry, testCSVDelay, 0, testPubkey, testPubkey, input.NoneTapLeaf(), + false, ) require.NoError(t, err) @@ -1671,7 +1672,7 @@ func genSuccessTx(t *testing.T, chanType channeldb.ChannelType) *wire.MsgTx { // Create the unsigned success tx. successTx, err := lnwallet.CreateHtlcSuccessTx( chanType, false, testOutPoint, testAmt, testCSVDelay, 0, - testPubkey, testPubkey, input.NoneTapLeaf(), + testPubkey, testPubkey, input.NoneTapLeaf(), false, ) require.NoError(t, err) diff --git a/lnwallet/aux_leaf_store.go b/lnwallet/aux_leaf_store.go index e4c22335f93..a1553ffada0 100644 --- a/lnwallet/aux_leaf_store.go +++ b/lnwallet/aux_leaf_store.go @@ -157,6 +157,15 @@ type CommitDiffAuxInput struct { // KeyRing is the key ring that can be used to derive keys for the // commitment transaction. KeyRing CommitmentKeyRing + + // SigHashDefault states whether the second-level HTLC transactions of + // the commitment being built use SigHashDefault. This is decided by + // whoever signs the commitment and stated on its commitment_signed, + // so the leaf store must take it from here and record it in the new + // blob. It must not derive it from the live feature negotiation, which + // can differ from what a retransmitted commitment_signed was signed + // with. + SigHashDefault bool } // CommitDiffAuxResult is the result of computing the diff of the auxiliary @@ -206,8 +215,8 @@ type AuxLeafStore interface { func auxLeavesFromView(leafStore AuxLeafStore, chanState *chanstate.OpenChannel, prevBlob fn.Option[tlv.Blob], originalView *HtlcView, whoseCommit lntypes.ChannelParty, ourBalance, - theirBalance lnwire.MilliSatoshi, - keyRing CommitmentKeyRing) fn.Result[CommitDiffAuxResult] { + theirBalance lnwire.MilliSatoshi, keyRing CommitmentKeyRing, + sigHashDefault bool) fn.Result[CommitDiffAuxResult] { return fn.MapOptionZ( prevBlob, func(blob tlv.Blob) fn.Result[CommitDiffAuxResult] { @@ -219,6 +228,7 @@ func auxLeavesFromView(leafStore AuxLeafStore, chanState *chanstate.OpenChannel, OurBalance: ourBalance, TheirBalance: theirBalance, KeyRing: keyRing, + SigHashDefault: sigHashDefault, }) }, ) @@ -229,8 +239,8 @@ func auxLeavesFromView(leafStore AuxLeafStore, chanState *chanstate.OpenChannel, func updateAuxBlob(leafStore AuxLeafStore, chanState *chanstate.OpenChannel, prevBlob fn.Option[tlv.Blob], nextViewUnfiltered *HtlcView, whoseCommit lntypes.ChannelParty, ourBalance, - theirBalance lnwire.MilliSatoshi, - keyRing CommitmentKeyRing) fn.Result[fn.Option[tlv.Blob]] { + theirBalance lnwire.MilliSatoshi, keyRing CommitmentKeyRing, + sigHashDefault bool) fn.Result[fn.Option[tlv.Blob]] { return fn.MapOptionZ( prevBlob, func(blob tlv.Blob) fn.Result[fn.Option[tlv.Blob]] { @@ -240,10 +250,11 @@ func updateAuxBlob(leafStore AuxLeafStore, chanState *chanstate.OpenChannel, UnfilteredView: newAuxHtlcView( nextViewUnfiltered, ), - WhoseCommit: whoseCommit, - OurBalance: ourBalance, - TheirBalance: theirBalance, - KeyRing: keyRing, + WhoseCommit: whoseCommit, + OurBalance: ourBalance, + TheirBalance: theirBalance, + KeyRing: keyRing, + SigHashDefault: sigHashDefault, }) }, ) diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index 38f540454f5..dfcb95b5ced 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -1,7 +1,9 @@ package lnwallet import ( + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/lntypes" @@ -19,6 +21,20 @@ var ( // message to indicate the presence of a noop HTLC. This has no encoded // value, its presence is used to indicate that the HTLC is a noop. NoOpHtlcTLVEntry tlv.TlvType65544 + + // commitSigHtlcSigHashType is the TLV type of the custom record of a + // commitment_signed that states the sighash type the second-level + // HTLC transactions of the signed commitment use. The record is only + // present when that is not the standard one of the channel type, and + // its value is the single byte of the sighash type. The only value in + // use is SigHashDefault. + // + // The signer of a commitment decides its sighash type from the + // features negotiated when it signs. The receiver may verify the + // message in a later connection, with different features negotiated, + // as a commitment_signed is retransmitted as it was first signed. So + // the type is stated on the message rather than derived on both ends. + commitSigHtlcSigHashType tlv.TlvType65638 ) // NoOpHtlcTLVType is the (golang) type of the TLV record that's used to signal @@ -305,4 +321,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 (to learn what the live feature negotiation +// asks for, which feeds the commitments we sign next) 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 the negotiation asks for. A + // commitment that is being verified does not use it, its sighash is + // stated on the commitment_signed. + 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) + + // The only supported override is SigHashDefault: it is what the + // whole deterministic second-level flow (fixed parent, embedded + // anchor, direct publish) keys off of. Any other value would be + // used for signing while the resolvers still treat the tx as + // sweeper-malleable, invalidating the signature, so we reject it + // here and fall back to the channel's standard sighash flags. + override := sigHash.UnwrapOr(HtlcSigHashType(chanType)) + if override != txscript.SigHashDefault { + return HtlcSigHashType(chanType) + } + + return override } diff --git a/lnwallet/aux_signer_test.go b/lnwallet/aux_signer_test.go new file mode 100644 index 00000000000..b3bcab4f5fc --- /dev/null +++ b/lnwallet/aux_signer_test.go @@ -0,0 +1,106 @@ +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. +// +// For reference, the sighash each channel type is expected to use for +// second-level HTLC transactions: +// +// legacy (no anchors): SIGHASH_ALL (0x01) +// anchor / taproot: SIGHASH_SINGLE|ANYONECANPAY (0x83) +// custom + negotiated: SIGHASH_DEFAULT (0x00) +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) + require.Equal(t, HtlcSigHashType(taprootChanType), got, + "non-custom taproot channel must ignore aux signer sighash") + + // Same for a legacy (non-taproot) channel type. + legacyChanType := channeldb.SingleFunderTweaklessBit + got = ResolveHtlcSigHashType(legacyChanType, signer, req) + require.Equal(t, HtlcSigHashType(legacyChanType), got, + "legacy channel must ignore aux signer sighash") + + // A custom channel (tapscript root) with the same signer negotiates + // SigHashDefault. + got = ResolveHtlcSigHashType(customChanType, signer, req) + require.Equal(t, txscript.SigHashDefault, got) + + // A custom channel without an aux signer falls back to the standard + // flags. + noSigner := fn.None[AuxSigner]() + got = ResolveHtlcSigHashType(customChanType, noSigner, req) + require.Equal(t, HtlcSigHashType(customChanType), got) +} + +// TestResolveHtlcSigHashTypeRejectsUnknownOverride asserts that the only +// accepted aux signer override is SigHashDefault: any other value would be +// used for signing while the resolvers still treat the second-level tx as +// sweeper-malleable, so it is rejected in favor of the channel's standard +// sighash flags. +func TestResolveHtlcSigHashTypeRejectsUnknownOverride(t *testing.T) { + t.Parallel() + + customChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + // An aux signer pushing an unsupported override. + signer := fn.Some[AuxSigner](&sigHashOverrideSigner{ + MockAuxSigner: NewAuxSignerMock(nil), + sigHash: txscript.SigHashAll, + }) + + req := HtlcSigHashReq{} + + got := ResolveHtlcSigHashType(customChanType, signer, req) + require.Equal(t, HtlcSigHashType(customChanType), got, + "unsupported override must fall back to standard flags") +} diff --git a/lnwallet/channel.go b/lnwallet/channel.go index b33a6cb4fd9..c59c7eaa959 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -8,9 +8,11 @@ import ( "errors" "fmt" "io" + "maps" "math" "slices" "sync" + "sync/atomic" "github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/btcec/v2" @@ -47,6 +49,23 @@ var ( ErrNoWindow = fmt.Errorf("unable to sign new commitment, the current" + " revocation window is exhausted") + // ErrUnknownHtlcSigHashType is returned when a commitment_signed + // states an HTLC sighash type we do not know. + ErrUnknownHtlcSigHashType = errors.New("commitment_signed states " + + "an unknown htlc sighash type") + + // ErrHtlcSigHashTypeNotNegotiated is returned when a commitment_signed + // states SigHashDefault for the second-level HTLC transactions of a + // channel that did not negotiate it. + ErrHtlcSigHashTypeNotNegotiated = errors.New("commitment_signed " + + "states an htlc sighash type that was not negotiated") + + // ErrHtlcSigHashTypeReverted is returned when a commitment_signed + // goes back to the legacy HTLC sighash type after our latest + // commitment used SigHashDefault. + ErrHtlcSigHashTypeReverted = errors.New("commitment_signed reverts " + + "the htlc sighash type") + // ErrMaxWeightCost is returned when the cost/weight (see segwit) // exceeds the widely used maximum allowed policy weight limit. In this // case the commitment transaction can't be propagated through the @@ -322,7 +341,7 @@ func locateOutputIndex(p *paymentDescriptor, tx *wire.MsgTx, // the current state to disk, and also to locate the paymentDescriptor // corresponding to HTLC outputs in the commitment transaction. func (c *commitment) populateHtlcIndexes(chanType channeldb.ChannelType, - cltvs []uint32) error { + cltvs []uint32, sigHashDefault bool) error { // First, we'll set up some state to allow us to locate the output // index of the all the HTLCs within the commitment transaction. We @@ -338,6 +357,7 @@ func (c *commitment) populateHtlcIndexes(chanType channeldb.ChannelType, isDust := HtlcIsDust( chanType, incoming, c.whoseCommit, c.feePerKw, htlc.Amount.ToSatoshis(), c.dustLimit, + sigHashDefault, ) var err error @@ -490,6 +510,195 @@ func (c *commitment) toDiskCommit( return commit } +// IsChanSigHashDefault returns whether SigHashDefault for second-level HTLC +// transactions is negotiated for this channel. This is the answer for future +// state only: it follows the aux signer's live feature negotiation (see +// RefreshHtlcSigHashType). A decision about a commitment that already exists +// must read the sighash recorded for that commitment instead, see +// commitSigHashType. The mode of the commitment that is being signed or +// verified is not this value either, see nextSigHashDefault and +// receivedSigHashDefault. +func (lc *LightningChannel) IsChanSigHashDefault() bool { + return lc.nextHtlcSigHashType() == txscript.SigHashDefault +} + +// nextHtlcSigHashType returns the HTLC sighash type the live feature +// negotiation asks for. +func (lc *LightningChannel) nextHtlcSigHashType() txscript.SigHashType { + return txscript.SigHashType(lc.htlcSigHashType.Load()) +} + +// RefreshHtlcSigHashType re-resolves the HTLC sighash type used for future +// commitments from the aux signer's live feature negotiation. The negotiated +// features of a channel are only known to the aux signer once the peer has +// (re)established the channel, which happens after the channel state machine +// is created, so the link calls this right after that point and before any +// new commitment is created. Commitments that already exist are unaffected: +// they keep the sighash recorded in their own custom blob. +func (lc *LightningChannel) RefreshHtlcSigHashType() { + lc.RLock() + defer lc.RUnlock() + + sigHashType := ResolveHtlcSigHashType( + lc.channelState.ChanType, lc.auxSigner, HtlcSigHashReq{ + ChanID: fn.Some(lnwire.NewChanIDFromOutPoint( + lc.channelState.FundingOutpoint, + )), + CommitBlob: lc.channelState.LocalCommitment.CustomBlob, + }, + ) + + old := txscript.SigHashType( + lc.htlcSigHashType.Swap(uint32(sigHashType)), + ) + if old != sigHashType { + lc.log.Infof("HTLC sighash type for new commitments changed "+ + "from %v to %v", old, sigHashType) + } +} + +// commitSigHashType returns the HTLC sighash type of a commitment that +// already exists, as recorded in that commitment's custom blob. Unlike +// nextHtlcSigHashType this never consults live feature negotiation, so the +// answer for a given commitment stays the same for as long as it exists. +func (lc *LightningChannel) commitSigHashType( + commitBlob fn.Option[tlv.Blob]) txscript.SigHashType { + + return ResolveHtlcSigHashType( + lc.channelState.ChanType, lc.auxSigner, HtlcSigHashReq{ + CommitBlob: commitBlob, + }, + ) +} + +// commitSigHashDefault returns true if the given existing commitment was +// built with SigHashDefault second-level HTLC transactions. +func (lc *LightningChannel) commitSigHashDefault( + commitBlob fn.Option[tlv.Blob]) bool { + + return lc.commitSigHashType(commitBlob) == txscript.SigHashDefault +} + +// nextSigHashDefault returns whether the next commitment on the given chain +// is expected to use SigHashDefault for its second-level HTLC transactions. +// That is the case once the feature is negotiated, and it stays the case for +// a chain whose latest commitment already uses it: a chain never goes back +// to the legacy sighash. +// +// For the remote chain this is the decision we make and state on the +// commitment_signed we send. For the local chain it is only what we expect: +// the remote party decides and states it on the commitment_signed, see +// receivedSigHashDefault. +// +// NOTE: The channel lock must be held. +func (lc *LightningChannel) nextSigHashDefault( + whoseCommitChain lntypes.ChannelParty) bool { + + if lc.IsChanSigHashDefault() { + return true + } + + commitChain := lc.commitChains.Local + if whoseCommitChain.IsRemote() { + commitChain = lc.commitChains.Remote + } + + return lc.commitSigHashDefault(commitChain.tip().customBlob) +} + +// htlcSigHashTypeOf maps the sighash mode of a commitment to the sighash type +// its second-level HTLC transactions are signed with. +func (lc *LightningChannel) htlcSigHashTypeOf( + sigHashDefault bool) txscript.SigHashType { + + if sigHashDefault { + return txscript.SigHashDefault + } + + return HtlcSigHashType(lc.channelState.ChanType) +} + +// statesHtlcSigHashType returns whether the commitment_signed messages of +// this channel state the HTLC sighash type of the commitment they sign. Only +// a custom channel driven by an aux signer can ever use anything but the +// standard sighash flags of its channel type, so the messages of every other +// channel are left exactly as they are. +func (lc *LightningChannel) statesHtlcSigHashType() bool { + return lc.channelState.ChanType.HasTapscriptRoot() && + lc.auxSigner.IsSome() +} + +// receivedSigHashDefault works out the sighash mode of a commitment the +// remote party signed for us from the custom records of its commitment_signed +// and returns it along with the records that are left for the aux signer. +// +// The signer of a commitment decides its mode and may have done so in an +// earlier connection, under a different feature negotiation: a +// commitment_signed that is retransmitted after both peers upgraded was +// signed before the feature existed. So the mode is read off the message and +// never guessed from the live negotiation. A message without the record uses +// the standard sighash flags of the channel type, which is what every +// message signed before the feature existed looks like. +// +// Two things are refused. A commitment that uses SigHashDefault while the +// feature is not negotiated and our latest commitment does not use it +// either, as we never agreed to it. And a commitment that goes back to the +// legacy sighash after our latest commitment used SigHashDefault. +// +// NOTE: The channel lock must be held. +func (lc *LightningChannel) receivedSigHashDefault( + auxSigBlob tlv.Blob) (bool, tlv.Blob, error) { + + // The messages of any other channel carry no such record, and their + // custom records are not ours to look at. + if !lc.statesHtlcSigHashType() { + return lc.IsChanSigHashDefault(), auxSigBlob, nil + } + + records, err := lnwire.ParseCustomRecords(auxSigBlob) + if err != nil { + return false, nil, fmt.Errorf("unable to parse commit sig "+ + "custom records: %w", err) + } + + var sigHashDefault bool + recordType := uint64(commitSigHtlcSigHashType.TypeVal()) + if val, ok := records[recordType]; ok { + defaultType := []byte{byte(txscript.SigHashDefault)} + if !bytes.Equal(val, defaultType) { + return false, nil, fmt.Errorf("%w: %x", + ErrUnknownHtlcSigHashType, val) + } + sigHashDefault = true + + // The record is ours, the aux signer only gets its own. + delete(records, recordType) + auxSigBlob = nil + if len(records) > 0 { + auxSigBlob, err = records.Serialize() + if err != nil { + return false, nil, fmt.Errorf("unable to "+ + "serialize aux sig blob: %w", err) + } + } + } + + tipSigHashDefault := lc.commitSigHashDefault( + lc.commitChains.Local.tip().customBlob, + ) + switch { + case sigHashDefault && !tipSigHashDefault && + !lc.IsChanSigHashDefault(): + + return false, nil, ErrHtlcSigHashTypeNotNegotiated + + case !sigHashDefault && tipSigHashDefault: + return false, nil, ErrHtlcSigHashTypeReverted + } + + return sigHashDefault, auxSigBlob, nil +} + // diskHtlcToPayDesc converts an HTLC previously written to disk within a // commitment state to the form required to manipulate in memory within the // commitment struct and updateLog. This function is used when we need to @@ -497,8 +706,8 @@ func (c *commitment) toDiskCommit( // restart a channel session. func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight, htlc *channeldb.HTLC, commitKeys lntypes.Dual[*CommitmentKeyRing], - whoseCommit lntypes.ChannelParty, - auxLeaf input.AuxTapLeaf) (paymentDescriptor, error) { + whoseCommit lntypes.ChannelParty, auxLeaf input.AuxTapLeaf, + sigHashDefault bool) (paymentDescriptor, error) { // The proper pkScripts for this paymentDescriptor must be // generated so we can easily locate them within the commitment @@ -518,6 +727,7 @@ func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight, isDustLocal := HtlcIsDust( chanType, htlc.Incoming, lntypes.Local, feeRate, htlc.Amt.ToSatoshis(), lc.channelState.LocalChanCfg.DustLimit, + sigHashDefault, ) localCommitKeys := commitKeys.GetForParty(lntypes.Local) if !isDustLocal && localCommitKeys != nil { @@ -535,6 +745,7 @@ func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight, isDustRemote := HtlcIsDust( chanType, htlc.Incoming, lntypes.Remote, feeRate, htlc.Amt.ToSatoshis(), lc.channelState.RemoteChanCfg.DustLimit, + sigHashDefault, ) remoteCommitKeys := commitKeys.GetForParty(lntypes.Remote) if !isDustRemote && remoteCommitKeys != nil { @@ -598,9 +809,8 @@ func (lc *LightningChannel) diskHtlcToPayDesc(feeRate chainfee.SatPerKWeight, // for each side. func (lc *LightningChannel) extractPayDescs(feeRate chainfee.SatPerKWeight, htlcs []channeldb.HTLC, commitKeys lntypes.Dual[*CommitmentKeyRing], - whoseCommit lntypes.ChannelParty, - auxLeaves fn.Option[CommitAuxLeaves]) ([]paymentDescriptor, - []paymentDescriptor, error) { + whoseCommit lntypes.ChannelParty, auxLeaves fn.Option[CommitAuxLeaves], + sigHashDefault bool) ([]paymentDescriptor, []paymentDescriptor, error) { var ( incomingHtlcs []paymentDescriptor @@ -628,6 +838,7 @@ func (lc *LightningChannel) extractPayDescs(feeRate chainfee.SatPerKWeight, payDesc, err := lc.diskHtlcToPayDesc( feeRate, &htlc, commitKeys, whoseCommit, auxLeaf, + sigHashDefault, ) if err != nil { return incomingHtlcs, outgoingHtlcs, err @@ -690,10 +901,13 @@ func (lc *LightningChannel) diskCommitToMemCommit( // With the key rings re-created, we'll now convert all the on-disk // HTLC"s into paymentDescriptor's so we can re-insert them into our - // update log. + // update log. This commitment already exists, so its HTLCs are + // classified with the sighash recorded for it, not with the one new + // commitments would use. incomingHtlcs, outgoingHtlcs, err := lc.extractPayDescs( chainfee.SatPerKWeight(diskCommit.FeePerKw), diskCommit.Htlcs, commitKeys, whoseCommit, auxResult.AuxLeaves, + lc.commitSigHashDefault(diskCommit.CustomBlob), ) if err != nil { return nil, err @@ -785,6 +999,18 @@ type LightningChannel struct { // custom channel variants. auxSigner fn.Option[AuxSigner] + // htlcSigHashType is the sighash type (a txscript.SigHashType) the + // second-level HTLC transactions of future commitments are signed + // with. It is resolved from the aux signer's live feature negotiation + // at construction and again whenever that negotiation may have + // changed, see RefreshHtlcSigHashType. It feeds the decision for the + // commitments we sign and the estimates for future ones, see + // nextSigHashDefault. A commitment we verify uses what its + // commitment_signed states, see receivedSigHashDefault. Commitments + // that already exist carry their own answer in their custom blob, see + // commitSigHashType. + htlcSigHashType atomic.Uint32 + // auxResolver is an optional component that can be used to modify the // way contracts are resolved. auxResolver fn.Option[AuxContractResolver] @@ -1001,6 +1227,22 @@ func NewLightningChannel(signer input.Signer, Remote: newCommitmentChain(), } + // Resolve the HTLC sighash type for the commitments this instance + // will create. The aux signer may not know the channel's negotiated + // features yet at this point, in which case it answers from the latest + // local commitment. The link refreshes the value once the channel is + // re-established, see RefreshHtlcSigHashType. + htlcSigHashType := ResolveHtlcSigHashType( + state.ChanType, opts.auxSigner, HtlcSigHashReq{ + ChanID: fn.Some( + lnwire.NewChanIDFromOutPoint( + state.FundingOutpoint, + ), + ), + CommitBlob: state.LocalCommitment.CustomBlob, + }, + ) + lc := &LightningChannel{ Signer: signer, leafStore: opts.leafStore, @@ -1019,6 +1261,7 @@ func NewLightningChannel(signer input.Signer, log: walletLog.WithPrefix(logPrefix), opts: opts, } + lc.htlcSigHashType.Store(uint32(htlcSigHashType)) switch { // At this point, we may already have nonces that were passed in, so @@ -1128,8 +1371,8 @@ func (lc *LightningChannel) ResetState() { func (lc *LightningChannel) logUpdateToPayDesc(logUpdate *channeldb.LogUpdate, remoteUpdateLog *updateLog, commitHeight uint64, feeRate chainfee.SatPerKWeight, remoteCommitKeys *CommitmentKeyRing, - remoteDustLimit btcutil.Amount, - auxLeaves fn.Option[CommitAuxLeaves]) (*paymentDescriptor, error) { + remoteDustLimit btcutil.Amount, auxLeaves fn.Option[CommitAuxLeaves], + sigHashDefault bool) (*paymentDescriptor, error) { // Depending on the type of update message we'll map that to a distinct // paymentDescriptor instance. @@ -1170,6 +1413,7 @@ func (lc *LightningChannel) logUpdateToPayDesc(logUpdate *channeldb.LogUpdate, isDustRemote := HtlcIsDust( lc.channelState.ChanType, false, lntypes.Remote, feeRate, wireMsg.Amount.ToSatoshis(), remoteDustLimit, + sigHashDefault, ) if !isDustRemote { auxLeaf := fn.FlatMapOption( @@ -1917,6 +2161,10 @@ func (lc *LightningChannel) restorePendingLocalUpdates( return fmt.Errorf("unable to fetch aux leaves: %w", err) } + // The pending commitment already exists, so its HTLCs are classified + // with the sighash recorded for it. + sigHashDefault := lc.commitSigHashDefault(pendingCommit.CustomBlob) + // If we did have a dangling commit, then we'll examine which updates // we included in that state and re-insert them into our update log. for _, logUpdate := range pendingRemoteCommitDiff.LogUpdates { @@ -1926,7 +2174,7 @@ func (lc *LightningChannel) restorePendingLocalUpdates( chainfee.SatPerKWeight(pendingCommit.FeePerKw), pendingRemoteKeys, lc.channelState.RemoteChanCfg.DustLimit, - auxResult.AuxLeaves, + auxResult.AuxLeaves, sigHashDefault, ) if err != nil { return err @@ -2114,7 +2362,8 @@ type BreachRetribution struct { func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, breachHeight uint32, spendTx *wire.MsgTx, leafStore fn.Option[AuxLeafStore], - auxResolver fn.Option[AuxContractResolver]) (*BreachRetribution, + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*BreachRetribution, error) { // Query the on-disk revocation log for the snapshot which was recorded @@ -2224,7 +2473,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, // are confident that no legacy format is in use. br, ourAmt, theirAmt, err = createBreachRetributionLegacy( revokedLogLegacy, chanState, keyRing, commitmentSecret, - ourScript, theirScript, leaseExpiry, + ourScript, theirScript, leaseExpiry, auxSigner, ) if err != nil { return nil, err @@ -2657,8 +2906,9 @@ func createBreachRetribution(revokedLog *channeldb.RevocationLog, func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, - ourScript, theirScript input.ScriptDescriptor, - leaseExpiry uint32) (*BreachRetribution, int64, int64, error) { + ourScript, theirScript input.ScriptDescriptor, leaseExpiry uint32, + auxSigner fn.Option[AuxSigner]) (*BreachRetribution, int64, int64, + error) { commitHash := revokedLog.CommitTx.TxHash() ourOutpoint := wire.OutPoint{ @@ -2679,6 +2929,17 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, } } + // Resolve the HTLC sighash type once for this retribution and reuse + // it for every HTLC below, so all dust decisions are made against the + // same resolved value. The answer must be the one recorded for the + // revoked state itself: that is the commitment whose outputs we are + // about to claim, and it may predate a change of the sighash type. + sigHashDefault := ResolveHtlcSigHashType( + chanState.ChanType, auxSigner, HtlcSigHashReq{ + CommitBlob: revokedLog.CustomBlob, + }, + ) == txscript.SigHashDefault + // With the commitment outputs located, we'll now generate all the // retribution structs for each of the HTLC transactions active on the // remote commitment transaction. We densely pack the slice so that @@ -2691,7 +2952,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState.ChanType, htlc.Incoming, lntypes.Remote, chainfee.SatPerKWeight(revokedLog.FeePerKw), htlc.Amt.ToSatoshis(), - chanState.RemoteChanCfg.DustLimit, + chanState.RemoteChanCfg.DustLimit, sigHashDefault, ) // If the HTLC is dust, then we'll skip it as it doesn't have @@ -2755,6 +3016,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, func HtlcIsDust(chanType channeldb.ChannelType, incoming bool, whoseCommit lntypes.ChannelParty, feePerKw chainfee.SatPerKWeight, htlcAmt, dustLimit btcutil.Amount, + sigHashDefault bool, ) bool { // First we'll determine the fee required for this HTLC based on if this is @@ -2766,28 +3028,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 { + htlcOutValue -= AnchorSize + } + + return htlcOutValue < dustLimit } // HtlcView represents the "active" HTLCs at a particular point within the @@ -2886,10 +3157,14 @@ func (lc *LightningChannel) fetchHTLCView(theirLogIndex, // both local and remote commitment transactions in order to sign or verify new // commitment updates. A fully populated commitment is returned which reflects // the proper balances for both sides at this point in the commitment chain. +// The sigHashDefault flag is the sighash mode of the commitment being built: +// the one we decided on for a commitment we sign, the one the remote party +// stated for a commitment we verify. func (lc *LightningChannel) fetchCommitmentView( whoseCommitChain lntypes.ChannelParty, ourLogIndex, ourHtlcIndex, theirLogIndex, theirHtlcIndex uint64, - keyRing *CommitmentKeyRing) (*commitment, error) { + keyRing *CommitmentKeyRing, + sigHashDefault bool) (*commitment, error) { commitChain := lc.commitChains.Local dustLimit := lc.channelState.LocalChanCfg.DustLimit @@ -2908,7 +3183,7 @@ func (lc *LightningChannel) fetchCommitmentView( htlcView := lc.fetchHTLCView(theirLogIndex, ourLogIndex) ourBalance, theirBalance, _, filteredHTLCView, err := lc.computeView( htlcView, whoseCommitChain, true, - fn.None[chainfee.SatPerKWeight](), + fn.None[chainfee.SatPerKWeight](), sigHashDefault, ) if err != nil { return nil, err @@ -2922,7 +3197,7 @@ func (lc *LightningChannel) fetchCommitmentView( commitTx, err := lc.commitBuilder.createUnsignedCommitmentTx( ourBalance, theirBalance, whoseCommitChain, feePerKw, nextHeight, htlcView, filteredHTLCView, keyRing, - commitChain.tip(), + commitChain.tip(), sigHashDefault, ) if err != nil { return nil, err @@ -2966,7 +3241,7 @@ func (lc *LightningChannel) fetchCommitmentView( s, lc.channelState, commitChain.tip().customBlob, htlcView, whoseCommitChain, ourBalance, theirBalance, - *keyRing, + *keyRing, sigHashDefault, ) }, ).Unpack() @@ -3016,7 +3291,9 @@ func (lc *LightningChannel) fetchCommitmentView( // locations of each HTLC in the commitment state. We pass in the sorted // slice of CLTV deltas in order to properly locate HTLCs that otherwise // have the same payment hash and amount. - err = c.populateHtlcIndexes(lc.channelState.ChanType, commitTx.cltvs) + err = c.populateHtlcIndexes( + lc.channelState.ChanType, commitTx.cltvs, sigHashDefault, + ) if err != nil { return nil, err } @@ -3371,10 +3648,15 @@ func (lc *LightningChannel) evaluateNoOpHtlc(entry *paymentDescriptor, // generating a new commitment for the remote party. The jobs generated by the // signature can be submitted to the sigPool to generate all the signatures // asynchronously and in parallel. +// The sigHashType passed in is the HTLC sighash type the channel uses for new +// commitments, the same value the commitment view was built with, so the +// signature sighash always matches the commitment shape the jobs are +// generated for. func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, chanState *chanstate.OpenChannel, leaseExpiry uint32, remoteCommitView *commitment, - leafStore fn.Option[AuxLeafStore]) ([]SignJob, []AuxSigJob, + leafStore fn.Option[AuxLeafStore], + sigHashType txscript.SigHashType) ([]SignJob, []AuxSigJob, chan struct{}, error) { var ( @@ -3387,7 +3669,6 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, txHash := remoteCommitView.txn.TxHash() dustLimit := remoteChanCfg.DustLimit feePerKw := remoteCommitView.feePerKw - sigHashType := HtlcSigHashType(chanType) // With the keys generated, we'll make a slice with enough capacity to // hold potentially all the HTLCs. The actual slice may be a bit @@ -3417,10 +3698,12 @@ 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 := sigHashType == txscript.SigHashDefault for _, htlc := range remoteCommitView.incomingHTLCs { if HtlcIsDust( chanType, true, lntypes.Remote, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -3437,7 +3720,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // HTLC timeout transaction for them. The output of the timeout // transaction needs to account for fees, so we'll compute the // required fee and output now. - htlcFee := HtlcTimeoutFee(chanType, feePerKw) + htlcFee := HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption( @@ -3457,7 +3740,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, chanType, isRemoteInitiator, op, outputAmt, htlc.Timeout, uint32(remoteChanCfg.CsvDelay), leaseExpiry, keyRing.RevocationKey, keyRing.ToLocalKey, - auxLeaf, + auxLeaf, sigHashDefault, ) if err != nil { return nil, nil, nil, err @@ -3504,6 +3787,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, if HtlcIsDust( chanType, false, lntypes.Remote, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -3518,7 +3802,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // HTLC success transaction for them. The output of the timeout // transaction needs to account for fees, so we'll compute the // required fee and output now. - htlcFee := HtlcSuccessFee(chanType, feePerKw) + htlcFee := HtlcSuccessFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption( @@ -3539,7 +3823,7 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, chanType, isRemoteInitiator, op, outputAmt, uint32(remoteChanCfg.CsvDelay), leaseExpiry, keyRing.RevocationKey, keyRing.ToLocalKey, - auxLeaf, + auxLeaf, sigHashDefault, ) if err != nil { return nil, nil, nil, err @@ -3590,10 +3874,13 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, // for the remote party and the necessary signatures for the remote party to // validate this new state. This function is called right before sending the // new commitment to the remote party. The commit diff returned contains all -// information necessary for retransmission. +// information necessary for retransmission. That includes the sighash mode of +// the commitment, which is stated on the commitment_signed and so travels +// with every retransmission of it. func (lc *LightningChannel) createCommitDiff(newCommit *commitment, commitSig lnwire.Sig, htlcSigs []lnwire.Sig, - auxSigs []fn.Option[tlv.Blob]) (*channeldb.CommitDiff, error) { + auxSigs []fn.Option[tlv.Blob], + sigHashDefault bool) (*channeldb.CommitDiff, error) { var ( logUpdates []channeldb.LogUpdate @@ -3671,6 +3958,22 @@ func (lc *LightningChannel) createCommitDiff(newCommit *commitment, HtlcSigs: htlcSigs, } + // A commitment that uses SigHashDefault says so. The record is left + // out for the standard sighash flags of the channel type, so the + // message of every other commitment is unchanged. + var sigHashRecords lnwire.CustomRecords + if sigHashDefault && lc.statesHtlcSigHashType() { + recordType := uint64(commitSigHtlcSigHashType.TypeVal()) + sigHashRecords = lnwire.CustomRecords{ + recordType: []byte{byte(txscript.SigHashDefault)}, + } + } + sigHashBlob, err := sigHashRecords.Serialize() + if err != nil { + return nil, fmt.Errorf("error encoding htlc sighash "+ + "record: %w", err) + } + // Encode and check the size of the custom records now. auxCustomRecords, err := fn.MapOptionZ( lc.auxSigner, @@ -3693,7 +3996,8 @@ func (lc *LightningChannel) createCommitDiff(newCommit *commitment, // records. We also subtract 8 bytes for encoding // overhead of the custom records (just some safety // padding). - available := lnwire.MaxMsgBody - buf.Len() - 8 + available := lnwire.MaxMsgBody - buf.Len() - 8 - + len(sigHashBlob) blob := blobOption.UnwrapOr(nil) if len(blob) > available { @@ -3716,6 +4020,13 @@ func (lc *LightningChannel) createCommitDiff(newCommit *commitment, return nil, fmt.Errorf("error packing aux sigs: %w", err) } + if len(sigHashRecords) > 0 { + if auxCustomRecords == nil { + auxCustomRecords = make(lnwire.CustomRecords) + } + maps.Copy(auxCustomRecords, sigHashRecords) + } + commitSigMsg.CustomRecords = auxCustomRecords return &channeldb.CommitDiff{ @@ -3913,7 +4224,7 @@ func (lc *LightningChannel) applyCommitFee( func (lc *LightningChannel) validateCommitmentSanity(theirLogCounter, ourLogCounter uint64, whoseCommitChain lntypes.ChannelParty, buffer BufferType, predictOurAdd, predictTheirAdd *paymentDescriptor, -) error { + sigHashDefault bool) error { // First fetch the initial balance before applying any updates. commitChain := lc.commitChains.Local @@ -3940,7 +4251,7 @@ func (lc *LightningChannel) validateCommitmentSanity(theirLogCounter, ourBalance, theirBalance, commitWeight, filteredView, err := lc.computeView( view, whoseCommitChain, false, - fn.None[chainfee.SatPerKWeight](), + fn.None[chainfee.SatPerKWeight](), sigHashDefault, ) if err != nil { return err @@ -4197,9 +4508,15 @@ func (lc *LightningChannel) SignNextCommitment( // We do not enforce the FeeBuffer here because when we reach this // point all updates will have to get locked-in so we enforce the // minimum requirement. + // + // The sighash mode of the new commitment is ours to decide, and it is + // decided here once for everything that follows: the dust + // classification, the commitment blob, the signatures and the record + // on the commitment_signed that tells the remote party about it. + sigHashDefault := lc.nextSigHashDefault(lntypes.Remote) err = lc.validateCommitmentSanity( remoteACKedIndex, lc.updateLogs.Local.logIndex, lntypes.Remote, - NoBuffer, nil, nil, + NoBuffer, nil, nil, sigHashDefault, ) if err != nil { return nil, err @@ -4223,7 +4540,7 @@ func (lc *LightningChannel) SignNextCommitment( newCommitView, err := lc.fetchCommitmentView( lntypes.Remote, lc.updateLogs.Local.logIndex, lc.updateLogs.Local.htlcCounter, remoteACKedIndex, - remoteHtlcIndex, keyRing, + remoteHtlcIndex, keyRing, sigHashDefault, ) if err != nil { return nil, err @@ -4250,7 +4567,7 @@ func (lc *LightningChannel) SignNextCommitment( } sigBatch, auxSigBatch, cancelChan, err := genRemoteHtlcSigJobs( keyRing, lc.channelState, leaseExpiry, newCommitView, - lc.leafStore, + lc.leafStore, lc.htlcSigHashTypeOf(sigHashDefault), ) if err != nil { return nil, err @@ -4366,7 +4683,7 @@ func (lc *LightningChannel) SignNextCommitment( // party, we'll write this pending state to disk before we exit, so we // can retransmit it if necessary. commitDiff, err := lc.createCommitDiff( - newCommitView, sig, htlcSigs, auxSigs, + newCommitView, sig, htlcSigs, auxSigs, sigHashDefault, ) if err != nil { return nil, err @@ -4849,10 +5166,14 @@ func (lc *LightningChannel) ProcessChanSyncMsg(ctx context.Context, // // If the updateState boolean is set true, the add and remove heights of the // HTLCs will be set to the next commitment height. +// +// The sigHashDefault flag is the sighash mode of the commitment the view is +// evaluated for, which decides which of its HTLCs are dust. func (lc *LightningChannel) computeView(view *HtlcView, whoseCommitChain lntypes.ChannelParty, updateState bool, - dryRunFee fn.Option[chainfee.SatPerKWeight]) (lnwire.MilliSatoshi, - lnwire.MilliSatoshi, lntypes.WeightUnit, *HtlcView, error) { + dryRunFee fn.Option[chainfee.SatPerKWeight], + sigHashDefault bool) (lnwire.MilliSatoshi, lnwire.MilliSatoshi, + lntypes.WeightUnit, *HtlcView, error) { commitChain := lc.commitChains.Local dustLimit := lc.channelState.LocalChanCfg.DustLimit @@ -4963,6 +5284,7 @@ func (lc *LightningChannel) computeView(view *HtlcView, if HtlcIsDust( lc.channelState.ChanType, false, whoseCommitChain, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -4974,6 +5296,7 @@ func (lc *LightningChannel) computeView(view *HtlcView, if HtlcIsDust( lc.channelState.ChanType, true, whoseCommitChain, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -5004,11 +5327,17 @@ func (lc *LightningChannel) recordSettlement( // commitment state. The jobs generated are fully populated, and can be sent // directly into the pool of workers. // +// The sigHashType passed in is the HTLC sighash type the channel uses for new +// commitments, the same value the commitment view was built with, so the +// sighash the signatures are verified against always matches the commitment +// shape the jobs are generated for. +// //nolint:funlen func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, localCommitmentView *commitment, keyRing *CommitmentKeyRing, htlcSigs []lnwire.Sig, leaseExpiry uint32, leafStore fn.Option[AuxLeafStore], auxSigner fn.Option[AuxSigner], + sigHashType txscript.SigHashType, sigBlob fn.Option[tlv.Blob]) ([]VerifyJob, []AuxVerifyJob, error) { var ( @@ -5019,7 +5348,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, txHash := localCommitmentView.txn.TxHash() feePerKw := localCommitmentView.feePerKw - sigHashType := HtlcSigHashType(chanType) + sigHashDefault := sigHashType == txscript.SigHashDefault // With the required state generated, we'll create a slice with large // enough capacity to hold verification jobs for all HTLC's in this @@ -5091,7 +5420,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, Index: uint32(htlc.localOutputIndex), } - htlcFee := HtlcSuccessFee(chanType, feePerKw) + htlcFee := HtlcSuccessFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption(func( @@ -5107,6 +5436,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, outputAmt, uint32(localChanCfg.CsvDelay), leaseExpiry, keyRing.RevocationKey, keyRing.ToLocalKey, auxLeaf, + sigHashDefault, ) if err != nil { return nil, err @@ -5184,7 +5514,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, Index: uint32(htlc.localOutputIndex), } - htlcFee := HtlcTimeoutFee(chanType, feePerKw) + htlcFee := HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) outputAmt := htlc.Amount.ToSatoshis() - htlcFee auxLeaf := fn.FlatMapOption(func( @@ -5201,6 +5531,7 @@ func genHtlcSigValidationJobs(chanState *chanstate.OpenChannel, uint32(localChanCfg.CsvDelay), leaseExpiry, keyRing.RevocationKey, keyRing.ToLocalKey, auxLeaf, + sigHashDefault, ) if err != nil { return nil, err @@ -5454,9 +5785,20 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { // point all updates will have to get locked-in (we already received // the UpdateAddHTLC msg from our peer prior to receiving the // commit-sig). - err := lc.validateCommitmentSanity( + // + // The remote party decided the sighash mode of this commitment when + // it signed it, so before anything is built or checked we read it off + // the message. + sigHashDefault, auxSigs, err := lc.receivedSigHashDefault( + commitSigs.AuxSigBlob, + ) + if err != nil { + return err + } + + err = lc.validateCommitmentSanity( lc.updateLogs.Remote.logIndex, localACKedIndex, lntypes.Local, - NoBuffer, nil, nil, + NoBuffer, nil, nil, sigHashDefault, ) if err != nil { return err @@ -5484,7 +5826,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { localCommitmentView, err := lc.fetchCommitmentView( lntypes.Local, localACKedIndex, localHtlcIndex, lc.updateLogs.Remote.logIndex, lc.updateLogs.Remote.htlcCounter, - keyRing, + keyRing, sigHashDefault, ) if err != nil { return err @@ -5501,8 +5843,8 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { lnutils.SpewLogClosure(localCommitmentView.txn)) var auxSigBlob fn.Option[tlv.Blob] - if commitSigs.AuxSigBlob != nil { - auxSigBlob = fn.Some(commitSigs.AuxSigBlob) + if auxSigs != nil { + auxSigBlob = fn.Some(auxSigs) } // As an optimization, we'll generate a series of jobs for the worker @@ -5515,7 +5857,7 @@ func (lc *LightningChannel) ReceiveNewCommitment(commitSigs *CommitSigs) error { verifyJobs, auxVerifyJobs, err := genHtlcSigValidationJobs( lc.channelState, localCommitmentView, keyRing, commitSigs.HtlcSigs, leaseExpiry, lc.leafStore, lc.auxSigner, - auxSigBlob, + lc.htlcSigHashTypeOf(sigHashDefault), auxSigBlob, ) if err != nil { return err @@ -6367,6 +6709,7 @@ func (lc *LightningChannel) GetDustSum(whoseCommit lntypes.ChannelParty, chanType := lc.channelState.ChanType feeRate := chainfee.SatPerKWeight(commit.FeePerKw) + sigHashDefault := lc.nextSigHashDefault(whoseCommit) // Optionally use the dry-run fee-rate. feeRate = dryRunFee.UnwrapOr(feeRate) @@ -6384,6 +6727,7 @@ func (lc *LightningChannel) GetDustSum(whoseCommit lntypes.ChannelParty, // amount to the dust sum. if HtlcIsDust( chanType, false, whoseCommit, feeRate, amt, dustLimit, + sigHashDefault, ) { dustSum += pd.Amount @@ -6403,7 +6747,7 @@ func (lc *LightningChannel) GetDustSum(whoseCommit lntypes.ChannelParty, // amount to the dust sum. if HtlcIsDust( chanType, true, whoseCommit, feeRate, - amt, dustLimit, + amt, dustLimit, sigHashDefault, ) { dustSum += pd.Amount @@ -6499,7 +6843,7 @@ func (lc *LightningChannel) validateAddHtlc(pd *paymentDescriptor, // commitment transaction without violation any of the constraints. err := lc.validateCommitmentSanity( remoteACKedIndex, lc.updateLogs.Local.logIndex, lntypes.Remote, - buffer, pd, nil, + buffer, pd, nil, lc.nextSigHashDefault(lntypes.Remote), ) if err != nil { return err @@ -6513,6 +6857,7 @@ func (lc *LightningChannel) validateAddHtlc(pd *paymentDescriptor, err = lc.validateCommitmentSanity( lc.updateLogs.Remote.logIndex, lc.updateLogs.Local.logIndex, lntypes.Local, buffer, pd, nil, + lc.nextSigHashDefault(lntypes.Local), ) if err != nil { return err @@ -6564,7 +6909,7 @@ func (lc *LightningChannel) ReceiveHTLC(htlc *lnwire.UpdateAddHTLC) (uint64, // reject ADDs already sent by the peer. err := lc.validateCommitmentSanity( lc.updateLogs.Remote.logIndex, localACKedIndex, lntypes.Local, - NoBuffer, nil, pd, + NoBuffer, nil, pd, lc.nextSigHashDefault(lntypes.Local), ) if err != nil { return 0, err @@ -7168,7 +7513,8 @@ func NewUnilateralCloseSummary(chanState *chanstate.OpenChannel, signer input.Signer, commitSpend *chainntnfs.SpendDetail, remoteCommit channeldb.ChannelCommitment, commitPoint *btcec.PublicKey, leafStore fn.Option[AuxLeafStore], - auxResolver fn.Option[AuxContractResolver]) (*UnilateralCloseSummary, + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*UnilateralCloseSummary, error) { // First, we'll generate the commitment point and the revocation point @@ -7211,7 +7557,7 @@ func NewUnilateralCloseSummary(chanState *chanstate.OpenChannel, &chanState.RemoteChanCfg, commitSpend.SpendingTx, commitTxHeight, chanState.ChanType, isRemoteInitiator, leaseExpiry, chanState, auxResult.AuxLeaves, - auxResolver, + auxResolver, auxSigner, remoteCommit.CustomBlob, ) if err != nil { return nil, fmt.Errorf("unable to create htlc resolutions: %w", @@ -7508,6 +7854,7 @@ func newOutgoingHtlcResolution(signer input.Signer, chanType channeldb.ChannelType, chanState *chanstate.OpenChannel, auxLeaves fn.Option[CommitAuxLeaves], auxResolver fn.Option[AuxContractResolver], + sigHashType txscript.SigHashType, ) (*OutgoingHtlcResolution, error) { op := wire.OutPoint{ @@ -7626,7 +7973,8 @@ func newOutgoingHtlcResolution(signer input.Signer, // In order to properly reconstruct the HTLC transaction, we'll need to // re-calculate the fee required at this state, so we can add the // correct output value amount to the transaction. - htlcFee := HtlcTimeoutFee(chanType, feePerKw) + sigHashDefault := sigHashType == txscript.SigHashDefault + htlcFee := HtlcTimeoutFee(chanType, feePerKw, sigHashDefault) secondLevelOutputAmt := htlc.Amt.ToSatoshis() - htlcFee // With the fee calculated, re-construct the second level timeout @@ -7641,6 +7989,7 @@ func newOutgoingHtlcResolution(signer input.Signer, chanType, isCommitFromInitiator, op, secondLevelOutputAmt, htlc.RefundTimeout, csvDelay, leaseExpiry, keyRing.RevocationKey, keyRing.ToLocalKey, secondLevelAuxLeaf, + sigHashDefault, ) if err != nil { return nil, err @@ -7672,7 +8021,6 @@ func newOutgoingHtlcResolution(signer input.Signer, // With the sign desc created, we can now construct the full witness // for the timeout transaction, and populate it as well. - sigHashType := HtlcSigHashType(chanType) var timeoutWitness wire.TxWitness if scriptTree, ok := htlcScriptInfo.(input.TapscriptDescriptor); ok { timeoutSignDesc.SignMethod = input.TaprootScriptSpendSignMethod @@ -7773,6 +8121,17 @@ func newOutgoingHtlcResolution(signer input.Signer, keyRing.CommitPoint, localChanCfg.DelayBasePoint.PubKey, ) + // The on-chain HTLC output value on the 2nd-level tx is reduced by + // AnchorSize under DeterministicHTLCs (CreateHtlcTimeoutTx splits + // secondLevelOutputAmt between the HTLC output and the appended + // anchor). The sweep SignDesc must reflect that reduced on-chain + // value or the sweeper later builds an over-spending tx and gets + // rejected by the mempool. + sweepOutputAmt := secondLevelOutputAmt + if sigHashDefault { + sweepOutputAmt -= AnchorSize + } + // In addition to the info in txSignDetails, we also need extra // information to sweep the second level output after confirmation. sweepSignDesc := input.SignDescriptor{ @@ -7781,12 +8140,12 @@ func newOutgoingHtlcResolution(signer input.Signer, WitnessScript: htlcSweepWitnessScript, Output: &wire.TxOut{ PkScript: htlcSweepScript.PkScript(), - Value: int64(secondLevelOutputAmt), + Value: int64(sweepOutputAmt), }, HashType: sweepSigHash(chanType), PrevOutputFetcher: txscript.NewCannedPrevOutputFetcher( htlcSweepScript.PkScript(), - int64(secondLevelOutputAmt), + int64(sweepOutputAmt), ), SignMethod: signMethod, ControlBlock: ctrlBlock, @@ -7882,6 +8241,7 @@ func newIncomingHtlcResolution(signer input.Signer, chanType channeldb.ChannelType, chanState *chanstate.OpenChannel, auxLeaves fn.Option[CommitAuxLeaves], auxResolver fn.Option[AuxContractResolver], + sigHashType txscript.SigHashType, ) (*IncomingHtlcResolution, error) { op := wire.OutPoint{ @@ -8005,12 +8365,14 @@ func newIncomingHtlcResolution(signer input.Signer, // // First, we'll reconstruct the original HTLC success transaction, // taking into account the fee rate used. - htlcFee := HtlcSuccessFee(chanType, feePerKw) + sigHashDefault := sigHashType == txscript.SigHashDefault + htlcFee := HtlcSuccessFee(chanType, feePerKw, sigHashDefault) secondLevelOutputAmt := htlc.Amt.ToSatoshis() - htlcFee successTx, err := CreateHtlcSuccessTx( chanType, isCommitFromInitiator, op, secondLevelOutputAmt, csvDelay, leaseExpiry, keyRing.RevocationKey, keyRing.ToLocalKey, secondLevelAuxLeaf, + sigHashDefault, ) if err != nil { return nil, err @@ -8044,7 +8406,6 @@ func newIncomingHtlcResolution(signer input.Signer, // will be supplied by the contract resolver, either directly or when it // becomes known. var successWitness wire.TxWitness - sigHashType := HtlcSigHashType(chanType) if scriptTree, ok := scriptInfo.(input.TapscriptDescriptor); ok { successSignDesc.SignMethod = input.TaprootScriptSpendSignMethod @@ -8143,6 +8504,14 @@ func newIncomingHtlcResolution(signer input.Signer, keyRing.CommitPoint, localChanCfg.DelayBasePoint.PubKey, ) + // See newOutgoingHtlcResolution for the AnchorSize reasoning. Under + // DeterministicHTLCs the 2nd-level HTLC output is reduced by + // AnchorSize to make room for the appended CPFP anchor. + sweepOutputAmt := secondLevelOutputAmt + if sigHashDefault { + sweepOutputAmt -= AnchorSize + } + // In addition to the info in txSignDetails, we also need extra // information to sweep the second level output after confirmation. sweepSignDesc := input.SignDescriptor{ @@ -8151,12 +8520,12 @@ func newIncomingHtlcResolution(signer input.Signer, WitnessScript: htlcSweepWitnessScript, Output: &wire.TxOut{ PkScript: htlcSweepScript.PkScript(), - Value: int64(secondLevelOutputAmt), + Value: int64(sweepOutputAmt), }, HashType: sweepSigHash(chanType), PrevOutputFetcher: txscript.NewCannedPrevOutputFetcher( htlcSweepScript.PkScript(), - int64(secondLevelOutputAmt), + int64(sweepOutputAmt), ), SignMethod: signMethod, ControlBlock: ctrlBlock, @@ -8266,7 +8635,9 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, chanType channeldb.ChannelType, isCommitFromInitiator bool, leaseExpiry uint32, chanState *chanstate.OpenChannel, auxLeaves fn.Option[CommitAuxLeaves], - auxResolver fn.Option[AuxContractResolver]) (*HtlcResolutions, error) { + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner], + commitBlob fn.Option[tlv.Blob]) (*HtlcResolutions, error) { // TODO(roasbeef): don't need to swap csv delay? dustLimit := remoteChanCfg.DustLimit @@ -8276,6 +8647,19 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, csvDelay = localChanCfg.CsvDelay } + // Resolve the HTLC sighash type once for this set of resolutions and + // reuse it below, both for the dust decisions and for reconstructing + // the second-level transactions, so all of them are guaranteed to be + // made against the same resolved value. The commitment being resolved + // already exists (it is on chain), so the answer is the one recorded + // in the blob of that very commitment, which the caller passes in. + sigHashType := ResolveHtlcSigHashType( + chanType, auxSigner, HtlcSigHashReq{ + CommitBlob: commitBlob, + }, + ) + sigHashDefault := sigHashType == txscript.SigHashDefault + incomingResolutions := make([]IncomingHtlcResolution, 0, len(htlcs)) outgoingResolutions := make([]OutgoingHtlcResolution, 0, len(htlcs)) for _, htlc := range htlcs { @@ -8285,7 +8669,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, // within the commitment transaction. if HtlcIsDust( chanType, htlc.Incoming, whoseCommit, feePerKw, - htlc.Amt.ToSatoshis(), dustLimit, + htlc.Amt.ToSatoshis(), dustLimit, sigHashDefault, ) { continue @@ -8301,6 +8685,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, &htlc, keyRing, feePerKw, uint32(csvDelay), leaseExpiry, whoseCommit, isCommitFromInitiator, chanType, chanState, auxLeaves, auxResolver, + sigHashType, ) if err != nil { return nil, fmt.Errorf("incoming resolution "+ @@ -8315,7 +8700,7 @@ func extractHtlcResolutions(feePerKw chainfee.SatPerKWeight, signer, localChanCfg, commitTx, commitTxHeight, &htlc, keyRing, feePerKw, uint32(csvDelay), leaseExpiry, whoseCommit, isCommitFromInitiator, chanType, chanState, - auxLeaves, auxResolver, + auxLeaves, auxResolver, sigHashType, ) if err != nil { return nil, fmt.Errorf("outgoing resolution "+ @@ -8469,7 +8854,7 @@ func (lc *LightningChannel) ForceClose(opts ...ForceCloseOpt) ( summary, err := NewLocalForceCloseSummary( lc.channelState, lc.Signer, commitTx, 0, localCommitment.CommitHeight, lc.leafStore, - lc.auxResolver, + lc.auxResolver, lc.auxSigner, ) if err != nil { return nil, fmt.Errorf("unable to gen force close "+ @@ -8488,8 +8873,8 @@ func (lc *LightningChannel) ForceClose(opts ...ForceCloseOpt) ( func NewLocalForceCloseSummary(chanState *chanstate.OpenChannel, signer input.Signer, commitTx *wire.MsgTx, commitTxHeight uint32, stateNum uint64, leafStore fn.Option[AuxLeafStore], - auxResolver fn.Option[AuxContractResolver]) (*LocalForceCloseSummary, - error) { + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner]) (*LocalForceCloseSummary, error) { // Re-derive the original pkScript for to-self output within the // commitment transaction. We'll need this to find the corresponding @@ -8658,7 +9043,8 @@ func NewLocalForceCloseSummary(chanState *chanstate.OpenChannel, signer, localCommit.Htlcs, keyRing, &chanState.LocalChanCfg, &chanState.RemoteChanCfg, commitTx, commitTxHeight, chanState.ChanType, chanState.IsInitiator, leaseExpiry, - chanState, auxResult.AuxLeaves, auxResolver, + chanState, auxResult.AuxLeaves, auxResolver, auxSigner, + localCommit.CustomBlob, ) if err != nil { return nil, fmt.Errorf("unable to gen htlc resolution: %w", err) @@ -9350,9 +9736,10 @@ func (lc *LightningChannel) availableCommitmentBalance(view *HtlcView, // Compute the current balances for this commitment. This will take // into account HTLCs to determine the commit weight, which the // initiator must pay the fee for. + sigHashDefault := lc.nextSigHashDefault(whoseCommitChain) ourBalance, theirBalance, commitWeight, filteredView, err := lc.computeView( view, whoseCommitChain, false, - fn.None[chainfee.SatPerKWeight](), + fn.None[chainfee.SatPerKWeight](), sigHashDefault, ) if err != nil { lc.log.Errorf("Unable to fetch available balance: %v", err) @@ -9435,7 +9822,8 @@ func (lc *LightningChannel) availableCommitmentBalance(view *HtlcView, // For an extra HTLC fee to be paid on our commitment, the HTLC must be // large enough to make a non-dust HTLC timeout transaction. htlcFee := lnwire.NewMSatFromSatoshis( - HtlcTimeoutFee(lc.channelState.ChanType, feePerKw), + HtlcTimeoutFee(lc.channelState.ChanType, feePerKw, + sigHashDefault), ) // If we are looking at the remote commitment, we must use the remote @@ -9445,13 +9833,20 @@ func (lc *LightningChannel) availableCommitmentBalance(view *HtlcView, lc.channelState.RemoteChanCfg.DustLimit, ) htlcFee = lnwire.NewMSatFromSatoshis( - HtlcSuccessFee(lc.channelState.ChanType, feePerKw), + HtlcSuccessFee(lc.channelState.ChanType, feePerKw, + sigHashDefault), ) } // The HTLC output will be manifested on the commitment if it - // is non-dust after paying the HTLC fee. + // is non-dust after paying the HTLC fee. Under DeterministicHTLCs + // the second-level tx also carries an AnchorSize CPFP anchor taken + // from the HTLC value (see HtlcIsDust), raising the dust threshold + // accordingly. nonDustHtlcAmt := dustlimit + htlcFee + if sigHashDefault { + nonDustHtlcAmt += lnwire.NewMSatFromSatoshis(AnchorSize) + } // commitFeeWithHtlc is the fee our peer has to pay in case we add // another htlc to the commitment. @@ -9595,6 +9990,7 @@ func (lc *LightningChannel) CommitFeeTotalAt( // Compute the local commitment's weight. _, _, localWeight, _, err := lc.computeView( localHtlcView, lntypes.Local, false, dryRunFee, + lc.nextSigHashDefault(lntypes.Local), ) if err != nil { return 0, 0, err @@ -9609,6 +10005,7 @@ func (lc *LightningChannel) CommitFeeTotalAt( // Compute the remote commitment's weight. _, _, remoteWeight, _, err := lc.computeView( remoteHtlcView, lntypes.Remote, false, dryRunFee, + lc.nextSigHashDefault(lntypes.Remote), ) if err != nil { return 0, 0, err diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index 86534e81472..a29fceb01c7 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -1561,6 +1561,7 @@ func TestHTLCDustLimit(t *testing.T) { chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ), + false, )) htlcAmount := lnwire.NewMSatFromSatoshis(htlcSat) @@ -1655,10 +1656,10 @@ func TestHTLCSigNumber(t *testing.T) { require.NoError(t, err, "unable to get fee") belowDust := btcutil.Amount(500) + HtlcTimeoutFee( - channeldb.SingleFunderTweaklessBit, feePerKw, + channeldb.SingleFunderTweaklessBit, feePerKw, false, ) aboveDust := btcutil.Amount(1400) + HtlcSuccessFee( - channeldb.SingleFunderTweaklessBit, feePerKw, + channeldb.SingleFunderTweaklessBit, feePerKw, false, ) // =================================================================== @@ -1806,6 +1807,7 @@ func TestChannelBalanceDustLimit(t *testing.T) { chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ), + false, ) htlcAmount := lnwire.NewMSatFromSatoshis(htlcSat) @@ -5803,11 +5805,12 @@ func TestChanAvailableBalanceNearHtlcFee(t *testing.T) { commitFee := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalCommitment.CommitFee, ) + chanType := aliceChannel.channelState.ChanType htlcTimeoutFee := lnwire.NewMSatFromSatoshis( - HtlcTimeoutFee(aliceChannel.channelState.ChanType, feeRate), + HtlcTimeoutFee(chanType, feeRate, false), ) htlcSuccessFee := lnwire.NewMSatFromSatoshis( - HtlcSuccessFee(aliceChannel.channelState.ChanType, feeRate), + HtlcSuccessFee(chanType, feeRate, false), ) // Helper method to check the current reported balance. @@ -5974,11 +5977,12 @@ func TestChanCommitWeightDustHtlcs(t *testing.T) { feeRate := chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ) + chanType := aliceChannel.channelState.ChanType htlcTimeoutFee := lnwire.NewMSatFromSatoshis( - HtlcTimeoutFee(aliceChannel.channelState.ChanType, feeRate), + HtlcTimeoutFee(chanType, feeRate, false), ) htlcSuccessFee := lnwire.NewMSatFromSatoshis( - HtlcSuccessFee(aliceChannel.channelState.ChanType, feeRate), + HtlcSuccessFee(chanType, feeRate, false), ) // Helper method to add an HTLC from Alice to Bob. @@ -6734,6 +6738,7 @@ func TestChannelUnilateralCloseHtlcResolution(t *testing.T) { aliceChannel.channelState.RemoteCurrentRevocation, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create alice close summary") @@ -6880,6 +6885,7 @@ func TestChannelUnilateralClosePendingCommit(t *testing.T) { aliceChannel.channelState.RemoteCurrentRevocation, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create alice close summary") @@ -6901,6 +6907,7 @@ func TestChannelUnilateralClosePendingCommit(t *testing.T) { &bobNextPoint, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create alice close summary") @@ -7548,6 +7555,7 @@ func TestChanReserveLocalInitiatorDustHtlc(t *testing.T) { chainfee.SatPerKWeight( aliceChannel.channelState.LocalCommitment.FeePerKw, ), + false, ) // Set Alice's channel reserve to be low enough to carry the value of @@ -7727,6 +7735,7 @@ func TestNewBreachRetributionSkipsDustHtlcs(t *testing.T) { aliceChannel.channelState, revokedStateNum, 100, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err, "unable to create breach retribution") @@ -10711,6 +10720,7 @@ func TestCreateBreachRetributionLegacy(t *testing.T) { br, ourAmt, theirAmt, err := createBreachRetributionLegacy( &revokedLog, aliceChannel.channelState, keyRing, dummyPrivate, ourScript, theirScript, leaseExpiry, + fn.None[AuxSigner](), ) require.NoError(t, err) @@ -10805,7 +10815,7 @@ func TestCreateBreachRetributionLegacyDustHtlcs(t *testing.T) { // Create the breach retribution using the legacy format. br, _, _, err := createBreachRetributionLegacy( &revokedLog, chanState, keyRing, dummyPrivate, ourScript, - theirScript, leaseExpiry, + theirScript, leaseExpiry, fn.None[AuxSigner](), ) require.NoError(t, err) @@ -10852,6 +10862,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrNoPastDeltas) @@ -10861,6 +10872,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, nil, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrNoPastDeltas) @@ -10908,6 +10920,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err) @@ -10921,6 +10934,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum, breachHeight, nil, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.NoError(t, err) assertRetribution(br, 1, 0) @@ -10931,6 +10945,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum+1, breachHeight, breachTx, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrLogEntryNotFound) @@ -10940,6 +10955,7 @@ func testNewBreachRetribution(t *testing.T, chanType channeldb.ChannelType) { aliceChannel.channelState, stateNum+1, breachHeight, nil, fn.Some[AuxLeafStore](&MockAuxLeafStore{}), fn.Some[AuxContractResolver](&MockAuxContractResolver{}), + fn.None[AuxSigner](), ) require.ErrorIs(t, err, channeldb.ErrLogEntryNotFound) } @@ -10978,7 +10994,7 @@ func TestExtractPayDescs(t *testing.T) { // scripts(`genHtlcScript`) as it should be tested independently. incomingPDs, outgoingPDs, err := lnChan.extractPayDescs( 0, htlcs, lntypes.Dual[*CommitmentKeyRing]{}, lntypes.Local, - fn.None[CommitAuxLeaves](), + fn.None[CommitAuxLeaves](), false, ) require.NoError(t, err) @@ -11234,7 +11250,9 @@ func TestAsynchronousSendingContraint(t *testing.T) { // |<----add------- // make sure this htlc is non-dust for alice. - htlcFee := HtlcSuccessFee(channeldb.SingleFunderTweaklessBit, feePerKw) + htlcFee := HtlcSuccessFee( + channeldb.SingleFunderTweaklessBit, feePerKw, false, + ) // We need to take the remote dustlimit amount, because it the greater // one. htlcAmt2 := lnwire.NewMSatFromSatoshis( @@ -11368,7 +11386,9 @@ func TestAsynchronousSendingWithFeeBuffer(t *testing.T) { // commitment as well. // |<----add------- // make sure this htlc is non-dust for alice. - htlcFee := HtlcSuccessFee(channeldb.SingleFunderTweaklessBit, feePerKw) + htlcFee := HtlcSuccessFee( + channeldb.SingleFunderTweaklessBit, feePerKw, false, + ) htlcAmt2 := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalChanCfg.DustLimit + htlcFee, ) @@ -11452,7 +11472,9 @@ func TestAsynchronousSendingWithFeeBuffer(t *testing.T) { // --------------- |-----sig------> // <----rev------- |--------------- // Update the non-dust amount because we updated the fee by 100%. - htlcFee = HtlcSuccessFee(channeldb.SingleFunderTweaklessBit, feePerKw*2) + htlcFee = HtlcSuccessFee( + channeldb.SingleFunderTweaklessBit, feePerKw*2, false, + ) htlcAmt3 := lnwire.NewMSatFromSatoshis( aliceChannel.channelState.LocalChanCfg.DustLimit + htlcFee, ) @@ -12706,3 +12728,631 @@ func TestAuxSigRejectionFailsCommitment(t *testing.T) { require.ErrorContains(t, err, "unable to validate aux sigs") require.ErrorContains(t, err, "second level sig verification failed") } + +// TestHtlcFeesSigHashDefault verifies that HtlcTimeoutFee and +// HtlcSuccessFee return non-zero baked-in fees for taproot channels +// with sigHashDefault=true, using the fixed sigHashDefaultFeeRate. +func TestHtlcFeesSigHashDefault(t *testing.T) { + t.Parallel() + + taprootChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + + // With sigHashDefault=false, taproot channels have zero + // second-level fees (zero-fee HTLC path). + timeoutFeeOff := HtlcTimeoutFee(taprootChanType, 0, false) + successFeeOff := HtlcSuccessFee(taprootChanType, 0, false) + require.Zero(t, timeoutFeeOff, + "taproot timeout fee should be zero without sigHashDefault") + require.Zero(t, successFeeOff, + "taproot success fee should be zero without sigHashDefault") + + // With sigHashDefault=true these functions return the fee baked into + // the pre-signed second-level tx: 1.1x the relay floor over the + // anchor-inclusive weight. See TestSecondLevelFeeBudget for why it is + // pinned to the floor rather than the commitment fee rate. + feeRate := chainfee.SatPerKWeight(2500) + timeoutFeeOn := HtlcTimeoutFee(taprootChanType, feeRate, true) + successFeeOn := HtlcSuccessFee(taprootChanType, feeRate, true) + require.NotZero(t, timeoutFeeOn, + "taproot timeout fee should be non-zero with sigHashDefault") + require.NotZero(t, successFeeOn, + "taproot success fee should be non-zero with sigHashDefault") + + floorRate := chainfee.FeePerKwFloor * 11 / 10 + expectedTimeout := floorRate.FeeForWeight( + SecondLevelTimeoutWeight(), + ) + expectedSuccess := floorRate.FeeForWeight( + SecondLevelSuccessWeight(), + ) + require.Equal(t, expectedTimeout, timeoutFeeOn) + require.Equal(t, expectedSuccess, successFeeOn) + + // On the on-chain budget aux channels put on an HTLC, the fee and the + // anchor must leave a second-level output above the taproot dust + // limit, with headroom to pay for the sweep that later claims it. + // See TestSecondLevelOutputFundsSweep for that sweep. + auxHtlcSat := btcutil.Amount(1200) + dustLimit := DustLimitForSize(input.P2TRSize) + require.Greater(t, auxHtlcSat-timeoutFeeOn-AnchorSize, dustLimit) + require.Greater(t, auxHtlcSat-successFeeOn-AnchorSize, dustLimit) + + // The minimum is a property of the relay floor, so it does not move + // with the negotiated commitment fee rate. + highFeeRate := chainfee.SatPerKWeight(50_000) + timeoutFeeHigh := HtlcTimeoutFee( + taprootChanType, highFeeRate, true, + ) + successFeeHigh := HtlcSuccessFee( + taprootChanType, highFeeRate, true, + ) + require.Equal(t, timeoutFeeOn, timeoutFeeHigh, + "min second-level fee must not depend on the commit fee rate") + require.Equal(t, successFeeOn, successFeeHigh, + "min second-level fee must not depend on the commit fee rate") + + // Non-taproot channel types should not be affected by + // sigHashDefault flag. + anchorChanType := channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + anchorTimeoutFee := HtlcTimeoutFee( + anchorChanType, highFeeRate, true, + ) + require.Zero(t, anchorTimeoutFee, + "non-taproot zero-fee channel should still have zero fee") +} + +// TestHtlcIsDustSigHashDefault exercises the deterministic-HTLC dust boundary +// of HtlcIsDust: under sigHashDefault the on-chain HTLC output value is the +// HTLC amount minus both the baked-in second-level fee and the AnchorSize of +// the embedded CPFP anchor, so the dust threshold sits at +// dustLimit + fee + AnchorSize. Every incoming/outgoing x local/remote +// combination is tested one satoshi below the threshold, at exact equality, +// and one satoshi above. +func TestHtlcIsDustSigHashDefault(t *testing.T) { + t.Parallel() + + customChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + const ( + feePerKw = chainfee.SatPerKWeight(2500) + dustLimit = btcutil.Amount(354) + ) + + timeoutFee := HtlcTimeoutFee(customChanType, feePerKw, true) + successFee := HtlcSuccessFee(customChanType, feePerKw, true) + + testCases := []struct { + name string + incoming bool + whoseCommit lntypes.ChannelParty + fee btcutil.Amount + }{{ + // Incoming HTLC on our commitment sweeps via the success tx. + name: "incoming local", + incoming: true, + whoseCommit: lntypes.Local, + fee: successFee, + }, { + // Incoming HTLC on their commitment: they added it, so the + // second level is a timeout tx. + name: "incoming remote", + incoming: true, + whoseCommit: lntypes.Remote, + fee: timeoutFee, + }, { + // Outgoing HTLC on our commitment times out via the timeout + // tx. + name: "outgoing local", + incoming: false, + whoseCommit: lntypes.Local, + fee: timeoutFee, + }, { + // Outgoing HTLC on their commitment: they receive it, so the + // second level is a success tx. + name: "outgoing remote", + incoming: false, + whoseCommit: lntypes.Remote, + fee: successFee, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + threshold := dustLimit + tc.fee + AnchorSize + + // One satoshi below the threshold the output value + // lands below the dust limit. + require.True(t, HtlcIsDust( + customChanType, tc.incoming, tc.whoseCommit, + feePerKw, threshold-1, dustLimit, true, + ), "amount below threshold must be dust") + + // At exact equality the output value equals the dust + // limit, which is spendable (strict less-than). + require.False(t, HtlcIsDust( + customChanType, tc.incoming, tc.whoseCommit, + feePerKw, threshold, dustLimit, true, + ), "amount at threshold must not be dust") + + // And one above is comfortably non-dust. + require.False(t, HtlcIsDust( + customChanType, tc.incoming, tc.whoseCommit, + feePerKw, threshold+1, dustLimit, true, + ), "amount above threshold must not be dust") + }) + } +} + +// TestSecondLevelOutputFundsSweep builds the pre-signed second-level timeout +// tx of an aux-channel HTLC with the fee actually baked in, and checks that +// the output it leaves can pay for the sweep that claims it at the relay +// floor, which is what the fee policy has to guarantee: the whole on-chain +// BTC value of such an HTLC is a small fixed budget that pays the baked-in +// fee, funds the CPFP anchor and must still leave an output that is non-dust +// and able to fund its own sweep. +func TestSecondLevelOutputFundsSweep(t *testing.T) { + t.Parallel() + + customChanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + // auxHtlcSat is the on-chain BTC value aux channels put on an HTLC + // (taproot-assets' DefaultOnChainHtlcSat). + const auxHtlcSat = btcutil.Amount(1200) + dustLimit := DustLimitForSize(input.P2TRSize) + + revPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + delayPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + // The sweep of the second-level output is a single-input, + // single-output tx. At the relay floor it costs this much. + var sweepWeight input.TxWeightEstimator + sweepWeight.AddWitnessInput(input.TaprootSecondLevelHtlcWitnessSize) + sweepWeight.AddP2TROutput() + sweepFee := chainfee.FeePerKwFloor.FeeForWeight(sweepWeight.Weight()) + + // The fee market well above the relay floor, as any channel that + // negotiated a realistic commitment fee rate sees it. + busyRate := chainfee.SatPerKWeight(12_500) + + // With the fee actually baked in, the HTLC output of the tx is above + // dust and the sweep that claims it at the relay floor still leaves + // an output above dust, so the value it carries can be claimed. + // + // The tx is built with the fee baked in, the way the channel state + // machine does. + bakedFee := HtlcTimeoutFee(customChanType, busyRate, true) + tx, err := CreateHtlcTimeoutTx( + customChanType, false, wire.OutPoint{Index: 1}, + auxHtlcSat-bakedFee, 100, 5, 0, revPriv.PubKey(), + delayPriv.PubKey(), input.NoneTapLeaf(), true, + ) + require.NoError(t, err) + require.Len(t, tx.TxOut, 2) + require.EqualValues(t, AnchorSize, tx.TxOut[1].Value) + require.Equal(t, auxHtlcSat-bakedFee-AnchorSize, + btcutil.Amount(tx.TxOut[0].Value)) + + secondLevelOut := btcutil.Amount(tx.TxOut[0].Value) + require.Greater(t, secondLevelOut, dustLimit) + require.Greater(t, secondLevelOut-sweepFee, dustLimit, + "the second-level output must fund its own sweep") +} + +// sigHashDefaultBlob is the commitment blob the liveAuxSigner test double +// treats as recording SigHashDefault. Any other blob records the default +// sighash of the channel type. +var sigHashDefaultBlob = tlv.Blob("sighash-default") + +// liveAuxSigner is an AuxSigner test double that answers HtlcSigHashType the +// way a real aux signer does: a request that carries a channel ID is a +// question about future state and is answered from the live feature +// negotiation when that is known, any other request is answered from the +// flag recorded in the given commitment blob. +type liveAuxSigner struct { + *MockAuxSigner + + // live is the negotiated answer. None means the peer has not + // (re)established the channel yet, so nothing is known. + live fn.Option[txscript.SigHashType] +} + +// HtlcSigHashType answers from live negotiation for future state, and from +// the commitment blob otherwise. +func (l *liveAuxSigner) HtlcSigHashType( + req HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + if req.ChanID.IsSome() && l.live.IsSome() { + return l.live + } + + blob := req.CommitBlob.UnwrapOr(nil) + if bytes.Equal(blob, sigHashDefaultBlob) { + return fn.Some(txscript.SigHashDefault) + } + + return fn.None[txscript.SigHashType]() +} + +// newLiveAuxSignerChannel creates a custom (tapscript root) channel instance +// driven by a liveAuxSigner. +func newLiveAuxSignerChannel(t *testing.T) (*LightningChannel, + *liveAuxSigner) { + + t.Helper() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + aliceChannel, _, err := CreateTestChannels(t, chanType) + require.NoError(t, err) + + signer := &liveAuxSigner{ + MockAuxSigner: NewDefaultAuxSignerMock(t), + } + sigPool := NewSigPool(1, aliceChannel.Signer) + channel, err := NewLightningChannel( + aliceChannel.Signer, aliceChannel.channelState, sigPool, + WithLeafStore(&MockAuxLeafStore{}), + WithAuxSigner(signer), + ) + require.NoError(t, err) + + return channel, signer +} + +// TestHtlcSigHashTypeFutureVsExisting asserts the rule the HTLC sighash type +// is resolved by. Decisions about future commitments follow the aux signer's +// live feature negotiation, which is picked up by RefreshHtlcSigHashType +// once the channel is re-established. Decisions about a commitment that +// already exists follow the flag recorded in that commitment's own blob and +// never the live negotiation. A channel opened before both peers upgraded +// therefore switches cleanly: its old commitments stay what they were built +// as, and only the new ones use SigHashDefault. +func TestHtlcSigHashTypeFutureVsExisting(t *testing.T) { + t.Parallel() + + channel, signer := newLiveAuxSignerChannel(t) + chanType := channel.channelState.ChanType + legacySigHash := HtlcSigHashType(chanType) + noBlob := fn.None[tlv.Blob]() + defaultBlob := fn.Some(sigHashDefaultBlob) + + // At construction the peer has not re-established the channel, so the + // aux signer answered from the latest local commitment, which + // predates the upgrade. + require.False(t, channel.IsChanSigHashDefault()) + require.Equal(t, legacySigHash, channel.nextHtlcSigHashType()) + + // The peer re-establishes and the feature is now negotiated. Nothing + // changes until the channel is told to pick the live answer up. + signer.live = fn.Some(txscript.SigHashDefault) + require.False(t, channel.IsChanSigHashDefault()) + + channel.RefreshHtlcSigHashType() + require.True(t, channel.IsChanSigHashDefault()) + require.Equal( + t, txscript.SigHashDefault, channel.nextHtlcSigHashType(), + ) + + // Existing commitments are untouched by the switch: one that was + // built before it still reports the legacy sighash, one built after + // reports SigHashDefault. + require.Equal(t, legacySigHash, channel.commitSigHashType(noBlob)) + require.False(t, channel.commitSigHashDefault(noBlob)) + require.True(t, channel.commitSigHashDefault(defaultBlob)) + + // The reverse holds as well. If the live negotiation is unknown again + // (a restart, before the peer reconnects) while the latest local + // commitment still predates the switch, new commitments fall back to + // that commitment's flag, and a commitment recorded as SigHashDefault + // keeps reporting SigHashDefault. + signer.live = fn.None[txscript.SigHashType]() + channel.RefreshHtlcSigHashType() + require.False(t, channel.IsChanSigHashDefault()) + require.True(t, channel.commitSigHashDefault(defaultBlob)) +} + +// TestRestoredCommitmentUsesRecordedSigHash asserts that the HTLCs of a +// commitment restored from disk are classified with the sighash recorded for +// that commitment, not with the one new commitments use. An HTLC whose value +// sits between the two dust thresholds has an output on a commitment built +// with the legacy sighash and none on one built with SigHashDefault. +func TestRestoredCommitmentUsesRecordedSigHash(t *testing.T) { + t.Parallel() + + channel, signer := newLiveAuxSignerChannel(t) + state := channel.channelState + chanType := state.ChanType + feePerKw := chainfee.SatPerKWeight(state.LocalCommitment.FeePerKw) + dustLimit := state.LocalChanCfg.DustLimit + + // Pick an incoming HTLC that is dust only under SigHashDefault. + htlcAmt := dustLimit + 100 + require.False(t, HtlcIsDust( + chanType, true, lntypes.Local, feePerKw, htlcAmt, dustLimit, + false, + )) + require.True(t, HtlcIsDust( + chanType, true, lntypes.Local, feePerKw, htlcAmt, dustLimit, + true, + )) + + localPoint := state.LocalChanCfg.RevocationBasePoint.PubKey + remotePoint := state.RemoteCurrentRevocation + + restore := func(blob fn.Option[tlv.Blob]) *commitment { + diskCommit := state.LocalCommitment + diskCommit.CustomBlob = blob + diskCommit.Htlcs = []channeldb.HTLC{{ + Amt: lnwire.NewMSatFromSatoshis(htlcAmt), + Incoming: true, + HtlcIndex: 0, + RHash: [32]byte{1}, + }} + + commit, err := channel.diskCommitToMemCommit( + lntypes.Local, &diskCommit, localPoint, remotePoint, + ) + require.NoError(t, err) + require.Len(t, commit.incomingHTLCs, 1) + + return commit + } + + // New commitments use SigHashDefault by now. + signer.live = fn.Some(txscript.SigHashDefault) + channel.RefreshHtlcSigHashType() + require.True(t, channel.IsChanSigHashDefault()) + + // A commitment recorded with the legacy sighash still has the HTLC + // output, so its script is restored. + legacy := restore(fn.None[tlv.Blob]()) + require.NotEmpty(t, legacy.incomingHTLCs[0].ourPkScript) + + // A commitment recorded with SigHashDefault trimmed the HTLC. + deterministic := restore(fn.Some(sigHashDefaultBlob)) + require.Empty(t, deterministic.incomingHTLCs[0].ourPkScript) + + // And the classification of a recorded commitment does not flip when + // new commitments go back to the legacy sighash. + signer.live = fn.None[txscript.SigHashType]() + channel.RefreshHtlcSigHashType() + require.False(t, channel.IsChanSigHashDefault()) + + deterministic = restore(fn.Some(sigHashDefaultBlob)) + require.Empty(t, deterministic.incomingHTLCs[0].ourPkScript) +} + +// TestHtlcResolutionsUseCommitmentSigHash asserts that the HTLC resolutions +// of a commitment are derived with the sighash recorded in the blob of the +// commitment being resolved, which the caller passes in, and not with the +// one recorded for our latest local commitment. The two differ when the +// remote party closes with a commitment built on the other side of a +// sighash switch. +func TestHtlcResolutionsUseCommitmentSigHash(t *testing.T) { + t.Parallel() + + channel, signer := newLiveAuxSignerChannel(t) + state := channel.channelState + chanType := state.ChanType + feePerKw := chainfee.SatPerKWeight(state.LocalCommitment.FeePerKw) + dustLimit := state.RemoteChanCfg.DustLimit + + // An HTLC that is dust only on a SigHashDefault commitment. + htlcAmt := dustLimit + 100 + htlcs := []channeldb.HTLC{{ + Amt: lnwire.NewMSatFromSatoshis(htlcAmt), + Incoming: true, + HtlcIndex: 0, + RHash: [32]byte{1}, + }} + + keyRing := DeriveCommitmentKeys( + state.RemoteCurrentRevocation, lntypes.Remote, chanType, + &state.LocalChanCfg, &state.RemoteChanCfg, + ) + commitTx := wire.NewMsgTx(2) + + resolve := func(blob fn.Option[tlv.Blob]) (*HtlcResolutions, error) { + return extractHtlcResolutions( + feePerKw, lntypes.Remote, channel.Signer, htlcs, + keyRing, &state.LocalChanCfg, &state.RemoteChanCfg, + commitTx, 0, chanType, !state.IsInitiator, 0, state, + fn.None[CommitAuxLeaves](), + fn.None[AuxContractResolver](), + fn.Some[AuxSigner](signer), blob, + ) + } + + // Our latest local commitment records the legacy sighash. The remote + // commitment being resolved records SigHashDefault, under which the + // HTLC was trimmed, so there is nothing to resolve. + require.True(t, state.LocalCommitment.CustomBlob.IsNone()) + res, err := resolve(fn.Some(sigHashDefaultBlob)) + require.NoError(t, err) + require.Empty(t, res.IncomingHTLCs) + require.Empty(t, res.OutgoingHTLCs) + + // The same HTLC on a commitment recorded with the legacy sighash is + // not dust and gets a resolution. + res, err = resolve(fn.None[tlv.Blob]()) + require.NoError(t, err) + require.Len(t, res.IncomingHTLCs, 1) +} + +// TestLegacyBreachRetributionUsesRevokedSigHash asserts that the HTLC dust +// decisions of a breach retribution are made with the sighash recorded for +// the revoked state itself, not with the one of our latest local commitment. +func TestLegacyBreachRetributionUsesRevokedSigHash(t *testing.T) { + t.Parallel() + + channel, signer := newLiveAuxSignerChannel(t) + chanState := channel.channelState + dummyPrivate, _ := btcec.PrivKeyFromBytes([]byte{1}) + leaseExpiry, keyRing, _ := deriveDummyRetributionParams(chanState) + + // An HTLC that is dust only on a SigHashDefault commitment. Its + // stored output index is non-negative, so the dust check is what + // decides whether it is part of the retribution. + dustLimit := chanState.RemoteChanCfg.DustLimit + htlcAmt := dustLimit + 100 + + retribution := func(blob fn.Option[tlv.Blob]) *BreachRetribution { + revokedLog := chanState.RemoteCommitment + revokedLog.CustomBlob = blob + revokedLog.Htlcs = []channeldb.HTLC{{ + Incoming: true, + Amt: lnwire.NewMSatFromSatoshis(htlcAmt), + OutputIndex: 2, + }} + + ourScript := &WitnessScriptDesc{ + OutputScript: revokedLog.CommitTx.TxOut[0].PkScript, + } + theirScript := &WitnessScriptDesc{ + OutputScript: revokedLog.CommitTx.TxOut[1].PkScript, + } + + br, _, _, err := createBreachRetributionLegacy( + &revokedLog, chanState, keyRing, dummyPrivate, + ourScript, theirScript, leaseExpiry, + fn.Some[AuxSigner](signer), + ) + require.NoError(t, err) + + return br + } + + // Our latest local commitment records the legacy sighash. + require.True(t, chanState.LocalCommitment.CustomBlob.IsNone()) + + // The revoked state records SigHashDefault: the HTLC was trimmed. + br := retribution(fn.Some(sigHashDefaultBlob)) + require.Empty(t, br.HtlcRetributions) + + // The revoked state records the legacy sighash: the HTLC has an + // output that must be punished. + br = retribution(fn.None[tlv.Blob]()) + require.Len(t, br.HtlcRetributions, 1) +} + +// sigHashDefaultAuxSigner is an AuxSigner that reports SigHashDefault for +// every request, standing in for a channel whose every commitment was built +// with DeterministicHTLCs. +type sigHashDefaultAuxSigner struct { + *MockAuxSigner +} + +// HtlcSigHashType always answers SigHashDefault. +func (s *sigHashDefaultAuxSigner) HtlcSigHashType( + _ HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + return fn.Some(txscript.SigHashDefault) +} + +// TestSigHashDefaultResolutionSweepAmount asserts that the sweep sign +// descriptor of a SigHashDefault second-level HTLC resolution describes the +// output that is actually on chain. The pre-signed second-level tx splits +// its value between the HTLC output and the CPFP anchor, so the descriptor +// must carry the HTLC output's value with the anchor carved out. Signing a +// taproot spend against any other value yields an invalid signature and the +// output could never be swept. +func TestSigHashDefaultResolutionSweepAmount(t *testing.T) { + t.Parallel() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.TapscriptRootBit + + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err) + + // Build the commitments with SigHashDefault second-level HTLCs. + sigHashDefault := uint32(txscript.SigHashDefault) + aliceChannel.htlcSigHashType.Store(sigHashDefault) + bobChannel.htlcSigHashType.Store(sigHashDefault) + + // One HTLC from Alice to Bob, locked into both commitments. + preimage := bytes.Repeat([]byte{7}, 32) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(preimage), + Amount: lnwire.NewMSatFromSatoshis(100_000), + Expiry: uint32(10), + } + _, err = aliceChannel.AddHTLC(htlc, nil) + require.NoError(t, err) + _, err = bobChannel.ReceiveHTLC(htlc) + require.NoError(t, err) + require.NoError(t, ForceStateTransition(aliceChannel, bobChannel)) + + // The commitments on chain record SigHashDefault. + aliceChannel.auxSigner = fn.Some[AuxSigner](&sigHashDefaultAuxSigner{ + MockAuxSigner: NewDefaultAuxSignerMock(t), + }) + bobChannel.auxSigner = fn.Some[AuxSigner](&sigHashDefaultAuxSigner{ + MockAuxSigner: NewDefaultAuxSignerMock(t), + }) + + assertSweepDesc := func(secondLevelTx *wire.MsgTx, + sweepDesc input.SignDescriptor) { + + t.Helper() + + // HTLC output first, CPFP anchor second. + require.Len(t, secondLevelTx.TxOut, 2) + htlcOut := secondLevelTx.TxOut[0] + require.EqualValues( + t, AnchorSize, secondLevelTx.TxOut[1].Value, + ) + + // The sweep descriptor targets exactly the HTLC output. + require.Equal(t, htlcOut.Value, sweepDesc.Output.Value) + require.Equal(t, htlcOut.PkScript, sweepDesc.Output.PkScript) + + prevOut := sweepDesc.PrevOutputFetcher.FetchPrevOutput( + wire.OutPoint{}, + ) + require.Equal(t, htlcOut.Value, prevOut.Value) + require.Equal(t, htlcOut.PkScript, prevOut.PkScript) + } + + // Alice offered the HTLC, so her force close yields the timeout path. + aliceClose, err := aliceChannel.ForceClose() + require.NoError(t, err) + aliceRes, err := aliceClose.ContractResolutions.UnwrapOrErr( + errors.New("no resolutions"), + ) + require.NoError(t, err) + require.Len(t, aliceRes.HtlcResolutions.OutgoingHTLCs, 1) + outgoing := aliceRes.HtlcResolutions.OutgoingHTLCs[0] + require.NotNil(t, outgoing.SignedTimeoutTx) + assertSweepDesc(outgoing.SignedTimeoutTx, outgoing.SweepSignDesc) + + // Bob accepted it, so his force close yields the success path. + bobClose, err := bobChannel.ForceClose() + require.NoError(t, err) + bobRes, err := bobClose.ContractResolutions.UnwrapOrErr( + errors.New("no resolutions"), + ) + require.NoError(t, err) + require.Len(t, bobRes.HtlcResolutions.IncomingHTLCs, 1) + incoming := bobRes.HtlcResolutions.IncomingHTLCs[0] + require.NotNil(t, incoming.SignedSuccessTx) + assertSweepDesc(incoming.SignedSuccessTx, incoming.SweepSignDesc) +} diff --git a/lnwallet/commitment.go b/lnwallet/commitment.go index 78b82125b6e..adea61d7874 100644 --- a/lnwallet/commitment.go +++ b/lnwallet/commitment.go @@ -376,8 +376,11 @@ func CommitScriptToRemote(chanType channeldb.ChannelType, initiator bool, } } -// HtlcSigHashType returns the sighash type to use for HTLC success and timeout -// transactions given the channel type. +// HtlcSigHashType returns the default sighash type to use for HTLC success +// and timeout transactions given the channel type. For channels where an +// AuxSigner is available, use ResolveHtlcSigHashType instead, which queries +// the aux signer for a channel-specific override based on negotiated feature +// bits. func HtlcSigHashType(chanType channeldb.ChannelType) txscript.SigHashType { if chanType.HasAnchors() { return txscript.SigHashSingle | txscript.SigHashAnyOneCanPay @@ -506,12 +509,74 @@ func CommitWeight(chanType channeldb.ChannelType) lntypes.WeightUnit { } } +// SecondLevelTimeoutWeight is the weight of a pre-signed second-level HTLC +// timeout transaction under DeterministicHTLCs, including the appended CPFP +// anchor output. +func SecondLevelTimeoutWeight() lntypes.WeightUnit { + return lntypes.WeightUnit(input.TaprootHtlcTimeoutWeight) + + lntypes.WeightUnit(input.TaprootCommitmentAnchorOutput*4) +} + +// SecondLevelSuccessWeight is the weight of a pre-signed second-level HTLC +// success transaction under DeterministicHTLCs, including the appended CPFP +// anchor output. +func SecondLevelSuccessWeight() lntypes.WeightUnit { + return lntypes.WeightUnit(input.TaprootHtlcSuccessWeight) + + lntypes.WeightUnit(input.TaprootCommitmentAnchorOutput*4) +} + +// secondLevelMinFee is the fee a pre-signed second-level HTLC tx of the given +// weight carries: 1.1x the relay floor over its virtual size, a small margin +// that lets the tx clear the default min-relay fee on its own. A parent the +// mempool rejects outright cannot be CPFP'd by its own anchor, so this is a +// hard lower bound. +// +// It is also the upper bound. The fee cannot instead track the negotiated +// commitment fee rate, even though that would be equally deterministic, +// because the whole on-chain BTC value of an aux-channel HTLC is a small +// fixed budget that is already fully allocated: it pays this fee, funds the +// CPFP anchor (AnchorSize), and must still leave a second-level output large +// enough to be non-dust AND to fund the third-level sweep (the CSV sweep, or +// the justice sweep after a breach) that finally claims it. For the ~1200 sat +// budget aux channels use, a commitment fee rate of a few sat/vB alone +// exceeds the entire budget, and even capping the fee at what keeps the +// second-level output non-dust leaves that output unable to pay for its own +// sweep, stranding the asset value it carries. +// +// Adapting to the fee market is therefore the CPFP child's job, not the +// parent's. Where that is not enough (a mempool minimum above the parent's +// own rate, which a separately published child cannot fix), parent and child +// would have to be submitted together as a package. The sweeper does not do +// that yet: package submission only works on bitcoind today, btcd has no +// submitpackage and neutrino can only broadcast both transactions and hope a +// peer assembles them. Until those backends support 1P1C relay the parent is +// published on its own and retried on every block until it is accepted. +func secondLevelMinFee(weight lntypes.WeightUnit) btcutil.Amount { + const numerator, denominator = 11, 10 + + return (chainfee.FeePerKwFloor * numerator / denominator).FeeForWeight( + weight, + ) +} + // 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, this is the fee baked into the pre-signed +// second-level transaction, which is also what defines the dust threshold for +// the HTLC; see secondLevelMinFee for why it is pinned to the relay floor. 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, so it must + // always be able to clear min-relay on its own. This is also the + // value HtlcIsDust measures the HTLC against, since the fee is + // carved out of the HTLC's on-chain value. + case chanType.IsTaproot() && sigHashDefault: + return secondLevelMinFee(SecondLevelTimeoutWeight()) + // For zero-fee HTLC channels, this will always be zero, regardless of // feerate. case chanType.ZeroHtlcTxFee() || chanType.IsTaproot(): @@ -526,11 +591,18 @@ func HtlcTimeoutFee(chanType channeldb.ChannelType, } // HtlcSuccessFee returns the fee in satoshis required for an HTLC success -// transaction based on the current fee rate. +// transaction based on the current fee rate. When sigHashDefault is true and +// the channel is taproot, this is the fee baked into the pre-signed +// second-level transaction (see HtlcTimeoutFee). func HtlcSuccessFee(chanType channeldb.ChannelType, - feePerKw chainfee.SatPerKWeight) btcutil.Amount { + feePerKw chainfee.SatPerKWeight, + sigHashDefault bool) btcutil.Amount { switch { + // See HtlcTimeoutFee for the min-relay rationale. + case chanType.IsTaproot() && sigHashDefault: + return secondLevelMinFee(SecondLevelSuccessWeight()) + // For zero-fee HTLC channels, this will always be zero, regardless of // feerate. case chanType.ZeroHtlcTxFee() || chanType.IsTaproot(): @@ -711,12 +783,16 @@ type unsignedCommitmentTx struct { // createUnsignedCommitmentTx generates the unsigned commitment transaction for // a commitment view and returns it as part of the unsignedCommitmentTx. The // passed in balances should be balances *before* subtracting any commitment -// fees, but after anchor outputs. +// fees, but after anchor outputs. The sigHashDefault flag states whether the +// second-level HTLC transactions of this new commitment use SigHashDefault, +// which the aux leaf store is told and which decides which HTLCs are dust on +// it. func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, theirBalance lnwire.MilliSatoshi, whoseCommit lntypes.ChannelParty, feePerKw chainfee.SatPerKWeight, height uint64, originalHtlcView, filteredHTLCView *HtlcView, keyRing *CommitmentKeyRing, - prevCommit *commitment) (*unsignedCommitmentTx, error) { + prevCommit *commitment, + sigHashDefault bool) (*unsignedCommitmentTx, error) { dustLimit := cb.chanState.LocalChanCfg.DustLimit if whoseCommit.IsRemote() { @@ -728,6 +804,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, false, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -739,6 +816,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, true, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -788,7 +866,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, return auxLeavesFromView( s, cb.chanState, prevCommit.customBlob, originalHtlcView, whoseCommit, ourBalance, - theirBalance, *keyRing, + theirBalance, *keyRing, sigHashDefault, ) }, ).Unpack() @@ -853,6 +931,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, false, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue @@ -881,6 +960,7 @@ func (cb *CommitmentBuilder) createUnsignedCommitmentTx(ourBalance, if HtlcIsDust( cb.chanState.ChanType, true, whoseCommit, feePerKw, htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { continue diff --git a/lnwallet/htlc_sighash_commit_sig_test.go b/lnwallet/htlc_sighash_commit_sig_test.go new file mode 100644 index 00000000000..dd335596e06 --- /dev/null +++ b/lnwallet/htlc_sighash_commit_sig_test.go @@ -0,0 +1,748 @@ +package lnwallet + +import ( + "bytes" + "crypto/sha256" + "testing" + + "github.com/btcsuite/btcd/txscript/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// legacySigHashBlob is the commitment blob the sigHashLeafStore records for a +// commitment built with the legacy HTLC sighash. Any blob other than +// sigHashDefaultBlob reads as legacy, this one just makes the intent explicit. +var legacySigHashBlob = tlv.Blob("sighash-legacy") + +// sigHashLeafStore is an AuxLeafStore test double that does what a real leaf +// store must do with the sighash mode lnd hands it: record it in the blob of +// the new commitment. It also keeps the modes it was asked for, so a test can +// assert that both calls that build a commitment were given the same one. +type sigHashLeafStore struct { + MockAuxLeafStore + + viewModes []bool + blobModes []bool +} + +// FetchLeavesFromView records the mode the leaves were asked for. +func (s *sigHashLeafStore) FetchLeavesFromView( + in CommitDiffAuxInput) fn.Result[CommitDiffAuxResult] { + + s.viewModes = append(s.viewModes, in.SigHashDefault) + + return fn.Ok(CommitDiffAuxResult{}) +} + +// ApplyHtlcView returns the blob that records the given mode. +func (s *sigHashLeafStore) ApplyHtlcView( + in CommitDiffAuxInput) fn.Result[fn.Option[tlv.Blob]] { + + s.blobModes = append(s.blobModes, in.SigHashDefault) + + if in.SigHashDefault { + return fn.Ok(fn.Some(sigHashDefaultBlob)) + } + + return fn.Ok(fn.Some(legacySigHashBlob)) +} + +// unpackRecordingSigner is a liveAuxSigner that keeps every blob it was asked +// to unpack. +type unpackRecordingSigner struct { + *liveAuxSigner + + unpacked []tlv.Blob +} + +// UnpackSigs records the blob and defers to the mock. +func (s *unpackRecordingSigner) UnpackSigs( + blob fn.Option[tlv.Blob]) fn.Result[[]fn.Option[tlv.Blob]] { + + s.unpacked = append(s.unpacked, blob.UnwrapOr(nil)) + + return s.liveAuxSigner.UnpackSigs(blob) +} + +// sigHashParty is one side of a custom channel whose HTLC sighash mode is +// driven by a live feature negotiation. +type sigHashParty struct { + channel *LightningChannel + signer *unpackRecordingSigner + store *sigHashLeafStore +} + +// negotiate sets the live answer of the party's aux signer and has the +// channel pick it up, which is what happens when the channel is +// re-established. +func (p *sigHashParty) negotiate(live fn.Option[txscript.SigHashType]) { + p.signer.live = live + p.channel.RefreshHtlcSigHashType() +} + +// tipDefault returns whether the latest commitment on the given chain of the +// party records SigHashDefault. +func (p *sigHashParty) tipDefault(chain lntypes.ChannelParty) bool { + commitChain := p.channel.commitChains.Local + if chain.IsRemote() { + commitChain = p.channel.commitChains.Remote + } + + return p.channel.commitSigHashDefault(commitChain.tip().customBlob) +} + +// newSigHashParties creates a custom (tapscript root) channel between two +// parties that both start out on the legacy HTLC sighash, with the feature +// not negotiated. +func newSigHashParties(t *testing.T) (*sigHashParty, *sigHashParty) { + t.Helper() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.TapscriptRootBit + + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err) + + party := func(channel *LightningChannel) *sigHashParty { + p := &sigHashParty{ + channel: channel, + signer: &unpackRecordingSigner{ + liveAuxSigner: &liveAuxSigner{ + MockAuxSigner: NewDefaultAuxSignerMock( + t, + ), + }, + }, + store: &sigHashLeafStore{}, + } + + channel.auxSigner = fn.Some[AuxSigner](p.signer) + channel.leafStore = fn.Some[AuxLeafStore](p.store) + channel.commitBuilder.auxLeafStore = channel.leafStore + + // The leaf store is only consulted for a commitment that + // follows one with a blob, so the commitments the channel + // starts with get one. + legacy := fn.Some(legacySigHashBlob) + channel.channelState.LocalCommitment.CustomBlob = legacy + channel.channelState.RemoteCommitment.CustomBlob = legacy + channel.commitChains.Local.tip().customBlob = legacy + channel.commitChains.Remote.tip().customBlob = legacy + + channel.RefreshHtlcSigHashType() + require.False(t, channel.IsChanSigHashDefault()) + + return p + } + + return party(aliceChannel), party(bobChannel) +} + +// addSigHashHtlc adds an HTLC of the given amount from one party to the +// other, without committing to it. +func addSigHashHtlc(t *testing.T, from, to *sigHashParty, + amt lnwire.MilliSatoshi, id byte) { + + t.Helper() + + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(bytes.Repeat([]byte{id}, 32)), + Amount: amt, + Expiry: uint32(10), + } + htlcID, err := from.channel.AddHTLC(htlc, nil) + require.NoError(t, err) + htlc.ID = htlcID + _, err = to.channel.ReceiveHTLC(htlc) + require.NoError(t, err) +} + +// statesSigHashDefault returns whether the custom records of a +// commitment_signed state SigHashDefault. +func statesSigHashDefault(t *testing.T, auxSigBlob tlv.Blob) bool { + t.Helper() + + records, err := lnwire.ParseCustomRecords(auxSigBlob) + require.NoError(t, err) + + val, ok := records[uint64(commitSigHtlcSigHashType.TypeVal())] + if !ok { + return false + } + require.Equal(t, []byte{byte(txscript.SigHashDefault)}, val) + + return true +} + +// withSigHashRecord returns the given custom records blob with the HTLC +// sighash record set to the given value, or removed when the value is nil. +func withSigHashRecord(t *testing.T, auxSigBlob tlv.Blob, + val []byte) tlv.Blob { + + t.Helper() + + records, err := lnwire.ParseCustomRecords(auxSigBlob) + require.NoError(t, err) + if records == nil { + records = make(lnwire.CustomRecords) + } + + recordType := uint64(commitSigHtlcSigHashType.TypeVal()) + delete(records, recordType) + if val != nil { + records[recordType] = val + } + + blob, err := records.Serialize() + require.NoError(t, err) + + return blob +} + +// commitSigsFromMsg turns a commitment_signed message into what the link +// hands the channel when it receives one. +func commitSigsFromMsg(t *testing.T, msg *lnwire.CommitSig) *CommitSigs { + t.Helper() + + auxSigBlob, err := msg.CustomRecords.Serialize() + require.NoError(t, err) + + return &CommitSigs{ + CommitSig: msg.CommitSig, + HtlcSigs: msg.HtlcSigs, + PartialSig: msg.PartialSig, + AuxSigBlob: auxSigBlob, + } +} + +// completeSigHashTransition has the receiver of a commitment revoke its old +// one and sign one for the sender in return, and the sender do the same. +func completeSigHashTransition(t *testing.T, sender, receiver *sigHashParty) { + t.Helper() + + revocation, _, _, err := receiver.channel.RevokeCurrentCommitment() + require.NoError(t, err) + _, _, err = sender.channel.ReceiveRevocation(revocation) + require.NoError(t, err) + + commit, err := receiver.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + err = sender.channel.ReceiveNewCommitment(commit.CommitSigs) + require.NoError(t, err) + + revocation, _, _, err = sender.channel.RevokeCurrentCommitment() + require.NoError(t, err) + _, _, err = receiver.channel.ReceiveRevocation(revocation) + require.NoError(t, err) +} + +// sigHashHtlcAmounts returns an HTLC amount that has an output under both +// sighash modes, and one that has an output under the legacy sighash only. +func sigHashHtlcAmounts(t *testing.T, + channel *LightningChannel) (lnwire.MilliSatoshi, lnwire.MilliSatoshi) { + + t.Helper() + + state := channel.channelState + feePerKw := chainfee.SatPerKWeight(state.LocalCommitment.FeePerKw) + dustLimit := state.RemoteChanCfg.DustLimit + + between := dustLimit + 100 + for _, incoming := range []bool{true, false} { + for _, whose := range []lntypes.ChannelParty{ + lntypes.Local, lntypes.Remote, + } { + require.False(t, HtlcIsDust( + state.ChanType, incoming, whose, feePerKw, + between, dustLimit, false, + )) + require.True(t, HtlcIsDust( + state.ChanType, incoming, whose, feePerKw, + between, dustLimit, true, + )) + } + } + + return lnwire.NewMSatFromSatoshis(100_000), + lnwire.NewMSatFromSatoshis(between) +} + +// TestCommitSigStatesHtlcSigHash asserts that a commitment_signed states the +// HTLC sighash mode of the commitment it signs, that the receiver builds and +// verifies the commitment with the stated mode, and that both sides record +// the same mode for it. The leaf store is handed that mode for both the +// leaves and the blob, and the aux signer never sees the record. +func TestCommitSigStatesHtlcSigHash(t *testing.T) { + t.Parallel() + + alice, bob := newSigHashParties(t) + htlcAmt, _ := sigHashHtlcAmounts(t, alice.channel) + + // Without the feature the message is what it always was. + addSigHashHtlc(t, alice, bob, htlcAmt, 1) + commit, err := alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.Len(t, commit.HtlcSigs, 1) + require.False(t, statesSigHashDefault(t, commit.AuxSigBlob)) + require.NoError( + t, bob.channel.ReceiveNewCommitment(commit.CommitSigs), + ) + require.False(t, alice.tipDefault(lntypes.Remote)) + require.False(t, bob.tipDefault(lntypes.Local)) + completeSigHashTransition(t, alice, bob) + + // Every commitment so far was built as legacy, on both ends and for + // both the leaves and the blob. + for _, p := range []*sigHashParty{alice, bob} { + require.NotEmpty(t, p.store.viewModes) + require.NotContains(t, p.store.viewModes, true) + require.NotEmpty(t, p.store.blobModes) + require.NotContains(t, p.store.blobModes, true) + + p.store.viewModes, p.store.blobModes = nil, nil + p.signer.unpacked = nil + } + + // Once the feature is negotiated the next commitment uses + // SigHashDefault and says so. + alice.negotiate(fn.Some(txscript.SigHashDefault)) + bob.negotiate(fn.Some(txscript.SigHashDefault)) + + addSigHashHtlc(t, alice, bob, htlcAmt, 2) + commit, err = alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.Len(t, commit.HtlcSigs, 2) + require.True(t, statesSigHashDefault(t, commit.AuxSigBlob)) + require.NoError( + t, bob.channel.ReceiveNewCommitment(commit.CommitSigs), + ) + require.True(t, alice.tipDefault(lntypes.Remote)) + require.True(t, bob.tipDefault(lntypes.Local)) + + // The aux signer got its own records and nothing else. + require.Len(t, bob.signer.unpacked, 1) + require.NotEmpty(t, bob.signer.unpacked[0]) + require.Equal( + t, withSigHashRecord(t, commit.AuxSigBlob, nil), + bob.signer.unpacked[0], + ) + + // The commitments Bob signs in return follow the same rule. + completeSigHashTransition(t, alice, bob) + require.True(t, bob.tipDefault(lntypes.Remote)) + require.True(t, alice.tipDefault(lntypes.Local)) + + for _, p := range []*sigHashParty{alice, bob} { + require.NotEmpty(t, p.store.viewModes) + require.NotContains(t, p.store.viewModes, false) + require.NotEmpty(t, p.store.blobModes) + require.NotContains(t, p.store.blobModes, false) + } +} + +// TestSigHashUpgradeWithPendingCommitSig asserts that a commitment_signed +// that was signed before both peers negotiated the feature is still accepted +// when it is retransmitted after they did. The receiver refreshes its view of +// the negotiation before it processes the retransmission, so it must take +// the sighash mode from the message: verifying a legacy signature as +// SigHashDefault fails and force closes the channel. The HTLC that sits +// between the two dust thresholds makes the two modes disagree about the +// commitment transaction itself, not only about the HTLC signatures. +func TestSigHashUpgradeWithPendingCommitSig(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + betweenDust bool + numLegacySigs int + numDefaultSigs int + }{{ + name: "htlc above both dust limits", + numLegacySigs: 1, + numDefaultSigs: 2, + }, { + name: "htlc between the dust limits", + betweenDust: true, + numLegacySigs: 1, + numDefaultSigs: 1, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + alice, bob := newSigHashParties(t) + htlcAmt, between := sigHashHtlcAmounts( + t, alice.channel, + ) + pendingAmt := htlcAmt + if tc.betweenDust { + pendingAmt = between + } + + // Alice signs a legacy commitment for Bob, who never + // gets the message. + addSigHashHtlc(t, alice, bob, pendingAmt, 1) + lost, err := alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.Len(t, lost.HtlcSigs, tc.numLegacySigs) + require.False( + t, statesSigHashDefault(t, lost.AuxSigBlob), + ) + + // Both upgrade, reconnect and negotiate the feature. + // The channel picks that up before the sync messages + // are processed. + _, err = alice.channel.GenMusigNonces() + require.NoError(t, err) + _, err = bob.channel.GenMusigNonces() + require.NoError(t, err) + + aliceState := alice.channel.channelState + aliceSync, err := aliceState.ChanSyncMsg() + require.NoError(t, err) + bobState := bob.channel.channelState + bobSync, err := bobState.ChanSyncMsg() + require.NoError(t, err) + + alice.negotiate(fn.Some(txscript.SigHashDefault)) + bob.negotiate(fn.Some(txscript.SigHashDefault)) + require.True(t, alice.channel.IsChanSigHashDefault()) + require.True(t, bob.channel.IsChanSigHashDefault()) + + // Alice retransmits the HTLC and the commitment as it + // was signed, Bob has nothing to send. + msgs, _, _, err := alice.channel.ProcessChanSyncMsg( + ctxb, bobSync, + ) + require.NoError(t, err) + require.Len(t, msgs, 2) + retransmit, ok := msgs[1].(*lnwire.CommitSig) + require.True(t, ok) + + bobMsgs, _, _, err := bob.channel.ProcessChanSyncMsg( + ctxb, aliceSync, + ) + require.NoError(t, err) + require.Empty(t, bobMsgs) + + // The retransmission still reads as legacy, and Bob + // accepts it as such although his next commitments + // would use SigHashDefault. + commitSigs := commitSigsFromMsg(t, retransmit) + require.False(t, statesSigHashDefault( + t, commitSigs.AuxSigBlob, + )) + require.NoError( + t, bob.channel.ReceiveNewCommitment(commitSigs), + ) + require.False(t, alice.tipDefault(lntypes.Remote)) + require.False(t, bob.tipDefault(lntypes.Local)) + + // The commitment Bob signs in return is a new one, so + // it uses SigHashDefault. + completeSigHashTransition(t, alice, bob) + require.True(t, bob.tipDefault(lntypes.Remote)) + require.True(t, alice.tipDefault(lntypes.Local)) + + // And so does the next one Alice signs. The HTLC + // between the dust limits no longer has an output on + // it. + addSigHashHtlc(t, alice, bob, htlcAmt, 2) + next, err := alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.Len(t, next.HtlcSigs, tc.numDefaultSigs) + require.True( + t, statesSigHashDefault(t, next.AuxSigBlob), + ) + require.NoError(t, bob.channel.ReceiveNewCommitment( + next.CommitSigs, + )) + require.True(t, alice.tipDefault(lntypes.Remote)) + require.True(t, bob.tipDefault(lntypes.Local)) + completeSigHashTransition(t, alice, bob) + }) + } +} + +// TestSigHashDefaultCommitSigRetransmitted asserts that a commitment_signed +// that states SigHashDefault is accepted when it is retransmitted in a later +// connection, and that the mode of a chain does not depend on the live +// negotiation once its latest commitment uses SigHashDefault: the sender +// keeps signing with it and the receiver keeps accepting it. +func TestSigHashDefaultCommitSigRetransmitted(t *testing.T) { + t.Parallel() + + alice, bob := newSigHashParties(t) + htlcAmt, _ := sigHashHtlcAmounts(t, alice.channel) + + alice.negotiate(fn.Some(txscript.SigHashDefault)) + bob.negotiate(fn.Some(txscript.SigHashDefault)) + + // The first SigHashDefault commitment is lost on the way to Bob. + addSigHashHtlc(t, alice, bob, htlcAmt, 1) + lost, err := alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.True(t, statesSigHashDefault(t, lost.AuxSigBlob)) + + _, err = alice.channel.GenMusigNonces() + require.NoError(t, err) + _, err = bob.channel.GenMusigNonces() + require.NoError(t, err) + + aliceSync, err := alice.channel.channelState.ChanSyncMsg() + require.NoError(t, err) + bobSync, err := bob.channel.channelState.ChanSyncMsg() + require.NoError(t, err) + + msgs, _, _, err := alice.channel.ProcessChanSyncMsg(ctxb, bobSync) + require.NoError(t, err) + require.Len(t, msgs, 2) + retransmit, ok := msgs[1].(*lnwire.CommitSig) + require.True(t, ok) + _, _, _, err = bob.channel.ProcessChanSyncMsg(ctxb, aliceSync) + require.NoError(t, err) + + commitSigs := commitSigsFromMsg(t, retransmit) + require.True(t, statesSigHashDefault(t, commitSigs.AuxSigBlob)) + require.NoError(t, bob.channel.ReceiveNewCommitment(commitSigs)) + require.True(t, bob.tipDefault(lntypes.Local)) + completeSigHashTransition(t, alice, bob) + + // The live negotiation is gone, as it is between a restart and the + // peer reconnecting. Alice's own latest commitment is the only thing + // her cached answer falls back to, so point that at a legacy blob to + // have the answer for new commitments go back to legacy. + legacy := fn.Some(legacySigHashBlob) + alice.channel.channelState.LocalCommitment.CustomBlob = legacy + bob.channel.channelState.LocalCommitment.CustomBlob = legacy + alice.negotiate(fn.None[txscript.SigHashType]()) + bob.negotiate(fn.None[txscript.SigHashType]()) + require.False(t, alice.channel.IsChanSigHashDefault()) + require.False(t, bob.channel.IsChanSigHashDefault()) + + // Both chains still use SigHashDefault. + require.True(t, alice.channel.nextSigHashDefault(lntypes.Remote)) + require.True(t, bob.channel.nextSigHashDefault(lntypes.Local)) + + addSigHashHtlc(t, alice, bob, htlcAmt, 2) + commit, err := alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.True(t, statesSigHashDefault(t, commit.AuxSigBlob)) + require.NoError( + t, bob.channel.ReceiveNewCommitment(commit.CommitSigs), + ) + require.True(t, bob.tipDefault(lntypes.Local)) +} + +// TestCommitSigHtlcSigHashRejected asserts the cases in which the receiver +// refuses the HTLC sighash mode a commitment_signed states, and that it does +// so before it looks at any signature. +func TestCommitSigHtlcSigHashRejected(t *testing.T) { + t.Parallel() + + sigHashDefault := []byte{byte(txscript.SigHashDefault)} + + testCases := []struct { + name string + + // negotiated is whether the feature is negotiated, in which + // case one SigHashDefault commitment is exchanged first. + negotiated bool + + // record is the value the record of the commitment_signed is + // replaced with, nil removes it. + record []byte + + expectedErr error + }{{ + name: "sighash default without the feature", + record: sigHashDefault, + expectedErr: ErrHtlcSigHashTypeNotNegotiated, + }, { + name: "back to legacy after sighash default", + negotiated: true, + expectedErr: ErrHtlcSigHashTypeReverted, + }, { + name: "unknown sighash type", + negotiated: true, + record: []byte{byte(txscript.SigHashAll)}, + expectedErr: ErrUnknownHtlcSigHashType, + }, { + name: "empty record", + negotiated: true, + record: []byte{}, + expectedErr: ErrUnknownHtlcSigHashType, + }, { + name: "record too long", + negotiated: true, + record: []byte{byte(txscript.SigHashDefault), 0}, + expectedErr: ErrUnknownHtlcSigHashType, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + alice, bob := newSigHashParties(t) + htlcAmt, _ := sigHashHtlcAmounts(t, alice.channel) + + if tc.negotiated { + defaultType := fn.Some(txscript.SigHashDefault) + alice.negotiate(defaultType) + bob.negotiate(defaultType) + + addSigHashHtlc(t, alice, bob, htlcAmt, 1) + require.NoError(t, ForceStateTransition( + alice.channel, bob.channel, + )) + require.True(t, bob.tipDefault(lntypes.Local)) + } + + addSigHashHtlc(t, alice, bob, htlcAmt, 2) + commit, err := alice.channel.SignNextCommitment(ctxb) + require.NoError(t, err) + + tipBefore := bob.channel.commitChains.Local.tip() + bob.signer.unpacked = nil + + commit.AuxSigBlob = withSigHashRecord( + t, commit.AuxSigBlob, tc.record, + ) + err = bob.channel.ReceiveNewCommitment( + commit.CommitSigs, + ) + require.ErrorIs(t, err, tc.expectedErr) + + // Nothing was verified and nothing changed. + require.Empty(t, bob.signer.unpacked) + require.Same( + t, tipBefore, + bob.channel.commitChains.Local.tip(), + ) + }) + } +} + +// TestCommitSigHtlcSigHashCustomOnly asserts that the HTLC sighash record is +// a matter of custom channels only. The commitment_signed of any other +// channel never carries it, and a record under that type on a message such a +// channel receives is not interpreted: it stays in the custom records, as +// every custom record did before. +func TestCommitSigHtlcSigHashCustomOnly(t *testing.T) { + t.Parallel() + + chanType := channeldb.SimpleTaprootFeatureBit + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err) + require.False(t, aliceChannel.statesHtlcSigHashType()) + + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(bytes.Repeat([]byte{1}, 32)), + Amount: lnwire.NewMSatFromSatoshis(100_000), + Expiry: uint32(10), + } + _, err = aliceChannel.AddHTLC(htlc, nil) + require.NoError(t, err) + _, err = bobChannel.ReceiveHTLC(htlc) + require.NoError(t, err) + + commit, err := aliceChannel.SignNextCommitment(ctxb) + require.NoError(t, err) + require.False(t, statesSigHashDefault(t, commit.AuxSigBlob)) + + // A record under our type changes nothing for Bob: the commitment is + // verified with the standard sighash of the channel type and the + // records are passed on untouched. + withRecord := withSigHashRecord( + t, commit.AuxSigBlob, []byte{byte(txscript.SigHashDefault)}, + ) + sigHashDefault, auxSigBlob, err := bobChannel.receivedSigHashDefault( + withRecord, + ) + require.NoError(t, err) + require.False(t, sigHashDefault) + require.Equal(t, withRecord, auxSigBlob) + + commit.AuxSigBlob = withRecord + require.NoError( + t, bobChannel.ReceiveNewCommitment(commit.CommitSigs), + ) + + // A custom channel without an aux signer cannot use anything but the + // standard sighash either. + customType := chanType | channeldb.TapscriptRootBit + customChannel, _, err := CreateTestChannels(t, customType) + require.NoError(t, err) + require.True(t, customChannel.statesHtlcSigHashType()) + customChannel.auxSigner = fn.None[AuxSigner]() + require.False(t, customChannel.statesHtlcSigHashType()) +} + +// TestComputeViewSigHashMode asserts that the view of a commitment is +// evaluated with the sighash mode it is given, for the HTLCs of both parties. +// An HTLC between the two dust thresholds adds its weight to a legacy +// commitment and none to a SigHashDefault one. The mode the channel would use +// for its next commitment must not leak into it. +func TestComputeViewSigHashMode(t *testing.T) { + t.Parallel() + + alice, bob := newSigHashParties(t) + _, between := sigHashHtlcAmounts(t, alice.channel) + addSigHashHtlc(t, alice, bob, between, 1) + + // The amount sits between the dust thresholds of Bob's commitment, + // which is the remote chain for Alice and the local one for Bob. + testCases := []struct { + name string + party *sigHashParty + chain lntypes.ChannelParty + }{{ + // The HTLC is one of Alice's own updates. + name: "offered htlc", + party: alice, + chain: lntypes.Remote, + }, { + // The HTLC is one of the remote party's updates for Bob. + name: "received htlc", + party: bob, + chain: lntypes.Local, + }} + + for _, tc := range testCases { + channel := tc.party.channel + weight := func(sigHashDefault bool) lntypes.WeightUnit { + view := channel.fetchHTLCView( + channel.updateLogs.Remote.logIndex, + channel.updateLogs.Local.logIndex, + ) + _, _, weight, _, err := channel.computeView( + view, tc.chain, false, + fn.None[chainfee.SatPerKWeight](), + sigHashDefault, + ) + require.NoError(t, err, tc.name) + + return weight + } + + for _, live := range []fn.Option[txscript.SigHashType]{ + fn.None[txscript.SigHashType](), + fn.Some(txscript.SigHashDefault), + } { + tc.party.negotiate(live) + + require.Equal( + t, weight(true)+input.HTLCWeight, + weight(false), tc.name, + ) + } + } +} diff --git a/lnwallet/mock.go b/lnwallet/mock.go index 166353aaded..9ca85df0aa4 100644 --- a/lnwallet/mock.go +++ b/lnwallet/mock.go @@ -14,6 +14,7 @@ import ( "github.com/btcsuite/btcd/chaincfg/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/btcsuite/btcwallet/waddrmgr" base "github.com/btcsuite/btcwallet/wallet" @@ -559,6 +560,13 @@ func (a *MockAuxSigner) VerifySecondLevelSigs(chanState AuxChanState, return args.Error(0) } +// HtlcSigHashType returns None, deferring to the default sighash behavior. +func (a *MockAuxSigner) HtlcSigHashType( + _ HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + return fn.None[txscript.SigHashType]() +} + type MockAuxContractResolver struct{} // ResolveContract is called to resolve a contract that needs diff --git a/lnwallet/transactions.go b/lnwallet/transactions.go index 397f2413a64..80a852aa2dc 100644 --- a/lnwallet/transactions.go +++ b/lnwallet/transactions.go @@ -2,6 +2,7 @@ package lnwallet import ( "encoding/binary" + "errors" "fmt" "github.com/btcsuite/btcd/btcec/v2" @@ -49,10 +50,15 @@ var ( // In order to spend the segwit v1 (taproot) HTLC output, the witness for the // passed transaction should be: // - +// +// When addAnchor is true, a taproot anchor output is appended that the +// broadcaster can sweep for CPFP fee bumping. AnchorSize sats are taken +// from htlcAmt to fund it. addAnchor is only set on DeterministicHTLCs +// (SigHashDefault) paths, where the pre-signed tx can't be RBF'd. func CreateHtlcSuccessTx(chanType channeldb.ChannelType, initiator bool, htlcOutput wire.OutPoint, htlcAmt btcutil.Amount, csvDelay, leaseExpiry uint32, revocationKey, delayKey *btcec.PublicKey, - auxLeaf input.AuxTapLeaf) (*wire.MsgTx, error) { + auxLeaf input.AuxTapLeaf, addAnchor bool) (*wire.MsgTx, error) { // Create a version two transaction (as the success version of this // spends an output with a CSV timeout). @@ -78,16 +84,67 @@ func CreateHtlcSuccessTx(chanType channeldb.ChannelType, initiator bool, return nil, err } + // The HTLC output absorbs the anchor's AnchorSize when an anchor is + // being added; otherwise the full htlcAmt goes to the HTLC output. + htlcOutValue := htlcAmt + if addAnchor { + htlcOutValue -= AnchorSize + } + // Finally, the output is simply the amount of the HTLC (minus the // required fees), paying to the timeout script. successTx.AddTxOut(&wire.TxOut{ - Value: int64(htlcAmt), + Value: int64(htlcOutValue), PkScript: scriptInfo.PkScript(), }) + if addAnchor { + _, anchorPkScript, err := SecondLevelAnchorScript(delayKey) + if err != nil { + return nil, err + } + successTx.AddTxOut(&wire.TxOut{ + Value: int64(AnchorSize), + PkScript: anchorPkScript, + }) + } + return successTx, nil } +// ErrNoSecondLevelDelayKey is returned when the anchor script of a +// second-level HTLC transaction is requested without a delay key. +var ErrNoSecondLevelDelayKey = errors.New("second-level anchor needs a " + + "delay key") + +// SecondLevelAnchorScript returns the script tree and the output script of +// the CPFP anchor appended to a pre-signed (SigHashDefault) second-level HTLC +// transaction. The anchor is keyed to the delay key of the party that +// broadcasts the transaction, the same key its HTLC output is swept with, so +// that party can spend it via key path right away while anyone can sweep it +// after 16 blocks. The builders of the second-level transactions and the +// resolvers that later reconstruct the anchor input must agree on this +// script, which is why there is a single place computing it. +func SecondLevelAnchorScript( + delayKey *btcec.PublicKey) (*input.AnchorScriptTree, []byte, error) { + + if delayKey == nil { + return nil, nil, ErrNoSecondLevelDelayKey + } + + anchorTree, err := input.NewAnchorScriptTree(delayKey) + if err != nil { + return nil, nil, err + } + + anchorPkScript, err := input.PayToTaprootScript(anchorTree.TaprootKey) + if err != nil { + return nil, nil, err + } + + return anchorTree, anchorPkScript, nil +} + // CreateHtlcTimeoutTx creates a transaction that spends the HTLC output on the // commitment transaction of the peer that created an HTLC (the sender). This // transaction essentially acts as an off-chain covenant as it spends a 2-of-2 @@ -108,11 +165,14 @@ func CreateHtlcSuccessTx(chanType channeldb.ChannelType, initiator bool, // NOTE: The passed amount for the HTLC should take into account the required // fee rate at the time the HTLC was created. The fee should be able to // entirely pay for this (tiny: 1-in 1-out) transaction. +// +// When addAnchor is true, a taproot anchor output is appended that the +// broadcaster can sweep for CPFP fee bumping. See CreateHtlcSuccessTx. func CreateHtlcTimeoutTx(chanType channeldb.ChannelType, initiator bool, htlcOutput wire.OutPoint, htlcAmt btcutil.Amount, cltvExpiry, csvDelay, leaseExpiry uint32, revocationKey, delayKey *btcec.PublicKey, - auxLeaf input.AuxTapLeaf) (*wire.MsgTx, error) { + auxLeaf input.AuxTapLeaf, addAnchor bool) (*wire.MsgTx, error) { // Create a version two transaction (as the success version of this // spends an output with a CSV timeout), and set the lock-time to the @@ -142,13 +202,31 @@ func CreateHtlcTimeoutTx(chanType channeldb.ChannelType, initiator bool, return nil, err } + // The HTLC output absorbs the anchor's AnchorSize when an anchor is + // being added; otherwise the full htlcAmt goes to the HTLC output. + htlcOutValue := htlcAmt + if addAnchor { + htlcOutValue -= AnchorSize + } + // Finally, the output is simply the amount of the HTLC (minus the // required fees), paying to the regular second level HTLC script. timeoutTx.AddTxOut(&wire.TxOut{ - Value: int64(htlcAmt), + Value: int64(htlcOutValue), PkScript: scriptInfo.PkScript(), }) + if addAnchor { + _, anchorPkScript, err := SecondLevelAnchorScript(delayKey) + if err != nil { + return nil, err + } + timeoutTx.AddTxOut(&wire.TxOut{ + Value: int64(AnchorSize), + PkScript: anchorPkScript, + }) + } + return timeoutTx, nil } diff --git a/lnwallet/transactions_test.go b/lnwallet/transactions_test.go index 1ae21d88701..ba2a5a704b1 100644 --- a/lnwallet/transactions_test.go +++ b/lnwallet/transactions_test.go @@ -1075,3 +1075,132 @@ func createTestChannelsForVectors(tc *testContext, chanType channeldb.ChannelTyp return channelRemote, channelLocal } + +// TestSecondLevelAnchorScript asserts that the anchor script the second-level +// tx builders append is the one the resolvers derive from the same delay key, +// and that it needs a key. +func TestSecondLevelAnchorScript(t *testing.T) { + t.Parallel() + + delayPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + delayKey := delayPriv.PubKey() + + tree, pkScript, err := SecondLevelAnchorScript(delayKey) + require.NoError(t, err) + require.Equal(t, delayKey, tree.InternalKey) + + expectedTree, err := input.NewAnchorScriptTree(delayKey) + require.NoError(t, err) + expectedPkScript, err := input.PayToTaprootScript( + expectedTree.TaprootKey, + ) + require.NoError(t, err) + require.Equal(t, expectedTree.TapscriptRoot, tree.TapscriptRoot) + require.Equal(t, expectedPkScript, pkScript) + + // A different key yields a different script, so a tx built for one + // commitment point cannot be mistaken for another's. + otherPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + _, otherPkScript, err := SecondLevelAnchorScript(otherPriv.PubKey()) + require.NoError(t, err) + require.NotEqual(t, pkScript, otherPkScript) + + _, _, err = SecondLevelAnchorScript(nil) + require.ErrorIs(t, err, ErrNoSecondLevelDelayKey) +} + +// TestCreateHtlcTxAnchorOutput asserts the shape of the pre-signed +// second-level HTLC transactions: with addAnchor set they gain a CPFP anchor +// output keyed to the broadcaster's delay key, with its value carved out of +// the HTLC output, and without it the transaction is unchanged. +func TestCreateHtlcTxAnchorOutput(t *testing.T) { + t.Parallel() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + revPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + delayPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + revKey := revPriv.PubKey() + delayKey := delayPriv.PubKey() + + _, anchorPkScript, err := SecondLevelAnchorScript(delayKey) + require.NoError(t, err) + + op := wire.OutPoint{Index: 1} + htlcAmt := btcutil.Amount(100_000) + noLeaf := input.NoneTapLeaf() + + testCases := []struct { + name string + success bool + addAnchor bool + numOutputs int + htlcValue btcutil.Amount + anchor *wire.TxOut + }{{ + name: "timeout without anchor", + numOutputs: 1, + htlcValue: htlcAmt, + }, { + name: "timeout with anchor", + addAnchor: true, + numOutputs: 2, + htlcValue: htlcAmt - AnchorSize, + anchor: &wire.TxOut{ + Value: int64(AnchorSize), + PkScript: anchorPkScript, + }, + }, { + name: "success without anchor", + success: true, + numOutputs: 1, + htlcValue: htlcAmt, + }, { + name: "success with anchor", + success: true, + addAnchor: true, + numOutputs: 2, + htlcValue: htlcAmt - AnchorSize, + anchor: &wire.TxOut{ + Value: int64(AnchorSize), + PkScript: anchorPkScript, + }, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var ( + tx *wire.MsgTx + err error + ) + if tc.success { + tx, err = CreateHtlcSuccessTx( + chanType, false, op, htlcAmt, 5, 0, + revKey, delayKey, noLeaf, tc.addAnchor, + ) + } else { + tx, err = CreateHtlcTimeoutTx( + chanType, false, op, htlcAmt, 100, 5, + 0, revKey, delayKey, noLeaf, + tc.addAnchor, + ) + } + require.NoError(t, err) + + require.Len(t, tx.TxOut, tc.numOutputs) + require.EqualValues(t, tc.htlcValue, tx.TxOut[0].Value) + + if tc.anchor != nil { + require.Equal(t, tc.anchor, tx.TxOut[1]) + } + }) + } +} diff --git a/server.go b/server.go index 3c4227a3c12..734be57ea5c 100644 --- a/server.go +++ b/server.go @@ -2031,6 +2031,7 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr, channel, commitHeight, 0, nil, implCfg.AuxLeafStore, implCfg.AuxContractResolver, + implCfg.AuxSigner, ) if err != nil { return nil, 0, err diff --git a/sweep/presigned.go b/sweep/presigned.go new file mode 100644 index 00000000000..98b11689228 --- /dev/null +++ b/sweep/presigned.go @@ -0,0 +1,676 @@ +package sweep + +import ( + "bytes" + "errors" + "fmt" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/chainntnfs" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/lnwallet" +) + +var ( + // ErrInvalidPreSignedTxRequest is returned by PublishPreSignedTx when + // the request is malformed. The wrapped error names the field. + ErrInvalidPreSignedTxRequest = errors.New("invalid pre-signed tx " + + "request") + + // ErrPreSignedTxConflict is returned when a pre-signed transaction + // can never confirm because one of its inputs was spent by a + // different, confirmed transaction. + ErrPreSignedTxConflict = errors.New("pre-signed tx input spent by " + + "a conflicting transaction") +) + +// PreSignedTxRequest asks the sweeper to take ownership of the lifecycle of a +// fully signed, immutable transaction: publish it verbatim once its locktime +// allows, keep re-broadcasting it on every block until the broadcast +// succeeds, and once it is in the mempool, CPFP it through the given anchor +// input. Such transactions cannot be rebuilt, aggregated or RBF'd by the +// sweeper (the counterparty's signature commits to the whole tx), so the +// anchor child is their only fee-bumping path. +type PreSignedTxRequest struct { + // Tx is the fully signed transaction to publish verbatim. + Tx *wire.MsgTx + + // SpentOutputs are the outputs Tx spends, one per input of Tx and in + // the same order. The sweeper watches them for a confirmed spend, + // which is the only evidence it accepts that Tx either confirmed or + // can never confirm. + SpentOutputs []*wire.TxOut + + // HeightHint is the height from which the inputs of Tx are watched, + // so a spend that confirmed while we were offline is still found. + HeightHint uint32 + + // Label is the wallet label attached to the broadcast. + Label string + + // Anchor is the CPFP anchor output of Tx, as a sweepable input. It is + // optional: without it the sweeper only publishes Tx. + Anchor input.Input + + // Budget bounds the fees the sweeper may spend on the anchor child. + Budget btcutil.Amount + + // DeadlineHeight is the height Tx should be confirmed by. It is passed + // to the anchor sweep, where it drives the fee rate of the child. It + // does not bound the lifecycle: the output Tx claims stays claimable + // past that height, so publication and anchor registration keep being + // retried until an input of Tx is spent on chain. + DeadlineHeight fn.Option[int32] +} + +// preSignedTxMessage carries a PreSignedTxRequest into the collector loop. +type preSignedTxMessage struct { + req PreSignedTxRequest + resultChan chan Result +} + +// preSignedTxState is the collector-owned state of one pre-signed tx. +type preSignedTxState struct { + req PreSignedTxRequest + + // listeners receive the single final Result of this lifecycle. + listeners []chan Result + + // watching is set once a spend notification is registered for every + // input of the tx. + watching bool + + // cancelWatch cancels the registered spend notifications. + cancelWatch []func() + + // confirmed is set once the chain notifier reported the tx itself as + // the spender of one of its inputs. From then on there is nothing + // left to publish, unless that confirmation is re-orged out, which + // clears the flag again. + confirmed bool + + // published is set once PublishTx accepted the transaction. + published bool + + // anchorOffered is set once the anchor input is registered with the + // sweeper's regular input machinery. + anchorOffered bool +} + +// preSignedAnchorResult carries the final result of an anchor sweep back +// into the collector loop. +type preSignedAnchorResult struct { + txid chainhash.Hash + result Result +} + +// preSignedSpend carries an event of the watch on one of the inputs of a +// pre-signed tx into the collector loop: either a confirmed spend of that +// input, or the re-org of a spend reported earlier. +type preSignedSpend struct { + txid chainhash.Hash + + // spend is the confirmed spend. It is nil for a re-org. + spend *chainntnfs.SpendDetail + + // reorged is set when the spend reported last for this input was + // re-orged out of the chain. + reorged bool +} + +// PublishPreSignedTx hands a pre-signed transaction to the sweeper, which +// owns its lifecycle from here on: publication (gated on the tx locktime and +// retried on every block), anchor CPFP registration, and the final outcome. +// +// The returned channel receives exactly one Result. The lifecycle ends in +// one of these ways only: +// - our anchor child confirmed: Result.Tx is the child (or the pre-signed +// tx itself when there is no anchor to sweep and the tx was published). +// - the anchor was spent by someone else: ErrRemoteSpend. +// - an input of the pre-signed tx was spent by a different, confirmed +// transaction: ErrPreSignedTxConflict. +// - the sweeper shut down: ErrSweeperShuttingDown. +// +// Everything else is retried on every block: a rejected publication, a +// failed anchor registration, and an anchor sweep that failed because its +// parent left the mempool (evicted or replaced), which nobody else would +// re-broadcast. The deadline only drives the fee rate of the anchor child; +// it never ends the lifecycle, since the output the tx claims stays +// claimable past it. Whether the tx confirmed or can no longer confirm is +// decided by the chain notifier alone: a publication error that reports an +// input as spent is retried like any other, until the spend confirms. +// A confirmation of the tx that is re-orged out takes it back to +// publication. +// +// Nothing is persisted: like regular sweep inputs, the caller re-submits the +// request after a restart, at which point an already-published tx is a +// no-op broadcast and the anchor is simply re-registered. +func (s *UtxoSweeper) PublishPreSignedTx( + req PreSignedTxRequest) (<-chan Result, error) { + + if err := validatePreSignedTxRequest(req); err != nil { + return nil, err + } + + msg := &preSignedTxMessage{ + req: req, + resultChan: make(chan Result, 1), + } + + select { + case s.preSignedReqs <- msg: + case <-s.quit: + return nil, ErrSweeperShuttingDown + } + + return msg.resultChan, nil +} + +// validatePreSignedTxRequest checks that a request is well formed: a tx with +// one spent output per input, and an anchor, when given, that is a well +// formed input describing an output the tx actually has. +func validatePreSignedTxRequest(req PreSignedTxRequest) error { + if req.Tx == nil { + return fmt.Errorf("%w: nil tx", ErrInvalidPreSignedTxRequest) + } + + if len(req.SpentOutputs) != len(req.Tx.TxIn) { + return fmt.Errorf("%w: %d spent outputs for %d inputs", + ErrInvalidPreSignedTxRequest, len(req.SpentOutputs), + len(req.Tx.TxIn)) + } + for i, txOut := range req.SpentOutputs { + if txOut == nil || len(txOut.PkScript) == 0 { + return fmt.Errorf("%w: spent output %d has no script", + ErrInvalidPreSignedTxRequest, i) + } + } + + if req.Anchor == nil { + return nil + } + + if req.Anchor.OutPoint() == input.EmptyOutPoint || + req.Anchor.SignDesc() == nil { + + return fmt.Errorf("%w: anchor is not a well formed input", + ErrInvalidPreSignedTxRequest) + } + anchorOp := req.Anchor.OutPoint() + if anchorOp.Hash != req.Tx.TxHash() { + return fmt.Errorf("%w: anchor %v does not belong to tx %v", + ErrInvalidPreSignedTxRequest, anchorOp, + req.Tx.TxHash()) + } + + // The anchor must be an output the tx really has, described the way + // the tx creates it. An outpoint past the last output, or one whose + // script differs, could never fund a child. + if int(anchorOp.Index) >= len(req.Tx.TxOut) { + return fmt.Errorf("%w: anchor %v is not an output of the tx, "+ + "which has %d", ErrInvalidPreSignedTxRequest, anchorOp, + len(req.Tx.TxOut)) + } + + txOut := req.Tx.TxOut[anchorOp.Index] + anchorOut := req.Anchor.SignDesc().Output + if anchorOut == nil || anchorOut.Value != txOut.Value || + !bytes.Equal(anchorOut.PkScript, txOut.PkScript) { + + return fmt.Errorf("%w: anchor %v does not describe output "+ + "%d of the tx", ErrInvalidPreSignedTxRequest, anchorOp, + anchorOp.Index) + } + + return nil +} + +// handlePreSignedTxReq registers a new pre-signed tx with the collector and +// immediately attempts to make progress on it (publishing it if its locktime +// already allows), so a request made between blocks doesn't idle until the +// next one. +func (s *UtxoSweeper) handlePreSignedTxReq(msg *preSignedTxMessage) { + txid := msg.req.Tx.TxHash() + + // A duplicate request (resolver relaunch, restart) attaches as an + // additional listener to the in-flight lifecycle. + if st, ok := s.preSigned[txid]; ok { + log.Infof("Pre-signed tx %v already tracked, adding listener", + txid) + st.listeners = append(st.listeners, msg.resultChan) + + return + } + + st := &preSignedTxState{ + req: msg.req, + listeners: []chan Result{msg.resultChan}, + } + s.preSigned[txid] = st + + log.Infof("Registered pre-signed tx %v (locktime=%d, anchor=%v, "+ + "budget=%v, deadline=%v) at height %d", txid, + msg.req.Tx.LockTime, msg.req.Anchor != nil, msg.req.Budget, + msg.req.DeadlineHeight, s.currentHeight) + + s.progressPreSignedTx(txid, st) +} + +// processPreSignedTxs is called on every new block and drives each tracked +// pre-signed tx one step further. +func (s *UtxoSweeper) processPreSignedTxs() { + for txid, st := range s.preSigned { + s.progressPreSignedTx(txid, st) + } +} + +// progressPreSignedTx performs whatever step the given pre-signed tx is +// waiting for at the current height: watching its inputs, then publication, +// then anchor registration. A failed step is retried on the next block. +func (s *UtxoSweeper) progressPreSignedTx(txid chainhash.Hash, + st *preSignedTxState) { + + // Step 0: watch the inputs of the tx. A confirmed spend of any of + // them is what tells us the tx confirmed, or that it never will. + // Without the watch in place we could publish and then miss the + // spend, so this comes first. + if !st.watching { + if err := s.watchPreSignedTxInputs(txid, st); err != nil { + s.retryPreSignedTx(txid, st, fmt.Errorf( + "watch inputs of pre-signed tx: %w", err)) + + return + } + } + + // Step 1: publication, gated on the locktime. A locktime'd tx is only + // final once the chain has reached that height. A tx the chain + // notifier already reported as confirmed has nothing to publish. + if !st.published && !st.confirmed { + if uint32(s.currentHeight) < st.req.Tx.LockTime { + log.Debugf("Pre-signed tx %v waiting for locktime %d "+ + "(height=%d)", txid, st.req.Tx.LockTime, + s.currentHeight) + + return + } + + err := s.cfg.Wallet.PublishTransaction(st.req.Tx, st.req.Label) + switch { + // The backend reports an input as already spent. That is not + // proof of anything: the backend maps a missing input to the + // same error, a conflicting spend in the mempool can still be + // evicted, and a commitment that is temporarily gone after a + // re-org comes back. Only a confirmed spend reported by the + // chain notifier ends the lifecycle, so keep retrying. + case errors.Is(err, lnwallet.ErrDoubleSpend): + s.retryPreSignedTx(txid, st, fmt.Errorf("publish "+ + "pre-signed tx, waiting for the chain "+ + "notifier to decide whether the reported "+ + "spend confirms: %w", err)) + + return + + case err != nil: + s.retryPreSignedTx(txid, st, fmt.Errorf( + "publish pre-signed tx: %w", err)) + + return + } + + st.published = true + log.Infof("Published pre-signed tx %v at height %d", txid, + s.currentHeight) + } + + // Step 2: without an anchor there is nothing left to supervise. + if st.req.Anchor == nil { + s.finishPreSignedTx(txid, st, Result{Tx: st.req.Tx}) + + return + } + + // The anchor is already being swept, its result will come in through + // handlePreSignedAnchorResult. + if st.anchorOffered { + return + } + + // An earlier sweep of the anchor that failed leaves its input behind + // in a final state until the next block prunes it. Offering the + // anchor now would only attach us to that dead entry, which is then + // deleted without ever producing a result. Wait for the prune. + anchorOp := st.req.Anchor.OutPoint() + if pi, ok := s.inputs[anchorOp]; ok && pi.terminated() { + s.retryPreSignedTx(txid, st, fmt.Errorf("anchor %v of "+ + "pre-signed tx is still tracked in state %v", anchorOp, + pi.state)) + + return + } + + // Register the anchor with the regular sweep machinery. This runs + // inline in the collector, so a nil error is a real acknowledgement + // that the spend notification is registered and the input is being + // swept; from here on the sweeper's own retry and fee-bumping logic + // owns the child. + // + // The anchor spends an unconfirmed parent, so it must not share a + // sweep tx with any other input: if the parent is evicted or + // replaced, the child fails with missing inputs and that failure + // would otherwise take every batched input down with it. + anchorResult := make(chan Result, 1) + err := s.handleNewInput(&sweepInputMessage{ + input: st.req.Anchor, + params: Params{ + Budget: st.req.Budget, + DeadlineHeight: st.req.DeadlineHeight, + NoInputBatch: true, + }, + resultChan: anchorResult, + }) + if err != nil { + s.retryPreSignedTx(txid, st, fmt.Errorf( + "register anchor of pre-signed tx: %w", err)) + + return + } + + st.anchorOffered = true + log.Infof("Registered CPFP anchor %v of pre-signed tx %v (budget=%v, "+ + "deadline=%v)", st.req.Anchor.OutPoint(), txid, st.req.Budget, + st.req.DeadlineHeight) + + // Forward the anchor's final result back into the collector so the + // lifecycle can conclude without blocking the main loop. + s.wg.Add(1) + go func() { + defer s.wg.Done() + + select { + case result, ok := <-anchorResult: + if !ok { + return + } + + select { + case s.preSignedAnchorResults <- &preSignedAnchorResult{ + txid: txid, + result: result, + }: + case <-s.quit: + } + + case <-s.quit: + } + }() +} + +// watchPreSignedTxInputs registers a spend notification for every input of +// the pre-signed tx and forwards every spend of each, and every re-org of +// such a spend, into the collector. +// Either all inputs are watched afterwards or none is. +func (s *UtxoSweeper) watchPreSignedTxInputs(txid chainhash.Hash, + st *preSignedTxState) error { + + cancels := make([]func(), 0, len(st.req.Tx.TxIn)) + cancelAll := func() { + for _, cancel := range cancels { + cancel() + } + } + + for i, txIn := range st.req.Tx.TxIn { + op := txIn.PreviousOutPoint + spendEvent, err := s.cfg.Notifier.RegisterSpendNtfn( + &op, st.req.SpentOutputs[i].PkScript, + st.req.HeightHint, + ) + if err != nil { + cancelAll() + + return fmt.Errorf("register spend ntfn for %v: %w", + op, err) + } + cancels = append(cancels, spendEvent.Cancel) + + s.wg.Add(1) + go func() { + defer s.wg.Done() + + // The watch outlives the first spend: a confirmed + // spend can be re-orged out and the input spent + // again, possibly by a different tx. It ends when the + // registration is cancelled, which closes its + // channels, or when the notifier is done with it + // because the spend reached the re-org safety depth. + for { + var ( + event *preSignedSpend + done bool + ) + select { + case spend, ok := <-spendEvent.Spend: + if !ok { + return + } + + event = &preSignedSpend{ + txid: txid, + spend: spend, + } + + case _, ok := <-spendEvent.Reorg: + if !ok { + return + } + + event = &preSignedSpend{ + txid: txid, + reorged: true, + } + + // The notifier dropped the registration, so + // nothing else will arrive and a later Cancel + // closes nothing. A spend may still sit + // unread in its channel, as both can be ready + // at once, so it is forwarded before leaving. + case <-spendEvent.Done: + done = true + + select { + case spend, ok := <-spendEvent.Spend: + if !ok { + return + } + + event = &preSignedSpend{ + txid: txid, + spend: spend, + } + + default: + return + } + + case <-s.quit: + return + } + + select { + case s.preSignedSpends <- event: + case <-s.quit: + return + } + + if done { + return + } + } + }() + } + + st.watching = true + st.cancelWatch = cancels + + log.Debugf("Watching %d input(s) of pre-signed tx %v from height %d", + len(cancels), txid, st.req.HeightHint) + + return nil +} + +// retryPreSignedTx logs a failed step and leaves the tx to be retried on the +// next block. +func (s *UtxoSweeper) retryPreSignedTx(txid chainhash.Hash, + st *preSignedTxState, stepErr error) { + + log.Warnf("Pre-signed tx %v: %v, retrying on next block (height=%d, "+ + "deadline=%v)", txid, stepErr, s.currentHeight, + st.req.DeadlineHeight) +} + +// handlePreSignedSpend acts on an event of the watch on one of the inputs of +// a pre-signed tx. For a confirmed spend, the tx itself as the spender means +// it confirmed: nothing is left to publish, only the anchor still needs to be +// swept. Any other spender means the tx can never confirm, which ends the +// lifecycle. A re-org of the tx's own confirmation takes it back to the +// publish step. +func (s *UtxoSweeper) handlePreSignedSpend(ps *preSignedSpend) { + st, ok := s.preSigned[ps.txid] + if !ok { + log.Debugf("Spend of an input of unknown pre-signed tx %v", + ps.txid) + + return + } + + if ps.reorged { + s.handlePreSignedReorg(ps.txid, st) + + return + } + + spender := *ps.spend.SpenderTxHash + if spender != ps.txid { + log.Infof("Input %v of pre-signed tx %v spent by %v at "+ + "height %d, giving up", ps.spend.SpentOutPoint, + ps.txid, spender, ps.spend.SpendingHeight) + + s.finishPreSignedTx(ps.txid, st, Result{ + Err: fmt.Errorf("%w: spent by %v", + ErrPreSignedTxConflict, spender), + }) + + return + } + + log.Infof("Pre-signed tx %v confirmed at height %d", ps.txid, + ps.spend.SpendingHeight) + + st.confirmed = true + st.published = true + + // A confirmed tx is past publication. If the anchor is not being + // swept yet (the publication kept failing, or the tx confirmed while + // we were offline), register it now. + s.progressPreSignedTx(ps.txid, st) +} + +// handlePreSignedReorg acts on a confirmed spend of an input of a pre-signed +// tx being re-orged out of the chain. The event does not say which spend that +// was, and it can be the first event seen for the input: the notifier drops +// a spend nobody read yet when it dispatches the re-org. So this never +// depends on the confirmation having been seen. Nothing guarantees the tx is +// in the mempool, and nobody else re-broadcasts it, so it is published again +// right away and on every block until it is accepted, whether or not its +// anchor is being swept. An anchor sweep that is still running is left alone: +// if the parent is really gone its child fails with a missing input, which +// registers the anchor anew once the parent is back. +func (s *UtxoSweeper) handlePreSignedReorg(txid chainhash.Hash, + st *preSignedTxState) { + + log.Warnf("Spend of an input of pre-signed tx %v re-orged out at "+ + "height %d, retrying publication", txid, s.currentHeight) + + st.confirmed = false + st.published = false + + s.progressPreSignedTx(txid, st) +} + +// handlePreSignedAnchorResult acts on the final result of the anchor sweep +// of a pre-signed tx. +func (s *UtxoSweeper) handlePreSignedAnchorResult(r *preSignedAnchorResult) { + st, ok := s.preSigned[r.txid] + if !ok { + log.Debugf("Anchor result for unknown pre-signed tx %v", r.txid) + + return + } + + switch { + // Our child confirmed, which means the parent did too. + case r.result.Err == nil: + if r.result.Tx != nil { + log.Infof("Anchor of pre-signed tx %v swept by tx=%v", + r.txid, r.result.Tx.TxHash()) + } + + s.finishPreSignedTx(r.txid, st, r.result) + + // Someone else spent the anchor. Once the parent has been confirmed + // for 16 blocks the output is anyone-can-spend, so this is the + // expected outcome when our own child never confirmed. Either way + // CPFP is moot now. + case errors.Is(r.result.Err, ErrRemoteSpend): + log.Debugf("Anchor of pre-signed tx %v spent by a third party", + r.txid) + + s.finishPreSignedTx(r.txid, st, r.result) + + // The anchor sweep gave up. The usual reason is a parent that left + // the mempool (evicted or replaced), which the child reports as a + // missing input. Nobody else re-broadcasts the parent and the output + // it claims is still ours, so go back to the publish step instead of + // concluding. The fatal anchor input is pruned from the sweeper on + // the next block, before the lifecycle is progressed again, so the + // anchor can then be registered afresh. The same holds for any other + // failure of the child: the lifecycle only ends with a spend. + default: + log.Warnf("Anchor sweep of pre-signed tx %v failed: %v, "+ + "going back to publishing the parent", r.txid, + r.result.Err) + + st.published = false + st.anchorOffered = false + } +} + +// finishPreSignedTx delivers the final result to every listener and drops the +// tx from the tracked set. +func (s *UtxoSweeper) finishPreSignedTx(txid chainhash.Hash, + st *preSignedTxState, result Result) { + + for _, cancel := range st.cancelWatch { + cancel() + } + + // Channels are buffered and only ever written once, so this never + // blocks. + for _, listener := range st.listeners { + listener <- result + } + + delete(s.preSigned, txid) +} + +// failPreSignedTxs concludes every tracked pre-signed tx with the given error. +// Used on shutdown so callers blocked on a result are released. +func (s *UtxoSweeper) failPreSignedTxs(err error) { + for txid, st := range s.preSigned { + s.finishPreSignedTx(txid, st, Result{Err: err}) + } +} diff --git a/sweep/presigned_test.go b/sweep/presigned_test.go new file mode 100644 index 00000000000..359925de654 --- /dev/null +++ b/sweep/presigned_test.go @@ -0,0 +1,1650 @@ +package sweep + +import ( + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/chainio" + "github.com/lightningnetwork/lnd/chainntnfs" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// preSignedTxCounter makes every test tx unique. +var preSignedTxCounter atomic.Uint32 + +// preSignedTestHarness bundles a sweeper built on mocks with the pieces the +// pre-signed tx tests poke at. +type preSignedTestHarness struct { + s *UtxoSweeper + wallet *MockWallet + notifier *chainntnfs.MockChainNotifier + store *MockSweeperStore +} + +// newPreSignedTestHarness creates a sweeper whose collector is NOT running, +// so the tests drive its handlers synchronously, the way the rest of the +// sweeper unit tests do. +func newPreSignedTestHarness(t *testing.T) *preSignedTestHarness { + t.Helper() + + wallet := &MockWallet{} + notifier := &chainntnfs.MockChainNotifier{} + store := NewMockSweeperStore() + aggregator := &mockUtxoAggregator{} + estimator := &chainfee.MockEstimator{} + + t.Cleanup(func() { + wallet.AssertExpectations(t) + notifier.AssertExpectations(t) + store.AssertExpectations(t) + aggregator.AssertExpectations(t) + }) + + // The pre-signed lifecycle never clusters or publishes sweeps itself, + // but the collector's block handling does, so give it an aggregator + // that produces no sets. + aggregator.On("ClusterInputs", mock.Anything).Return( + []InputSet{}, + ).Maybe() + estimator.On("RelayFeePerKW").Return( + chainfee.FeePerKwFloor, + ).Maybe() + + s := New(&UtxoSweeperConfig{ + Wallet: wallet, + Notifier: notifier, + Store: store, + Aggregator: aggregator, + FeeEstimator: estimator, + NoDeadlineConfTarget: 100, + }) + s.currentHeight = 100 + + return &preSignedTestHarness{ + s: s, + wallet: wallet, + notifier: notifier, + store: store, + } +} + +// newPreSignedTx builds a two-output pre-signed tx (HTLC output + anchor) +// with the given locktime and the anchor input spending its index 1. +func newPreSignedTx(t *testing.T, lockTime uint32) (*wire.MsgTx, input.Input) { + t.Helper() + + priv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + // Give every tx a distinct prevout so two txs built in the same test + // never collide on txid. + tx := wire.NewMsgTx(2) + tx.LockTime = lockTime + tx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Index: preSignedTxCounter.Add(1), + }, + }) + tx.AddTxOut(&wire.TxOut{Value: 630, PkScript: []byte{0x51}}) + tx.AddTxOut(&wire.TxOut{Value: 330, PkScript: []byte{0x52}}) + + op := wire.OutPoint{Hash: tx.TxHash(), Index: 1} + signDesc := &input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{PubKey: priv.PubKey()}, + Output: tx.TxOut[1], + HashType: txscript.SigHashDefault, + } + anchor := input.MakeBaseInput( + &op, input.TaprootAnchorSweepSpend, signDesc, 100, + &input.TxInfo{Fee: 227, Weight: 817}, + ) + + return tx, &anchor +} + +// spentOutputs returns the outputs a test tx spends, one per input. +func spentOutputs(tx *wire.MsgTx) []*wire.TxOut { + outs := make([]*wire.TxOut, len(tx.TxIn)) + for i := range outs { + outs[i] = &wire.TxOut{Value: 1200, PkScript: []byte{0x53}} + } + + return outs +} + +// newRequest builds a well formed request for the given tx. +func newRequest(tx *wire.MsgTx, anchor input.Input) PreSignedTxRequest { + return PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + HeightHint: 90, + Label: "test", + Anchor: anchor, + } +} + +// spendWatch is a mocked spend registration: the channel the test delivers +// the spend on, and how often the registration was cancelled. +type spendWatch struct { + spend chan *chainntnfs.SpendDetail + reorg chan struct{} + done chan struct{} + cancelled atomic.Int32 +} + +// expectSpendRegistration mocks a successful spend registration for the +// given outpoint. +func (h *preSignedTestHarness) expectSpendRegistration( + op wire.OutPoint) *spendWatch { + + w := &spendWatch{ + spend: make(chan *chainntnfs.SpendDetail, 1), + } + h.notifier.On( + "RegisterSpendNtfn", &op, mock.Anything, mock.Anything, + ).Return(&chainntnfs.SpendEvent{ + Spend: w.spend, + Cancel: func() { + w.cancelled.Add(1) + }, + }, nil).Once() + + return w +} + +// expectInputWatch mocks the spend registration the lifecycle makes for the +// single input of a test tx, asserting it is made with the spent output's +// script and the request's height hint. +func (h *preSignedTestHarness) expectInputWatch( + req PreSignedTxRequest) *spendWatch { + + op := req.Tx.TxIn[0].PreviousOutPoint + w := &spendWatch{ + spend: make(chan *chainntnfs.SpendDetail, 1), + reorg: make(chan struct{}, 1), + done: make(chan struct{}, 1), + } + h.notifier.On( + "RegisterSpendNtfn", &op, req.SpentOutputs[0].PkScript, + req.HeightHint, + ).Return(&chainntnfs.SpendEvent{ + Spend: w.spend, + Reorg: w.reorg, + Done: w.done, + Cancel: func() { + w.cancelled.Add(1) + }, + }, nil).Once() + + return w +} + +// submit hands a request to the collector handler directly and returns the +// listener channel. +func (h *preSignedTestHarness) submit(t *testing.T, + req PreSignedTxRequest) chan Result { + + t.Helper() + + resultChan := make(chan Result, 1) + h.s.handlePreSignedTxReq(&preSignedTxMessage{ + req: req, + resultChan: resultChan, + }) + + return resultChan +} + +// nextBlock mimics what the collector does on a new block: prune final-state +// inputs, then drive the pre-signed txs. +func (h *preSignedTestHarness) nextBlock() { + h.s.currentHeight++ + h.s.updateSweeperInputs() + h.s.processPreSignedTxs() +} + +// spendInput hands the collector a confirmed spend of the input of the given +// tx by the given spender, the way the input watch delivers it. +func (h *preSignedTestHarness) spendInput(tx, spender *wire.MsgTx) { + op := tx.TxIn[0].PreviousOutPoint + spenderHash := spender.TxHash() + h.s.handlePreSignedSpend(&preSignedSpend{ + txid: tx.TxHash(), + spend: &chainntnfs.SpendDetail{ + SpentOutPoint: &op, + SpendingTx: spender, + SpenderTxHash: &spenderHash, + SpendingHeight: h.s.currentHeight, + }, + }) +} + +// reorgInput hands the collector the re-org of the spend last reported for +// the input of the given tx, the way the input watch delivers it. +func (h *preSignedTestHarness) reorgInput(tx *wire.MsgTx) { + h.s.handlePreSignedSpend(&preSignedSpend{ + txid: tx.TxHash(), + reorged: true, + }) +} + +// conflictingTx builds a tx that spends the same input as the given tx. +func conflictingTx(tx *wire.MsgTx) *wire.MsgTx { + conflict := wire.NewMsgTx(2) + conflict.AddTxIn(&wire.TxIn{ + PreviousOutPoint: tx.TxIn[0].PreviousOutPoint, + }) + conflict.AddTxOut(&wire.TxOut{Value: 1}) + + return conflict +} + +// failAnchorMissingParent mimics what the sweeper does when the anchor child +// can no longer be published because its parent left the mempool: the anchor +// input is marked fatal and its ErrInputMissing result is handed to the +// lifecycle. +func (h *preSignedTestHarness) failAnchorMissingParent(tx *wire.MsgTx, + anchor input.Input) { + + h.s.inputs[anchor.OutPoint()].state = Fatal + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Err: ErrInputMissing}, + }) +} + +// requireNoResult asserts that no final result has been delivered. +func requireNoResult(t *testing.T, resultChan <-chan Result) { + t.Helper() + + select { + case r := <-resultChan: + t.Fatalf("unexpected result: %v", r) + default: + } +} + +// requireResult waits for the final result of a lifecycle. +func requireResult(t *testing.T, resultChan <-chan Result) Result { + t.Helper() + + select { + case r := <-resultChan: + return r + case <-time.After(5 * time.Second): + t.Fatal("no result delivered") + } + + return Result{} +} + +// TestPublishPreSignedTxValidation asserts the synchronous validation of a +// request: a tx is required, every input needs its spent output, and an +// anchor, when given, must be a well formed input that actually belongs to +// the tx. Every rejection wraps ErrInvalidPreSignedTxRequest. +func TestPublishPreSignedTxValidation(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + otherTx, otherAnchor := newPreSignedTx(t, 0) + + emptyAnchor := &input.MockInput{} + emptyAnchor.On("OutPoint").Return(input.EmptyOutPoint) + + // anchorAt builds an anchor input claiming the given output index of + // tx, described by the given output. + anchorAt := func(index uint32, txOut *wire.TxOut) input.Input { + op := wire.OutPoint{Hash: tx.TxHash(), Index: index} + anchor := input.MakeBaseInput( + &op, input.TaprootAnchorSweepSpend, + &input.SignDescriptor{Output: txOut}, 100, nil, + ) + + return &anchor + } + anchorOut := tx.TxOut[1] + + testCases := []struct { + name string + req PreSignedTxRequest + ok bool + }{{ + name: "nil tx", + req: PreSignedTxRequest{}, + }, { + name: "no spent outputs", + req: PreSignedTxRequest{Tx: tx}, + }, { + name: "too many spent outputs", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: append( + spentOutputs(tx), spentOutputs(otherTx)..., + ), + }, + }, { + name: "spent output without script", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: []*wire.TxOut{{Value: 1}}, + }, + }, { + name: "empty anchor", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: emptyAnchor, + }, + }, { + name: "anchor of another tx", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: otherAnchor, + }, + }, { + name: "anchor index past the last output", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: anchorAt(2, anchorOut), + }, + }, { + name: "anchor without output", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: anchorAt(1, nil), + }, + }, { + name: "anchor with the script of another output", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: anchorAt(1, &wire.TxOut{ + Value: anchorOut.Value, + PkScript: tx.TxOut[0].PkScript, + }), + }, + }, { + name: "anchor with another value", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: anchorAt(1, &wire.TxOut{ + Value: anchorOut.Value + 1, + PkScript: anchorOut.PkScript, + }), + }, + }, { + name: "anchor at another index than 1", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + Anchor: anchorAt(0, tx.TxOut[0]), + }, + ok: true, + }, { + name: "well formed without anchor", + req: PreSignedTxRequest{ + Tx: tx, + SpentOutputs: spentOutputs(tx), + }, + ok: true, + }, { + name: "well formed with anchor", + req: newRequest(tx, anchor), + ok: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if tc.ok { + require.NoError( + t, validatePreSignedTxRequest(tc.req), + ) + + return + } + + // The public API rejects the request before it + // reaches the collector. The collector is not + // running, so a request that is let through would + // block: run the call on the side to fail instead. + errChan := make(chan error, 1) + go func() { + _, err := h.s.PublishPreSignedTx(tc.req) + errChan <- err + }() + + select { + case err := <-errChan: + require.ErrorIs( + t, err, ErrInvalidPreSignedTxRequest, + ) + + case <-time.After(5 * time.Second): + t.Fatal("request was not rejected") + } + }) + } + + require.Empty(t, h.s.preSigned) +} + +// TestPreSignedTxLocktimeGate asserts that a tx whose locktime lies in the +// future is not published until the chain reaches that height, while its +// inputs are watched from the start. +func TestPreSignedTxLocktimeGate(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 102) + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + resultChan := h.submit(t, req) + + st := h.s.preSigned[tx.TxHash()] + require.True(t, st.watching) + require.False(t, st.published) + requireNoResult(t, resultChan) + + // Height 101 is still below the locktime. + h.nextBlock() + require.False(t, st.published) + + // Height 102 reaches it: publish and register the anchor. + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() + + require.True(t, st.published) + require.True(t, st.anchorOffered) + require.Contains(t, h.s.inputs, anchor.OutPoint()) + requireNoResult(t, resultChan) +} + +// TestPreSignedTxInputWatchRetry asserts that nothing is published before +// the inputs of the tx are watched: a failed spend registration is retried +// on the next block, and only then does the publication follow. +func TestPreSignedTxInputWatchRetry(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + htlcOp := tx.TxIn[0].PreviousOutPoint + + h.notifier.On( + "RegisterSpendNtfn", &htlcOp, mock.Anything, mock.Anything, + ).Return(nil, errors.New("notifier down")).Once() + resultChan := h.submit(t, req) + + st := h.s.preSigned[tx.TxHash()] + require.False(t, st.watching) + require.False(t, st.published, "must not publish unwatched") + requireNoResult(t, resultChan) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() + + require.True(t, st.watching) + require.True(t, st.published) + require.True(t, st.anchorOffered) +} + +// TestPreSignedTxPublishRetry asserts that a rejected publication is retried +// on every block for as long as it takes, past the deadline included: the +// deadline is an urgency target for the anchor child, not the point at +// which the output stops being claimable. Once the mempool accepts the +// parent, the anchor is registered and nothing is repeated afterwards. +func TestPreSignedTxPublishRetry(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + req.DeadlineHeight = fn.Some(int32(102)) + + // A persistent fee rejection: the mempool minimum sits above the + // parent's fixed fee rate. Submission at height 100 and the blocks + // 101 to 105 all fail, three of them past the deadline. + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrMempoolFee, + ).Times(6) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + + for range 5 { + h.nextBlock() + require.False(t, st.published) + require.False(t, st.anchorOffered) + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) + } + require.Greater(t, h.s.currentHeight, int32(102), + "the test must run past the deadline") + + // The fee market relaxes and the parent is accepted: CPFP follows. + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() + + require.True(t, st.published) + require.True(t, st.anchorOffered) + require.Contains(t, h.s.inputs, anchor.OutPoint()) + + // Further blocks must not re-publish or re-register (the mocks are + // .Once(), so a second call would fail the test). + h.nextBlock() + h.nextBlock() + requireNoResult(t, resultChan) +} + +// TestPreSignedTxNoDeadlineKeepsRetrying asserts that without a deadline a +// failing publication is retried indefinitely as well. +func TestPreSignedTxNoDeadlineKeepsRetrying(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, _ := newPreSignedTx(t, 0) + req := newRequest(tx, nil) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + errors.New("rejected"), + ).Times(6) + resultChan := h.submit(t, req) + + for range 5 { + h.nextBlock() + } + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) +} + +// TestPreSignedTxAnchorRegistrationRetry asserts the registration +// acknowledgement boundary: when the anchor cannot be registered (spend +// notification registration fails), the lifecycle does NOT consider the +// anchor offered, and retries the registration on every block, past the +// deadline included, without repeating the publication. +func TestPreSignedTxAnchorRegistrationRetry(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + op := anchor.OutPoint() + req := newRequest(tx, anchor) + req.DeadlineHeight = fn.Some(int32(101)) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.notifier.On( + "RegisterSpendNtfn", &op, mock.Anything, mock.Anything, + ).Return(nil, errors.New("notifier down")).Times(3) + + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + require.True(t, st.published, "publication must not be redone") + require.False(t, st.anchorOffered, + "a failed registration is not an acknowledgement") + requireNoResult(t, resultChan) + + // Blocks 101 and 102 (past the deadline) retry and fail again. + h.nextBlock() + h.nextBlock() + require.False(t, st.anchorOffered) + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) + + // Block 103: the registration succeeds. + h.expectSpendRegistration(op) + h.nextBlock() + require.True(t, st.anchorOffered) + require.Contains(t, h.s.inputs, op) + require.Equal(t, Init, h.s.inputs[op].state) +} + +// TestPreSignedTxWithoutAnchor asserts that a tx without an anchor concludes +// successfully as soon as it is published, with the tx itself as the result, +// and that its input watch is cancelled. +func TestPreSignedTxWithoutAnchor(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, _ := newPreSignedTx(t, 0) + req := newRequest(tx, nil) + + watch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + resultChan := h.submit(t, req) + + result := requireResult(t, resultChan) + require.NoError(t, result.Err) + require.Equal(t, tx.TxHash(), result.Tx.TxHash()) + require.NotContains(t, h.s.preSigned, tx.TxHash()) + require.EqualValues(t, 1, watch.cancelled.Load()) +} + +// TestPreSignedTxDuplicateRequest asserts that re-submitting an in-flight tx +// (resolver relaunch) attaches an additional listener instead of restarting +// the lifecycle, and that every listener receives the final result. +func TestPreSignedTxDuplicateRequest(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + + first := h.submit(t, req) + second := h.submit(t, req) + + st := h.s.preSigned[tx.TxHash()] + require.Len(t, st.listeners, 2) + + // Conclude via the anchor result path. + child := wire.NewMsgTx(2) + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Tx: child}, + }) + + for _, c := range []chan Result{first, second} { + result := requireResult(t, c) + require.NoError(t, result.Err) + require.Equal(t, child.TxHash(), result.Tx.TxHash()) + } + require.NotContains(t, h.s.preSigned, tx.TxHash()) +} + +// TestPreSignedTxAnchorOutcomes asserts which anchor sweep results conclude +// the lifecycle: our child confirming, and a third-party spend of the +// anchor. Both imply the parent confirmed. +func TestPreSignedTxAnchorOutcomes(t *testing.T) { + t.Parallel() + + child := wire.NewMsgTx(2) + child.AddTxOut(&wire.TxOut{Value: 1}) + + testCases := []struct { + name string + result Result + }{{ + name: "swept by our child", + result: Result{Tx: child}, + }, { + name: "remote spend of the anchor", + result: Result{Err: ErrRemoteSpend}, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + watch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test"). + Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + requireNoResult(t, resultChan) + + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: tc.result, + }) + + result := requireResult(t, resultChan) + require.Equal(t, tc.result, result) + require.NotContains(t, h.s.preSigned, tx.TxHash()) + require.EqualValues(t, 1, watch.cancelled.Load()) + + // No re-offer must follow a final result. + h.nextBlock() + requireNoResult(t, resultChan) + }) + } +} + +// TestPreSignedTxAnchorFailureRepublishes asserts that a terminal failure of +// the anchor sweep other than a third-party spend does not conclude the +// lifecycle: the output is still ours to claim, so the lifecycle goes back +// to publishing the parent and offers the anchor again on the next block. +func TestPreSignedTxAnchorFailureRepublishes(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + + h.s.inputs[anchor.OutPoint()].state = Fatal + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Err: ErrNotEnoughBudget}, + }) + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) + require.False(t, st.published) + require.False(t, st.anchorOffered) + + // The next block re-publishes (a no-op for a tx still in the + // mempool) and registers the anchor afresh. + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() + require.True(t, st.published) + require.True(t, st.anchorOffered) + requireNoResult(t, resultChan) +} + +// TestPreSignedTxAnchorNotBatched asserts that the anchor is registered with +// input batching disabled. It spends an unconfirmed parent, so a missing +// parent must only ever fail the anchor's own sweep tx, never the sweeps of +// unrelated inputs that happen to share its deadline. +func TestPreSignedTxAnchorNotBatched(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + req.Budget = 1_000 + req.DeadlineHeight = fn.Some(int32(200)) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.submit(t, req) + + pi, ok := h.s.inputs[anchor.OutPoint()] + require.True(t, ok) + require.True(t, pi.params.NoInputBatch) + require.Nil(t, pi.params.ExclusiveGroup) + require.Equal(t, btcutil.Amount(1_000), pi.params.Budget) + require.Equal(t, fn.Some(int32(200)), pi.params.DeadlineHeight, + "the deadline drives the fee rate of the child") +} + +// TestPreSignedTxParentEvicted asserts that a missing-input failure of the +// anchor sweep does not conclude the lifecycle. The parent left the mempool +// (evicted or replaced) and nobody else re-broadcasts it, so the lifecycle +// must go back to publishing the parent and then register the anchor again. +func TestPreSignedTxParentEvicted(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + require.True(t, st.anchorOffered) + + // The child fails because the parent is gone. The lifecycle is not + // concluded and falls back to the publish step. + h.failAnchorMissingParent(tx, anchor) + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) + require.False(t, st.published) + require.False(t, st.anchorOffered) + + // The next block re-broadcasts the parent. The first attempt is + // rejected (the mempool minimum is still above its fee rate), which + // is retried like any other failed publication. + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrMempoolFee, + ).Once() + h.nextBlock() + require.False(t, st.published) + require.NotContains(t, h.s.inputs, anchor.OutPoint()) + requireNoResult(t, resultChan) + + // Once the parent is accepted again, the anchor is registered anew. + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() + require.True(t, st.published) + require.True(t, st.anchorOffered) + require.Contains(t, h.s.inputs, anchor.OutPoint()) + requireNoResult(t, resultChan) + + // A final result of the re-registered anchor concludes as usual. + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Err: ErrRemoteSpend}, + }) + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrRemoteSpend) +} + +// TestPreSignedTxParentEvictedPastDeadline asserts that an eviction of the +// parent after the deadline is handled like one before it: the output is +// still claimable, so the parent is published again. +func TestPreSignedTxParentEvictedPastDeadline(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + req.DeadlineHeight = fn.Some(int32(101)) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + + h.nextBlock() // 101 + h.nextBlock() // 102, past the deadline. + h.failAnchorMissingParent(tx, anchor) + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) + + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() // 103 + require.True(t, st.published) + require.True(t, st.anchorOffered) + requireNoResult(t, resultChan) +} + +// TestPreSignedTxDoubleSpendError asserts that a publication rejected as a +// double spend is not taken as proof of a confirmed conflict: the backend +// maps a missing input to the same error, and a commitment that is gone +// after a re-org comes back. The publication is retried like any other +// failure, and succeeds once the backend sees the input again. +func TestPreSignedTxDoubleSpendError(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + // No mempool is configured, as on neutrino: there is nothing else + // to consult, and the lifecycle must not conclude on its own. + require.Nil(t, h.s.cfg.Mempool) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrDoubleSpend, + ).Times(3) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + + h.nextBlock() + h.nextBlock() + requireNoResult(t, resultChan) + require.Contains(t, h.s.preSigned, tx.TxHash()) + require.False(t, st.published) + require.NotContains(t, h.s.inputs, anchor.OutPoint()) + + // The input is back (the re-org settled) and the publication goes + // through. + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.nextBlock() + require.True(t, st.published) + require.True(t, st.anchorOffered) + requireNoResult(t, resultChan) +} + +// TestPreSignedTxConflictingSpend asserts that a confirmed spend of the +// parent's input by a different transaction ends the lifecycle with +// ErrPreSignedTxConflict, whether the parent was still being published or +// its anchor was already being swept, and that the input watch is cancelled. +func TestPreSignedTxConflictingSpend(t *testing.T) { + t.Parallel() + + t.Run("while publishing", func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + watch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrDoubleSpend, + ).Once() + resultChan := h.submit(t, req) + requireNoResult(t, resultChan) + + conflict := conflictingTx(tx) + h.spendInput(tx, conflict) + + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrPreSignedTxConflict) + require.ErrorContains(t, result.Err, conflict.TxHash().String()) + require.NotContains(t, h.s.preSigned, tx.TxHash()) + require.NotContains(t, h.s.inputs, anchor.OutPoint()) + require.EqualValues(t, 1, watch.cancelled.Load()) + + // Nothing is retried after the final result. + h.nextBlock() + requireNoResult(t, resultChan) + }) + + t.Run("while sweeping the anchor", func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + watch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + require.True(t, h.s.preSigned[tx.TxHash()].anchorOffered) + + h.spendInput(tx, conflictingTx(tx)) + + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrPreSignedTxConflict) + require.NotContains(t, h.s.preSigned, tx.TxHash()) + require.EqualValues(t, 1, watch.cancelled.Load()) + + // The anchor sweep reports the missing parent later; the + // lifecycle is gone and the result is ignored. + h.failAnchorMissingParent(tx, anchor) + requireNoResult(t, resultChan) + require.Empty(t, h.s.preSigned) + }) +} + +// TestPreSignedTxConfirmedByNotifier asserts that the chain notifier +// reporting the parent itself as the spender of its input is what marks the +// parent confirmed: publication stops being attempted and the anchor is +// registered, even when every publication attempt was rejected (the tx was +// broadcast by someone else, or confirmed while we were offline). Without +// an anchor the lifecycle concludes with the tx. +func TestPreSignedTxConfirmedByNotifier(t *testing.T) { + t.Parallel() + + t.Run("with anchor", func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrDoubleSpend, + ).Twice() + resultChan := h.submit(t, req) + h.nextBlock() + st := h.s.preSigned[tx.TxHash()] + require.False(t, st.published) + + // The parent itself confirmed. The anchor is registered right + // away and no further publication is attempted (the publish + // mock is exhausted). + h.expectSpendRegistration(anchor.OutPoint()) + h.spendInput(tx, tx) + require.True(t, st.confirmed) + require.True(t, st.anchorOffered) + require.Contains(t, h.s.inputs, anchor.OutPoint()) + requireNoResult(t, resultChan) + + h.nextBlock() + requireNoResult(t, resultChan) + }) + + t.Run("without anchor", func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, _ := newPreSignedTx(t, 0) + req := newRequest(tx, nil) + + watch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + errors.New("rejected"), + ).Once() + resultChan := h.submit(t, req) + requireNoResult(t, resultChan) + + h.spendInput(tx, tx) + + result := requireResult(t, resultChan) + require.NoError(t, result.Err) + require.Equal(t, tx.TxHash(), result.Tx.TxHash()) + require.NotContains(t, h.s.preSigned, tx.TxHash()) + require.EqualValues(t, 1, watch.cancelled.Load()) + }) +} + +// TestPreSignedTxRestartConfirmedParent runs a re-submission after a restart +// through the live collector, for a parent that already confirmed and whose +// anchor was since swept by someone else. The broadcast is a no-op, the +// anchor is registered, and the historical spend of the anchor concludes the +// lifecycle with ErrRemoteSpend. +func TestPreSignedTxRestartConfirmedParent(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + op := anchor.OutPoint() + req := newRequest(tx, anchor) + req.Budget = 10_000 + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + anchorWatch := h.expectSpendRegistration(op) + + thirdParty := wire.NewMsgTx(2) + thirdParty.AddTxIn(&wire.TxIn{PreviousOutPoint: op}) + thirdPartyHash := thirdParty.TxHash() + h.store.On("IsOurTx", thirdPartyHash).Return(false).Once() + h.store.On("ListSweeps").Return([]chainhash.Hash{}, nil).Once() + + beat := &chainio.MockBlockbeat{} + beat.On("Height").Return(int32(100)).Maybe() + beat.On("logger").Return(log).Maybe() + require.NoError(t, h.s.Start(beat)) + t.Cleanup(func() { + require.NoError(t, h.s.Stop()) + }) + + resultChan, err := h.s.PublishPreSignedTx(req) + require.NoError(t, err) + + anchorWatch.spend <- &chainntnfs.SpendDetail{ + SpentOutPoint: &op, + SpendingTx: thirdParty, + SpenderTxHash: &thirdPartyHash, + } + + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrRemoteSpend) +} + +// TestPreSignedTxConfirmedWhileAnchorFatal asserts that the anchor is not +// offered to the sweeper while its previous, failed input is still tracked. +// The child failing with a missing parent leaves that input behind in a +// final state until the next block prunes it. If the parent's confirmation +// is reported in that window, offering the anchor would attach the lifecycle +// to the dead entry, which is then deleted without a result, leaving nothing +// to sweep the anchor and nothing to end the lifecycle. +func TestPreSignedTxConfirmedWhileAnchorFatal(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + op := anchor.OutPoint() + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(op) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + require.True(t, st.anchorOffered) + + // The child fails, the anchor input stays behind as fatal. + h.failAnchorMissingParent(tx, anchor) + deadInput := h.s.inputs[op] + require.Equal(t, Fatal, deadInput.state) + numListeners := len(deadInput.listeners) + + // The parent turns out to have confirmed, before the next block. The + // anchor must not be attached to the dead input. + h.spendInput(tx, tx) + require.True(t, st.confirmed) + require.False(t, st.anchorOffered) + require.Len(t, deadInput.listeners, numListeners) + requireNoResult(t, resultChan) + + // The next block prunes the dead input and registers the anchor + // afresh, with a new spend watch, without publishing the confirmed + // parent again. + h.expectSpendRegistration(op) + h.nextBlock() + require.True(t, st.anchorOffered) + liveInput, ok := h.s.inputs[op] + require.True(t, ok) + require.NotSame(t, deadInput, liveInput) + require.Equal(t, Init, liveInput.state) + requireNoResult(t, resultChan) + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 1) + + // The live input still ends the lifecycle. + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Tx: tx}, + }) + require.NoError(t, requireResult(t, resultChan).Err) +} + +// TestPreSignedTxAnchorFinalStates asserts that the anchor is held back for +// every final state its previous input can be left in, and offered for a +// state that is not final. +func TestPreSignedTxAnchorFinalStates(t *testing.T) { + t.Parallel() + + testCases := []struct { + state SweepState + heldBack bool + }{ + {state: Fatal, heldBack: true}, + {state: Swept, heldBack: true}, + {state: Excluded, heldBack: true}, + {state: PublishFailed}, + } + + for _, tc := range testCases { + t.Run(tc.state.String(), func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + // Another party already has the anchor tracked. + h.s.inputs[anchor.OutPoint()] = &SweeperInput{ + Input: anchor, + state: tc.state, + } + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return( + nil, + ).Once() + h.submit(t, req) + + st := h.s.preSigned[tx.TxHash()] + require.True(t, st.published) + require.Equal(t, !tc.heldBack, st.anchorOffered) + }) + } +} + +// TestPreSignedTxParentReorged asserts that a confirmation of the pre-signed +// tx that is re-orged out makes the tx eligible for publication again: it is +// re-broadcast right away and, if rejected, on every block, and once its +// child reports it missing the anchor is registered anew. +func TestPreSignedTxParentReorged(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + op := anchor.OutPoint() + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(op) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + + // The parent confirms. Nothing is published while it is. + h.spendInput(tx, tx) + require.True(t, st.confirmed) + h.nextBlock() + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 1) + + // The confirmation is re-orged out. The parent is published again + // right away, although its anchor is still being swept. The mempool + // rejects it, so the next block tries again. + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrMempoolFee, + ).Once() + h.reorgInput(tx) + require.False(t, st.confirmed) + require.False(t, st.published) + require.True(t, st.anchorOffered) + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 2) + requireNoResult(t, resultChan) + + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.nextBlock() + require.True(t, st.published) + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 3) + + // Once published, later blocks leave it alone, and the anchor that + // is still being swept is not registered a second time. + h.nextBlock() + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 3) + h.notifier.AssertNumberOfCalls(t, "RegisterSpendNtfn", 2) + + // The child reports the parent as missing after all: the parent is + // published and the anchor registered again on the next block. + h.failAnchorMissingParent(tx, anchor) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(op) + h.nextBlock() + require.True(t, st.published) + require.True(t, st.anchorOffered) + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 4) + + // The parent confirms again and the lifecycle ends as usual. + h.spendInput(tx, tx) + require.True(t, st.confirmed) + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Err: ErrRemoteSpend}, + }) + require.ErrorIs(t, requireResult(t, resultChan).Err, ErrRemoteSpend) +} + +// TestPreSignedTxReorgThenConflict asserts that after its confirmation was +// re-orged out, the pre-signed tx can still lose to a conflicting spend, +// which ends the lifecycle. +func TestPreSignedTxReorgThenConflict(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + inputWatch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + + h.spendInput(tx, tx) + h.wallet.On("PublishTransaction", tx, "test").Return( + lnwallet.ErrDoubleSpend, + ).Once() + h.reorgInput(tx) + requireNoResult(t, resultChan) + + h.spendInput(tx, conflictingTx(tx)) + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrPreSignedTxConflict) + require.NotContains(t, h.s.preSigned, tx.TxHash()) + require.EqualValues(t, 1, inputWatch.cancelled.Load()) +} + +// TestPreSignedTxReorgNotConfirmed asserts that a re-org reported for a tx +// that was never seen confirmed publishes it again. The notifier drops a +// spend nobody read yet when it dispatches the re-org, so the re-org can be +// the first event of an input. The anchor that is already being swept is not +// registered a second time. +func TestPreSignedTxReorgNotConfirmed(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Twice() + h.expectSpendRegistration(anchor.OutPoint()) + resultChan := h.submit(t, req) + st := h.s.preSigned[tx.TxHash()] + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 1) + + h.reorgInput(tx) + require.False(t, st.confirmed) + require.True(t, st.published) + require.True(t, st.anchorOffered) + h.wallet.AssertNumberOfCalls(t, "PublishTransaction", 2) + h.notifier.AssertNumberOfCalls(t, "RegisterSpendNtfn", 2) + requireNoResult(t, resultChan) +} + +// TestPreSignedTxInputWatchEndsOnDone asserts that the watch on an input +// ends once the notifier is done with the registration, and that a spend +// that is still unread at that point is forwarded first. +func TestPreSignedTxInputWatchEndsOnDone(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + pendingSpend bool + }{{ + name: "no pending spend", + }, { + name: "pending spend", + pendingSpend: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + txid := tx.TxHash() + + // Both events are in place before the watch starts, + // so they are ready in the same iteration. Whichever + // the watch picks first, the spend is forwarded once. + inputWatch := h.expectInputWatch(req) + spend := &chainntnfs.SpendDetail{SpenderTxHash: &txid} + inputWatch.done <- struct{}{} + if tc.pendingSpend { + inputWatch.spend <- spend + } + + h.wallet.On( + "PublishTransaction", tx, "test", + ).Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.submit(t, req) + + if tc.pendingSpend { + select { + case event := <-h.s.preSignedSpends: + require.Same(t, spend, event.spend) + case <-time.After(5 * time.Second): + t.Fatal("pending spend not forwarded") + } + } + + // The watch is gone: nothing sent afterwards is + // forwarded. + require.Eventually(t, func() bool { + return len(inputWatch.done) == 0 + }, 5*time.Second, 10*time.Millisecond) + inputWatch.reorg <- struct{}{} + select { + case event := <-h.s.preSignedSpends: + t.Fatalf("unexpected event: %v", event) + case <-time.After(100 * time.Millisecond): + } + }) + } +} + +// TestPreSignedTxInputWatchOutlivesSpend asserts that the watch on an input +// keeps forwarding events after the first spend: the re-org of that spend +// and the spend that follows it. +func TestPreSignedTxInputWatchOutlivesSpend(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + txid := tx.TxHash() + + inputWatch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + h.submit(t, req) + + nextEvent := func() *preSignedSpend { + t.Helper() + + select { + case event := <-h.s.preSignedSpends: + return event + case <-time.After(5 * time.Second): + t.Fatal("no event forwarded") + } + + return nil + } + + spend := &chainntnfs.SpendDetail{SpenderTxHash: &txid} + inputWatch.spend <- spend + event := nextEvent() + require.Equal(t, txid, event.txid) + require.Same(t, spend, event.spend) + require.False(t, event.reorged) + + inputWatch.reorg <- struct{}{} + event = nextEvent() + require.Equal(t, txid, event.txid) + require.Nil(t, event.spend) + require.True(t, event.reorged) + + conflictHash := conflictingTx(tx).TxHash() + respend := &chainntnfs.SpendDetail{SpenderTxHash: &conflictHash} + inputWatch.spend <- respend + event = nextEvent() + require.Same(t, respend, event.spend) + require.False(t, event.reorged) + + // Cancelling the registration closes its channels, which ends the + // watch without forwarding anything else. + close(inputWatch.spend) + close(inputWatch.reorg) + select { + case event := <-h.s.preSignedSpends: + t.Fatalf("unexpected event: %v", event) + case <-time.After(50 * time.Millisecond): + } +} + +// TestPreSignedTxEndToEndReorg runs a confirmation, its re-org and the +// second confirmation through the live collector. +func TestPreSignedTxEndToEndReorg(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + txid := tx.TxHash() + op := anchor.OutPoint() + inOp := tx.TxIn[0].PreviousOutPoint + req := newRequest(tx, anchor) + + inputWatch := h.expectInputWatch(req) + published := make(chan struct{}, 2) + h.wallet.On("PublishTransaction", tx, "test").Run(func(mock.Arguments) { + published <- struct{}{} + }).Return(nil).Twice() + h.expectSpendRegistration(op) + + beat := &chainio.MockBlockbeat{} + beat.On("Height").Return(int32(100)).Maybe() + beat.On("logger").Return(log).Maybe() + require.NoError(t, h.s.Start(beat)) + t.Cleanup(func() { + require.NoError(t, h.s.Stop()) + }) + + waitPublished := func() { + t.Helper() + + select { + case <-published: + case <-time.After(5 * time.Second): + t.Fatal("tx not published") + } + } + + resultChan, err := h.s.PublishPreSignedTx(req) + require.NoError(t, err) + waitPublished() + + // Confirm the tx, then re-org the confirmation out: the collector + // publishes the tx a second time. + inputWatch.spend <- &chainntnfs.SpendDetail{ + SpentOutPoint: &inOp, + SpendingTx: tx, + SpenderTxHash: &txid, + } + + // The notifier reports the two events on separate channels. Only + // report the re-org once the watch has taken the spend, so that the + // collector sees them in the order they happened. + require.Eventually(t, func() bool { + return len(inputWatch.spend) == 0 + }, 5*time.Second, time.Millisecond) + inputWatch.reorg <- struct{}{} + waitPublished() + requireNoResult(t, resultChan) + + // A conflicting spend confirms instead and ends the lifecycle. + conflict := conflictingTx(tx) + conflictHash := conflict.TxHash() + inputWatch.spend <- &chainntnfs.SpendDetail{ + SpentOutPoint: &inOp, + SpendingTx: conflict, + SpenderTxHash: &conflictHash, + } + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrPreSignedTxConflict) +} + +// TestPreSignedTxUnknownEvents asserts that a late anchor result or input +// spend for a lifecycle that already concluded is ignored. +func TestPreSignedTxUnknownEvents(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, _ := newPreSignedTx(t, 0) + + h.s.handlePreSignedAnchorResult(&preSignedAnchorResult{ + txid: tx.TxHash(), + result: Result{Err: ErrRemoteSpend}, + }) + h.spendInput(tx, conflictingTx(tx)) + h.reorgInput(tx) + require.Empty(t, h.s.preSigned) +} + +// TestPreSignedTxShutdown asserts that pending lifecycles are released with +// ErrSweeperShuttingDown when the sweeper stops, and their watches are +// cancelled. +func TestPreSignedTxShutdown(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, _ := newPreSignedTx(t, 500) + req := newRequest(tx, nil) + + watch := h.expectInputWatch(req) + resultChan := h.submit(t, req) + requireNoResult(t, resultChan) + + h.s.failPreSignedTxs(ErrSweeperShuttingDown) + + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrSweeperShuttingDown) + require.Empty(t, h.s.preSigned) + require.EqualValues(t, 1, watch.cancelled.Load()) +} + +// TestPreSignedTxEndToEnd runs the lifecycle through the live collector: a +// request is submitted via the public API, a block is processed, the tx is +// published, the anchor registered, and a spend of the anchor by our own +// sweep tx concludes the lifecycle with that tx as the result. +func TestPreSignedTxEndToEnd(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 101) + op := anchor.OutPoint() + req := newRequest(tx, anchor) + req.Budget = 10_000 + req.DeadlineHeight = fn.Some(int32(200)) + + h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + anchorWatch := h.expectSpendRegistration(op) + + child := wire.NewMsgTx(2) + child.AddTxIn(&wire.TxIn{PreviousOutPoint: op}) + childHash := child.TxHash() + h.store.On("IsOurTx", childHash).Return(true).Once() + + beat := &chainio.MockBlockbeat{} + beat.On("Height").Return(int32(100)).Maybe() + beat.On("logger").Return(log).Maybe() + require.NoError(t, h.s.Start(beat)) + t.Cleanup(func() { + require.NoError(t, h.s.Stop()) + }) + + resultChan, err := h.s.PublishPreSignedTx(req) + require.NoError(t, err) + + // Height 100 is below the locktime; the collector must hold the tx. + requireNoResult(t, resultChan) + + // Process block 101 through the real blockbeat path: publish and + // anchor registration happen inside the collector. + beat101 := &chainio.MockBlockbeat{} + beat101.On("Height").Return(int32(101)).Maybe() + beat101.On("logger").Return(log).Maybe() + require.NoError(t, h.s.ProcessBlock(beat101)) + + // Deliver the spend of the anchor by our child tx. The sweeper's + // regular spend handling marks the anchor swept and the lifecycle + // concludes with the spending tx. + anchorWatch.spend <- &chainntnfs.SpendDetail{ + SpentOutPoint: &op, + SpendingTx: child, + SpenderTxHash: &childHash, + } + + result := requireResult(t, resultChan) + require.NoError(t, result.Err) + require.Equal(t, childHash, result.Tx.TxHash()) +} + +// TestPreSignedTxEndToEndConflict runs a confirmed conflict through the live +// collector: the spend delivered by the input watch ends the lifecycle. +func TestPreSignedTxEndToEndConflict(t *testing.T) { + t.Parallel() + + h := newPreSignedTestHarness(t) + tx, anchor := newPreSignedTx(t, 0) + req := newRequest(tx, anchor) + + inputWatch := h.expectInputWatch(req) + h.wallet.On("PublishTransaction", tx, "test").Return(nil).Once() + h.expectSpendRegistration(anchor.OutPoint()) + + beat := &chainio.MockBlockbeat{} + beat.On("Height").Return(int32(100)).Maybe() + beat.On("logger").Return(log).Maybe() + require.NoError(t, h.s.Start(beat)) + t.Cleanup(func() { + require.NoError(t, h.s.Stop()) + }) + + resultChan, err := h.s.PublishPreSignedTx(req) + require.NoError(t, err) + + conflict := conflictingTx(tx) + conflictHash := conflict.TxHash() + htlcOp := tx.TxIn[0].PreviousOutPoint + inputWatch.spend <- &chainntnfs.SpendDetail{ + SpentOutPoint: &htlcOp, + SpendingTx: conflict, + SpenderTxHash: &conflictHash, + SpendingHeight: 100, + } + + result := requireResult(t, resultChan) + require.ErrorIs(t, result.Err, ErrPreSignedTxConflict) +} diff --git a/sweep/sweeper.go b/sweep/sweeper.go index 73f817d75f1..111c6bf289d 100644 --- a/sweep/sweeper.go +++ b/sweep/sweeper.go @@ -387,6 +387,22 @@ type UtxoSweeper struct { // bumpRespChan is a channel that receives broadcast results from the // TxPublisher. bumpRespChan chan *bumpResp + + // preSignedReqs delivers PublishPreSignedTx requests into the main + // event loop. + preSignedReqs chan *preSignedTxMessage + + // preSignedAnchorResults delivers the final result of a pre-signed + // tx's anchor sweep back into the main event loop. + preSignedAnchorResults chan *preSignedAnchorResult + + // preSignedSpends delivers confirmed spends of the inputs of + // pre-signed txs into the main event loop. + preSignedSpends chan *preSignedSpend + + // preSigned tracks the pre-signed transactions whose lifecycle the + // sweeper currently owns, keyed by txid. + preSigned map[chainhash.Hash]*preSignedTxState } // Compile-time check for the chainio.Consumer interface. @@ -475,6 +491,12 @@ func New(cfg *UtxoSweeperConfig) *UtxoSweeper { inputs: make(InputsMap), excludedWalletInputs: fn.NewSet[wire.OutPoint](), bumpRespChan: make(chan *bumpResp, 100), + preSignedReqs: make(chan *preSignedTxMessage), + preSignedAnchorResults: make( + chan *preSignedAnchorResult, 100, + ), + preSignedSpends: make(chan *preSignedSpend, 100), + preSigned: make(map[chainhash.Hash]*preSignedTxState), } // Mount the block consumer. @@ -732,6 +754,20 @@ func (s *UtxoSweeper) collector() { err) } + // A pre-signed transaction is handed to us to publish and + // CPFP; take ownership of its lifecycle. + case msg := <-s.preSignedReqs: + s.handlePreSignedTxReq(msg) + + // The anchor sweep of a pre-signed transaction concluded. + case r := <-s.preSignedAnchorResults: + s.handlePreSignedAnchorResult(r) + + // An input of a pre-signed transaction was spent on chain, + // either by the transaction itself or by a conflicting one. + case ps := <-s.preSignedSpends: + s.handlePreSignedSpend(ps) + // A new block comes in, update the bestHeight, perform a check // over all pending inputs and publish sweeping txns if needed. case beat := <-s.BlockbeatChan: @@ -751,10 +787,18 @@ func (s *UtxoSweeper) collector() { // Attempt to sweep any pending inputs. s.sweepPendingInputs(inputs, nil) + // Drive the pre-signed transactions we own one step + // further (publish once the locktime allows, register + // their anchors). + s.processPreSignedTxs() + // Notify we've processed the block. s.NotifyBlockProcessed(beat, nil) case <-s.quit: + // Release anyone waiting on a pre-signed tx outcome. + s.failPreSignedTxs(ErrSweeperShuttingDown) + return } }