[bug]: taproot channel_reestablish without a usable nonce is rejected before the data-loss mark, so a force close stays allowed

Open
#11,600 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
30/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
blockchain, go
Domain
backend, payments

Research direction

The missing-nonce error is raised in ProcessChanSyncMsg in lnwallet/channel.go, before the ErrCommitSyncLocalDataLoss return, and handleChanSyncErr in htlcswitch/link.go is where MarkDataLoss would run. Start by reproducing with go test -count=1 -run TestTaprootResyncWithoutNonce -v ./htlcswitch/ using htlcswitch/taproot_resync_test.go. Done means the nonce-stripped case reports ChanStatusLocalDataLoss and ForceClose is refused, matching the honest case.

Written by the indexing model from the issue text.

Description

bug needs triage
Pre-Submission Checklist
  • I have searched the existing issues and believe this is a new bug.
  • I am not asking a question about how to use lnd, but reporting a bug (otherwise open a discussion).
LND Version

master 8cdbf85c0860 (2026-11-18), v0.21.8-beta and v0.20.8-beta

LND Configuration

Default.

Backend Version

None. The code runs inside lnd's own packages.

Backend Configuration

None.

OS/Distribution

Linux x86_64

Bug Details & Steps to Reproduce

On lnd master 8cdbf85c0860, ProcessChanSyncMsg on a simple taproot channel returns the missing-nonce error before it reaches the data-loss branch. The node runs on an older copy of its channel state. The peer's channel_reestablish has the right counters and a correct your_last_per_commitment_secret, but no usable next_local_nonces (absent, or without an entry for the funding txid). lnd fails the link and sends an error (channel.go L4465-L4551). It never reaches the ErrCommitSyncLocalDataLoss return (L4575-L4601), so handleChanSyncErr never calls MarkDataLoss (link.go L1297-L1371). The channel keeps its default status, and ForceClose refuses only the data-loss and restored statuses (channel.go L8439-L8452), so a later force close is allowed.

BOLT 2 says the receiver of such a message MUST NOT broadcast its commitment transaction.

The test below drives lnd's channelLink on a stale taproot channel, with the peer's message sent with and without the nonce. Run go test -count=1 -run TestTaprootResyncWithoutNonce -v ./htlcswitch/. The output is:

honest: status after sync: ChanStatusLocalDataLoss (local data loss: true)
honest: ForceClose from disk: cannot force close channel with local data loss: channel_state=ChanStatusLocalDataLoss
nonce-stripped: status after sync: ChanStatusDefault (local data loss: false)
nonce-stripped: ForceClose from disk: <nil>

The output is the same on v0.21.8-beta and v0.20.8-beta. On those releases the test needs btcutil and wire without /v2 in the imports and channeldb in place of chanstate; v0.20.8-beta also has no LocalNonces field, no NotifyChannelUpdate field, and calls the endorsement field ShouldFwdExpEndorsement, so the test drops the first two lines and uses that name.

Test file, htlcswitch/taproot_resync_test.go:

// Drives lnd's channelLink on a simple taproot channel whose local database
// is one state older than the peer's, with the peer's real channel_reestablish
// sent with and without the MuSig2 nonce.
package htlcswitch

import (
    "os"
    "path/filepath"
    "sort"
    "testing"
    "time"

    "github.com/btcsuite/btcd/btcec/v2"
    "github.com/btcsuite/btcd/btcutil/v2"
    "github.com/btcsuite/btcd/wire/v2"
    "github.com/lightningnetwork/lnd/channeldb"
    cstate "github.com/lightningnetwork/lnd/chanstate"
    "github.com/lightningnetwork/lnd/contractcourt"
    "github.com/lightningnetwork/lnd/graph/db/models"
    "github.com/lightningnetwork/lnd/htlcswitch/hop"
    "github.com/lightningnetwork/lnd/lnwallet"
    "github.com/lightningnetwork/lnd/lnwire"
    "github.com/lightningnetwork/lnd/ticker"
    "github.com/stretchr/testify/require"
)

func copyFile(t *testing.T, from, to string) {
    b, err := os.ReadFile(from)
    require.NoError(t, err)
    require.NoError(t, os.MkdirAll(filepath.Dir(to), 0o700))
    require.NoError(t, os.WriteFile(to, b, 0o600))
}

