diff --git a/channeldb/channel_test.go b/channeldb/channel_test.go index 248f5348dc0..b4df8e7af43 100644 --- a/channeldb/channel_test.go +++ b/channeldb/channel_test.go @@ -660,6 +660,47 @@ func assertRevocationLogEntryEqual(t *testing.T, c *ChannelCommitment, } } +// TestUpdateCommitmentRevocationAuxSigsRollback asserts that the revocation +// aux sigs held in memory always match what was persisted. They are set on +// the channel before the store writes them, so a write that fails must leave +// the previous value in place. Otherwise a retransmission would send a blob +// that is gone after a restart. +func TestUpdateCommitmentRevocationAuxSigsRollback(t *testing.T) { + t.Parallel() + + fullDB, err := MakeTestDB(t) + require.NoError(t, err, "unable to make test database") + + cdb := fullDB.ChannelStateDB() + channel := createTestChannel(t, cdb) + + commitment := channel.LocalCommitment + commitment.CommitHeight++ + + // A successful update persists the sigs. + firstSigs := fn.Some(tlv.Blob{1, 2, 3}) + _, err = channel.UpdateCommitment(&commitment, nil, firstSigs) + require.NoError(t, err) + require.Equal(t, firstSigs, channel.RevocationAuxSigs) + + // Once the channel is borked, further updates are refused by the + // store. The sigs of the refused update must not stick in memory. + require.NoError(t, channel.MarkBorked()) + + commitment.CommitHeight++ + _, err = channel.UpdateCommitment( + &commitment, nil, fn.Some(tlv.Blob{4, 5, 6}), + ) + require.ErrorIs(t, err, ErrChanBorked) + require.Equal(t, firstSigs, channel.RevocationAuxSigs) + + // What is on disk is the first blob as well. + openChannels, err := cdb.FetchOpenChannels(channel.IdentityPub) + require.NoError(t, err) + require.Len(t, openChannels, 1) + require.Equal(t, firstSigs, openChannels[0].RevocationAuxSigs) +} + func TestChannelStateTransition(t *testing.T) { t.Parallel() @@ -736,7 +777,9 @@ func TestChannelStateTransition(t *testing.T) { }, } - _, err = channel.UpdateCommitment(&commitment, unsignedAckedUpdates) + _, err = channel.UpdateCommitment( + &commitment, unsignedAckedUpdates, fn.None[tlv.Blob](), + ) require.NoError(t, err, "unable to update commitment") // Assert that update is correctly written to the database. diff --git a/channeldb/db_test.go b/channeldb/db_test.go index 1f87e3b668a..b43f48a8c61 100644 --- a/channeldb/db_test.go +++ b/channeldb/db_test.go @@ -14,6 +14,7 @@ import ( "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/graph/db/models" "github.com/lightningnetwork/lnd/keychain" "github.com/lightningnetwork/lnd/kvdb" @@ -21,6 +22,7 @@ import ( "github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/routing/route" "github.com/lightningnetwork/lnd/shachain" + "github.com/lightningnetwork/lnd/tlv" "github.com/stretchr/testify/require" ) @@ -382,7 +384,7 @@ func TestRestoreChannelShells(t *testing.T) { // Ensure that it isn't possible to modify the commitment state machine // of this restored channel. channel := nodeChans[0] - _, err = channel.UpdateCommitment(nil, nil) + _, err = channel.UpdateCommitment(nil, nil, fn.None[tlv.Blob]()) if err != ErrNoRestoredChannelMutation { t.Fatalf("able to mutate restored channel") } diff --git a/chanstate/kv_open_channel.go b/chanstate/kv_open_channel.go index 98d5ab7cd34..96c1ea5a938 100644 --- a/chanstate/kv_open_channel.go +++ b/chanstate/kv_open_channel.go @@ -620,6 +620,13 @@ type openChannelTlvData struct { // Note: if not set, it means either the channel has not been // closed yet, or it was closed before this field was introduced. closeConfirmationHeight tlv.OptionalRecordT[tlv.TlvType9, uint32] + + // revocationAuxSigs is an optional blob carrying the revocation aux + // signatures attached to the most recently sent RevokeAndAck. It is + // only ever set for aux/custom (taproot asset) channels, so the same + // signatures can be re-attached if that RevokeAndAck has to be + // retransmitted on channel reestablish. + revocationAuxSigs tlv.OptionalRecordT[tlv.TlvType10, tlv.Blob] } // encode serializes the openChannelTlvData to the given io.Writer. @@ -648,6 +655,12 @@ func (c *openChannelTlvData) encode(w io.Writer) error { }, ) + c.revocationAuxSigs.WhenSome( + func(sigs tlv.RecordT[tlv.TlvType10, tlv.Blob]) { + tlvRecords = append(tlvRecords, sigs.Record()) + }, + ) + tlv.SortRecords(tlvRecords) // Create the tlv stream. @@ -665,6 +678,7 @@ func (c *openChannelTlvData) decode(r io.Reader) error { tapscriptRoot := c.tapscriptRoot.Zero() blob := c.customBlob.Zero() closeConfHeight := c.closeConfirmationHeight.Zero() + revocationAuxSigs := c.revocationAuxSigs.Zero() // Create the tlv stream. tlvStream, err := tlv.NewStream( @@ -677,6 +691,7 @@ func (c *openChannelTlvData) decode(r io.Reader) error { blob.Record(), c.confirmationHeight.Record(), closeConfHeight.Record(), + revocationAuxSigs.Record(), ) if err != nil { return err @@ -699,6 +714,9 @@ func (c *openChannelTlvData) decode(r io.Reader) error { if _, ok := tlvs[closeConfHeight.TlvType()]; ok { c.closeConfirmationHeight = tlv.SomeRecordT(closeConfHeight) } + if _, ok := tlvs[revocationAuxSigs.TlvType()]; ok { + c.revocationAuxSigs = tlv.SomeRecordT(revocationAuxSigs) + } return nil } @@ -748,6 +766,9 @@ func amendOpenChannelTlvData(channel *OpenChannel, auxData openChannelTlvData) { auxData.closeConfirmationHeight.WhenSomeV(func(h uint32) { channel.CloseConfirmationHeight = fn.Some(h) }) + auxData.revocationAuxSigs.WhenSomeV(func(sigs tlv.Blob) { + channel.RevocationAuxSigs = fn.Some(sigs) + }) } // extractOpenChannelTlvData creates a new openChannelTlvData from the given @@ -791,6 +812,11 @@ func extractOpenChannelTlvData(channel *OpenChannel) openChannelTlvData { tlv.NewPrimitiveRecord[tlv.TlvType9](h), ) }) + channel.RevocationAuxSigs.WhenSome(func(sigs tlv.Blob) { + auxData.revocationAuxSigs = tlv.SomeRecordT( + tlv.NewPrimitiveRecord[tlv.TlvType10](sigs), + ) + }) return auxData } diff --git a/chanstate/open_channel.go b/chanstate/open_channel.go index e0558f392e9..033e64f69dd 100644 --- a/chanstate/open_channel.go +++ b/chanstate/open_channel.go @@ -223,6 +223,15 @@ type OpenChannel struct { // immutable. CustomBlob fn.Option[tlv.Blob] + // RevocationAuxSigs is an optional blob carrying the revocation aux + // signatures attached to the most recently sent RevokeAndAck. It is + // only ever set for aux/custom (taproot asset) channels, and is + // persisted so the exact same signatures can be re-attached if that + // RevokeAndAck has to be retransmitted on channel reestablish. Only + // the latest revocation can ever be owed to the peer, so a single + // slot suffices; it is overwritten on every revocation. + RevocationAuxSigs fn.Option[tlv.Blob] + // Db persists channel state through the Store contract. This field // intentionally keeps the existing name while callers still construct // channels through the channeldb compatibility alias. The store @@ -814,7 +823,8 @@ func (c *OpenChannel) SyncPending(addr net.Addr, pendingHeight uint32) error { // commitment. Keys correspond to htlc indices and values indicate whether the // htlc was settled or failed. func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, - unsignedAckedUpdates []LogUpdate) (map[uint64]bool, error) { + unsignedAckedUpdates []LogUpdate, + revocationAuxSigs fn.Option[tlv.Blob]) (map[uint64]bool, error) { c.Lock() defer c.Unlock() @@ -826,10 +836,24 @@ func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, return nil, ErrNoRestoredChannelMutation } + // Record the aux sigs attached to the RevokeAndAck this commitment + // update corresponds to (custom channels only, None otherwise), so + // they persist alongside it and survive for retransmission. This + // overwrites the previous revocation's sigs, which can no longer be + // owed to the peer. The store serializes them from the channel + // itself, so they have to be set before the write, and are rolled + // back if the write fails: the in-memory copy must never hold sigs + // that were not persisted, or a retransmission would send a blob + // that does not survive a restart. + prevRevocationAuxSigs := c.RevocationAuxSigs + c.RevocationAuxSigs = revocationAuxSigs + finalHtlcs, err := c.Db.UpdateChannelCommitment( c, newCommitment, unsignedAckedUpdates, ) if err != nil { + c.RevocationAuxSigs = prevRevocationAuxSigs + return nil, err } diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index dfcb95b5ced..c22df7acb26 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -208,7 +208,9 @@ type BaseAuxJob struct { HTLC AuxHtlcDescriptor // Incoming is a boolean that indicates if the HTLC is incoming or - // outgoing. + // outgoing from the LOCAL party's perspective. This is used with + // WhoseCommit to determine the correct HTLC script variant + // (sender vs receiver). Incoming bool // CommitBlob is the commitment transaction blob that contains the aux @@ -218,6 +220,16 @@ type BaseAuxJob struct { // HtlcLeaf is the aux tap leaf that corresponds to the HTLC being // signed/verified. HtlcLeaf input.AuxTapLeaf + + // WhoseCommit indicates which party's commitment transaction the + // second-level HTLC belongs to. + WhoseCommit lntypes.ChannelParty + + // HtlcTimeout, if set, overrides the timeout logic in + // generateHtlcSignature and verifyHtlcSignature. When nil, + // the timeout is derived from Incoming (the normal CommitSig + // convention). When set, it is used directly. + HtlcTimeout fn.Option[uint32] } // AuxSigJob is a struct that contains all the information needed to sign an @@ -238,10 +250,24 @@ type AuxSigJob struct { Cancel <-chan struct{} } -// NewAuxSigJob creates a new AuxSigJob. +// NewAuxSigJob creates a new AuxSigJob. The whoseCommit parameter indicates +// which party's commitment the HTLC belongs to. +// +// HtlcTimeout is set explicitly to the CommitSig-time convention (an +// incoming HTLC signs the counterparty's timeout tx, which carries the CLTV; +// an outgoing HTLC signs their success tx, which has no locktime) so that +// the aux signer never has to re-derive it from the direction. Callers with +// a different convention (the revocation sign path, which signs the HTLC +// paths of our own commitment) override the field after construction. func NewAuxSigJob(sigJob SignJob, keyRing CommitmentKeyRing, incoming bool, htlc AuxHtlcDescriptor, commitBlob fn.Option[tlv.Blob], - htlcLeaf input.AuxTapLeaf, cancelChan <-chan struct{}) AuxSigJob { + htlcLeaf input.AuxTapLeaf, whoseCommit lntypes.ChannelParty, + cancelChan <-chan struct{}) AuxSigJob { + + htlcTimeout := fn.None[uint32]() + if incoming { + htlcTimeout = fn.Some(htlc.Timeout) + } return AuxSigJob{ SignDesc: sigJob.SignDesc, @@ -252,6 +278,8 @@ func NewAuxSigJob(sigJob SignJob, keyRing CommitmentKeyRing, incoming bool, Incoming: incoming, CommitBlob: commitBlob, HtlcLeaf: htlcLeaf, + WhoseCommit: whoseCommit, + HtlcTimeout: htlcTimeout, }, Resp: make(chan AuxSigJobResp, 1), Cancel: cancelChan, @@ -283,19 +311,34 @@ type AuxVerifyJob struct { BaseAuxJob } -// NewAuxVerifyJob creates a new AuxVerifyJob. +// NewAuxVerifyJob creates a new AuxVerifyJob for a signature the remote party +// sent for a second-level HTLC of our own commitment, which is what +// WhoseCommit is set to. +// +// HtlcTimeout is set explicitly to the CommitSig-time convention: on our +// local commitment an outgoing HTLC's signature covers our timeout tx +// (which carries the CLTV), while an incoming HTLC's signature covers our +// success tx (no locktime). Callers with a different convention (the +// revocation verify path) override the field after construction. func NewAuxVerifyJob(sig fn.Option[tlv.Blob], keyRing CommitmentKeyRing, incoming bool, htlc AuxHtlcDescriptor, commitBlob fn.Option[tlv.Blob], htlcLeaf input.AuxTapLeaf) AuxVerifyJob { + htlcTimeout := fn.None[uint32]() + if !incoming { + htlcTimeout = fn.Some(htlc.Timeout) + } + return AuxVerifyJob{ SigBlob: sig, BaseAuxJob: BaseAuxJob{ - KeyRing: keyRing, - HTLC: htlc, - Incoming: incoming, - CommitBlob: commitBlob, - HtlcLeaf: htlcLeaf, + KeyRing: keyRing, + HTLC: htlc, + Incoming: incoming, + CommitBlob: commitBlob, + HtlcLeaf: htlcLeaf, + WhoseCommit: lntypes.Local, + HtlcTimeout: htlcTimeout, }, } } diff --git a/lnwallet/channel.go b/lnwallet/channel.go index c59c7eaa959..65905863b5d 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -3780,7 +3780,8 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, auxSigBatch = append(auxSigBatch, NewAuxSigJob( sigJob, *keyRing, true, newAuxHtlcDescriptor(&htlc), - remoteCommitView.customBlob, auxLeaf, cancelChan, + remoteCommitView.customBlob, auxLeaf, + lntypes.Remote, cancelChan, )) } for _, htlc := range remoteCommitView.outgoingHTLCs { @@ -3863,13 +3864,952 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, auxSigBatch = append(auxSigBatch, NewAuxSigJob( sigJob, *keyRing, false, newAuxHtlcDescriptor(&htlc), - remoteCommitView.customBlob, auxLeaf, cancelChan, + remoteCommitView.customBlob, auxLeaf, + lntypes.Remote, cancelChan, )) } return sigBatch, auxSigBatch, cancelChan, nil } +// revocationAuxSigType is the TLV type used to store the remote party's +// aux signatures for their own second-level HTLCs in the HTLC +// CustomRecords within the revocation log. We use a different type than +// htlcCustomSigType to avoid collisions with the sigs the remote sent +// for OUR local commitment (stored during genHtlcSigValidationJobs). The +// number was drawn at random from the custom range, as the HTLC custom +// records are shared with every other user of that range. +const revocationAuxSigType uint64 = 884256149 + +// revokeAndAckAuxSigType is the TLV type of the custom record of a +// revoke_and_ack that carries the packed revocation aux sigs. The number was +// drawn at random from the custom range to keep clear of other users of the +// custom records of this message. +const revokeAndAckAuxSigType uint64 = 3496008566 + +// revocationAuxSigKey identifies an HTLC on a revoked commitment. HTLC +// indexes are per-offerer counters that both start at zero, so an index alone +// is ambiguous: a commitment routinely carries an HTLC offered by each side +// under the same index. The direction disambiguates them. +type revocationAuxSigKey struct { + // signerIncoming is true if the HTLC is incoming to the party that + // revokes the commitment and signs the entry, i.e. it was offered by + // the party receiving the revocation. + signerIncoming bool + + // htlcIndex is the index of the HTLC in its offerer's counter. + htlcIndex uint64 +} + +// revocationAuxSigEntry holds a single HTLC's revocation AuxSig, tagged with +// the HTLC's direction and index so the receiver can match sigs to HTLCs +// unambiguously regardless of HTLC ordering differences between the local +// and remote views. +// +// The sig covers the one second-level path the HTLC has on the signer's own +// commitment: HTLC-success for an HTLC incoming to the signer, HTLC-timeout +// for one the signer offered. It is empty for an HTLC that carries no aux +// outputs. +// +// On the wire, each entry is encoded as a TLV stream with three records +// (HtlcIndex / Sig / SignerIncoming). The full blob is a BigSize-prefixed +// count followed by length-prefixed entry streams: TLV streams aren't +// natively self-delimiting at the list level, so we wrap each entry with +// its byte length so the decoder can frame the next entry. +type revocationAuxSigEntry struct { + revocationAuxSigKey + + sig []byte +} + +const ( + // revAuxSigIndexType is the TLV type of an entry's HTLC index. + revAuxSigIndexType tlv.Type = 0 + + // revAuxSigSigType is the TLV type of an entry's aux signature. + revAuxSigSigType tlv.Type = 1 + + // revAuxSigIncomingType is the TLV type of an entry's direction. + revAuxSigIncomingType tlv.Type = 2 +) + +// encode writes the entry as a TLV stream. +func (e *revocationAuxSigEntry) encode(w io.Writer) error { + htlcIdx := e.htlcIndex + sig := e.sig + + var incoming uint8 + if e.signerIncoming { + incoming = 1 + } + + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(revAuxSigIndexType, &htlcIdx), + tlv.MakePrimitiveRecord(revAuxSigSigType, &sig), + tlv.MakePrimitiveRecord(revAuxSigIncomingType, &incoming), + ) + if err != nil { + return err + } + + return stream.Encode(w) +} + +// decode reads the entry from a TLV stream. The HTLC index and the direction +// are mandatory: without either the entry cannot be attributed to an HTLC. +func (e *revocationAuxSigEntry) decode(r io.Reader) error { + var incoming uint8 + + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(revAuxSigIndexType, &e.htlcIndex), + tlv.MakePrimitiveRecord(revAuxSigSigType, &e.sig), + tlv.MakePrimitiveRecord(revAuxSigIncomingType, &incoming), + ) + if err != nil { + return err + } + + parsed, err := stream.DecodeWithParsedTypesP2P(r) + if err != nil { + return err + } + + if _, ok := parsed[revAuxSigIndexType]; !ok { + return errors.New("missing HTLC index") + } + if _, ok := parsed[revAuxSigIncomingType]; !ok { + return errors.New("missing HTLC direction") + } + if incoming > 1 { + return fmt.Errorf("invalid HTLC direction %d", incoming) + } + e.signerIncoming = incoming == 1 + + return nil +} + +// packRevocationAuxSigs encodes a list of tagged HTLC sigs into a single +// blob. Format: BigSize count + repeated [BigSize entryLen + +// entry-TLV-stream] records. Each entry's TLV stream carries records 0 +// (HtlcIndex), 1 (Sig), 2 (SignerIncoming). +func packRevocationAuxSigs(entries []revocationAuxSigEntry) ([]byte, error) { + var ( + buf bytes.Buffer + scratch [8]byte + ) + + if err := tlv.WriteVarInt( + &buf, uint64(len(entries)), &scratch, + ); err != nil { + return nil, fmt.Errorf("write entry count: %w", err) + } + + for i := range entries { + var inner bytes.Buffer + if err := entries[i].encode(&inner); err != nil { + return nil, fmt.Errorf("encode entry %d: %w", i, err) + } + + if err := tlv.WriteVarInt( + &buf, uint64(inner.Len()), &scratch, + ); err != nil { + return nil, fmt.Errorf("write entry %d length: %w", + i, err) + } + if _, err := buf.Write(inner.Bytes()); err != nil { + return nil, fmt.Errorf("write entry %d bytes: %w", + i, err) + } + } + + return buf.Bytes(), nil +} + +// unpackRevocationAuxSigs decodes a blob produced by packRevocationAuxSigs +// into a map of HTLC (direction, index) to its entry. +// +// The blob comes from the remote peer, so nothing in it is trusted. The +// entry count is never used to size an allocation, every entry must consume +// exactly the length it declares, an HTLC may appear only once, and no bytes +// may follow the last entry. +func unpackRevocationAuxSigs( + blob []byte) (map[revocationAuxSigKey]revocationAuxSigEntry, error) { + + r := bytes.NewReader(blob) + var scratch [8]byte + + count, err := tlv.ReadVarInt(r, &scratch) + if err != nil { + return nil, fmt.Errorf("read entry count: %w", err) + } + + // Every entry takes at least one byte (its length prefix), so a count + // beyond what is left of the blob can only be a lie. + if count > uint64(r.Len()) { + return nil, fmt.Errorf("entry count %d exceeds the %d bytes "+ + "of entry data", count, r.Len()) + } + + result := make(map[revocationAuxSigKey]revocationAuxSigEntry) + for i := range count { + entryLen, err := tlv.ReadVarInt(r, &scratch) + if err != nil { + return nil, fmt.Errorf("read entry %d length: %w", + i, err) + } + if entryLen > uint64(r.Len()) { + return nil, fmt.Errorf("entry %d length %d exceeds "+ + "the %d bytes left", i, entryLen, r.Len()) + } + + // The entry is decoded from a view of exactly its declared + // length. The TLV decoder reads until that view is exhausted, + // so the entry can neither run into the next one nor leave + // undeclared bytes behind. + entryBytes := make([]byte, entryLen) + if _, err := io.ReadFull(r, entryBytes); err != nil { + return nil, fmt.Errorf("read entry %d: %w", i, err) + } + + var entry revocationAuxSigEntry + err = entry.decode(bytes.NewReader(entryBytes)) + if err != nil { + return nil, fmt.Errorf("decode entry %d: %w", i, err) + } + + if _, ok := result[entry.revocationAuxSigKey]; ok { + return nil, fmt.Errorf("duplicate entry for HTLC "+ + "index %d (signer incoming=%v)", + entry.htlcIndex, entry.signerIncoming) + } + result[entry.revocationAuxSigKey] = entry + } + + if r.Len() != 0 { + return nil, fmt.Errorf("%d trailing bytes after the last "+ + "entry", r.Len()) + } + + return result, nil +} + +// injectRevocationAuxSigs takes the packed aux sig blob from a RevokeAndAck +// and injects individual HTLC sigs into the remote commitment's HTLC entries. +// This must be called before AdvanceCommitChainTail so the sigs are persisted +// in the revocation log. +func (lc *LightningChannel) injectRevocationAuxSigs(auxSigBlob []byte) { + sigMap, err := unpackRevocationAuxSigs(auxSigBlob) + if err != nil { + lc.log.Warnf("Unable to unpack revocation aux sigs: %v", err) + return + } + + sigType := revocationAuxSigType + htlcs := lc.channelState.RemoteCommitment.Htlcs + for i := range htlcs { + // The HTLC's custom records originate from the peer's + // UpdateAddHTLC for the HTLCs it offered. Whatever sits under + // our record type there was not verified as a revocation sig, + // so it must never make it into the revocation log, where the + // breach code would later take it for one. + delete(htlcs[i].CustomRecords, sigType) + + // Match sigs to HTLCs by direction and HTLC index. An HTLC + // that is incoming to us was offered by us to the signer, so + // it is outgoing for the signer and vice versa. + entry, ok := sigMap[revocationAuxSigKey{ + signerIncoming: !htlcs[i].Incoming, + htlcIndex: htlcs[i].HtlcIndex, + }] + if !ok || len(entry.sig) == 0 { + continue + } + + if htlcs[i].CustomRecords == nil { + htlcs[i].CustomRecords = make(lnwire.CustomRecords) + } + htlcs[i].CustomRecords[sigType] = entry.sig + } +} + +// exchangesRevocationAuxSigs is the single gate deciding whether revocation +// AuxSigs are attached to the outgoing RevokeAndAck that revokes the given +// commitment, and verified on the incoming one. This is strictly a +// custom-channel feature, and the gate requires ALL of: +// +// 1. The channel type carries a tapscript root. Only the aux/custom (taproot +// asset) funding path ever sets TapscriptRootBit, so no vanilla lnd +// channel can pass this check. +// +// 2. An aux signer is attached to the channel. +// +// 3. The commitment being revoked was built with SigHashDefault second-level +// HTLCs (DeterministicHTLCs). The commitment already exists, so this +// reads the sighash recorded in its own custom blob. Both peers hold the +// same record for the same commitment, so they always agree on whether +// its revocation carries the signatures, even while the sighash type +// used for new commitments is changing. +// +// For every other channel this returns false: nothing is signed, no custom +// records are attached to or read from RevokeAndAck, and the message stays +// byte-identical to before this feature existed. +func (lc *LightningChannel) exchangesRevocationAuxSigs( + revoked *commitment) bool { + + // Explicit hard gate on the channel type. The sighash check below + // can only ever be true for tapscript-root channels anyway (see + // ResolveHtlcSigHashType), but checking it here first makes the + // custom-channel-only isolation locally auditable. + if !lc.channelState.ChanType.HasTapscriptRoot() { + return false + } + + if lc.auxSigner.IsNone() || revoked == nil { + return false + } + + return lc.commitSigHashDefault(revoked.customBlob) +} + +// revocationAuxVerifyJob builds the verification job for a single HTLC's +// revocation aux sig entry. +// +// The sig covers the HTLC's second-level path on the signer's own +// commitment. From OUR perspective the direction is mirrored: an HTLC that +// is incoming to us is outgoing for the signer, whose second-level path for +// it is the timeout, and an HTLC that is outgoing for us is incoming for the +// signer, whose second-level path for it is the success. +// +// So: our incoming -> signer's outgoing -> timeout path +// +// our outgoing -> signer's incoming -> success path +// +// A job is built even when the entry carries no sig: only the aux signer +// knows whether the HTLC carries aux outputs and therefore owes one, so it +// is the one to reject a missing sig. +func revocationAuxVerifyJob(sigEntry revocationAuxSigEntry, + htlc *paymentDescriptor, incoming bool, keyRing *CommitmentKeyRing, + commitBlob fn.Option[tlv.Blob], auxLeaf input.AuxTapLeaf) AuxVerifyJob { + + sigBlob := fn.None[tlv.Blob]() + if len(sigEntry.sig) > 0 { + sigBlob = fn.Some[tlv.Blob](sigEntry.sig) + } + + job := AuxVerifyJob{ + SigBlob: sigBlob, + BaseAuxJob: BaseAuxJob{ + OutputIndex: htlc.remoteOutputIndex, + KeyRing: *keyRing, + HTLC: newAuxHtlcDescriptor(htlc), + Incoming: incoming, + CommitBlob: commitBlob, + HtlcLeaf: auxLeaf, + WhoseCommit: lntypes.Remote, + }, + } + + // Our incoming is the signer's outgoing, which goes through the + // timeout path and needs the timeout. The success path does not. + if incoming { + job.HtlcTimeout = fn.Some(htlc.Timeout) + } + + return job +} + +// verifyRevocationAuxSigs verifies the aux sigs received in a RevokeAndAck +// message. It derives the same key ring that the breach-time code will use +// (DeriveCommitmentKeys with whoseCommit=Remote and our local configs) and +// verifies the signatures against the remote commitment's HTLCs. If the +// signatures don't verify now, they won't work at breach time either. +// +// The commitPoint must be the RemoteCurrentRevocation BEFORE it is rotated. +func (lc *LightningChannel) verifyRevocationAuxSigs( + auxSigBlob []byte, commitPoint *btcec.PublicKey) error { + + // Get the remote commitment view (about to be revoked). + remoteCommitView := lc.commitChains.Remote.tail() + + // Defense in depth: this must only ever run for aux/custom channels + // revoking a DeterministicHTLCs commitment (the caller already + // checks). + if !lc.exchangesRevocationAuxSigs(remoteCommitView) { + return nil + } + + // If there's no aux signer, nothing to verify. + if lc.auxSigner.IsNone() { + return nil + } + + auxSigner, _ := lc.auxSigner.UnwrapOrErr( + fmt.Errorf("no aux signer"), + ) + + // Unpack the tagged blob. An absent blob simply means zero entries: + // the per-HTLC loop below is what decides whether that is acceptable + // (all HTLCs dust or none at all) or a withheld signature (any + // non-dust HTLC present). + sigMap := make(map[revocationAuxSigKey]revocationAuxSigEntry) + if len(auxSigBlob) > 0 { + var err error + sigMap, err = unpackRevocationAuxSigs(auxSigBlob) + if err != nil { + return fmt.Errorf("unable to unpack revocation aux "+ + "sigs for verification: %w", err) + } + } + + numHTLCs := len(remoteCommitView.incomingHTLCs) + + len(remoteCommitView.outgoingHTLCs) + if numHTLCs == 0 { + return nil + } + + // Derive the key ring the same way the breach code does. + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Remote, + lc.channelState.ChanType, + &lc.channelState.LocalChanCfg, + &lc.channelState.RemoteChanCfg, + ) + + chanState := lc.channelState + chanType := chanState.ChanType + remoteChanCfg := chanState.RemoteChanCfg + feePerKw := remoteCommitView.feePerKw + dustLimit := remoteChanCfg.DustLimit + + // The gate above established that the commitment being revoked was + // built with SigHashDefault second-level HTLCs, so that is what its + // dust decisions are made against. + const sigHashDefault = true + + // Fetch aux leaves for the remote commitment. + diskCommit := remoteCommitView.toDiskCommit(lntypes.Remote) + auxResult, err := fn.MapOptionZ( + lc.leafStore, + func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { + return s.FetchLeavesFromCommit( + NewAuxChanState(chanState), *diskCommit, + *keyRing, lntypes.Remote, + ) + }, + ).Unpack() + if err != nil { + return fmt.Errorf("unable to fetch aux leaves for "+ + "revocation verification: %w", err) + } + + // Build a verify job for each non-dust HTLC, matched by direction and + // HTLC index from the unpacked sig map. + type htlcEntry struct { + htlc *paymentDescriptor + incoming bool + } + var htlcList []htlcEntry + for i := range remoteCommitView.incomingHTLCs { + htlcList = append(htlcList, htlcEntry{ + htlc: &remoteCommitView.incomingHTLCs[i], + incoming: true, + }) + } + for i := range remoteCommitView.outgoingHTLCs { + htlcList = append(htlcList, htlcEntry{ + htlc: &remoteCommitView.outgoingHTLCs[i], + incoming: false, + }) + } + + auxVerifyJobs := make([]AuxVerifyJob, 0, numHTLCs) + commitBlob := remoteCommitView.customBlob + consumedEntries := make(map[revocationAuxSigKey]struct{}, len(sigMap)) + + for _, entry := range htlcList { + htlc := entry.htlc + incoming := entry.incoming + + if HtlcIsDust( + chanType, incoming, lntypes.Remote, feePerKw, + htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, + ) { + + continue + } + + // An HTLC incoming to us was offered by us, so it is incoming + // from the signer's point of view when it is outgoing from + // ours. + key := revocationAuxSigKey{ + signerIncoming: !incoming, + htlcIndex: htlc.HtlcIndex, + } + sigEntry, ok := sigMap[key] + if !ok { + return fmt.Errorf("no revocation aux sig for HTLC "+ + "index %d (incoming=%v)", htlc.HtlcIndex, + incoming) + } + consumedEntries[key] = struct{}{} + + // Determine the aux leaf for this HTLC. + var auxLeaf input.AuxTapLeaf + if incoming { + auxLeaf = fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.IncomingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(auxResult.AuxLeaves) + } else { + auxLeaf = fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.OutgoingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(auxResult.AuxLeaves) + } + + auxVerifyJobs = append(auxVerifyJobs, revocationAuxVerifyJob( + sigEntry, htlc, incoming, keyRing, commitBlob, + auxLeaf, + )) + } + + // Every received entry must correspond to a non-dust HTLC on the + // revoked commitment: an honest signer never packs anything else, so + // entries with unknown or dust HTLC indexes are garbage we refuse to + // accept a revocation over. + for key := range sigMap { + if _, ok := consumedEntries[key]; !ok { + return fmt.Errorf("unexpected revocation aux sig "+ + "entry for HTLC index %d (signer incoming=%v)", + key.htlcIndex, key.signerIncoming) + } + } + + if len(auxVerifyJobs) == 0 { + return nil + } + + lc.log.Infof("Verifying revocation aux sigs of %d HTLCs against "+ + "breach-time key ring", len(auxVerifyJobs)) + + err = auxSigner.VerifySecondLevelSigs( + NewAuxChanState(lc.channelState), + remoteCommitView.txn, auxVerifyJobs, + ) + if err != nil { + return fmt.Errorf("revocation aux sig verification "+ + "failed: %w", err) + } + + lc.log.Infof("Revocation aux sig verification passed") + + return nil +} + +// htlcAuxSigParams bundles the parameters shared across both the incoming +// and outgoing HTLC aux-signing loops. +type htlcAuxSigParams struct { + chanType channeldb.ChannelType + isRemoteInitiator bool + localChanCfg channeldb.ChannelConfig + localHtlcKeyTweak []byte + feePerKw chainfee.SatPerKWeight + dustLimit btcutil.Amount + txHash chainhash.Hash + ourDelay uint32 + leaseExpiry uint32 + sigHashDefault bool + sigHashType txscript.SigHashType + keyRing *CommitmentKeyRing + auxResult CommitDiffAuxResult + commitView *commitment + cancelChan chan struct{} +} + +// signHTLCAuxSigs creates the aux sig jobs for the non-dust HTLCs of one +// direction on the local commitment. Each HTLC is signed for the one +// second-level path it has on our own commitment: success for an incoming +// HTLC, timeout for an outgoing one. +func (p *htlcAuxSigParams) signHTLCAuxSigs(htlcs []paymentDescriptor, + incoming bool) ([]AuxSigJob, error) { + + var jobs []AuxSigJob + for i := range htlcs { + htlc := &htlcs[i] + if HtlcIsDust( + p.chanType, incoming, lntypes.Local, + p.feePerKw, htlc.Amount.ToSatoshis(), + p.dustLimit, p.sigHashDefault, + ) { + + continue + } + + job, err := p.signHTLC(htlc, incoming) + if err != nil { + return nil, err + } + + jobs = append(jobs, job) + } + + return jobs, nil +} + +// signHTLC creates the AuxSigJob for the second-level path of an HTLC on our +// own commitment: the success tx for an incoming HTLC, the timeout tx for an +// outgoing one. +func (p *htlcAuxSigParams) signHTLC(htlc *paymentDescriptor, + incoming bool) (AuxSigJob, error) { + + auxLeaf := p.getAuxLeaf(htlc, incoming) + op := wire.OutPoint{ + Hash: p.txHash, + Index: uint32(htlc.localOutputIndex), + } + + secondLevelTx, _, err := p.createSecondLevelTx( + op, htlc, incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, err + } + + amt := htlc.Amount.ToSatoshis() + txOut := p.commitView.txn.TxOut[htlc.localOutputIndex] + prevFetcher := txscript.NewCannedPrevOutputFetcher( + txOut.PkScript, int64(amt), + ) + + job, err := p.buildSigJob( + secondLevelTx, txOut, prevFetcher, htlc, incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, err + } + + // The success path has no timeout, the timeout path carries the + // HTLC's. + if incoming { + job.HtlcTimeout = fn.None[uint32]() + } else { + job.HtlcTimeout = fn.Some(htlc.Timeout) + } + + return job, nil +} + +// createSecondLevelTx creates the second-level HTLC transaction for +// the given path. When incoming is true a success-tx is created; +// when false a timeout-tx is created. Returns the tx and its fee. +func (p *htlcAuxSigParams) createSecondLevelTx( + op wire.OutPoint, htlc *paymentDescriptor, + incoming bool, auxLeaf input.AuxTapLeaf, +) (*wire.MsgTx, btcutil.Amount, error) { + + if incoming { + fee := HtlcSuccessFee( + p.chanType, p.feePerKw, p.sigHashDefault, + ) + amt := htlc.Amount.ToSatoshis() - fee + tx, err := CreateHtlcSuccessTx( + p.chanType, p.isRemoteInitiator, op, + amt, p.ourDelay, p.leaseExpiry, + p.keyRing.RevocationKey, + p.keyRing.ToLocalKey, auxLeaf, + p.sigHashDefault, + ) + + return tx, fee, err + } + + fee := HtlcTimeoutFee( + p.chanType, p.feePerKw, p.sigHashDefault, + ) + amt := htlc.Amount.ToSatoshis() - fee + tx, err := CreateHtlcTimeoutTx( + p.chanType, p.isRemoteInitiator, op, amt, + htlc.Timeout, p.ourDelay, p.leaseExpiry, + p.keyRing.RevocationKey, + p.keyRing.ToLocalKey, auxLeaf, + p.sigHashDefault, + ) + + return tx, fee, err +} + +// buildSigJob creates an AuxSigJob for a second-level HTLC +// transaction, wrapping the sign descriptor and script generation. +func (p *htlcAuxSigParams) buildSigJob( + tx *wire.MsgTx, txOut *wire.TxOut, + prevFetcher txscript.PrevOutputFetcher, + htlc *paymentDescriptor, incoming bool, + auxLeaf input.AuxTapLeaf, +) (AuxSigJob, error) { + + hashCache := txscript.NewTxSigHashes(tx, prevFetcher) + htlcScript, err := genHtlcScript( + p.chanType, incoming, lntypes.Local, + htlc.Timeout, htlc.RHash, p.keyRing, + fn.None[txscript.TapLeaf](), + ) + if err != nil { + return AuxSigJob{}, err + } + + ws := htlcScript.WitnessScriptToSign() + sigJob := SignJob{ + SignDesc: input.SignDescriptor{ + KeyDesc: p.localChanCfg.HtlcBasePoint, + SingleTweak: p.localHtlcKeyTweak, + WitnessScript: ws, + Output: txOut, + PrevOutputFetcher: prevFetcher, + HashType: p.sigHashType, + SigHashes: hashCache, + InputIndex: 0, + }, + Tx: tx, + OutputIndex: htlc.localOutputIndex, + } + if p.chanType.IsTaproot() { + sigJob.SignDesc.SignMethod = input.TaprootScriptSpendSignMethod + } + + auxJob := NewAuxSigJob( + sigJob, *p.keyRing, incoming, + newAuxHtlcDescriptor(htlc), + p.commitView.customBlob, auxLeaf, + lntypes.Local, p.cancelChan, + ) + + return auxJob, nil +} + +// getAuxLeaf returns the aux tap leaf for the given HTLC. +func (p *htlcAuxSigParams) getAuxLeaf( + htlc *paymentDescriptor, incoming bool, +) input.AuxTapLeaf { + + if incoming { + return fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.IncomingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(p.auxResult.AuxLeaves) + } + + return fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.OutgoingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(p.auxResult.AuxLeaves) +} + +// signLocalHtlcAuxSigs signs the second-level HTLC virtual packets for the +// current local commitment (the one being revoked). These signatures allow +// the remote party to reconstruct valid aux proofs for the +// commitment-to-second-level transition if a breach occurs. The returned +// blob is packed in the same format as CommitSig aux sigs and can be +// attached to RevokeAndAck.CustomRecords. +// +// This method must be called BEFORE advanceTail() since it needs access to the +// current local commitment view and the commitment secret at currentHeight. +func (lc *LightningChannel) signLocalHtlcAuxSigs() ([]byte, error) { + // Get the current local commitment view (about to be revoked). + localCommitView := lc.commitChains.Local.tail() + + // Defense in depth: this must only ever run for aux/custom channels + // revoking a DeterministicHTLCs commitment (the caller already + // checks). + if !lc.exchangesRevocationAuxSigs(localCommitView) { + return nil, nil + } + + // If there's no aux signer, nothing to do. + if lc.auxSigner.IsNone() { + return nil, nil + } + + // Check if there are any HTLCs to sign. + numHTLCs := len(localCommitView.incomingHTLCs) + + len(localCommitView.outgoingHTLCs) + if numHTLCs == 0 { + return nil, nil + } + + // Derive the key ring for our local commitment using the + // standard perspective (whoseCommit=Local, standard config + // order). This matches how the commitment was originally + // built, so the AuxSig will be over the actual on-chain + // second-level HTLC outputs. + commitSecret, err := lc.channelState.RevocationProducer.AtIndex( + lc.currentHeight, + ) + if err != nil { + return nil, err + } + commitPoint := input.ComputeCommitmentPoint(commitSecret[:]) + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Local, + lc.channelState.ChanType, + &lc.channelState.LocalChanCfg, + &lc.channelState.RemoteChanCfg, + ) + + chanState := lc.channelState + chanType := chanState.ChanType + + var leaseExpiry uint32 + if chanType.HasLeaseExpiration() { + leaseExpiry = chanState.ThawHeight + } + + // Sign with the sighash recorded for the commitment being revoked, + // which the gate above established to be SigHashDefault. This is the + // sighash its second-level HTLC transactions were built with, no + // matter what new commitments use by now. + sigHashType := lc.commitSigHashType(localCommitView.customBlob) + sigHashDefault := sigHashType == txscript.SigHashDefault + + // Fetch aux leaves for our local commitment, matching how + // the commitment was originally constructed. + diskCommit := localCommitView.toDiskCommit(lntypes.Local) + auxResult, err := fn.MapOptionZ( + lc.leafStore, + func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { + return s.FetchLeavesFromCommit( + NewAuxChanState(chanState), *diskCommit, + *keyRing, lntypes.Local, + ) + }, + ).Unpack() + if err != nil { + return nil, fmt.Errorf("unable to fetch aux leaves: %w", err) + } + + cancelChan := make(chan struct{}) + + localChanCfg := chanState.LocalChanCfg + params := htlcAuxSigParams{ + chanType: chanType, + isRemoteInitiator: !chanState.IsInitiator, + localChanCfg: localChanCfg, + localHtlcKeyTweak: keyRing.LocalHtlcKeyTweak, + feePerKw: localCommitView.feePerKw, + dustLimit: chanState.LocalChanCfg.DustLimit, + txHash: localCommitView.txn.TxHash(), + ourDelay: uint32(localChanCfg.CsvDelay), + leaseExpiry: leaseExpiry, + sigHashDefault: sigHashDefault, + sigHashType: sigHashType, + keyRing: keyRing, + auxResult: auxResult, + commitView: localCommitView, + cancelChan: cancelChan, + } + + // Sign the second-level path of every non-dust HTLC: success for the + // incoming ones, timeout for the outgoing ones. + inJobs, err := params.signHTLCAuxSigs( + localCommitView.incomingHTLCs, true, + ) + if err != nil { + return nil, err + } + + outJobs, err := params.signHTLCAuxSigs( + localCommitView.outgoingHTLCs, false, + ) + if err != nil { + return nil, err + } + + auxSigBatch := append(inJobs, outJobs...) //nolint:gocritic + + if len(auxSigBatch) == 0 { + return nil, nil + } + + // Sort by output index, the order the aux signer processes a batch + // in elsewhere (same as genRemoteHtlcSigJobs). + slices.SortFunc(auxSigBatch, func(i, j AuxSigJob) int { + return cmp.Compare(i.OutputIndex, j.OutputIndex) + }) + + // Submit the signing batch using the standard chanState + // (matching the commitment construction perspective). + auxSigner, _ := lc.auxSigner.UnwrapOrErr( + fmt.Errorf("no aux signer"), + ) + err = auxSigner.SubmitSecondLevelSigBatch( + NewAuxChanState(lc.channelState), + localCommitView.txn, auxSigBatch, + ) + if err != nil { + return nil, fmt.Errorf("unable to submit aux sig batch: %w", + err) + } + + // Collect the signatures from the batch into entries tagged with the + // HTLC's direction and index. The index alone would not do: both + // parties count the HTLCs they offer from zero, so an incoming and an + // outgoing HTLC regularly share one. + entries := make([]revocationAuxSigEntry, len(auxSigBatch)) + for i, sigJob := range auxSigBatch { + resp := <-sigJob.Resp + if resp.Err != nil { + close(cancelChan) + return nil, fmt.Errorf("aux sig job %d "+ + "failed: %w", i, resp.Err) + } + + entries[i] = revocationAuxSigEntry{ + revocationAuxSigKey: revocationAuxSigKey{ + signerIncoming: sigJob.Incoming, + htlcIndex: sigJob.HTLC.HtlcIndex, + }, + sig: resp.SigBlob.UnwrapOr(nil), + } + } + + // Pack the entries in a deterministic order. + slices.SortFunc(entries, func(i, j revocationAuxSigEntry) int { + if i.signerIncoming != j.signerIncoming { + if i.signerIncoming { + return 1 + } + + return -1 + } + + return cmp.Compare(i.htlcIndex, j.htlcIndex) + }) + + // The blob is packed and attached even if no entry carries actual sig + // data (e.g. all non-dust HTLCs are BTC-only): the receiver requires + // one entry per non-dust HTLC, in lockstep with the BTC-level + // signatures, so it can tell a sig-less HTLC apart from a withheld + // signature. + packed, err := packRevocationAuxSigs(entries) + if err != nil { + return nil, fmt.Errorf("pack revocation aux sigs: %w", err) + } + + return packed, nil +} + // createCommitDiff will create a commit diff given a new pending commitment // for the remote party and the necessary signatures for the remote party to // validate this new state. This function is called right before sending the @@ -4948,6 +5888,24 @@ func (lc *LightningChannel) ProcessChanSyncMsg(ctx context.Context, return nil, nil, nil, err } + // Re-attach the revocation aux sigs that accompanied the + // original RevokeAndAck. This is a custom-channel-only + // concern: RevocationAuxSigs is only ever set (persisted + // atomically with our commitment tail advance) when + // exchangesRevocationAuxSigs held at revocation time, and the + // receiving peer requires the sigs for every non-dust HTLC on + // the revoked commitment. + lc.channelState.RevocationAuxSigs.WhenSome( + func(sigs tlv.Blob) { + revocationMsg.CustomRecords = make( + lnwire.CustomRecords, + ) + + recType := revokeAndAckAuxSigType + revocationMsg.CustomRecords[recType] = sigs + }, + ) + updates = append(updates, revocationMsg) // Next, as a precaution, we'll check a special edge case. If @@ -6219,6 +7177,37 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, lc.commitChains.Local.tail().height, lc.currentHeight+1) + // Attach revocation AuxSigs to the RevokeAndAck, but ONLY for + // aux/custom (taproot asset) channels with the DeterministicHTLCs + // feature negotiated: see exchangesRevocationAuxSigs. A vanilla lnd + // channel never signs or appends these records and its RevokeAndAck + // is byte-identical to before this feature. Without + // DeterministicHTLCs the remote party has no use for the signatures + // (and wouldn't know how to parse them). + revocationAuxSigs := fn.None[tlv.Blob]() + if lc.exchangesRevocationAuxSigs(lc.commitChains.Local.tail()) { + // A signing failure fails the revocation as a whole: the + // receiving peer requires the sigs for every non-dust HTLC, + // so sending a sig-less RevokeAndAck would just fail the + // channel on their side instead. Nothing has been advanced or + // persisted yet, so failing here is safe and retryable. + auxSigBlob, err := lc.signLocalHtlcAuxSigs() + if err != nil { + return nil, nil, nil, fmt.Errorf("unable to sign "+ + "local HTLC aux sigs for revocation: %w", err) + } + if auxSigBlob != nil { + revocationMsg.CustomRecords = + make(lnwire.CustomRecords) + + recType := revokeAndAckAuxSigType + revocationMsg.CustomRecords[recType] = + auxSigBlob + + revocationAuxSigs = fn.Some[tlv.Blob](auxSigBlob) + } + } + // Advance our tail, as we've revoked our previous state. lc.commitChains.Local.advanceTail() lc.currentHeight++ @@ -6228,8 +7217,11 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, chainTail := lc.commitChains.Local.tail() newCommitment := chainTail.toDiskCommit(lntypes.Local) + // The aux sigs (custom channels only, None otherwise) are persisted + // atomically with the commitment advance, so a retransmission of this + // RevokeAndAck carries the exact same signatures. finalHtlcs, err := lc.channelState.UpdateCommitment( - newCommitment, unsignedAckedUpdates, + newCommitment, unsignedAckedUpdates, revocationAuxSigs, ) if err != nil { return nil, nil, nil, err @@ -6508,6 +7500,36 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) ( lc.musigSessions.RemoteSession = session } + // Revocation AuxSigs are a custom-channel-only concern. On aux/custom + // (taproot asset) channels with DeterministicHTLCs negotiated, the + // RevokeAndAck carries aux sigs for the remote party's second-level + // HTLCs; we verify them against the breach-time key ring before + // accepting the revocation, then store them in the revocation log for + // breach recovery. For every non-custom channel + // exchangesRevocationAuxSigs is false, so we skip this block entirely + // and never inspect CustomRecords. + if lc.exchangesRevocationAuxSigs(lc.commitChains.Remote.tail()) { + recType := revokeAndAckAuxSigType + auxSigBlob := revMsg.CustomRecords[recType] + + // The blob is verified unconditionally: an absent blob is not + // a pass. The peer owes us one entry per non-dust HTLC on the + // revoked commitment (mirroring the aux sig count check on + // CommitSig), otherwise withholding the sigs would silently + // strip our breach protection. + err = lc.verifyRevocationAuxSigs( + auxSigBlob, currentCommitPoint, + ) + if err != nil { + return nil, nil, fmt.Errorf("invalid "+ + "revocation aux sigs: %w", err) + } + + if len(auxSigBlob) > 0 { + lc.injectRevocationAuxSigs(auxSigBlob) + } + } + // At this point, the revocation has been accepted, and we've rotated // the current revocation key+hash for the remote party. Therefore we // sync now to ensure the revocation producer state is consistent with diff --git a/lnwallet/revocation_aux_sig_test.go b/lnwallet/revocation_aux_sig_test.go new file mode 100644 index 00000000000..bf8a2f73c67 --- /dev/null +++ b/lnwallet/revocation_aux_sig_test.go @@ -0,0 +1,1434 @@ +package lnwallet + +import ( + "bytes" + "cmp" + "crypto/sha256" + "errors" + "fmt" + "math" + "runtime" + "slices" + "testing" + + "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2" + "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/lntypes" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// newRevAuxSigEntry is a shorthand for building a revocation aux sig entry. +func newRevAuxSigEntry(signerIncoming bool, htlcIndex uint64, + sig []byte) revocationAuxSigEntry { + + return revocationAuxSigEntry{ + revocationAuxSigKey: revocationAuxSigKey{ + signerIncoming: signerIncoming, + htlcIndex: htlcIndex, + }, + sig: sig, + } +} + +// TestPackUnpackRevocationAuxSigs tests the round-trip encoding and decoding +// of revocation aux sig entries. +func TestPackUnpackRevocationAuxSigs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + entries []revocationAuxSigEntry + }{ + { + name: "empty entries", + entries: []revocationAuxSigEntry{}, + }, + { + name: "single entry with one HTLC", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry( + true, 42, []byte{0xaa, 0xbb, 0xcc}, + ), + }, + }, + { + name: "multiple entries with various HTLC indices", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry(false, 0, []byte{0x01}), + newRevAuxSigEntry( + true, 100, []byte{0x04, 0x05, 0x06}, + ), + newRevAuxSigEntry( + false, 999, []byte{0x08, 0x09}, + ), + }, + }, + { + // Both parties count the HTLCs they offer from zero, + // so the same index in both directions is the normal + // case and must not collapse into one entry. + name: "same HTLC index in both directions", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry(false, 0, []byte{0x0a}), + newRevAuxSigEntry(true, 0, []byte{0x0b}), + }, + }, + { + name: "entry without a sig", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry(true, 7, []byte{}), + }, + }, + { + name: "max uint64 HTLC index", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry( + false, math.MaxUint64, + []byte{0xde, 0xad}, + ), + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + packed, err := packRevocationAuxSigs(tc.entries) + require.NoError(t, err) + + sigMap, err := unpackRevocationAuxSigs(packed) + require.NoError(t, err) + + require.Len(t, sigMap, len(tc.entries)) + + for _, entry := range tc.entries { + got, ok := sigMap[entry.revocationAuxSigKey] + require.True(t, ok, "missing HTLC index %d "+ + "(signer incoming=%v)", + entry.htlcIndex, entry.signerIncoming) + + require.Equal( + t, entry.revocationAuxSigKey, + got.revocationAuxSigKey, + ) + require.Equal(t, entry.sig, got.sig) + } + }) + } +} + +// TestRevokeAndAckAuxSigsCustomOnly asserts the custom-channel-only gating of +// the revocation AuxSig hooks: on a NON-custom taproot channel, even with an +// aux signer present that negotiates SigHashDefault, RevokeCurrentCommitment +// must not attach any custom records to the RevokeAndAck, and +// ReceiveRevocation must accept a revocation while ignoring any custom +// records it may carry. +func TestRevokeAndAckAuxSigsCustomOnly(t *testing.T) { + t.Parallel() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err, "unable to create test channels") + + // An aux signer that would negotiate SigHashDefault. Since the + // channel type carries no tapscript root, the custom-channel gate + // must ignore it entirely. It is attached right before the + // revocation steps below (rather than at channel creation) so the + // unrelated CommitSig-time aux machinery stays out of the picture. + pushySigner := fn.Some[AuxSigner](&sigHashOverrideSigner{ + MockAuxSigner: NewAuxSignerMock(nil), + sigHash: txscript.SigHashDefault, + }) + + // Lock in an HTLC so the revoked commitment actually carries one. + paymentPreimage := bytes.Repeat([]byte{1}, 32) + paymentHash := sha256.Sum256(paymentPreimage) + htlcAmt := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: paymentHash, + Amount: htlcAmt, + Expiry: uint32(5), + } + _, err = aliceChannel.AddHTLC(htlc, nil) + require.NoError(t, err) + _, err = bobChannel.ReceiveHTLC(htlc) + require.NoError(t, err) + + aliceNewCommit, err := aliceChannel.SignNextCommitment(t.Context()) + require.NoError(t, err) + err = bobChannel.ReceiveNewCommitment(aliceNewCommit.CommitSigs) + require.NoError(t, err) + + // Bob revokes: the resulting RevokeAndAck must carry NO custom + // records on a non-custom channel. + bobChannel.auxSigner = pushySigner + bobRevocation, _, _, err := bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + require.Empty(t, bobRevocation.CustomRecords, + "non-custom channel must not attach revocation aux sigs") + + // Alice processes the revocation: even if the message carried stray + // custom records, a non-custom channel must ignore them and accept + // the revocation. + bobRevocation.CustomRecords = lnwire.CustomRecords{ + revokeAndAckAuxSigType: []byte{0xde, 0xad}, + } + aliceChannel.auxSigner = pushySigner + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err, + "non-custom channel must ignore revocation custom records") +} + +// fakeAuxSigFor returns the canned signature blob fakeRevocationAuxSigner +// hands out for an HTLC. It is distinct per direction and index, so tests can +// assert that a sig is never attributed to another HTLC between signing, +// packing, wire transfer, verification and persistence. +func fakeAuxSigFor(signerIncoming bool, htlcIndex uint64) []byte { + direction := byte(0x00) + if signerIncoming { + direction = 0x01 + } + + return []byte{0x51, direction, byte(htlcIndex)} +} + +// fakeRevocationAuxSigner is a minimal AuxSigner used to exercise the +// revocation AuxSig paths end to end on a custom channel. It negotiates +// SigHashDefault, answers every sign job with the canned signature blob of +// the job's HTLC, and records the sign and verify jobs it processes. +type fakeRevocationAuxSigner struct { + signJobs []AuxSigJob + verifyJobs []AuxVerifyJob + verifyErr error + + // noneSigs makes every sign job respond without a signature blob, + // simulating BTC-only HTLCs on a custom channel that need no aux + // sigs. + noneSigs bool + + // signErr makes SubmitSecondLevelSigBatch fail as a whole, + // simulating an aux signer that cannot take the batch at all. + signErr error + + // respErr makes every sign job respond with an error, simulating an + // aux signer that fails while signing. + respErr error + + // strict makes verification behave like a real aux signer for a + // commitment whose every HTLC carries aux outputs: a job must carry + // a sig, and it must be the sig of exactly that HTLC, direction + // included. + strict bool +} + +func (s *fakeRevocationAuxSigner) SubmitSecondLevelSigBatch(_ AuxChanState, + _ *wire.MsgTx, jobs []AuxSigJob) error { + + if s.signErr != nil { + return s.signErr + } + + s.signJobs = append(s.signJobs, jobs...) + for _, job := range jobs { + if s.respErr != nil { + job.Resp <- AuxSigJobResp{ + HtlcIndex: job.HTLC.HtlcIndex, + Err: s.respErr, + } + + continue + } + if s.noneSigs { + job.Resp <- AuxSigJobResp{ + SigBlob: fn.None[tlv.Blob](), + HtlcIndex: job.HTLC.HtlcIndex, + } + + continue + } + + // The job describes an HTLC of the signer's own commitment, + // so its direction is already the signer's. + blob := fakeAuxSigFor(job.Incoming, job.HTLC.HtlcIndex) + job.Resp <- AuxSigJobResp{ + SigBlob: fn.Some[tlv.Blob](blob), + HtlcIndex: job.HTLC.HtlcIndex, + } + } + + return nil +} + +func (s *fakeRevocationAuxSigner) PackSigs( + []fn.Option[tlv.Blob]) fn.Result[fn.Option[tlv.Blob]] { + + return fn.Ok(fn.None[tlv.Blob]()) +} + +func (s *fakeRevocationAuxSigner) UnpackSigs( + fn.Option[tlv.Blob]) fn.Result[[]fn.Option[tlv.Blob]] { + + return fn.Ok([]fn.Option[tlv.Blob]{}) +} + +func (s *fakeRevocationAuxSigner) VerifySecondLevelSigs(_ AuxChanState, + _ *wire.MsgTx, jobs []AuxVerifyJob) error { + + s.verifyJobs = append(s.verifyJobs, jobs...) + + if s.verifyErr != nil { + return s.verifyErr + } + if !s.strict { + return nil + } + + for _, job := range jobs { + idx := job.HTLC.HtlcIndex + if job.SigBlob.IsNone() { + return fmt.Errorf("missing aux sig for HTLC index %d "+ + "(incoming=%v)", idx, job.Incoming) + } + + // The job describes an HTLC of the remote commitment from + // the verifier's point of view, so the signer saw it in the + // opposite direction. + want := fakeAuxSigFor(!job.Incoming, idx) + if !bytes.Equal(want, job.SigBlob.UnwrapOr(nil)) { + return fmt.Errorf("aux sig of another HTLC for HTLC "+ + "index %d (incoming=%v)", idx, job.Incoming) + } + } + + return nil +} + +func (s *fakeRevocationAuxSigner) HtlcSigHashType( + _ HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + return fn.Some(txscript.SigHashDefault) +} + +// setupRevocationAuxSigTest creates a custom (tapscript root) channel pair, +// locks in the HTLCs of setupRevocationAuxSigChannels, then lets Bob revoke +// the commitment carrying them. Bob's fake aux signer is attached right +// before his revocation, so the sigs it produces end up in the returned +// RevokeAndAck. Alice's fake signer is returned unattached: callers attach +// it (after optionally configuring it) right before feeding the revocation +// to Alice. +func setupRevocationAuxSigTest(t *testing.T, + bobSigner *fakeRevocationAuxSigner) (*LightningChannel, + *LightningChannel, *lnwire.RevokeAndAck, *fakeRevocationAuxSigner) { + + t.Helper() + + aliceChannel, bobChannel := setupRevocationAuxSigChannels(t) + + // Attach Bob's fake signer only now, so only the revocation-time aux + // paths see it. + bobChannel.auxSigner = fn.Some[AuxSigner](bobSigner) + + bobRevocation, _, _, err := bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + + return aliceChannel, bobChannel, bobRevocation, + &fakeRevocationAuxSigner{} +} + +// markChanSigHashDefault emulates a channel whose aux signer negotiated +// DeterministicHTLCs (SigHashDefault), by setting the sighash type the +// channel uses for new commitments to the value NewLightningChannel would +// have resolved. +func markChanSigHashDefault(c *LightningChannel) { + c.htlcSigHashType.Store(uint32(txscript.SigHashDefault)) +} + +// Amounts of the HTLCs the revocation aux sig tests lock in. +const ( + // revAuxNonDustAmt is far above every dust threshold. + revAuxNonDustAmt = btcutil.Amount(100_000) + + // revAuxDustAmt is dust on both commitments once the second-level + // fee and anchor are accounted for. + revAuxDustAmt = btcutil.Amount(400) + + // revAuxBobDustAmt sits between the two parties' dust thresholds: it + // is dust on Bob's commitment and would not be on Alice's. It is what + // tells the two dust limits apart in these tests. + revAuxBobDustAmt = btcutil.Amount(1_000) +) + +// revAuxHtlcAdder adds HTLCs to a pair of channels in either direction, +// keeping the per-offerer HTLC counters the way the wire protocol does. +type revAuxHtlcAdder struct { + t *testing.T + + alice *LightningChannel + bob *LightningChannel + + nextPreimage byte +} + +// add offers an HTLC of the given amount from one channel to the other and +// returns its HTLC index. +func (a *revAuxHtlcAdder) add(from, to *LightningChannel, + amt btcutil.Amount) uint64 { + + a.t.Helper() + + a.nextPreimage++ + preimage := bytes.Repeat([]byte{a.nextPreimage}, 32) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(preimage), + Amount: lnwire.NewMSatFromSatoshis(amt), + Expiry: uint32(10), + } + + htlcIndex, err := from.AddHTLC(htlc, nil) + require.NoError(a.t, err) + + htlc.ID = htlcIndex + _, err = to.ReceiveHTLC(htlc) + require.NoError(a.t, err) + + return htlcIndex +} + +// fromAlice offers an HTLC from Alice to Bob. +func (a *revAuxHtlcAdder) fromAlice(amt btcutil.Amount) uint64 { + return a.add(a.alice, a.bob, amt) +} + +// fromBob offers an HTLC from Bob to Alice. +func (a *revAuxHtlcAdder) fromBob(amt btcutil.Amount) uint64 { + return a.add(a.bob, a.alice, amt) +} + +// newRevocationAuxSigChannels creates the custom channel pair the revocation +// aux sig tests run on, with DeterministicHTLCs negotiated on both sides. +func newRevocationAuxSigChannels(t *testing.T) (*LightningChannel, + *LightningChannel, *revAuxHtlcAdder) { + + t.Helper() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.TapscriptRootBit + + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err, "unable to create test channels") + + // Emulate channels whose aux signer negotiated DeterministicHTLCs: + // the sighash type used for new commitments is set to exactly what + // NewLightningChannel would have resolved had a + // SigHashDefault-negotiating signer been attached from the start. A + // late signer swap (as done below for the fake revocation signers) + // does not change it, as it is only re-resolved on request. + markChanSigHashDefault(aliceChannel) + markChanSigHashDefault(bobChannel) + + // The tests rely on the two parties having different dust limits, so + // that using the wrong party's limit shows. + aliceDust := aliceChannel.channelState.LocalChanCfg.DustLimit + bobDust := bobChannel.channelState.LocalChanCfg.DustLimit + require.Less(t, aliceDust, bobDust) + + return aliceChannel, bobChannel, &revAuxHtlcAdder{ + t: t, + alice: aliceChannel, + bob: bobChannel, + } +} + +// signRevokedCommitment makes Alice sign a new commitment for Bob and Bob +// accept it, which leaves Bob about to revoke his previous commitment. No +// aux signer is attached yet, so the CommitSig-time aux machinery stays out +// of the picture. +func signRevokedCommitment(t *testing.T, aliceChannel, + bobChannel *LightningChannel) { + + t.Helper() + + aliceNewCommit, err := aliceChannel.SignNextCommitment(t.Context()) + require.NoError(t, err) + err = bobChannel.ReceiveNewCommitment(aliceNewCommit.CommitSigs) + require.NoError(t, err) +} + +// setupRevocationAuxSigChannels creates the custom channel pair and runs the +// commitment dance right up to (but not including) Bob's revocation of the +// commitment carrying three HTLCs offered by Alice: index 0 (non-dust), index +// 1 (dust for both parties) and index 2 (dust under Bob's dust limit only). +// No fake revocation aux signer is attached yet. +func setupRevocationAuxSigChannels(t *testing.T) (*LightningChannel, + *LightningChannel) { + + t.Helper() + + aliceChannel, bobChannel, adder := newRevocationAuxSigChannels(t) + + require.EqualValues(t, 0, adder.fromAlice(revAuxNonDustAmt)) + require.EqualValues(t, 1, adder.fromAlice(revAuxDustAmt)) + require.EqualValues(t, 2, adder.fromAlice(revAuxBobDustAmt)) + + // The HTLC at index 2 is dust on the commitment Bob revokes, which is + // built with Bob's dust limit, and would not be with Alice's. + bobState := bobChannel.channelState + feePerKw := chainfee.SatPerKWeight(bobState.LocalCommitment.FeePerKw) + isDust := func(dustLimit btcutil.Amount) bool { + return HtlcIsDust( + bobState.ChanType, true, lntypes.Local, feePerKw, + revAuxBobDustAmt, dustLimit, true, + ) + } + require.True(t, isDust(bobState.LocalChanCfg.DustLimit)) + require.False(t, isDust(bobState.RemoteChanCfg.DustLimit)) + + // Lock the HTLCs into both commitments. + require.NoError(t, ForceStateTransition(aliceChannel, bobChannel)) + + // A further add triggers the state transition whose revocation we + // care about: Bob will revoke the commitment carrying HTLCs 0 to 2. + adder.fromAlice(revAuxNonDustAmt) + signRevokedCommitment(t, aliceChannel, bobChannel) + + return aliceChannel, bobChannel +} + +// revokedHtlcAuxSigs returns the revocation aux sig persisted for each HTLC +// of the given revoked state, keyed by direction and HTLC index. +func revokedHtlcAuxSigs(t *testing.T, channel *LightningChannel, + revokedHeight uint64) map[revocationAuxSigKey][]byte { + + t.Helper() + + revokedLog, _, err := channel.channelState.FindPreviousState( + revokedHeight, + ) + require.NoError(t, err) + + sigType := revocationAuxSigType + sigs := make(map[revocationAuxSigKey][]byte) + for _, htlcEntry := range revokedLog.HTLCEntries { + htlcIndex, err := htlcEntry.HtlcIndex.ValOpt().UnwrapOrErr( + errors.New("revocation log entry without HTLC index"), + ) + require.NoError(t, err) + + key := revocationAuxSigKey{ + // The log is ours, so an HTLC incoming to us is + // outgoing for the party that revoked the state. + signerIncoming: !htlcEntry.Incoming.Val, + htlcIndex: htlcIndex.Int(), + } + + blob := htlcEntry.CustomBlob.ValOpt().UnwrapOr(nil) + if len(blob) == 0 { + sigs[key] = nil + + continue + } + + records, err := lnwire.ParseCustomRecords(blob) + require.NoError(t, err) + sigs[key] = records[sigType] + } + + return sigs +} + +// TestRevocationAuxSigsRoundTrip exercises the full happy path on a custom +// channel: Bob's revocation signs the second-level path of every non-dust +// HTLC on the revoked commitment, ships the sigs in +// RevokeAndAck.CustomRecords, and Alice verifies them before accepting the +// revocation and persists them into the remote commitment's HTLC custom +// records. Dust HTLCs are excluded on both sides, as decided by the dust +// limit of the commitment's owner. +func TestRevocationAuxSigsRoundTrip(t *testing.T) { + t.Parallel() + + bobSigner := &fakeRevocationAuxSigner{} + aliceChannel, _, bobRevocation, aliceSigner := + setupRevocationAuxSigTest(t, bobSigner) + + // The remote chain tail is the commitment Bob is revoking; its height + // keys the revocation log entry we'll inspect below. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + + // Bob signed exactly one HTLC: the two dust HTLCs must not have + // produced sign jobs. The HTLC is incoming to him, so the path he + // signs is the success, which carries no timeout. + require.Len(t, bobSigner.signJobs, 1) + signJob := bobSigner.signJobs[0] + require.True(t, signJob.Incoming) + require.EqualValues(t, 0, signJob.HTLC.HtlcIndex) + require.Equal(t, lntypes.Local, signJob.WhoseCommit) + require.True(t, signJob.HtlcTimeout.IsNone()) + + // The RevokeAndAck carries the packed sig for HTLC index 0 only. + recType := revokeAndAckAuxSigType + blob := bobRevocation.CustomRecords[recType] + require.NotEmpty(t, blob, "revocation aux sig blob missing") + + sigMap, err := unpackRevocationAuxSigs(blob) + require.NoError(t, err) + require.Len(t, sigMap, 1) + + htlcKey := revocationAuxSigKey{signerIncoming: true, htlcIndex: 0} + entry, ok := sigMap[htlcKey] + require.True(t, ok, "expected sig for HTLC index 0") + require.Equal(t, fakeAuxSigFor(true, 0), entry.sig) + + // Alice verifies and accepts. Her verifier insists on the sig of + // exactly this HTLC. + aliceSigner.strict = true + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err) + + // Alice verified the non-dust HTLC only. From her side it is an + // outgoing HTLC on the remote commitment. + require.Len(t, aliceSigner.verifyJobs, 1) + verifyJob := aliceSigner.verifyJobs[0] + require.False(t, verifyJob.Incoming) + require.EqualValues(t, 0, verifyJob.HTLC.HtlcIndex) + require.Equal(t, lntypes.Remote, verifyJob.WhoseCommit) + require.True(t, verifyJob.HtlcTimeout.IsNone()) + require.Equal( + t, fakeAuxSigFor(true, 0), verifyJob.SigBlob.UnwrapOr(nil), + ) + + // The verified sig is persisted in the revocation log entry of the + // revoked commitment (the breach-time source of truth). The dust + // HTLCs have no entry there at all. + require.Equal(t, map[revocationAuxSigKey][]byte{ + htlcKey: fakeAuxSigFor(true, 0), + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// TestRevocationAuxSigsSameIndexBothDirections asserts that the revocation +// aux sigs of an HTLC offered by each party under the same HTLC index stay +// apart. Both parties count the HTLCs they offer from zero, so this is the +// normal state of any channel that carries traffic in both directions. +// Keying the sigs by the bare index would fold the two HTLCs into one entry: +// the receiver would then either reject an honest revocation, leaving the +// channel unusable, or store one HTLC's sig for the other, leaving it +// without breach protection. +func TestRevocationAuxSigsSameIndexBothDirections(t *testing.T) { + t.Parallel() + + aliceChannel, bobChannel, adder := newRevocationAuxSigChannels(t) + + // One HTLC in each direction, both at index 0. + require.EqualValues(t, 0, adder.fromAlice(revAuxNonDustAmt)) + require.EqualValues(t, 0, adder.fromBob(revAuxNonDustAmt)) + + // Lock both HTLCs into both commitments. + require.NoError(t, ForceStateTransition(aliceChannel, bobChannel)) + require.NoError(t, ForceStateTransition(bobChannel, aliceChannel)) + + // Bob is about to revoke the commitment carrying both. + adder.fromAlice(revAuxNonDustAmt) + signRevokedCommitment(t, aliceChannel, bobChannel) + + bobSigner := &fakeRevocationAuxSigner{} + bobChannel.auxSigner = fn.Some[AuxSigner](bobSigner) + bobRevocation, _, _, err := bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + + // Bob signed each HTLC once: the success path of the one he + // received, the timeout path of the one he offered. + require.Len(t, bobSigner.signJobs, 2) + for _, job := range bobSigner.signJobs { + require.EqualValues(t, 0, job.HTLC.HtlcIndex) + require.Equal(t, !job.Incoming, job.HtlcTimeout.IsSome()) + } + require.NotEqual( + t, bobSigner.signJobs[0].Incoming, + bobSigner.signJobs[1].Incoming, + ) + + // The blob carries one entry per HTLC, each with its own sig. + recType := revokeAndAckAuxSigType + sigMap, err := unpackRevocationAuxSigs( + bobRevocation.CustomRecords[recType], + ) + require.NoError(t, err) + require.Len(t, sigMap, 2) + + receivedKey := revocationAuxSigKey{signerIncoming: true} + offeredKey := revocationAuxSigKey{signerIncoming: false} + require.Equal(t, fakeAuxSigFor(true, 0), sigMap[receivedKey].sig) + require.Equal(t, fakeAuxSigFor(false, 0), sigMap[offeredKey].sig) + + // Alice's verifier rejects a sig that belongs to another HTLC, so + // accepting the revocation proves each sig reached the right one. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + aliceSigner := &fakeRevocationAuxSigner{strict: true} + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err) + require.Len(t, aliceSigner.verifyJobs, 2) + + // And each HTLC keeps its own sig in the revocation log. + require.Equal(t, map[revocationAuxSigKey][]byte{ + receivedKey: fakeAuxSigFor(true, 0), + offeredKey: fakeAuxSigFor(false, 0), + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// TestRevocationAuxSigsRejected asserts that ReceiveRevocation rejects the +// revocation BEFORE advancing the remote chain tail whenever the received +// aux sigs are unverifiable, malformed, or missing for a non-dust HTLC. +func TestRevocationAuxSigsRejected(t *testing.T) { + t.Parallel() + + recType := revokeAndAckAuxSigType + + // appendEntry adds the given entry to the blob of a revocation. + appendEntry := func(entry revocationAuxSigEntry) func( + *lnwire.RevokeAndAck, *fakeRevocationAuxSigner) { + + return func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + mutatePackedEntries(t, rev, + func(entries []revocationAuxSigEntry, + ) []revocationAuxSigEntry { + + return append(entries, entry) + }, + ) + } + } + + testCases := []struct { + name string + mutate func(*lnwire.RevokeAndAck, *fakeRevocationAuxSigner) + wantErr string + }{{ + name: "verification failure", + mutate: func(_ *lnwire.RevokeAndAck, + s *fakeRevocationAuxSigner) { + + s.verifyErr = fmt.Errorf("sig does not verify") + }, + wantErr: "invalid revocation aux sigs", + }, { + name: "malformed blob", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + rev.CustomRecords[recType] = []byte{0xde, 0xad} + }, + wantErr: "invalid revocation aux sigs", + }, { + name: "missing sig for non-dust HTLC", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + // A well-formed blob whose sig is tagged with an HTLC + // index that isn't on the commitment. + packed, err := packRevocationAuxSigs( + []revocationAuxSigEntry{newRevAuxSigEntry( + true, 99, fakeAuxSigFor(true, 99), + )}, + ) + if err != nil { + panic(err) + } + rev.CustomRecords[recType] = packed + }, + wantErr: "no revocation aux sig for HTLC index 0", + }, { + name: "sig tagged with the wrong direction", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + // The right index, but for an HTLC the signer would + // have offered. The HTLC on the commitment is one it + // received. + packed, err := packRevocationAuxSigs( + []revocationAuxSigEntry{newRevAuxSigEntry( + false, 0, fakeAuxSigFor(true, 0), + )}, + ) + if err != nil { + panic(err) + } + rev.CustomRecords[recType] = packed + }, + wantErr: "no revocation aux sig for HTLC index 0", + }, { + name: "withheld blob", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + // A peer that strips the records entirely must not + // get its revocation accepted while non-dust HTLCs + // sit on the revoked commitment. + rev.CustomRecords = nil + }, + wantErr: "no revocation aux sig for HTLC index 0", + }, { + // An entry is there, but it carries no sig. Only the aux + // signer knows that the HTLC carries aux outputs and owes + // one, so it must be asked, and its refusal must fail the + // revocation. Otherwise a peer could opt out of the breach + // protection for exactly the states it means to broadcast. + name: "sig withheld from the entry", + mutate: func(rev *lnwire.RevokeAndAck, + s *fakeRevocationAuxSigner) { + + s.strict = true + mutatePackedEntries(t, rev, + func(entries []revocationAuxSigEntry, + ) []revocationAuxSigEntry { + + entries[0].sig = nil + + return entries + }, + ) + }, + wantErr: "missing aux sig for HTLC index 0", + }, { + name: "sig of another HTLC", + mutate: func(rev *lnwire.RevokeAndAck, + s *fakeRevocationAuxSigner) { + + s.strict = true + mutatePackedEntries(t, rev, + func(entries []revocationAuxSigEntry, + ) []revocationAuxSigEntry { + + entries[0].sig = fakeAuxSigFor( + false, 0, + ) + + return entries + }, + ) + }, + wantErr: "aux sig of another HTLC", + }, { + name: "extra entry for unknown HTLC index", + mutate: appendEntry( + newRevAuxSigEntry(true, 99, []byte{0x99}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 99", + }, { + // The same index as the HTLC on the commitment, but in the + // direction nothing was offered in. + name: "extra entry for the other direction", + mutate: appendEntry( + newRevAuxSigEntry(false, 0, []byte{0x99}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 0", + }, { + // HTLC index 1 is dust for both parties: an honest signer + // never packs an entry for it. + name: "entry for dust HTLC", + mutate: appendEntry( + newRevAuxSigEntry(true, 1, []byte{0x01}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 1", + }, { + // HTLC index 2 is dust on the revoked commitment, which is + // built with the signer's dust limit. It would not be dust + // under ours, so this entry is only refused if the dust + // limit of the right party is applied. + name: "entry for HTLC that is dust for the signer only", + mutate: appendEntry( + newRevAuxSigEntry(true, 2, []byte{0x02}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 2", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + aliceChannel, _, bobRevocation, aliceSigner := + setupRevocationAuxSigTest( + t, &fakeRevocationAuxSigner{}, + ) + + tc.mutate(bobRevocation, aliceSigner) + + tailBefore := aliceChannel.commitChains.Remote. + tail().height + + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err := aliceChannel.ReceiveRevocation( + bobRevocation, + ) + require.ErrorContains(t, err, tc.wantErr) + + // The revocation must not have been accepted. + require.Equal( + t, tailBefore, + aliceChannel.commitChains.Remote.tail().height, + ) + }) + } +} + +// TestRevocationAuxSigsBtcOnlyHtlcs asserts the lockstep-entry semantics for +// HTLCs that need no aux signature (BTC-only HTLCs on a custom channel): the +// revoking party still attaches one entry per non-dust HTLC, just without +// signature data. The receiver still hands the HTLC to its aux signer, which +// is the one to know that no sig is owed for it, and accepts the revocation +// when the signer agrees. This is what lets the receiver tell a sig-less +// HTLC apart from a withheld signature. +func TestRevocationAuxSigsBtcOnlyHtlcs(t *testing.T) { + t.Parallel() + + bobSigner := &fakeRevocationAuxSigner{noneSigs: true} + aliceChannel, _, bobRevocation, aliceSigner := + setupRevocationAuxSigTest(t, bobSigner) + + // The non-dust HTLC was still offered to the signer. + require.Len(t, bobSigner.signJobs, 1) + + // The RevokeAndAck carries a blob with a sig-less entry for the + // non-dust HTLC. + recType := revokeAndAckAuxSigType + blob := bobRevocation.CustomRecords[recType] + require.NotEmpty(t, blob, "lockstep entry blob missing") + + sigMap, err := unpackRevocationAuxSigs(blob) + require.NoError(t, err) + require.Len(t, sigMap, 1) + + htlcKey := revocationAuxSigKey{signerIncoming: true, htlcIndex: 0} + entry, ok := sigMap[htlcKey] + require.True(t, ok) + require.Empty(t, entry.sig) + + // Alice's aux signer is asked about the HTLC, with no sig attached, + // and has no objection. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err) + + require.Len(t, aliceSigner.verifyJobs, 1) + require.True(t, aliceSigner.verifyJobs[0].SigBlob.IsNone()) + + // Nothing is stored for the HTLC. + require.Equal(t, map[revocationAuxSigKey][]byte{ + htlcKey: nil, + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// TestRevocationAuxSigsPeerRecordNotPersisted asserts that a custom record +// the peer put on its own UpdateAddHTLC under the type we store verified +// revocation aux sigs with never reaches the revocation log. The breach code +// reads that type back as a sig we verified, so a record the peer chose +// itself must not survive there, whether or not the revocation carries a sig +// for the HTLC. +func TestRevocationAuxSigsPeerRecordNotPersisted(t *testing.T) { + t.Parallel() + + sigType := revocationAuxSigType + + testCases := []struct { + name string + noneSigs bool + want []byte + }{{ + name: "replaced by the verified sig", + want: fakeAuxSigFor(false, 0), + }, { + name: "dropped when the revocation carries no sig", + noneSigs: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + aliceChannel, bobChannel, adder := + newRevocationAuxSigChannels(t) + + // Bob offers an HTLC and plants a record of our + // storage type on it. + preimage := bytes.Repeat([]byte{9}, 32) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(preimage), + Amount: lnwire.NewMSatFromSatoshis( + revAuxNonDustAmt, + ), + Expiry: uint32(10), + CustomRecords: lnwire.CustomRecords{ + sigType: []byte{0xba, 0xad}, + }, + } + htlcIndex, err := bobChannel.AddHTLC(htlc, nil) + require.NoError(t, err) + htlc.ID = htlcIndex + _, err = aliceChannel.ReceiveHTLC(htlc) + require.NoError(t, err) + + require.NoError( + t, + ForceStateTransition(bobChannel, aliceChannel), + ) + require.NoError( + t, + ForceStateTransition(aliceChannel, bobChannel), + ) + + // Bob revokes the commitment carrying the HTLC. + adder.fromAlice(revAuxNonDustAmt) + signRevokedCommitment(t, aliceChannel, bobChannel) + + bobChannel.auxSigner = fn.Some[AuxSigner]( + &fakeRevocationAuxSigner{noneSigs: tc.noneSigs}, + ) + bobRevocation, _, _, err := + bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + + revokedHeight := aliceChannel.commitChains.Remote. + tail().height + aliceChannel.auxSigner = fn.Some[AuxSigner]( + &fakeRevocationAuxSigner{}, + ) + _, _, err = aliceChannel.ReceiveRevocation( + bobRevocation, + ) + require.NoError(t, err) + + sigs := revokedHtlcAuxSigs( + t, aliceChannel, revokedHeight, + ) + require.Equal(t, tc.want, sigs[revocationAuxSigKey{ + signerIncoming: false, + htlcIndex: htlcIndex, + }]) + }) + } +} + +// TestRevocationAuxSigsRetransmission asserts that a retransmitted +// RevokeAndAck carries the exact same revocation aux sigs as the original: +// the packed blob is persisted atomically with the commitment advance and +// survives a restart, so a peer that never processed the original still +// receives the sigs it is owed on reestablish, and accepts them. +func TestRevocationAuxSigsRetransmission(t *testing.T) { + t.Parallel() + + bobSigner := &fakeRevocationAuxSigner{} + aliceChannel, bobChannel, bobRevocation, aliceSigner := + setupRevocationAuxSigTest(t, bobSigner) + + // Sanity check: Bob's original RevokeAndAck carries the sigs. + require.NotEmpty(t, bobRevocation.CustomRecords) + + // Alice never processes the revocation. On reconnect, her channel + // reestablish message tells Bob her view of his commitment tail is + // one behind, so Bob owes her the revocation again. + aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() + require.NoError(t, err) + + // Bob restarts: his channel is rebuilt from what is on disk, with a + // fresh signer. The retransmission must come from the persisted + // blob, not from signing the revoked commitment again. + bobState := bobChannel.channelState + bobState.RevocationAuxSigs = fn.None[tlv.Blob]() + require.NoError(t, bobState.Refresh()) + require.True( + t, bobState.RevocationAuxSigs.IsSome(), + "revocation aux sigs not persisted to disk", + ) + + restartedSigner := &fakeRevocationAuxSigner{} + restartedBob, err := NewLightningChannel( + bobChannel.Signer, bobState, bobChannel.sigPool, + WithLeafStore(&MockAuxLeafStore{}), + WithAuxSigner(restartedSigner), + ) + require.NoError(t, err) + + bobSyncMsg, err := bobState.ChanSyncMsg() + require.NoError(t, err) + + // Simulate the link/peer binding the generated musig nonces on + // reconnect. + aliceChannel.pendingVerificationNonce = &musig2.Nonces{ + PubNonce: aliceSyncMsg.LocalNonce.UnwrapOrFail(t).Val, + } + restartedBob.pendingVerificationNonce = &musig2.Nonces{ + PubNonce: bobSyncMsg.LocalNonce.UnwrapOrFail(t).Val, + } + + // Bob processes Alice's reestablish and must retransmit a single + // RevokeAndAck carrying the exact same aux sig records. + bobMsgs, _, _, err := restartedBob.ProcessChanSyncMsg( + t.Context(), aliceSyncMsg, + ) + require.NoError(t, err) + + // Bob may also owe Alice a CommitSig for the pending state + // transition; the RevokeAndAck retransmission is what we care about + // here. + var reRevoke *lnwire.RevokeAndAck + for _, msg := range bobMsgs { + if rev, ok := msg.(*lnwire.RevokeAndAck); ok { + reRevoke = rev + } + } + require.NotNil(t, reRevoke, "expected RevokeAndAck retransmission") + require.Equal( + t, bobRevocation.CustomRecords, reRevoke.CustomRecords, + "retransmitted RevokeAndAck must carry the original aux sigs", + ) + + // Whatever the restarted signer was asked to sign is a CommitSig for + // Alice's commitment, never the HTLCs of Bob's own revoked one. + for _, job := range restartedSigner.signJobs { + require.Equal(t, lntypes.Remote, job.WhoseCommit) + } + + // Alice verifies the retransmitted sigs like the original ones and + // accepts the revocation. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + aliceSigner.strict = true + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(reRevoke) + require.NoError(t, err) + require.Len(t, aliceSigner.verifyJobs, 1) + + htlcKey := revocationAuxSigKey{signerIncoming: true, htlcIndex: 0} + require.Equal(t, map[revocationAuxSigKey][]byte{ + htlcKey: fakeAuxSigFor(true, 0), + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// mutatePackedEntries unpacks the aux sig blob carried by the given +// RevokeAndAck, applies f to the entries (sorted by direction, then HTLC +// index), and packs the result back into the message. +func mutatePackedEntries(t *testing.T, rev *lnwire.RevokeAndAck, + f func([]revocationAuxSigEntry) []revocationAuxSigEntry) { + + t.Helper() + + recType := revokeAndAckAuxSigType + sigMap, err := unpackRevocationAuxSigs(rev.CustomRecords[recType]) + require.NoError(t, err) + + entries := make([]revocationAuxSigEntry, 0, len(sigMap)) + for _, entry := range sigMap { + entries = append(entries, entry) + } + slices.SortFunc(entries, func(i, j revocationAuxSigEntry) int { + if i.signerIncoming != j.signerIncoming { + if i.signerIncoming { + return 1 + } + + return -1 + } + + return cmp.Compare(i.htlcIndex, j.htlcIndex) + }) + + packed, err := packRevocationAuxSigs(f(entries)) + require.NoError(t, err) + + rev.CustomRecords[recType] = packed +} + +// TestRevocationAuxSigsSignFailure asserts that a failure of the aux signer +// at revocation time fails RevokeCurrentCommitment as a whole, BEFORE any +// state is advanced or persisted: sending a sig-less RevokeAndAck would only +// fail the channel on the peer's side. +func TestRevocationAuxSigsSignFailure(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + signer *fakeRevocationAuxSigner + }{{ + name: "batch submission fails", + signer: &fakeRevocationAuxSigner{ + signErr: fmt.Errorf("signer offline"), + }, + }, { + name: "sign job fails", + signer: &fakeRevocationAuxSigner{ + respErr: fmt.Errorf("cannot sign"), + }, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, bobChannel := setupRevocationAuxSigChannels(t) + bobChannel.auxSigner = fn.Some[AuxSigner](tc.signer) + + tailBefore := bobChannel.commitChains.Local. + tail().height + heightBefore := bobChannel.currentHeight + + _, _, _, err := bobChannel.RevokeCurrentCommitment() + require.ErrorContains( + t, err, "unable to sign local HTLC aux sigs", + ) + + // Nothing advanced: the revocation can be retried. + require.Equal( + t, tailBefore, + bobChannel.commitChains.Local.tail().height, + ) + require.Equal( + t, heightBefore, bobChannel.currentHeight, + ) + }) + } +} + +// revAuxSigBlob assembles a raw revocation aux sig blob from an entry count +// and already framed entries, bypassing the encoder so tests can build blobs +// an honest peer never would. +func revAuxSigBlob(t *testing.T, count uint64, framed ...[]byte) []byte { + t.Helper() + + var ( + buf bytes.Buffer + scratch [8]byte + ) + require.NoError(t, tlv.WriteVarInt(&buf, count, &scratch)) + for _, entry := range framed { + buf.Write(entry) + } + + return buf.Bytes() +} + +// framedRevAuxSigEntry returns the length-prefixed encoding of an entry, the +// way it sits in a blob. +func framedRevAuxSigEntry(t *testing.T, entry revocationAuxSigEntry) []byte { + t.Helper() + + var inner bytes.Buffer + require.NoError(t, entry.encode(&inner)) + + return framedRevAuxSigBytes(t, inner.Bytes()) +} + +// framedRevAuxSigBytes length-prefixes raw entry bytes. +func framedRevAuxSigBytes(t *testing.T, entry []byte) []byte { + t.Helper() + + var ( + buf bytes.Buffer + scratch [8]byte + ) + require.NoError( + t, tlv.WriteVarInt(&buf, uint64(len(entry)), &scratch), + ) + buf.Write(entry) + + return buf.Bytes() +} + +// TestUnpackRevocationAuxSigsCorrupt asserts that corrupt and hostile packed +// blobs are rejected by the decoder rather than yielding partial results. +func TestUnpackRevocationAuxSigsCorrupt(t *testing.T) { + t.Parallel() + + first := newRevAuxSigEntry(true, 0, fakeAuxSigFor(true, 0)) + second := newRevAuxSigEntry(true, 1, fakeAuxSigFor(true, 1)) + + valid, err := packRevocationAuxSigs( + []revocationAuxSigEntry{first, second}, + ) + require.NoError(t, err) + + // An entry stream with a single record of the given type and value. + record := func(typ tlv.Type, val []byte) []byte { + return append([]byte{byte(typ), byte(len(val))}, val...) + } + indexRecord := record(revAuxSigIndexType, make([]byte, 8)) + incomingRecord := record(revAuxSigIncomingType, []byte{1}) + + testCases := []struct { + name string + blob []byte + wantErr string + }{{ + name: "truncated mid-entry", + blob: valid[:len(valid)-3], + }, { + name: "truncated to first entry", + blob: valid[:len(valid)/2], + }, { + name: "garbage", + blob: []byte{0xde, 0xad, 0xbe, 0xef}, + }, { + // Two entries for the same HTLC: the second must not + // silently replace the first. + name: "duplicate entry", + blob: revAuxSigBlob( + t, 2, framedRevAuxSigEntry(t, first), + framedRevAuxSigEntry(t, first), + ), + wantErr: "duplicate entry for HTLC index 0", + }, { + name: "trailing bytes", + blob: append(slices.Clone(valid), 0x00), + wantErr: "1 trailing bytes after the last entry", + }, { + // Fewer entries declared than present leaves a whole entry + // behind as trailing data. + name: "undeclared entry", + blob: revAuxSigBlob( + t, 1, framedRevAuxSigEntry(t, first), + framedRevAuxSigEntry(t, second), + ), + wantErr: "trailing bytes after the last entry", + }, { + name: "count beyond the blob", + blob: revAuxSigBlob(t, 3, framedRevAuxSigEntry(t, first)), + wantErr: "read entry 1 length", + }, { + name: "entry length beyond the blob", + blob: append(revAuxSigBlob(t, 1), 0x40, 0x00), + wantErr: "entry 0 length 64 exceeds the 1 bytes left", + }, { + // The entry's declared length covers more than its records, + // so the stream ends in a record that is cut short. + name: "entry with a cut-off record", + blob: revAuxSigBlob(t, 1, framedRevAuxSigBytes( + t, append( + append(slices.Clone(indexRecord), + incomingRecord..., + ), 0x05, 0x04, 0x00, + ), + )), + wantErr: "decode entry 0", + }, { + name: "entry without an HTLC index", + blob: revAuxSigBlob( + t, 1, framedRevAuxSigBytes(t, incomingRecord), + ), + wantErr: "missing HTLC index", + }, { + name: "entry without a direction", + blob: revAuxSigBlob( + t, 1, framedRevAuxSigBytes(t, indexRecord), + ), + wantErr: "missing HTLC direction", + }, { + name: "entry with an invalid direction", + blob: revAuxSigBlob(t, 1, framedRevAuxSigBytes( + t, append( + slices.Clone(indexRecord), + record(revAuxSigIncomingType, []byte{2})..., + ), + )), + wantErr: "invalid HTLC direction 2", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := unpackRevocationAuxSigs(tc.blob) + require.Error(t, err) + require.ErrorContains(t, err, tc.wantErr) + }) + } +} + +// TestUnpackRevocationAuxSigsHugeCount asserts that the entry count a peer +// declares is never used to size an allocation. The blob is a handful of +// bytes long; a count of billions must be rejected without the decoder ever +// reserving memory for that many entries, which would take the node down. +func TestUnpackRevocationAuxSigsHugeCount(t *testing.T) { + // Not parallel: the test measures this goroutine's allocations. + for _, count := range []uint64{1 << 22, 1 << 32, math.MaxUint64} { + blob := revAuxSigBlob(t, count) + require.LessOrEqual(t, len(blob), 9) + + var unpackErr error + allocated := testing.AllocsPerRun(1, func() { + _, unpackErr = unpackRevocationAuxSigs(blob) + }) + require.ErrorContains(t, unpackErr, "exceeds the 0 bytes") + + // A map sized for the declared count would be a single + // allocation as well, so bound the bytes, not the count. + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, _ = unpackRevocationAuxSigs(blob) + runtime.ReadMemStats(&after) + + require.Less(t, allocated, float64(32)) + require.Less( + t, after.TotalAlloc-before.TotalAlloc, + uint64(1<<20), "decoding a %d byte blob allocated "+ + "memory for its declared entry count", + len(blob), + ) + } +} + +// TestRevocationAuxSigsGateFollowsRevokedCommitment asserts that whether a +// revocation carries aux sigs is decided by the sighash recorded for the +// commitment being revoked, not by the one new commitments use. While the +// sighash type of a channel is switching, the two differ, and both peers +// must still agree on which revocations carry the signatures. +func TestRevocationAuxSigsGateFollowsRevokedCommitment(t *testing.T) { + t.Parallel() + + channel, signer := newLiveAuxSignerChannel(t) + + legacyCommit := &commitment{} + deterministicCommit := &commitment{ + customBlob: fn.Some(sigHashDefaultBlob), + } + + // New commitments use the legacy sighash, yet revoking a commitment + // that was built with SigHashDefault still exchanges the sigs. + require.False(t, channel.IsChanSigHashDefault()) + require.False(t, channel.exchangesRevocationAuxSigs(legacyCommit)) + require.True( + t, channel.exchangesRevocationAuxSigs(deterministicCommit), + ) + + // New commitments switch to SigHashDefault. Revoking a commitment + // that predates the switch must not start exchanging the sigs: its + // second-level HTLCs are not deterministic and the peer does not + // expect any. + signer.live = fn.Some(txscript.SigHashDefault) + channel.RefreshHtlcSigHashType() + require.True(t, channel.IsChanSigHashDefault()) + require.False(t, channel.exchangesRevocationAuxSigs(legacyCommit)) + require.True( + t, channel.exchangesRevocationAuxSigs(deterministicCommit), + ) + + // Without a commitment or an aux signer nothing is exchanged. + require.False(t, channel.exchangesRevocationAuxSigs(nil)) + channel.auxSigner = fn.None[AuxSigner]() + require.False( + t, channel.exchangesRevocationAuxSigs(deterministicCommit), + ) +} diff --git a/lnwire/revoke_and_ack.go b/lnwire/revoke_and_ack.go index e2a4c930798..222ef35e13e 100644 --- a/lnwire/revoke_and_ack.go +++ b/lnwire/revoke_and_ack.go @@ -42,6 +42,13 @@ type RevokeAndAck struct { // nonces, keyed by TXID. This is used for splice nonce coordination. LocalNonces OptLocalNonces + // CustomRecords is a set of custom TLV records that can be used to + // attach auxiliary data to the revocation message. For custom + // channels, this carries the revoking party's aux signatures for + // the second-level HTLC transactions on the commitment being + // revoked. + CustomRecords CustomRecords + // ExtraData is the set of data that was appended to this message to // fill out the full maximum transport message size. These fields can // be used to specify optional data such as custom TLV fields. @@ -50,9 +57,7 @@ type RevokeAndAck struct { // NewRevokeAndAck creates a new RevokeAndAck message. func NewRevokeAndAck() *RevokeAndAck { - return &RevokeAndAck{ - ExtraData: make([]byte, 0), - } + return &RevokeAndAck{} } // A compile time check to ensure RevokeAndAck implements the lnwire.Message @@ -68,43 +73,41 @@ var _ SizeableMessage = (*RevokeAndAck)(nil) // // This is part of the lnwire.Message interface. func (c *RevokeAndAck) Decode(r io.Reader, pver uint32) error { + // msgExtraData is a temporary variable used to read the message extra + // data field from the reader. + var msgExtraData ExtraOpaqueData + err := ReadElements(r, &c.ChanID, c.Revocation[:], &c.NextRevocationKey, + &msgExtraData, ) if err != nil { return err } - var tlvRecords ExtraOpaqueData - if err := ReadElements(r, &tlvRecords); err != nil { - return err - } - - var ( - localNonce = c.LocalNonce.Zero() - localNoncesData LocalNoncesData - ) + // Extract TLV records from the extra data field. + localNonce := c.LocalNonce.Zero() + var localNoncesData LocalNoncesData - typeMap, err := tlvRecords.ExtractRecords( - &localNonce, &localNoncesData, + customRecords, parsed, extraData, err := ParseAndExtractCustomRecords( + msgExtraData, &localNonce, &localNoncesData, ) if err != nil { return err } // Set the corresponding TLV types if they were included in the stream. - if val, ok := typeMap[c.LocalNonce.TlvType()]; ok && val == nil { + if _, ok := parsed[localNonce.TlvType()]; ok { c.LocalNonce = tlv.SomeRecordT(localNonce) } - if val, ok := typeMap[(LocalNoncesRecordTypeDef)(nil).TypeVal()]; ok && val == nil { //nolint:ll + if _, ok := parsed[(LocalNoncesRecordTypeDef)(nil).TypeVal()]; ok { c.LocalNonces = SomeLocalNonces(localNoncesData) } - if len(tlvRecords) != 0 { - c.ExtraData = tlvRecords - } + c.CustomRecords = customRecords + c.ExtraData = extraData return nil } @@ -121,7 +124,10 @@ func (c *RevokeAndAck) Encode(w *bytes.Buffer, pver uint32) error { c.LocalNonces.WhenSome(func(ln LocalNoncesData) { recordProducers = append(recordProducers, &ln) }) - err := EncodeMessageExtraData(&c.ExtraData, recordProducers...) + + extraData, err := MergeAndEncode( + recordProducers, c.ExtraData, c.CustomRecords, + ) if err != nil { return err } @@ -138,7 +144,7 @@ func (c *RevokeAndAck) Encode(w *bytes.Buffer, pver uint32) error { return err } - return WriteBytes(w, c.ExtraData) + return WriteBytes(w, extraData) } // MsgType returns the integer uniquely identifying this message type on the diff --git a/lnwire/revoke_and_ack_test.go b/lnwire/revoke_and_ack_test.go new file mode 100644 index 00000000000..93098919d35 --- /dev/null +++ b/lnwire/revoke_and_ack_test.go @@ -0,0 +1,110 @@ +package lnwire + +import ( + "bytes" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestRevokeAndAckEncodeDecode tests RevokeAndAck message encoding and +// decoding with and without custom records, asserting that a message without +// custom records is byte-identical to its pre-CustomRecords encoding. +func TestRevokeAndAckEncodeDecode(t *testing.T) { + t.Parallel() + + chanIDBytes, err := generateRandomBytes(32) + require.NoError(t, err) + var chanID ChannelID + copy(chanID[:], chanIDBytes) + + revBytes, err := generateRandomBytes(32) + require.NoError(t, err) + var revocation [32]byte + copy(revocation[:], revBytes) + + nextRevKey, err := pubkeyFromHex( + "0228f2af0abe322403480fb3ee172f7f1601e67d1da6cad40b54c4468d4" + + "8236c39", + ) + require.NoError(t, err) + + recordValue, err := generateRandomBytes(10) + require.NoError(t, err) + customRecords := CustomRecords{ + uint64(MinCustomRecordsTlvType): recordValue, + } + + testCases := []struct { + name string + msg RevokeAndAck + expectEncodeError bool + }{{ + name: "with custom records", + msg: RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + CustomRecords: customRecords, + }, + }, { + name: "without custom records", + msg: RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + }, + }, { + name: "invalid custom records", + msg: RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + CustomRecords: CustomRecords{ + MinCustomRecordsTlvType - 1: recordValue, + }, + }, + expectEncodeError: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + err := tc.msg.Encode(&buf, 0) + if tc.expectEncodeError { + require.Error(t, err) + return + } + require.NoError(t, err) + + var decoded RevokeAndAck + err = decoded.Decode(bytes.NewReader(buf.Bytes()), 0) + require.NoError(t, err) + require.Equal(t, tc.msg, decoded) + }) + } + + // A message without custom records must be byte-identical to the + // legacy encoding: fixed fields only, no TLV appendix at all. + var legacyBuf bytes.Buffer + require.NoError( + t, WriteChannelID(&legacyBuf, chanID), + ) + require.NoError(t, WriteBytes(&legacyBuf, revocation[:])) + require.NoError(t, WritePublicKey(&legacyBuf, nextRevKey)) + + var noRecordsBuf bytes.Buffer + msg := RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + } + require.NoError(t, msg.Encode(&noRecordsBuf, 0)) + require.Equal( + t, legacyBuf.Bytes(), noRecordsBuf.Bytes(), + fmt.Sprintf("no-records encoding must stay byte-identical "+ + "to the legacy wire format, got %x", + noRecordsBuf.Bytes()), + ) +}