type syncOutcome struct {
    linkErr      *LinkFailureError
    status       string
    dataLoss     bool
    forceErr     error
    sentToPeer   []string
}

func runTaprootSync(t *testing.T, stripNonce bool) syncOutcome {
    alice, bob, err := lnwallet.CreateTestChannels(
        t, channeldb.SimpleTaprootFeatureBit,
    )
    require.NoError(t, err)

    // One full state transition, then copy Alice's database: this is
    // the "older backup". CreateTestChannels opens Alice's database in
    // the first t.TempDir() of the test and Bob's in the second.
    require.NoError(t, lnwallet.ForceStateTransition(alice, bob))
    root := filepath.Dir(t.TempDir())
    dbs, _ := filepath.Glob(filepath.Join(root, "*", "channel.db"))
    sort.Strings(dbs)
    require.GreaterOrEqual(t, len(dbs), 2)
    backup := filepath.Join(root, "alice-backup", "channel.db")
    copyFile(t, dbs[0], backup)

    // Two more transitions: Bob now holds later states.
    require.NoError(t, lnwallet.ForceStateTransition(alice, bob))
    require.NoError(t, lnwallet.ForceStateTransition(alice, bob))

    // Alice restarts from the backup.
    staleDB := channeldb.OpenForTesting(t, filepath.Dir(backup))
    chans, err := staleDB.ChannelStateDB().FetchOpenChannels(
        alice.State().IdentityPub,
    )
    require.NoError(t, err)
    require.Len(t, chans, 1)
    pool := lnwallet.NewSigPool(1, alice.Signer)
    require.NoError(t, pool.Start())
    t.Cleanup(func() { pool.Stop() })
    staleAlice, err := lnwallet.NewLightningChannel(
        alice.Signer, chans[0], pool,
    )
    require.NoError(t, err)
    t.Logf("alice (restored) local commitment %d; bob local %d remote %d",
        staleAlice.State().LocalCommitment.CommitHeight,
        bob.State().LocalCommitment.CommitHeight,
        bob.State().RemoteCommitment.CommitHeight)

    // Bob's real channel_reestablish.
    bobSync, err := bob.State().ChanSyncMsg()
    require.NoError(t, err)
    if stripNonce {
        bobSync.LocalNonce = lnwire.OptMusig2NonceTLV{}
        bobSync.LocalNonces = lnwire.OptLocalNonces{}
    }

    // Alice's link, configured as newSingleLinkTestHarness does, with
    // SyncStates set as the peer sets it for a link it resumes
    // (peer/brontide.go addLink).
    alicePeer := &mockPeer{
        sentMsgs: make(chan lnwire.Message, 2000),
        quit:     make(chan struct{}),
    }
    t.Cleanup(func() { close(alicePeer.quit) })
    aliceSwitch, err := initSwitchWithDB(testStartingHeight, staleDB)
    require.NoError(t, err)
    decoder := newMockIteratorDecoder()
    obfuscator := NewMockObfuscator()
    invoiceRegistry := newMockRegistry(t)
    linkErrs := make(chan LinkFailureError, 1)
    cfg := ChannelLinkConfig{
        FwrdingPolicy: models.ForwardingPolicy{
            MinHTLCOut:    lnwire.NewMSatFromSatoshis(5),
            MaxHTLC:       lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin),
            BaseFee:       lnwire.NewMSatFromSatoshis(1),
            TimeLockDelta: 6,
        },
        Peer:       alicePeer,
        BestHeight: aliceSwitch.BestHeight,
        Circuits:   aliceSwitch.CircuitModifier(),
        ForwardPackets: func(linkQuit <-chan struct{}, _ bool,
            packets ...*htlcPacket) error {
            return aliceSwitch.ForwardPackets(linkQuit, packets...)
        },
        DecodeHopIterators: decoder.DecodeHopIterators,
        ExtractErrorEncrypter: func(*btcec.PublicKey) (
            hop.ErrorEncrypter, lnwire.FailCode) {
            return obfuscator, lnwire.CodeNone
        },
        FetchLastChannelUpdate: mockGetChanUpdateMessage,
        PreimageCache:          newMockPreimageCache(),
        OnChannelFailure: func(_ lnwire.ChannelID,
            _ lnwire.ShortChannelID, linkErr LinkFailureError) {
            linkErrs <- linkErr
        },
        UpdateContractSignals: func(*contractcourt.ContractSignals) error {
            return nil
        },
        NotifyContractUpdate: func(*contractcourt.ContractUpdate) error {
            return nil
        },
        Registry:                invoiceRegistry,
        FeeEstimator:            newMockFeeEstimator(),
        ChainEvents:             &contractcourt.ChainEventSubscription{},
        BatchTicker:             ticker.NewForce(time.Hour),
        FwdPkgGCTicker:          ticker.NewForce(15 * time.Second),
        PendingCommitTicker:     ticker.New(time.Minute),
        BatchSize:               10000,
        MinUpdateTimeout:        30 * time.Minute,
        MaxUpdateTimeout:        40 * time.Minute,
        MaxOutgoingCltvExpiry:   DefaultMaxOutgoingCltvExpiry,
        MaxFeeAllocation:        DefaultMaxLinkFeeAllocation,
        NotifyActiveLink:        func(wire.OutPoint) {},
        NotifyActiveChannel:     func(wire.OutPoint) {},
        NotifyChannelUpdate:     func(*cstate.OpenChannel) {},
        NotifyInactiveChannel:   func(wire.OutPoint) {},
        NotifyInactiveLinkEvent: func(wire.OutPoint) {},
        HtlcNotifier: invoiceRegistry.htlcNotifier(
            aliceSwitch.cfg.HtlcNotifier,
        ),
        GetAliases: func(lnwire.ShortChannelID) []lnwire.ShortChannelID {
            return nil
        },
        ShouldFwdExpAccountability: func() bool { return true },
        SyncStates:                 true,
    }
    link := NewChannelLink(cfg, staleAlice)
    require.NoError(t, aliceSwitch.AddLink(link))
    link.HandleChannelUpdate(bobSync)

    var out syncOutcome
    select {
    case e := <-linkErrs:
        out.linkErr = &e
    case <-time.After(10 * time.Second):
    }
    for done := false; !done; {
        select {
        case m := <-alicePeer.sentMsgs:
            out.sentToPeer = append(out.sentToPeer, m.MsgType().String())
        default:
            done = true
        }
    }

    // What Alice's database says now, and whether a force close from it
    // is refused: the path every force close takes (the arbitrator's
    // ForceCloseChan: a fresh LightningChannel from disk, then
    // ForceClose; contractcourt/chain_arbitrator.go 386-407).
    st, err := staleDB.ChannelStateDB().FetchChannel(
        staleAlice.ChannelPoint(),
    )
    require.NoError(t, err)
    out.status = st.ChanStatus().String()
    out.dataLoss = st.HasChanStatus(cstate.ChanStatusLocalDataLoss)
    fresh, err := lnwallet.NewLightningChannel(alice.Signer, st, pool)
    require.NoError(t, err)
    _, out.forceErr = fresh.ForceClose()
    return out
}

func TestTaprootResyncWithoutNonce(t *testing.T) {
    for _, strip := range []bool{false, true} {
        name := map[bool]string{false: "honest", true: "nonce-stripped"}[strip]
        t.Run(name, func(t *testing.T) {
            o := runTaprootSync(t, strip)
            if o.linkErr != nil {
                t.Logf("%s: link failure: code=%v action=%v permanent=%v: %v",
                    name, o.linkErr.code, o.linkErr.FailureAction,
                    o.linkErr.PermanentFailure, o.linkErr.Error())
            } else {
                t.Logf("%s: no link failure", name)
            }
            t.Logf("%s: alice sent %v", name, o.sentToPeer)
            t.Logf("%s: status after sync: %s (local data loss: %v)",
                name, o.status, o.dataLoss)
            t.Logf("%s: ForceClose from disk: %v", name, o.forceErr)
        })
    }
}
Expected Behavior

The channel is marked with local data loss, as it is when the same message carries a usable nonce, and a force close is refused.

Debug Information

No response

Environment

No response

Dominant language
Go
Stars
8.2k
Forks
2.3k
Avg merge
1d 11h
Merged PRs (30d)
103

Getting set up

  • Ships a Dockerfile or Docker Compose file
  • Has a pull request template
  • No contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from lightningnetwork/lnd

All issues in lightningnetwork/lnd

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.