Merge pull request #11164 from ViktorT-11/2026-08-sync-gossip-with-spec
What changed, and why it matters
This commit updates LND's experimental gossip-v2 protocol implementation to match a newer version of the Lightning BOLT specification. It changes how several peer-to-peer messages are encoded and decoded, adds stricter checks for required fields, and fixes edge cases such as default HTLC limits and address port handling. The changes are primarily a protocol conformance and hardening patch rather than a fix for a known active vulnerability.
Treat as a protocol-hardening update. Nodes running experimental taproot-gossip code should upgrade to stay interoperable with the revised spec and to benefit from stricter decoding checks. Reviewers should verify that signature verification logic correctly handles the new 240 signature TLV and the changed signed/unsigned ranges, and that peers cannot bypass the new required-field checks with malformed truncated-integer encodings.
Security signals we found
Strict required-field enforcement added to gossip v2 decoders (assertRequiredPresent)
Partial signature scalars now validated against curve order to prevent silent mod-n reduction
Non-minimal and oversized tu32/tu64 encodings rejected during decode
HTLC maximum defaulting changed from possibly-unbounded to half capacity, with explicit handling for unknown capacity
Address port overflow now guarded during local encoding; zero-port addresses ignored rather than failing whole announcement
Signature TLV type moved from 160 to 240, widening signed range and altering message digest composition
Evidence from the diff
The merge synchronizes LND’s lnwire gossip v2 messages with BOLT PR #1059 (taproot-gossip review updates). Key changes: signature TLVs move from type 160 to 240 and the signed range widens from 0..=159 to 0..=239; pure-TLV decoders now reject messages missing compulsory fields; channel_update_2 uses sciddir short_channel_id encoding, tu32 fees, tu64 HTLC bounds, splits inbound fees into two tu32 TLVs (20/22), and defaults absent htlc_maximum_msat to half channel capacity; channel_announcement_2 uses tu64 capacity and optional chain_hash/features; node_announcement_2 uses a list of DNS hostnames and ignores zero-port addresses instead of rejecting the whole message; announcement_signatures_2 now requires a funding_txid TLV and carries two raw 32-byte MuSig2 partial signatures; gossip_timestamp_filter collapses its two block-height TLVs into a single block_height_range TLV. New validation rejects partial signatures above the curve order and non-minimal truncated integers.
Changed components
lnwire gossip v2 message codecs (ChannelAnnouncement2, ChannelUpdate2, NodeAnnouncement2, AnnounceSignatures2, GossipTimestampRange)graph/db/models.ChannelEdgePolicyFromWire and CachedEdgePolicydiscovery/AuthenticatedGossiper.handleChanUpdategraph/Builder.ApplyChannelUpdatenetann channel update validationrouting router testsInspect captured patch +2364 / −351
### channeldb/waitingproof_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/btcsuite/btcd/btcec/v2"
+ "github.com/btcsuite/btcd/chainhash/v2"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/stretchr/testify/require"
@@ -108,7 +109,8 @@ func TestWaitingProofV2RoundTrip(t *testing.T) {
annSig2 := lnwire.NewAnnSigs2(
lnwire.ChannelID{1, 2, 3},
lnwire.NewShortChanIDFromInt(42),
- partialSig,
+ lnwire.NewAnnouncementSigPair(partialSig.Sig, partialSig.Sig),
+ chainhash.Hash{1, 2, 3},
)
// Generate a deterministic public key for the combined nonce.
@@ -205,7 +207,8 @@ func TestWaitingProofV2Store(t *testing.T) {
annSig2 := lnwire.NewAnnSigs2(
lnwire.ChannelID{5, 6, 7},
lnwire.NewShortChanIDFromInt(100),
- partialSig,
+ lnwire.NewAnnouncementSigPair(partialSig.Sig, partialSig.Sig),
+ chainhash.Hash{5, 6, 7},
)
proof := NewV2WaitingProof(true, annSig2, pubKey)
@@ -251,7 +254,8 @@ func TestWaitingProofCrossVersionKeyIsolation(t *testing.T) {
v2AnnSig := lnwire.NewAnnSigs2(
lnwire.ChannelID{9, 9, 9},
scid,
- partialSig,
+ lnwire.NewAnnouncementSigPair(partialSig.Sig, partialSig.Sig),
+ chainhash.Hash{9, 9, 9},
)
v2Proof := NewV2WaitingProof(true, v2AnnSig, pubKey)
### discovery/gossiper.go
@@ -3441,7 +3441,7 @@ func (d *AuthenticatedGossiper) handleChanUpdate(ctx context.Context,
// signs a different SCID than the database SCID, but since there will
// only be a difference if AuthProof == nil, this is fine.
update, err := models.ChanEdgePolicyFromWire(
- chanInfo.ChannelID, upd,
+ chanInfo.ChannelID, chanInfo.Capacity, upd,
)
if err != nil {
completeGossipResult(nMsg.errPromise, err)
### docs/release-notes/unreleased/11164.md
@@ -0,0 +1,24 @@
+# Technical and Architectural Updates
+
+## BOLT Spec Updates
+
+* The gossip v2 wire messages in `lnwire`
+ ([#11164](https://github.com/lightningnetwork/lnd/pull/11164)) have been
+ pulled in line with the BOLT taproot-gossip extension
+ ([lightning/bolts#1059](https://github.com/lightning/bolts/pull/1059)).
+ Signature TLVs move from type 160 to 240, and the signed TLV range widens
+ from `0..=159` to `0..=239` to match BOLT 12. Each gossip v2 reader now
+ rejects a message that is missing a compulsory field. `channel_update_2`
+ encodes its fees as `tu32` and its HTLC bounds as `tu64`. Its experimental
+ inbound-fee TLV is replaced by two `tu32` records at types 20 and 22, and
+ its `short_channel_id` uses the `sciddir` form of BOLT 1's
+ `sciddir_or_pubkey`, whose direction byte replaces the old `second_peer`
+ TLV. `channel_announcement_2` encodes its capacity as `tu64`, and encodes
+ its optional `features` only when the sender included them.
+ `node_announcement_2` encodes `dns_hostnames` as a list of length-prefixed
+ entries, and an address with a zero port is ignored instead of causing the
+ whole announcement to be rejected. `announcement_signatures_2` gains a
+ required `funding_txid` TLV and carries two raw MuSig2 partial signatures
+ (64 bytes) rather than a single pre-aggregated 32-byte value.
+ `gossip_timestamp_filter`'s two block-height TLVs collapse into a single
+ `block_height_range` TLV.
### graph/builder.go
@@ -1012,7 +1012,7 @@ func (b *Builder) ApplyChannelUpdate(msg *lnwire.ChannelUpdate1) bool {
}
update, err := models.ChanEdgePolicyFromWire(
- msg.ShortChannelID.ToUint64(), msg,
+ msg.ShortChannelID.ToUint64(), ch.Capacity, msg,
)
if err != nil {
log.Errorf("Unable to parse channel update: %v", err)
### graph/db/models/cached_edge_policy.go
@@ -97,9 +97,13 @@ func NewCachedPolicy(policy *ChannelEdgePolicy) *CachedEdgePolicy {
}
}
+ // A gossip v2 policy carries no presence bit for htlc_maximum_msat.
+ // ChanEdgePolicyFromWire resolves the spec default when the sender
+ // omits the TLV, and the field is only left at zero when neither the
+ // TLV nor the channel capacity was known, which means no limit.
return &CachedEdgePolicy{
ChannelID: policy.ChannelID,
- HasMaxHTLC: true,
+ HasMaxHTLC: policy.MaxHTLC != 0,
IsNode1: !policy.SecondPeer,
IsDisabled: !policy.DisableFlags.IsEnabled(),
TimeLockDelta: policy.TimeLockDelta,
### graph/db/models/channel_edge_policy.go
@@ -2,8 +2,10 @@ package models
import (
"fmt"
+ "math"
"time"
+ "github.com/btcsuite/btcd/btcutil/v2"
"github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/lnwire"
)
@@ -101,7 +103,11 @@ type ChannelEdgePolicy struct {
// ChanEdgePolicyFromWire constructs a ChannelEdgePolicy from a channel update
// message.
-func ChanEdgePolicyFromWire(scid uint64,
+//
+// The capacity is only used by gossip v2, whose htlc_maximum_msat defaults to
+// half the channel capacity when the sender omits the TLV. Pass zero when the
+// capacity is unknown, which stores the policy without an HTLC limit.
+func ChanEdgePolicyFromWire(scid uint64, capacity btcutil.Amount,
update lnwire.ChannelUpdate) (*ChannelEdgePolicy, error) {
switch upd := update.(type) {
@@ -124,24 +130,51 @@ func ChanEdgePolicyFromWire(scid uint64,
}, nil
case *lnwire.ChannelUpdate2:
+ // Inbound fees in gossip v2 are two uint32 TLVs that are
+ // suppressed on the wire when they take their default value
+ // of 0 (i.e. no inbound surcharge). Treat the both-zero case
+ // as "no inbound fee" so the downstream Option semantics
+ // still hold.
+ var inboundFee fn.Option[lnwire.Fee]
+ baseFee, propFee := upd.InboundFee()
+
+ // The graph's fee model uses signed values to support v1
+ // discounts. Reject v2 surcharges that would wrap into
+ // discounts.
+ if baseFee > math.MaxInt32 || propFee > math.MaxInt32 {
+ return nil, fmt.Errorf("inbound fees exceed signed "+
+ "32-bit range: base=%d, rate=%d",
+ baseFee, propFee)
+ }
+
+ if baseFee != 0 || propFee != 0 {
+ inboundFee = fn.Some(lnwire.Fee{
+ BaseFee: int32(baseFee),
+ FeeRate: int32(propFee),
+ })
+ }
+
+ policy := upd.ForwardingPolicy()
+ sigBytes := upd.Signature.Val.ToSignatureBytes()
+
+ maxHTLC := upd.MaxHTLC(
+ lnwire.NewMSatFromSatoshis(capacity),
+ ).UnwrapOr(0)
+
return &ChannelEdgePolicy{
- Version: lnwire.GossipVersion2,
- SigBytes: upd.Signature.Val.ToSignatureBytes(),
- ChannelID: scid,
- LastBlockHeight: upd.BlockHeight.Val,
- SecondPeer: upd.SecondPeer.IsSome(),
- DisableFlags: upd.DisabledFlags.Val,
- TimeLockDelta: upd.CLTVExpiryDelta.Val,
- MinHTLC: upd.HTLCMinimumMsat.Val,
- MaxHTLC: upd.HTLCMaximumMsat.Val,
- FeeBaseMSat: lnwire.MilliSatoshi(
- upd.FeeBaseMsat.Val,
- ),
- FeeProportionalMillionths: lnwire.MilliSatoshi(
- upd.FeeProportionalMillionths.Val,
- ),
- InboundFee: upd.InboundFee.ValOpt(),
- ExtraSignedFields: upd.ExtraSignedFields,
+ Version: lnwire.GossipVersion2,
+ SigBytes: sigBytes,
+ ChannelID: scid,
+ LastBlockHeight: upd.BlockHeight.Val,
+ SecondPeer: !upd.IsNode1(),
+ DisableFlags: upd.DisableFlags(),
+ TimeLockDelta: policy.TimeLockDelta,
+ MinHTLC: policy.MinHTLC,
+ MaxHTLC: maxHTLC,
+ FeeBaseMSat: policy.BaseFee,
+ FeeProportionalMillionths: policy.FeeRate,
+ InboundFee: inboundFee,
+ ExtraSignedFields: upd.ExtraSignedFields,
}, nil
}
### graph/db/models/channel_edge_policy_test.go
@@ -0,0 +1,207 @@
+package models
+
+import (
+ "math"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
+ "github.com/lightningnetwork/lnd/lnwire"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// TestChanEdgePolicyFromWireV2 tests the gossip v2 branch of
+// ChanEdgePolicyFromWire: the inbound-fee Option semantics, the rejection of
+// fees that do not fit the graph's signed fee model, the direction carried by
+// the sciddir, and the htlc_maximum_msat default.
+func TestChanEdgePolicyFromWireV2(t *testing.T) {
+ t.Parallel()
+
+ const (
+ scid = uint64(1234)
+ capacity = btcutil.Amount(1_000_000)
+ )
+
+ halfCapacity := lnwire.NewMSatFromSatoshis(capacity) / 2
+
+ // The inbound fee TLVs are Options so a case can tell an absent TLV
+ // apart from one that the sender encoded with the default value of
+ // zero. Both must read back as no inbound fee.
+ newUpdate := func(direction byte, inboundBase,
+ inboundRate fn.Option[uint32],
+ maxHTLC fn.Option[lnwire.MilliSatoshi]) *lnwire.ChannelUpdate2 {
+
+ upd := &lnwire.ChannelUpdate2{}
+ upd.ShortChannelID.Val = lnwire.SciddirIntro{
+ Direction: direction,
+ SCID: [8]byte{0, 0, 0, 0, 0, 0, 0, 1},
+ }
+ upd.BlockHeight.Val = 100
+
+ inboundBase.WhenSome(func(base uint32) {
+ upd.InboundFeeBaseMsat = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType20, uint32](
+ base,
+ ),
+ )
+ })
+ inboundRate.WhenSome(func(rate uint32) {
+ upd.InboundFeeProportionalMillionths = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType22, uint32](
+ rate,
+ ),
+ )
+ })
+
+ maxHTLC.WhenSome(func(m lnwire.MilliSatoshi) {
+ upd.HTLCMaximumMsat = tlv.SomeRecordT(
+ tlv.NewRecordT[
+ tlv.TlvType14, lnwire.MilliSatoshi,
+ ](m),
+ )
+ })
+
+ return upd
+ }
+
+ tests := []struct {
+ name string
+ direction byte
+ inboundBase fn.Option[uint32]
+ inboundRate fn.Option[uint32]
+ maxHTLC fn.Option[lnwire.MilliSatoshi]
+
+ wantSecondPeer bool
+ wantInboundFee fn.Option[lnwire.Fee]
+ wantMaxHTLC lnwire.MilliSatoshi
+ wantErr string
+ }{
+ {
+ // Both TLVs absent is the no-surcharge default, which
+ // must read back as None rather than a zero Fee.
+ name: "absent inbound fees",
+ maxHTLC: fn.Some(halfCapacity),
+ wantMaxHTLC: halfCapacity,
+ },
+ {
+ // An explicit zero means the same thing, so it must
+ // also collapse to None.
+ name: "explicit zero inbound fees",
+ inboundBase: fn.Some[uint32](0),
+ inboundRate: fn.Some[uint32](0),
+ maxHTLC: fn.Some(halfCapacity),
+ wantMaxHTLC: halfCapacity,
+ },
+ {
+ name: "non-zero inbound base only",
+ inboundBase: fn.Some[uint32](7),
+ maxHTLC: fn.Some(halfCapacity),
+ wantInboundFee: fn.Some(lnwire.Fee{BaseFee: 7}),
+ wantMaxHTLC: halfCapacity,
+ },
+ {
+ name: "non-zero inbound rate only",
+ inboundRate: fn.Some[uint32](9),
+ maxHTLC: fn.Some(halfCapacity),
+ wantInboundFee: fn.Some(
+ lnwire.Fee{FeeRate: 9},
+ ),
+ wantMaxHTLC: halfCapacity,
+ },
+ {
+ name: "both inbound fees",
+ inboundBase: fn.Some[uint32](7),
+ inboundRate: fn.Some[uint32](9),
+ maxHTLC: fn.Some(halfCapacity),
+ wantInboundFee: fn.Some(
+ lnwire.Fee{BaseFee: 7, FeeRate: 9},
+ ),
+ wantMaxHTLC: halfCapacity,
+ },
+ {
+ name: "inbound base above int32",
+ inboundBase: fn.Some[uint32](math.MaxInt32 + 1),
+ maxHTLC: fn.Some(halfCapacity),
+ wantErr: "exceed signed 32-bit range",
+ },
+ {
+ name: "inbound rate above int32",
+ inboundRate: fn.Some[uint32](math.MaxInt32 + 1),
+ maxHTLC: fn.Some(halfCapacity),
+ wantErr: "exceed signed 32-bit range",
+ },
+ {
+ name: "direction one is the second peer",
+ direction: 1,
+ maxHTLC: fn.Some(halfCapacity),
+ wantSecondPeer: true,
+ wantMaxHTLC: halfCapacity,
+ },
+ {
+ // An absent htlc_maximum_msat takes the spec default
+ // of half the channel capacity.
+ name: "absent max htlc",
+ wantMaxHTLC: halfCapacity,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ upd := newUpdate(
+ test.direction, test.inboundBase,
+ test.inboundRate, test.maxHTLC,
+ )
+
+ // Guard the fixture itself: a case that means to
+ // encode an explicit zero must produce a present
+ // TLV, not an absent one.
+ require.Equal(
+ t, test.inboundBase.IsSome(),
+ upd.InboundFeeBaseMsat.IsSome(),
+ )
+ require.Equal(
+ t, test.inboundRate.IsSome(),
+ upd.InboundFeeProportionalMillionths.IsSome(),
+ )
+
+ policy, err := ChanEdgePolicyFromWire(
+ scid, capacity, upd,
+ )
+ if test.wantErr != "" {
+ require.ErrorContains(t, err, test.wantErr)
+
+ return
+ }
+ require.NoError(t, err)
+
+ require.Equal(t, lnwire.GossipVersion2, policy.Version)
+ require.Equal(t, scid, policy.ChannelID)
+ require.EqualValues(t, 100, policy.LastBlockHeight)
+ require.Equal(t, test.wantSecondPeer, policy.SecondPeer)
+ require.Equal(t, test.wantInboundFee, policy.InboundFee)
+ require.Equal(t, test.wantMaxHTLC, policy.MaxHTLC)
+ })
+ }
+}
+
+// TestChanEdgePolicyFromWireV2UnknownCapacity tests that an absent
+// htlc_maximum_msat with an unknown capacity stores no limit, and that the
+// cached policy then reports that the edge has none.
+func TestChanEdgePolicyFromWireV2UnknownCapacity(t *testing.T) {
+ t.Parallel()
+
+ upd := &lnwire.ChannelUpdate2{}
+ upd.ShortChannelID.Val = lnwire.SciddirIntro{
+ SCID: [8]byte{0, 0, 0, 0, 0, 0, 0, 1},
+ }
+ upd.BlockHeight.Val = 100
+
+ policy, err := ChanEdgePolicyFromWire(1234, 0, upd)
+ require.NoError(t, err)
+ require.Zero(t, policy.MaxHTLC)
+
+ require.False(t, NewCachedPolicy(policy).HasMaxHTLC)
+}
### lnwire/announcement_signatures_2.go
@@ -4,6 +4,7 @@ import (
"bytes"
"io"
+ "github.com/btcsuite/btcd/chainhash/v2"
"github.com/lightningnetwork/lnd/tlv"
)
@@ -25,10 +26,20 @@ type AnnounceSignatures2 struct {
// index which pays to the channel.
ShortChannelID tlv.RecordT[tlv.TlvType2, ShortChannelID]
- // PartialSignature is the combination of the partial Schnorr signature
- // created for the node's bitcoin key with the partial signature created
- // for the node's node ID key.
- PartialSignature tlv.RecordT[tlv.TlvType4, PartialSig]
+ // PartialSignatures carries the two raw musig2 partial signatures
+ // produced by the sender (one with its node_id key, one with its
+ // bitcoin key), concatenated as `node || bitcoin` (64 bytes total).
+ // The receiver verifies each half independently with the standard
+ // MuSig2 partial-sig verify routine.
+ PartialSignatures tlv.RecordT[tlv.TlvType4, AnnouncementSigPair]
+
+ // FundingTxID is the txid of the funding transaction that this
+ // announcement signature covers.
+ //
+ // The txid is in the internal byte order of chainhash.Hash, which is
+ // the order Bitcoin uses on the wire and the reverse of the displayed
+ // txid string.
+ FundingTxID tlv.RecordT[tlv.TlvType6, chainhash.Hash]
// Any extra fields in the signed range that we do not yet know about,
// but we need to keep them for signature validation and to produce a
@@ -38,15 +49,19 @@ type AnnounceSignatures2 struct {
// NewAnnSigs2 is a constructor for AnnounceSignatures2.
func NewAnnSigs2(chanID ChannelID, scid ShortChannelID,
- partialSig PartialSig) *AnnounceSignatures2 {
+ sigs AnnouncementSigPair,
+ fundingTxID chainhash.Hash) *AnnounceSignatures2 {
return &AnnounceSignatures2{
ChannelID: tlv.NewRecordT[tlv.TlvType0, ChannelID](chanID),
ShortChannelID: tlv.NewRecordT[tlv.TlvType2, ShortChannelID](
scid,
),
- PartialSignature: tlv.NewRecordT[tlv.TlvType4, PartialSig](
- partialSig,
+ PartialSignatures: tlv.NewRecordT[
+ tlv.TlvType4, AnnouncementSigPair,
+ ](sigs),
+ FundingTxID: tlv.NewPrimitiveRecord[tlv.TlvType6](
+ fundingTxID,
),
ExtraSignedFields: make(ExtraSignedFields),
}
@@ -69,8 +84,13 @@ var _ PureTLVMessage = (*AnnounceSignatures2)(nil)
//
// This is part of the lnwire.Message interface.
func (a *AnnounceSignatures2) Decode(r io.Reader, _ uint32) error {
+ // The tlv package cannot encode a chainhash.Hash, so the txid goes
+ // through a [32]byte record, as the chain hash of ChannelAnnouncement2
+ // does.
+ fundingTxID := tlv.ZeroRecordT[tlv.TlvType6, [32]byte]()
stream, err := tlv.NewStream(ProduceRecordsSorted(
- &a.ChannelID, &a.ShortChannelID, &a.PartialSignature,
+ &a.ChannelID, &a.ShortChannelID, &a.PartialSignatures,
+ &fundingTxID,
)...)
if err != nil {
return err
@@ -81,6 +101,17 @@ func (a *AnnounceSignatures2) Decode(r io.Reader, _ uint32) error {
return err
}
+ if err := assertRequiredPresent(
+ typeMap,
+ a.ChannelID.TlvType(),
+ a.ShortChannelID.TlvType(),
+ a.PartialSignatures.TlvType(),
+ a.FundingTxID.TlvType(),
+ ); err != nil {
+ return err
+ }
+ a.FundingTxID.Val = chainhash.Hash(fundingTxID.Val)
+
a.ExtraSignedFields = ExtraSignedFieldsFromTypeMap(typeMap)
return nil
@@ -122,9 +153,12 @@ func (a *AnnounceSignatures2) SerializedSize() (uint32, error) {
//
// NOTE: this is part of the PureTLVMessage interface.
func (a *AnnounceSignatures2) AllRecords() []tlv.Record {
+ fundingTxID := tlv.NewPrimitiveRecord[tlv.TlvType6, [32]byte](
+ [32]byte(a.FundingTxID.Val),
+ )
recordProducers := []tlv.RecordProducer{
&a.ChannelID, &a.ShortChannelID,
- &a.PartialSignature,
+ &a.PartialSignatures, &fundingTxID,
}
recordProducers = append(recordProducers, RecordsAsProducers(
### lnwire/announcement_signatures_2_test.go
@@ -32,12 +32,23 @@ func TestAnnSigs2EncodeDecode(t *testing.T) {
0, 0, 1, 0, 0, 2, 0, 3, // value
}...)
- // PartialSignature.
+ // PartialSignatures (node || bitcoin, 64 bytes total).
rawBytes = append(rawBytes, []byte{
0x04, // type
+ 0x40, // length
+ }...)
+ rawBytes = append(rawBytes, make([]byte, 64)...) // value
+
+ // FundingTxID. Distinct bytes, so the test can check their order.
+ var fundingTxID [32]byte
+ for i := range fundingTxID {
+ fundingTxID[i] = byte(i + 1)
+ }
+ rawBytes = append(rawBytes, []byte{
+ 0x06, // type
0x20, // length
}...)
- rawBytes = append(rawBytes, make([]byte, 32)...) // value
+ rawBytes = append(rawBytes, fundingTxID[:]...) // value
// Extra field in the first signed range.
rawBytes = append(rawBytes, []byte{
@@ -67,6 +78,10 @@ func TestAnnSigs2EncodeDecode(t *testing.T) {
// At this point, we expect 2 extra signed fields.
require.Len(t, msg.ExtraSignedFields, 2)
+ // The wire bytes are the internal byte order of chainhash.Hash, so
+ // they land in the hash unchanged.
+ require.Equal(t, fundingTxID, [32]byte(msg.FundingTxID.Val))
+
// Next, encode the message back into a new byte buffer.
var b bytes.Buffer
err = msg.Encode(&b, 0)
### lnwire/block_height_range_test.go
@@ -0,0 +1,34 @@
+package lnwire
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// TestBlockHeightRangeRejectsShort tests that a block height range shorter
+// than its fixed-width first block height is rejected.
+func TestBlockHeightRangeRejectsShort(t *testing.T) {
+ t.Parallel()
+
+ decode := func(raw []byte) error {
+ var rng BlockHeightRange
+
+ return blockHeightRangeDecoder(
+ bytes.NewReader(raw), &rng, &[8]byte{},
+ uint64(len(raw)),
+ )
+ }
+
+ for length := range 4 {
+ require.ErrorAs(
+ t, decode(make([]byte, length)),
+ &tlv.ErrTypeForDecoding{},
+ )
+ }
+
+ // Four bytes is the first block height with an empty block count.
+ require.NoError(t, decode(make([]byte, 4)))
+}
### lnwire/channel_announcement_2.go
@@ -14,13 +14,20 @@ import (
type ChannelAnnouncement2 struct {
// ChainHash denotes the target chain that this channel was opened
// within. This value should be the genesis hash of the target chain.
- ChainHash tlv.RecordT[tlv.TlvType0, chainhash.Hash]
+ // When absent, it is the bitcoin mainnet genesis block hash. It is
+ // present exactly when the sender included it, because the signature
+ // covers the records as sent.
+ ChainHash tlv.OptionalRecordT[tlv.TlvType0, chainhash.Hash]
// Features is the feature vector that encodes the features supported
// by the target node. This field can be used to signal the type of the
// channel, or modifications to the fields that would normally follow
// this vector.
- Features tlv.RecordT[tlv.TlvType2, RawFeatureVector]
+ //
+ // The spec makes the field optional. It is present exactly when the
+ // sender included it, even when empty, because the signature covers
+ // the records as sent.
+ Features tlv.OptionalRecordT[tlv.TlvType2, RawFeatureVector]
// ShortChannelID is the unique description of the funding transaction,
// or where exactly it's located within the target blockchain.
@@ -61,7 +68,7 @@ type ChannelAnnouncement2 struct {
// Signature is a Schnorr signature over serialised signed-range TLV
// stream of the message.
- Signature tlv.RecordT[tlv.TlvType160, Sig]
+ Signature tlv.RecordT[tlv.TlvType240, Sig]
// Any extra fields in the signed range that we do not yet know about,
// but we need to keep them for signature validation and to produce a
@@ -95,19 +102,25 @@ func (c *ChannelAnnouncement2) AllRecords() []tlv.Record {
//
//nolint:ll
func (c *ChannelAnnouncement2) nonSignatureRecordProducers() []tlv.RecordProducer {
- // The chain-hash record is only included if it is _not_ equal to the
- // bitcoin mainnet genisis block hash.
var recordProducers []tlv.RecordProducer
- if !c.ChainHash.Val.IsEqual(chaincfg.MainNetParams.GenesisHash) {
- hash := tlv.ZeroRecordT[tlv.TlvType0, [32]byte]()
- hash.Val = c.ChainHash.Val
+ c.ChainHash.WhenSome(
+ func(r tlv.RecordT[tlv.TlvType0, chainhash.Hash]) {
+ hash := tlv.NewPrimitiveRecord[tlv.TlvType0, [32]byte](
+ r.Val,
+ )
+ recordProducers = append(recordProducers, &hash)
+ },
+ )
- recordProducers = append(recordProducers, &hash)
- }
+ c.Features.WhenSome(
+ func(f tlv.RecordT[tlv.TlvType2, RawFeatureVector]) {
+ recordProducers = append(recordProducers, &f)
+ },
+ )
recordProducers = append(recordProducers,
- &c.Features, &c.ShortChannelID, &c.Capacity, &c.NodeID1,
- &c.NodeID2,
+ &c.ShortChannelID, truncatedUint64Record(&c.Capacity),
+ &c.NodeID1, &c.NodeID2,
)
c.BitcoinKey1.WhenSome(func(key tlv.RecordT[tlv.TlvType12, [33]byte]) {
@@ -137,6 +150,7 @@ func (c *ChannelAnnouncement2) nonSignatureRecordProducers() []tlv.RecordProduce
//
// This is part of the lnwire.Message interface.
func (c *ChannelAnnouncement2) Decode(r io.Reader, _ uint32) error {
+ features := tlv.ZeroRecordT[tlv.TlvType2, RawFeatureVector]()
var (
chainHash = tlv.ZeroRecordT[tlv.TlvType0, [32]byte]()
btcKey1 = tlv.ZeroRecordT[tlv.TlvType12, [33]byte]()
@@ -145,9 +159,9 @@ func (c *ChannelAnnouncement2) Decode(r io.Reader, _ uint32) error {
)
stream, err := tlv.NewStream(ProduceRecordsSorted(
&chainHash,
- &c.Features,
+ &features,
&c.ShortChannelID,
- &c.Capacity,
+ truncatedUint64Record(&c.Capacity),
&c.NodeID1,
&c.NodeID2,
&btcKey1,
@@ -166,10 +180,26 @@ func (c *ChannelAnnouncement2) Decode(r io.Reader, _ uint32) error {
return err
}
- // By default, the chain-hash is the bitcoin mainnet genesis block hash.
- c.ChainHash.Val = *chaincfg.MainNetParams.GenesisHash
+ if err := assertRequiredPresent(
+ typeMap,
+ c.ShortChannelID.TlvType(),
+ c.Outpoint.TlvType(),
+ c.Capacity.TlvType(),
+ c.NodeID1.TlvType(),
+ c.NodeID2.TlvType(),
+ c.Signature.TlvType(),
+ ); err != nil {
+ return err
+ }
+
if _, ok := typeMap[c.ChainHash.TlvType()]; ok {
- c.ChainHash.Val = chainHash.Val
+ hash := c.ChainHash.Zero()
+ hash.Val = chainHash.Val
+ c.ChainHash = tlv.SomeRecordT(hash)
+ }
+
+ if _, ok := typeMap[c.Features.TlvType()]; ok {
+ c.Features = tlv.SomeRecordT(features)
}
if _, ok := typeMap[c.BitcoinKey1.TlvType()]; ok {
@@ -191,6 +221,7 @@ func (c *ChannelAnnouncement2) Decode(r io.Reader, _ uint32) error {
// DecodeNonSigTLVRecords decodes only the TLV section of the message.
func (c *ChannelAnnouncement2) DecodeNonSigTLVRecords(r io.Reader) error {
+ features := tlv.ZeroRecordT[tlv.TlvType2, RawFeatureVector]()
var (
chainHash = tlv.ZeroRecordT[tlv.TlvType0, [32]byte]()
btcKey1 = tlv.ZeroRecordT[tlv.TlvType12, [33]byte]()
@@ -199,9 +230,9 @@ func (c *ChannelAnnouncement2) DecodeNonSigTLVRecords(r io.Reader) error {
)
stream, err := tlv.NewStream(ProduceRecordsSorted(
&chainHash,
- &c.Features,
+ &features,
&c.ShortChannelID,
- &c.Capacity,
+ truncatedUint64Record(&c.Capacity),
&c.NodeID1,
&c.NodeID2,
&btcKey1,
@@ -218,10 +249,14 @@ func (c *ChannelAnnouncement2) DecodeNonSigTLVRecords(r io.Reader) error {
return err
}
- // By default, the chain-hash is the bitcoin mainnet genesis block hash.
- c.ChainHash.Val = *chaincfg.MainNetParams.GenesisHash
if _, ok := typeMap[c.ChainHash.TlvType()]; ok {
- c.ChainHash.Val = chainHash.Val
+ hash := c.ChainHash.Zero()
+ hash.Val = chainHash.Val
+ c.ChainHash = tlv.SomeRecordT(hash)
+ }
+
+ if _, ok := typeMap[c.Features.TlvType()]; ok {
+ c.Features = tlv.SomeRecordT(features)
}
if _, ok := typeMap[c.BitcoinKey1.TlvType()]; ok {
@@ -297,7 +332,9 @@ func (c *ChannelAnnouncement2) Node2KeyBytes() [33]byte {
//
// NOTE: This is part of the ChannelAnnouncement interface.
func (c *ChannelAnnouncement2) GetChainHash() chainhash.Hash {
- return c.ChainHash.Val
+ return c.ChainHash.ValOpt().UnwrapOr(
+ *chaincfg.MainNetParams.GenesisHash,
+ )
}
// SCID returns the short channel ID of the channel.
### lnwire/channel_announcement_2_test.go
@@ -40,9 +40,9 @@ func TestChanAnn2EncodeDecode(t *testing.T) {
0xab, 0xcd, // value.
// Capacity record.
- 0x06, // type.
- 0x08, // length.
- 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x86, 0xa0, // value: 100000.
+ 0x06, // type.
+ 0x03, // length.
+ 0x1, 0x86, 0xa0, // value (tu64: 100000).
// NodeID1 record.
0x08, // type.
@@ -75,7 +75,7 @@ func TestChanAnn2EncodeDecode(t *testing.T) {
0x79, 0x79, // value.
// Signature.
- 0xa0, // type.
+ 0xf0, // type.
0x40, // length.
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb,
0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
### lnwire/channel_update_2.go
@@ -2,34 +2,48 @@ package lnwire
import (
"bytes"
+ "encoding/binary"
"fmt"
"io"
"github.com/btcsuite/btcd/chaincfg/v2"
"github.com/btcsuite/btcd/chainhash/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/tlv"
)
const (
- defaultCltvExpiryDelta = uint16(80)
- defaultHtlcMinMsat = MilliSatoshi(1)
- defaultFeeBaseMsat = uint32(1000)
- defaultFeeProportionalMillionths = uint32(1)
+ defaultCltvExpiryDelta = uint16(80)
+ defaultHtlcMinMsat = MilliSatoshi(1)
+ defaultFeeBaseMsat = uint32(1000)
+ defaultFeeProportionalMillionths = uint32(1)
+ defaultInboundFeeBaseMsat = uint32(0)
+ defaultInboundFeeProportionalMillionths = uint32(0)
)
// ChannelUpdate2 message is used after taproot channel has been initially
// announced. Each side independently announces its fees and minimum expiry for
// HTLCs and other parameters. This message is also used to redeclare initially
// set channel parameters.
+//
+// Every field with a spec default is optional. A field is present exactly
+// when the sender included it, even when it holds the default value, because
+// the signature covers the records as sent. The default applies only when a
+// caller reads an absent field.
type ChannelUpdate2 struct {
// ChainHash denotes the target chain that this channel was opened
// within. This value should be the genesis hash of the target chain.
// Along with the short channel ID, this uniquely identifies the
- // channel globally in a blockchain.
- ChainHash tlv.RecordT[tlv.TlvType0, chainhash.Hash]
+ // channel globally in a blockchain. When absent, it is the bitcoin
+ // mainnet genesis block hash.
+ ChainHash tlv.OptionalRecordT[tlv.TlvType0, chainhash.Hash]
- // ShortChannelID is the unique description of the funding transaction.
- ShortChannelID tlv.RecordT[tlv.TlvType2, ShortChannelID]
+ // ShortChannelID identifies the channel and the side of it that sent
+ // this update. It is BOLT 1's `sciddir_or_pubkey` type constrained to
+ // the `sciddir` form: 9 wire bytes of `<dirbyte><scid>`, where the
+ // direction byte is `0` for `node_id_1` and `1` for `node_id_2`. It is
+ // the only field that says which side sent the update.
+ ShortChannelID tlv.RecordT[tlv.TlvType2, SciddirIntro]
// BlockHeight allows ordering in the case of multiple announcements. We
// should ignore the message if block height is not greater than the
@@ -40,44 +54,49 @@ type ChannelUpdate2 struct {
// DisabledFlags is an optional bitfield that describes various reasons
// that the node is communicating that the channel should be considered
- // disabled.
- DisabledFlags tlv.RecordT[tlv.TlvType6, ChanUpdateDisableFlags]
-
- // SecondPeer is used to indicate which node the channel node has
- // created and signed this message. If this field is present, it was
- // node 2 otherwise it was node 1.
- SecondPeer tlv.OptionalRecordT[tlv.TlvType8, TrueBoolean]
+ // disabled. When absent, the channel is enabled.
+ DisabledFlags tlv.OptionalRecordT[tlv.TlvType6, ChanUpdateDisableFlags]
// CLTVExpiryDelta is the minimum number of blocks this node requires to
// be added to the expiry of HTLCs. This is a security parameter
// determined by the node operator. This value represents the required
// gap between the time locks of the incoming and outgoing HTLC's set
- // to this node.
- CLTVExpiryDelta tlv.RecordT[tlv.TlvType10, uint16]
+ // to this node. When absent, it is 80.
+ CLTVExpiryDelta tlv.OptionalRecordT[tlv.TlvType10, uint16]
// HTLCMinimumMsat is the minimum HTLC value which will be accepted.
- HTLCMinimumMsat tlv.RecordT[tlv.TlvType12, MilliSatoshi]
+ // When absent, it is 1.
+ HTLCMinimumMsat tlv.OptionalRecordT[tlv.TlvType12, MilliSatoshi]
// HtlcMaximumMsat is the maximum HTLC value which will be accepted.
- HTLCMaximumMsat tlv.RecordT[tlv.TlvType14, MilliSatoshi]
+ HTLCMaximumMsat tlv.OptionalRecordT[tlv.TlvType14, MilliSatoshi]
// FeeBaseMsat is the base fee that must be used for incoming HTLC's to
// this particular channel. This value will be tacked onto the required
- // for a payment independent of the size of the payment.
- FeeBaseMsat tlv.RecordT[tlv.TlvType16, uint32]
+ // for a payment independent of the size of the payment. When absent,
+ // it is 1000.
+ FeeBaseMsat tlv.OptionalRecordT[tlv.TlvType16, uint32]
// FeeProportionalMillionths is the fee rate that will be charged per
- // millionth of a satoshi.
- FeeProportionalMillionths tlv.RecordT[tlv.TlvType18, uint32]
-
- // InboundFee is an optional TLV record that contains the fee
- // information for incoming HTLCs.
- // TODO(elle): assign normal tlv type?
- InboundFee tlv.OptionalRecordT[tlv.TlvType55555, Fee]
+ // millionth of a satoshi. When absent, it is 1.
+ FeeProportionalMillionths tlv.OptionalRecordT[tlv.TlvType18, uint32]
+
+ // InboundFeeBaseMsat is the base fee (in millisatoshis) added by this
+ // node for HTLCs forwarded *in* via this channel, regardless of which
+ // channel they are forwarded out on. Default 0. Positive-only: this
+ // version of gossip does not support negative inbound fees.
+ InboundFeeBaseMsat tlv.OptionalRecordT[tlv.TlvType20, uint32]
+
+ // InboundFeeProportionalMillionths is the proportional inbound fee (in
+ // millionths of a satoshi) added by this node per transferred satoshi
+ // for HTLCs forwarded *in* via this channel. Default 0. Positive-only.
+ InboundFeeProportionalMillionths tlv.OptionalRecordT[
+ tlv.TlvType22, uint32,
+ ]
// Signature is used to validate the announced data and prove the
// ownership of node id.
- Signature tlv.RecordT[tlv.TlvType160, Sig]
+ Signature tlv.RecordT[tlv.TlvType240, Sig]
// Any extra fields in the signed range that we do not yet know about,
// but we need to keep them for signature validation and to produce a
@@ -112,60 +131,54 @@ func (c *ChannelUpdate2) Decode(r io.Reader, _ uint32) error {
}
var (
- chainHash = tlv.ZeroRecordT[tlv.TlvType0, [32]byte]()
- secondPeer = tlv.ZeroRecordT[tlv.TlvType8, TrueBoolean]()
- inboundFee = tlv.ZeroRecordT[tlv.TlvType55555, Fee]()
+ chainHash = tlv.ZeroRecordT[tlv.TlvType0, [32]byte]()
+ disabledFlags = tlv.ZeroRecordT[
+ tlv.TlvType6, ChanUpdateDisableFlags,
+ ]()
+ cltvDelta = tlv.ZeroRecordT[tlv.TlvType10, uint16]()
+ htlcMin = tlv.ZeroRecordT[tlv.TlvType12, MilliSatoshi]()
+ htlcMax = tlv.ZeroRecordT[tlv.TlvType14, MilliSatoshi]()
+ feeBase = tlv.ZeroRecordT[tlv.TlvType16, uint32]()
+ feeRate = tlv.ZeroRecordT[tlv.TlvType18, uint32]()
+ inboundBase = tlv.ZeroRecordT[tlv.TlvType20, uint32]()
+ inboundRate = tlv.ZeroRecordT[tlv.TlvType22, uint32]()
)
typeMap, err := tlvRecords.ExtractRecords(
- &chainHash, &c.ShortChannelID, &c.BlockHeight, &c.DisabledFlags,
- &secondPeer, &c.CLTVExpiryDelta, &c.HTLCMinimumMsat,
- &c.HTLCMaximumMsat, &c.FeeBaseMsat,
- &c.FeeProportionalMillionths, &inboundFee,
- &c.Signature,
+ &chainHash, sciddirRecord(&c.ShortChannelID), &c.BlockHeight,
+ &disabledFlags, &cltvDelta, truncatedUint64Record(&htlcMin),
+ truncatedUint64Record(&htlcMax),
+ truncatedUint32Record(&feeBase),
+ truncatedUint32Record(&feeRate),
+ truncatedUint32Record(&inboundBase),
+ truncatedUint32Record(&inboundRate), &c.Signature,
)
if err != nil {
return err
}
c.Signature.Val.ForceSchnorr()
- // By default, the chain-hash is the bitcoin mainnet genesis block hash.
- c.ChainHash.Val = *chaincfg.MainNetParams.GenesisHash
- if _, ok := typeMap[c.ChainHash.TlvType()]; ok {
- c.ChainHash.Val = chainHash.Val
- }
-
- // The presence of the second_peer tlv type indicates "true".
- if _, ok := typeMap[c.SecondPeer.TlvType()]; ok {
- c.SecondPeer = tlv.SomeRecordT(secondPeer)
- }
-
- // If the CLTV expiry delta was not encoded, then set it to the default
- // value.
- if _, ok := typeMap[c.CLTVExpiryDelta.TlvType()]; !ok {
- c.CLTVExpiryDelta.Val = defaultCltvExpiryDelta
- }
-
- // If the HTLC Minimum msat was not encoded, then set it to the default
- // value.
- if _, ok := typeMap[c.HTLCMinimumMsat.TlvType()]; !ok {
- c.HTLCMinimumMsat.Val = defaultHtlcMinMsat
- }
-
- // If the base fee was not encoded, then set it to the default value.
- if _, ok := typeMap[c.FeeBaseMsat.TlvType()]; !ok {
- c.FeeBaseMsat.Val = defaultFeeBaseMsat
- }
-
- // If the proportional fee was not encoded, then set it to the default
- // value.
- if _, ok := typeMap[c.FeeProportionalMillionths.TlvType()]; !ok {
- c.FeeProportionalMillionths.Val = defaultFeeProportionalMillionths //nolint:ll
+ if err := assertRequiredPresent(
+ typeMap,
+ c.ShortChannelID.TlvType(),
+ c.BlockHeight.TlvType(),
+ c.Signature.TlvType(),
+ ); err != nil {
+ return err
}
- // If the inbound fee was encoded, set it.
- if _, ok := typeMap[c.InboundFee.TlvType()]; ok {
- c.InboundFee = tlv.SomeRecordT(inboundFee)
+ if _, ok := typeMap[c.ChainHash.TlvType()]; ok {
+ hash := c.ChainHash.Zero()
+ hash.Val = chainHash.Val
+ c.ChainHash = tlv.SomeRecordT(hash)
}
+ SetOptFromMap(typeMap, &c.DisabledFlags, disabledFlags)
+ SetOptFromMap(typeMap, &c.CLTVExpiryDelta, cltvDelta)
+ SetOptFromMap(typeMap, &c.HTLCMinimumMsat, htlcMin)
+ SetOptFromMap(typeMap, &c.HTLCMaximumMsat, htlcMax)
+ SetOptFromMap(typeMap, &c.FeeBaseMsat, feeBase)
+ SetOptFromMap(typeMap, &c.FeeProportionalMillionths, feeRate)
+ SetOptFromMap(typeMap, &c.InboundFeeBaseMsat, inboundBase)
+ SetOptFromMap(typeMap, &c.InboundFeeProportionalMillionths, inboundRate)
c.ExtraSignedFields = ExtraSignedFieldsFromTypeMap(typeMap)
@@ -178,56 +191,28 @@ func (c *ChannelUpdate2) Decode(r io.Reader, _ uint32) error {
//
// NOTE: this is part of the PureTLVMessage interface.
func (c *ChannelUpdate2) AllRecords() []tlv.Record {
- var recordProducers []tlv.RecordProducer
-
- // The chain-hash record is only included if it is _not_ equal to the
- // bitcoin mainnet genisis block hash.
- if !c.ChainHash.Val.IsEqual(chaincfg.MainNetParams.GenesisHash) {
- hash := tlv.ZeroRecordT[tlv.TlvType0, [32]byte]()
- hash.Val = c.ChainHash.Val
-
- recordProducers = append(recordProducers, &hash)
+ recordProducers := []tlv.RecordProducer{
+ sciddirRecord(&c.ShortChannelID), &c.BlockHeight, &c.Signature,
}
- recordProducers = append(recordProducers,
- &c.ShortChannelID, &c.BlockHeight, &c.Signature,
+ // Each optional record is emitted exactly when it is present, so a
+ // decoded message re-encodes to the bytes that the sender signed.
+ c.ChainHash.WhenSome(
+ func(r tlv.RecordT[tlv.TlvType0, chainhash.Hash]) {
+ hash := tlv.NewPrimitiveRecord[tlv.TlvType0, [32]byte](
+ r.Val,
+ )
+ recordProducers = append(recordProducers, &hash)
+ },
)
-
- // Only include the disable flags if any bit is set.
- if !c.DisabledFlags.Val.IsEnabled() {
- recordProducers = append(recordProducers, &c.DisabledFlags)
- }
-
- // We only need to encode the second peer boolean if it is true
- c.SecondPeer.WhenSome(func(r tlv.RecordT[tlv.TlvType8, TrueBoolean]) {
- recordProducers = append(recordProducers, &r)
- })
-
- // We only encode the cltv expiry delta if it is not equal to the
- // default.
- if c.CLTVExpiryDelta.Val != defaultCltvExpiryDelta {
- recordProducers = append(recordProducers, &c.CLTVExpiryDelta)
- }
-
- if c.HTLCMinimumMsat.Val != defaultHtlcMinMsat {
- recordProducers = append(recordProducers, &c.HTLCMinimumMsat)
- }
-
- recordProducers = append(recordProducers, &c.HTLCMaximumMsat)
-
- if c.FeeBaseMsat.Val != defaultFeeBaseMsat {
- recordProducers = append(recordProducers, &c.FeeBaseMsat)
- }
-
- if c.FeeProportionalMillionths.Val != defaultFeeProportionalMillionths {
- recordProducers = append(
- recordProducers, &c.FeeProportionalMillionths,
- )
- }
-
- c.InboundFee.WhenSome(func(r tlv.RecordT[tlv.TlvType55555, Fee]) {
- recordProducers = append(recordProducers, &r)
- })
+ AddOpt(&recordProducers, c.DisabledFlags)
+ AddOpt(&recordProducers, c.CLTVExpiryDelta)
+ addOptTU64(&recordProducers, c.HTLCMinimumMsat)
+ addOptTU64(&recordProducers, c.HTLCMaximumMsat)
+ addOptTU32(&recordProducers, c.FeeBaseMsat)
+ addOptTU32(&recordProducers, c.FeeProportionalMillionths)
+ addOptTU32(&recordProducers, c.InboundFeeBaseMsat)
+ addOptTU32(&recordProducers, c.InboundFeeProportionalMillionths)
recordProducers = append(recordProducers, RecordsAsProducers(
tlv.MapToRecords(c.ExtraSignedFields),
@@ -259,47 +244,88 @@ var _ Message = (*ChannelUpdate2)(nil)
// lnwire.PureTLVMessage interface.
var _ PureTLVMessage = (*ChannelUpdate2)(nil)
-// SCID returns the ShortChannelID of the channel that the update applies to.
+// SCID returns the ShortChannelID of the channel that the update applies to,
+// projecting away the direction byte that the wire encoding carries.
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) SCID() ShortChannelID {
- return c.ShortChannelID.Val
+ return c.ShortChannelID.Val.ShortChannelID()
}
// IsNode1 is true if the update was produced by node 1 of the channel peers.
-// Node 1 is the node with the lexicographically smaller public key.
+// Node 1 is the node with the lexicographically smaller public key, and is
+// indicated by a direction byte of 0 in the encoded ShortChannelID.
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) IsNode1() bool {
- return c.SecondPeer.IsNone()
+ return c.ShortChannelID.Val.Direction == 0
+}
+
+// MaxHTLC returns the htlc_maximum_msat that applies to this update, which is
+// the largest HTLC the sender will forward over the channel.
+//
+// Unlike the other gossip v2 defaults, this one is not a constant: the spec
+// defaults an absent htlc_maximum_msat to floor(channel capacity / 2), and the
+// message does not carry the capacity. The caller therefore supplies it in
+// millisatoshis, and passes zero when it is unknown. An absent TLV with an
+// unknown capacity leaves the update with no advertised limit, which is None.
+//
+// Reading the value never changes the message, so the signed TLV stays exactly
+// as the sender wrote it.
+func (c *ChannelUpdate2) MaxHTLC(
+ capacityMsat MilliSatoshi) fn.Option[MilliSatoshi] {
+
+ if maxHTLC := c.HTLCMaximumMsat.ValOpt(); maxHTLC.IsSome() {
+ return maxHTLC
+ }
+
+ if capacityMsat == 0 {
+ return fn.None[MilliSatoshi]()
+ }
+
+ return fn.Some(capacityMsat / 2)
}
// IsDisabled is true if the update is announcing that the channel should be
// considered disabled.
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) IsDisabled() bool {
- return !c.DisabledFlags.Val.IsEnabled()
+ return !c.DisableFlags().IsEnabled()
}
// GetChainHash returns the hash of the chain that the message is referring to.
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) GetChainHash() chainhash.Hash {
- return c.ChainHash.Val
+ return c.ChainHash.ValOpt().UnwrapOr(
+ *chaincfg.MainNetParams.GenesisHash,
+ )
}
// ForwardingPolicy returns the set of forwarding constraints of the update.
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) ForwardingPolicy() *ForwardingPolicy {
+ maxHTLC := c.HTLCMaximumMsat.ValOpt()
+
return &ForwardingPolicy{
- TimeLockDelta: c.CLTVExpiryDelta.Val,
- BaseFee: MilliSatoshi(c.FeeBaseMsat.Val),
- FeeRate: MilliSatoshi(c.FeeProportionalMillionths.Val),
- MinHTLC: c.HTLCMinimumMsat.Val,
- HasMaxHTLC: true,
- MaxHTLC: c.HTLCMaximumMsat.Val,
+ TimeLockDelta: c.CLTVExpiryDelta.ValOpt().UnwrapOr(
+ defaultCltvExpiryDelta,
+ ),
+ BaseFee: MilliSatoshi(c.FeeBaseMsat.ValOpt().UnwrapOr(
+ defaultFeeBaseMsat,
+ )),
+ FeeRate: MilliSatoshi(
+ c.FeeProportionalMillionths.ValOpt().UnwrapOr(
+ defaultFeeProportionalMillionths,
+ ),
+ ),
+ MinHTLC: c.HTLCMinimumMsat.ValOpt().UnwrapOr(
+ defaultHtlcMinMsat,
+ ),
+ HasMaxHTLC: maxHTLC.IsSome(),
+ MaxHTLC: maxHTLC.UnwrapOr(0),
}
}
@@ -329,20 +355,54 @@ func (c *ChannelUpdate2) CmpAge(update ChannelUpdate) (CompareResult, error) {
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) SetDisabledFlag(disabled bool) {
+ flags := c.DisableFlags()
if disabled {
- c.DisabledFlags.Val |= ChanUpdateDisableIncoming
- c.DisabledFlags.Val |= ChanUpdateDisableOutgoing
+ flags |= ChanUpdateDisableIncoming
+ flags |= ChanUpdateDisableOutgoing
} else {
- c.DisabledFlags.Val &^= ChanUpdateDisableIncoming
- c.DisabledFlags.Val &^= ChanUpdateDisableOutgoing
+ flags &^= ChanUpdateDisableIncoming
+ flags &^= ChanUpdateDisableOutgoing
}
+
+ // The update is re-signed after this change, so the flags follow the
+ // writer rule and are omitted when they take the default value.
+ c.DisabledFlags = tlv.OptionalRecordT[
+ tlv.TlvType6, ChanUpdateDisableFlags,
+ ]{}
+ if !flags.IsEnabled() {
+ c.DisabledFlags = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType6](flags),
+ )
+ }
+}
+
+// DisableFlags returns the disable flags of the update, or the enabled default
+// when the update does not carry them.
+func (c *ChannelUpdate2) DisableFlags() ChanUpdateDisableFlags {
+ return c.DisabledFlags.ValOpt().UnwrapOr(0)
}
-// SetSCID can be used to overwrite the SCID of the update.
+// InboundFee returns the inbound base fee and the inbound fee rate of the
+// update, with the default of 0 for each fee that the update does not carry.
+func (c *ChannelUpdate2) InboundFee() (uint32, uint32) {
+ base := c.InboundFeeBaseMsat.ValOpt().UnwrapOr(
+ defaultInboundFeeBaseMsat,
+ )
+ rate := c.InboundFeeProportionalMillionths.ValOpt().UnwrapOr(
+ defaultInboundFeeProportionalMillionths,
+ )
+
+ return base, rate
+}
+
+// SetSCID can be used to overwrite the SCID of the update, leaving the
+// existing direction byte in place.
//
// NOTE: this is part of the ChannelUpdate interface.
func (c *ChannelUpdate2) SetSCID(scid ShortChannelID) {
- c.ShortChannelID.Val = scid
+ binary.BigEndian.PutUint64(
+ c.ShortChannelID.Val.SCID[:], scid.ToUint64(),
+ )
}
// A compile time check to ensure ChannelUpdate2 implements the
### lnwire/channel_update_2_test.go
@@ -2,12 +2,145 @@ package lnwire
import (
"bytes"
+ "fmt"
+ "math"
"testing"
+ "github.com/btcsuite/btcd/chaincfg/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
)
+// TestChanUpdate2FeeEncoding checks each fee against canonical tu32 vectors
+// and rejects non-minimal or oversized values received from peers.
+func TestChanUpdate2FeeEncoding(t *testing.T) {
+ t.Parallel()
+
+ // defaults holds the value each fee field takes when its TLV is
+ // absent.
+ defaults := map[uint64]uint32{
+ 16: defaultFeeBaseMsat,
+ 18: defaultFeeProportionalMillionths,
+ 20: defaultInboundFeeBaseMsat,
+ 22: defaultInboundFeeProportionalMillionths,
+ }
+
+ tests := []struct {
+ name string
+ raw []byte
+ value uint32
+
+ // wantErrIs is the sentinel the decode must report, and
+ // wantErrAs is set instead for an error that is a type rather
+ // than a sentinel. Both empty means the decode must succeed.
+ wantErrIs error
+ wantErrAs bool
+ }{
+ {name: "zero"},
+ {name: "one byte", raw: []byte{0xff}, value: 255},
+ {name: "two bytes", raw: []byte{1, 0}, value: 256},
+ {name: "three bytes", raw: []byte{1, 0, 0}, value: 65536},
+ {
+ name: "four bytes",
+ raw: []byte{0xff, 0xff, 0xff, 0xff},
+ value: math.MaxUint32,
+ },
+ {
+ name: "non-minimal zero",
+ raw: []byte{0},
+ wantErrIs: tlv.ErrTUintNotMinimal,
+ },
+ {
+ name: "leading zero",
+ raw: []byte{0, 1},
+ wantErrIs: tlv.ErrTUintNotMinimal,
+ },
+ {
+ name: "oversized",
+ raw: []byte{1, 0, 0, 0, 0},
+ wantErrAs: true,
+ },
+ }
+ for _, typ := range []uint64{16, 18, 20, 22} {
+ for _, test := range tests {
+ name := fmt.Sprintf("%d/%s", typ, test.name)
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+
+ data, err := EncodeRecords(tlv.MapToRecords(
+ map[uint64][]byte{
+ 2: make([]byte, sciddirLen),
+ 4: make([]byte, 4),
+ 240: make([]byte, 64),
+ typ: test.raw,
+ },
+ ))
+ require.NoError(t, err)
+
+ var msg ChannelUpdate2
+ err = msg.Decode(bytes.NewReader(data), 0)
+ switch {
+ case test.wantErrIs != nil:
+ require.ErrorIs(t, err, test.wantErrIs)
+
+ return
+
+ case test.wantErrAs:
+ require.ErrorAs(
+ t, err,
+ &tlv.ErrTypeForDecoding{},
+ )
+
+ return
+ }
+ require.NoError(t, err)
+
+ // The TLV under test fills its own field. The
+ // other fee fields read as their defaults.
+ policy := msg.ForwardingPolicy()
+ inboundBase, inboundRate := msg.InboundFee()
+ fields := map[uint64]uint32{
+ 16: uint32(policy.BaseFee),
+ 18: uint32(policy.FeeRate),
+ 20: inboundBase,
+ 22: inboundRate,
+ }
+ for fieldType, got := range fields {
+ want := defaults[fieldType]
+ if fieldType == typ {
+ want = test.value
+ }
+ require.Equalf(
+ t, want, got, "fee TLV %d",
+ fieldType,
+ )
+ }
+
+ var found bool
+ for _, record := range msg.AllRecords() {
+ if uint64(record.Type()) != typ {
+ continue
+ }
+
+ found = true
+ var encoded bytes.Buffer
+ require.NoError(
+ t, record.Encode(&encoded),
+ )
+ require.Equal(
+ t, test.raw, encoded.Bytes(),
+ )
+ }
+
+ // The record is re-encoded because it was
+ // present, even when it holds the default.
+ require.True(t, found)
+ })
+ }
+ }
+}
+
// TestChanUpdate2EncodeDecode tests the encoding and decoding of the
// ChannelUpdate2 message using hardcoded byte slices.
func TestChanUpdate2EncodeDecode(t *testing.T) {
@@ -24,10 +157,11 @@ func TestChanUpdate2EncodeDecode(t *testing.T) {
0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1,
0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1,
- // ShortChannelID record.
+ // ShortChannelID record (sciddir form: dir byte + 8-byte scid).
0x2, // type.
- 0x8, // length.
- 0x0, 0x0, 0x1, 0x0, 0x0, 0x2, 0x0, 0x3, // value.
+ 0x9, // length.
+ 0x1, // dir byte: node_id_2.
+ 0x0, 0x0, 0x1, 0x0, 0x0, 0x2, 0x0, 0x3, // scid value.
// BlockHeight record.
0x4, // type.
@@ -39,10 +173,6 @@ func TestChanUpdate2EncodeDecode(t *testing.T) {
0x1, // length.
0x1, // value.
- // SecondPeer record.
- 0x8, // type.
- 0x0, // length.
-
// Unknown odd-type TLV record.
0x9, // type.
0x2, // length.
@@ -54,32 +184,42 @@ func TestChanUpdate2EncodeDecode(t *testing.T) {
0x0, 0x10, // value.
// HTLCMinimumMsat record.
- 0xc, // type.
- 0x5, // length.
- 0xfe, 0x0, 0xf, 0x42, 0x40, // value (BigSize: 1_000_000).
+ 0xc, // type.
+ 0x3, // length.
+ 0xf, 0x42, 0x40, // value (tu64: 1_000_000).
// HTLCMaximumMsat record.
- 0xe, // type.
- 0x5, // length.
- 0xfe, 0x0, 0xf, 0x42, 0x40, // value (BigSize: 1_000_000).
+ 0xe, // type.
+ 0x3, // length.
+ 0xf, 0x42, 0x40, // value (tu64: 1_000_000).
// FeeBaseMsat record.
- 0x10, // type.
- 0x4, // length.
- 0x0, 0x0, 0x1, 0x0, // value.
+ 0x10, // type.
+ 0x2, // length.
+ 0x1, 0x0, // value.
// FeeProportionalMillionths record.
- 0x12, // type.
- 0x4, // length.
- 0x0, 0x0, 0x1, 0x0, // value.
+ 0x12, // type.
+ 0x2, // length.
+ 0x1, 0x0, // value.
+
+ // InboundFeeBaseMsat record.
+ 0x14, // type.
+ 0x1, // length.
+ 0x5, // value (5).
+
+ // InboundFeeProportionalMillionths record.
+ 0x16, // type.
+ 0x1, // length.
+ 0x3, // value (3).
// Extra Opaque Data - Unknown Record.
- 0x14, // type.
+ 0x18, // type.
0x2, // length.
0x79, 0x79, // value.
// Signature.
- 0xa0, // type.
+ 0xf0, // type.
0x40, // length.
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb,
0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
@@ -117,3 +257,153 @@ func TestChanUpdate2EncodeDecode(t *testing.T) {
// bytes.
require.Equal(t, rawBytes, b.Bytes())
}
+
+// TestGossipV2ExplicitDefaults tests that a gossip v2 message re-encodes to the
+// bytes that the sender signed, both when the sender omits a field that has a
+// default and when it encodes the default value explicitly.
+func TestGossipV2ExplicitDefaults(t *testing.T) {
+ t.Parallel()
+
+ mainnet := chaincfg.MainNetParams.GenesisHash[:]
+
+ // The compulsory records of each message, which every case includes.
+ compulsory := map[MessageType]map[uint64][]byte{
+ MsgChannelUpdate2: {
+ 2: make([]byte, sciddirLen),
+ 4: make([]byte, 4),
+ 240: make([]byte, 64),
+ },
+ MsgChannelAnnouncement2: {
+ 4: make([]byte, 8),
+ 6: {1},
+ 8: make([]byte, 33),
+ 10: make([]byte, 33),
+ 18: make([]byte, 34),
+ 240: make([]byte, 64),
+ },
+ }
+
+ tests := []struct {
+ name string
+ msgType MessageType
+
+ // typ and value are the defaulted TLV that the sender encodes
+ // explicitly. A nil value leaves every defaulted TLV absent,
+ // and then typ is unused.
+ typ uint64
+ value []byte
+ }{
+ {
+ name: "update/all absent",
+ msgType: MsgChannelUpdate2,
+ },
+ {
+ name: "update/chain_hash",
+ msgType: MsgChannelUpdate2,
+ typ: 0,
+ value: mainnet,
+ },
+ {
+ name: "update/disable_flags",
+ msgType: MsgChannelUpdate2,
+ typ: 6,
+ value: []byte{0},
+ },
+ {
+ name: "update/cltv_expiry_delta",
+ msgType: MsgChannelUpdate2,
+ typ: 10,
+ value: []byte{0, 80},
+ },
+ {
+ name: "update/htlc_minimum_msat",
+ msgType: MsgChannelUpdate2,
+ typ: 12,
+ value: []byte{1},
+ },
+ {
+ name: "update/fee_base_msat",
+ msgType: MsgChannelUpdate2,
+ typ: 16,
+ value: []byte{3, 0xe8},
+ },
+ {
+ name: "update/fee_proportional",
+ msgType: MsgChannelUpdate2,
+ typ: 18,
+ value: []byte{1},
+ },
+ {
+ name: "announcement/all absent",
+ msgType: MsgChannelAnnouncement2,
+ },
+ {
+ name: "announcement/chain_hash",
+ msgType: MsgChannelAnnouncement2,
+ typ: 0,
+ value: mainnet,
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ var msg Message
+ switch test.msgType {
+ case MsgChannelUpdate2:
+ msg = &ChannelUpdate2{}
+
+ case MsgChannelAnnouncement2:
+ msg = &ChannelAnnouncement2{}
+
+ default:
+ t.Fatalf("unhandled message type %v",
+ test.msgType)
+ }
+
+ records := compulsory[test.msgType]
+ fields := make(map[uint64][]byte, len(records)+1)
+ for typ, value := range records {
+ fields[typ] = value
+ }
+
+ // A nil value leaves every defaulted field absent.
+ if test.value != nil {
+ fields[test.typ] = test.value
+ }
+ raw, err := EncodeRecords(tlv.MapToRecords(fields))
+ require.NoError(t, err)
+
+ require.NoError(t, msg.Decode(bytes.NewReader(raw), 0))
+
+ var b bytes.Buffer
+ require.NoError(t, msg.Encode(&b, 0))
+ require.Equal(t, raw, b.Bytes())
+ })
+ }
+}
+
+// TestChanUpdate2MaxHTLCLeavesRecordAbsent tests that deriving the spec
+// default for an absent htlc_maximum_msat does not add the record to the
+// message. The signature covers the records as the sender wrote them, so
+// materialising the default would invalidate it, and no round trip would
+// notice because the message is only re-encoded after a decode.
+//
+// The values MaxHTLC returns for each state are covered through
+// netann.TestValidateChannelUpdate2MaxHTLC.
+func TestChanUpdate2MaxHTLCLeavesRecordAbsent(t *testing.T) {
+ t.Parallel()
+
+ const capacityMsat = MilliSatoshi(1_000_000_000)
+
+ upd := &ChannelUpdate2{}
+ require.True(t, upd.HTLCMaximumMsat.IsNone())
+
+ // The limit is derived from the capacity the caller supplies, ...
+ require.Equal(
+ t, fn.Some(capacityMsat/2), upd.MaxHTLC(capacityMsat),
+ )
+
+ // ... but the record stays absent, so the signed bytes do not move.
+ require.True(t, upd.HTLCMaximumMsat.IsNone())
+}
### lnwire/custom_records.go
@@ -275,6 +275,34 @@ func AddOpt[T tlv.TlvType, V any](producers *[]tlv.RecordProducer,
)
}
+// addOptTU32 appends a tu32 record producer for the given optional record to
+// producers when the optional is set, leaving producers unchanged otherwise.
+func addOptTU32[T tlv.TlvType](producers *[]tlv.RecordProducer,
+ opt tlv.OptionalRecordT[T, uint32]) {
+
+ opt.WhenSome(
+ func(r tlv.RecordT[T, uint32]) {
+ *producers = append(
+ *producers, truncatedUint32Record(&r),
+ )
+ },
+ )
+}
+
+// addOptTU64 appends a tu64 record producer for the given optional record to
+// producers when the optional is set, leaving producers unchanged otherwise.
+func addOptTU64[T tlv.TlvType, V ~uint64](producers *[]tlv.RecordProducer,
+ opt tlv.OptionalRecordT[T, V]) {
+
+ opt.WhenSome(
+ func(r tlv.RecordT[T, V]) {
+ *producers = append(
+ *producers, truncatedUint64Record(&r),
+ )
+ },
+ )
+}
+
// SetOptFromMap marks target as Some(record) when record's TLV type appeared
// on the wire (i.e., is a key in the decoded TypeMap).
//
@@ -289,6 +317,65 @@ func SetOptFromMap[T tlv.TlvType, V any](typeMap tlv.TypeMap,
}
}
+// truncatedUint32Record preserves a typed record's value and type while using
+// BOLT's tu32 encoding, which omits leading zero bytes.
+func truncatedUint32Record[T tlv.TlvType](
+ value *tlv.RecordT[T, uint32]) *tlv.Record {
+
+ record := tlv.MakeDynamicRecord(
+ value.TlvType(), &value.Val,
+ func() uint64 {
+ return tlv.SizeTUint32(value.Val)
+ },
+ tlv.ETUint32, tlv.DTUint32,
+ )
+
+ return &record
+}
+
+// truncatedUint64Record preserves a typed record's value and type while using
+// BOLT's tu64 encoding, which omits leading zero bytes. It accepts any type
+// whose underlying type is uint64, such as MilliSatoshi, because the tlv
+// codecs only take a plain *uint64.
+func truncatedUint64Record[T tlv.TlvType, V ~uint64](
+ value *tlv.RecordT[T, V]) *tlv.Record {
+
+ record := tlv.MakeDynamicRecord(
+ value.TlvType(), &value.Val,
+ func() uint64 {
+ return tlv.SizeTUint64(uint64(value.Val))
+ },
+ func(w io.Writer, val interface{}, buf *[8]byte) error {
+ v, ok := val.(*V)
+ if !ok {
+ return tlv.NewTypeForEncodingErr(val, "tu64")
+ }
+
+ return tlv.ETUint64T(w, uint64(*v), buf)
+ },
+ func(r io.Reader, val interface{}, buf *[8]byte,
+ l uint64) error {
+
+ v, ok := val.(*V)
+ if !ok {
+ return tlv.NewTypeForDecodingErr(
+ val, "tu64", l, 8,
+ )
+ }
+
+ var x uint64
+ if err := tlv.DTUint64(r, &x, buf, l); err != nil {
+ return err
+ }
+ *v = V(x)
+
+ return nil
+ },
+ )
+
+ return &record
+}
+
// AssertUniqueTypes asserts that the given records have unique types.
func AssertUniqueTypes(r []tlv.Record) error {
seen := make(fn.Set[tlv.Type], len(r))
### lnwire/dns_addrs.go
@@ -0,0 +1,127 @@
+package lnwire
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+ "math"
+
+ "github.com/lightningnetwork/lnd/tlv"
+)
+
+// dnsAddrEntryOverhead is the number of bytes that each dns_hostname entry
+// carries in addition to its hostname: a u16 length and a u16 port.
+const dnsAddrEntryOverhead = 2 + 2
+
+// DNSAddrs is the dns_hostnames list of a node_announcement_2. Each entry is
+// encoded as a u16 hostname length, the hostname and a u16 port.
+//
+// The codec does not validate the hostname or the port. The list is in the
+// signed range and the signature digest is rebuilt from the decoded records,
+// so the codec must round-trip every entry exactly.
+type DNSAddrs []*DNSAddress
+
+// Record returns a Record that can be used to encode/decode a DNSAddrs to/from
+// a TLV stream.
+func (a *DNSAddrs) Record() tlv.Record {
+ return tlv.MakeDynamicRecord(
+ 0, a, a.encodedSize, dnsAddrsEncoder, dnsAddrsDecoder,
+ )
+}
+
+// encodedSize returns the number of bytes required to encode a DNSAddrs
+// variable.
+func (a *DNSAddrs) encodedSize() uint64 {
+ var size uint64
+ for _, addr := range *a {
+ size += uint64(dnsAddrEntryOverhead + len(addr.Hostname))
+ }
+
+ return size
+}
+
+// dnsAddrsEncoder encodes a list of DNS addresses as TLV bytes.
+func dnsAddrsEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
+ if v, ok := val.(*DNSAddrs); ok {
+ for _, addr := range *v {
+ if len(addr.Hostname) > math.MaxUint16 {
+ return fmt.Errorf("dns_hostname length %d "+
+ "exceeds %d", len(addr.Hostname),
+ math.MaxUint16)
+ }
+
+ var buf [2]byte
+ binary.BigEndian.PutUint16(
+ buf[:], uint16(len(addr.Hostname)),
+ )
+ if _, err := w.Write(buf[:]); err != nil {
+ return err
+ }
+
+ _, err := w.Write([]byte(addr.Hostname))
+ if err != nil {
+ return err
+ }
+
+ binary.BigEndian.PutUint16(buf[:], addr.Port)
+ if _, err := w.Write(buf[:]); err != nil {
+ return err
+ }
+ }
+
+ return nil
+ }
+
+ return tlv.NewTypeForEncodingErr(val, "lnwire.DNSAddrs")
+}
+
+// dnsAddrsDecoder decodes TLV bytes into a list of DNS addresses.
+func dnsAddrsDecoder(r io.Reader, val interface{}, _ *[8]byte,
+ l uint64) error {
+
+ if v, ok := val.(*DNSAddrs); ok {
+ var (
+ addrs DNSAddrs
+ remaining = l
+ buf [2]byte
+ )
+ for remaining > 0 {
+ if remaining < dnsAddrEntryOverhead {
+ return fmt.Errorf("truncated dns_hostname: %d "+
+ "bytes left", remaining)
+ }
+
+ if _, err := io.ReadFull(r, buf[:]); err != nil {
+ return err
+ }
+ hostLen := uint64(binary.BigEndian.Uint16(buf[:]))
+
+ entryLen := dnsAddrEntryOverhead + hostLen
+ if entryLen > remaining {
+ return fmt.Errorf("dns_hostname length %d "+
+ "exceeds the %d bytes left", hostLen,
+ remaining-2)
+ }
+
+ hostname := make([]byte, hostLen)
+ if _, err := io.ReadFull(r, hostname); err != nil {
+ return err
+ }
+
+ if _, err := io.ReadFull(r, buf[:]); err != nil {
+ return err
+ }
+
+ addrs = append(addrs, &DNSAddress{
+ Hostname: string(hostname),
+ Port: binary.BigEndian.Uint16(buf[:]),
+ })
+ remaining -= entryLen
+ }
+ *v = addrs
+
+ return nil
+ }
+
+ return tlv.NewTypeForDecodingErr(val, "lnwire.DNSAddrs", l, l)
+}
### lnwire/dns_addrs_test.go
@@ -0,0 +1,95 @@
+package lnwire
+
+import (
+ "bytes"
+ "encoding/hex"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// hexOf returns the hex encoding of a hostname, for building wire vectors.
+func hexOf(hostname string) string {
+ return hex.EncodeToString([]byte(hostname))
+}
+
+// TestDNSAddrsWireFormat tests that the dns_hostnames list uses the spec
+// layout of a u16 hostname length, the hostname and a u16 port per entry, and
+// that the codec round-trips entries it does not validate, such as a zero
+// port.
+func TestDNSAddrsWireFormat(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ raw string
+ expected DNSAddrs
+ expectErr bool
+ }{
+ {
+ name: "single entry",
+ raw: "000b" + hexOf("example.com") + "2607",
+ expected: DNSAddrs{
+ {Hostname: "example.com", Port: 9735},
+ },
+ },
+ {
+ name: "two entries",
+ raw: "0003" + hexOf("a.b") + "0001" +
+ "0003" + hexOf("c.d") + "ffff",
+ expected: DNSAddrs{
+ {Hostname: "a.b", Port: 1},
+ {Hostname: "c.d", Port: 65535},
+ },
+ },
+ {
+ // The codec must not reject a zero port. The entry is
+ // signed, so dropping or refusing it here would break
+ // signature verification.
+ name: "zero port round-trips",
+ raw: "0003" + hexOf("a.b") + "0000",
+ expected: DNSAddrs{
+ {Hostname: "a.b", Port: 0},
+ },
+ },
+ {
+ name: "entry shorter than its overhead",
+ raw: "000b00",
+ expectErr: true,
+ },
+ {
+ name: "hostname length overruns the value",
+ raw: "000b" + hexOf("a.b") + "0001",
+ expectErr: true,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ raw, err := hex.DecodeString(test.raw)
+ require.NoError(t, err)
+
+ var addrs DNSAddrs
+ rec := addrs.Record()
+ err = rec.Decode(
+ bytes.NewReader(raw), uint64(len(raw)),
+ )
+ if test.expectErr {
+ require.Error(t, err)
+
+ return
+ }
+ require.NoError(t, err)
+ require.Equal(t, test.expected, addrs)
+
+ // Re-encoding must reproduce the exact bytes, and the
+ // advertised size must match what the encoder writes.
+ var b bytes.Buffer
+ require.NoError(t, rec.Encode(&b))
+ require.Equal(t, raw, b.Bytes())
+ require.EqualValues(t, len(raw), rec.Size())
+ })
+ }
+}
### lnwire/fuzz_test.go
@@ -6,6 +6,7 @@ import (
"encoding/binary"
"testing"
+ "github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/require"
)
@@ -122,12 +123,22 @@ func FuzzChannelAnnouncement2(f *testing.F) {
require.IsType(t, &ChannelAnnouncement2{}, y)
second, _ := y.(*ChannelAnnouncement2)
- require.True(
- t,
- first.Features.Val.Equals(&second.Features.Val),
- )
- first.Features.Val = *NewRawFeatureVector()
- second.Features.Val = *NewRawFeatureVector()
+ // The field is optional, so both sides must agree on
+ // whether it is present before comparing the vectors.
+ firstF := first.Features.ValOpt()
+ secondF := second.Features.ValOpt()
+ require.Equal(t, firstF.IsSome(), secondF.IsSome())
+ if firstF.IsSome() {
+ f := firstF.UnsafeFromSome()
+ s := secondF.UnsafeFromSome()
+ require.True(t, f.Equals(&s))
+ }
+
+ var noFeatures tlv.OptionalRecordT[
+ tlv.TlvType2, RawFeatureVector,
+ ]
+ first.Features = noFeatures
+ second.Features = noFeatures
require.Equal(t, first, second)
}
### lnwire/gossip_timestamp_range.go
@@ -32,16 +32,12 @@ type GossipTimestampRange struct {
// Unix timestamps.
TimestampRange uint32
- // FirstBlockHeight is the height of earliest announcement message that
- // should be sent by the receiver. This is used only for querying
- // announcement messages that use block heights as a timestamp.
- FirstBlockHeight tlv.OptionalRecordT[tlv.TlvType2, uint32]
-
- // BlockRange is the horizon beyond FirstBlockHeight that any
- // announcement messages should be sent for. The receiving node MUST NOT
- // send any announcements that have a timestamp greater than
- // FirstBlockHeight + BlockRange.
- BlockRange tlv.OptionalRecordT[tlv.TlvType4, uint32]
+ // BlockHeightRange is the block-height equivalent of (FirstTimestamp,
+ // TimestampRange) used for gossip messages timestamped by block
+ // height. The receiving node MUST NOT send any announcements that have
+ // a block height greater than BlockHeightRange.FirstBlockHeight +
+ // BlockHeightRange.NumBlocks.
+ BlockHeightRange tlv.OptionalRecordT[tlv.TlvType2, BlockHeightRange]
// ExtraData is the set of data that was appended to this message to
// fill out the full maximum transport message size. These fields can
@@ -54,6 +50,71 @@ func NewGossipTimestampRange() *GossipTimestampRange {
return &GossipTimestampRange{}
}
+// BlockHeightRange describes a window of blocks that an announcement may have
+// been timestamped within. It is serialised as a u32 first_block_height
+// followed by a tu32 num_blocks; the tu32 (truncated uint32) drops any
+// leading zero bytes from num_blocks to save space on the wire.
+type BlockHeightRange struct {
+ // FirstBlockHeight is the height of the earliest announcement message
+ // that should be sent by the receiver.
+ FirstBlockHeight uint32
+
+ // NumBlocks is the size of the window beyond FirstBlockHeight that
+ // announcements should be sent for.
+ NumBlocks uint32
+}
+
+// Record returns the TLV record used to encode/decode a BlockHeightRange. The
+// type number is supplied by the wrapping RecordT.
+func (b *BlockHeightRange) Record() tlv.Record {
+ sizeFunc := func() uint64 {
+ // FirstBlockHeight is a fixed-width u32, followed by the
+ // variable-width tu32 encoding of NumBlocks.
+ return 4 + tlv.SizeTUint32(b.NumBlocks)
+ }
+
+ return tlv.MakeDynamicRecord(
+ 0, b, sizeFunc, blockHeightRangeEncoder,
+ blockHeightRangeDecoder,
+ )
+}
+
+// blockHeightRangeEncoder encodes a fixed-width first block height followed by
+// a truncated block count.
+func blockHeightRangeEncoder(w io.Writer, val interface{},
+ buf *[8]byte) error {
+
+ v, ok := val.(*BlockHeightRange)
+ if !ok {
+ return tlv.NewTypeForEncodingErr(val, "lnwire.BlockHeightRange")
+ }
+
+ if err := tlv.EUint32T(w, v.FirstBlockHeight, buf); err != nil {
+ return err
+ }
+
+ return tlv.ETUint32T(w, v.NumBlocks, buf)
+}
+
+// blockHeightRangeDecoder decodes a fixed-width first block height followed by
+// a truncated block count.
+func blockHeightRangeDecoder(r io.Reader, val interface{}, buf *[8]byte,
+ l uint64) error {
+
+ v, ok := val.(*BlockHeightRange)
+ if !ok || l < 4 {
+ return tlv.NewTypeForDecodingErr(
+ val, "lnwire.BlockHeightRange", l, 4,
+ )
+ }
+
+ if err := tlv.DUint32(r, &v.FirstBlockHeight, buf, 4); err != nil {
+ return err
+ }
+
+ return tlv.DTUint32(r, &v.NumBlocks, buf, l-4)
+}
+
// A compile time check to ensure GossipTimestampRange implements the
// lnwire.Message interface.
var _ Message = (*GossipTimestampRange)(nil)
@@ -81,20 +142,14 @@ func (g *GossipTimestampRange) Decode(r io.Reader, _ uint32) error {
return err
}
- var (
- firstBlock = tlv.ZeroRecordT[tlv.TlvType2, uint32]()
- blockRange = tlv.ZeroRecordT[tlv.TlvType4, uint32]()
- )
- typeMap, err := tlvRecords.ExtractRecords(&firstBlock, &blockRange)
+ bhRange := tlv.ZeroRecordT[tlv.TlvType2, BlockHeightRange]()
+ typeMap, err := tlvRecords.ExtractRecords(&bhRange)
if err != nil {
return err
}
- if val, ok := typeMap[g.FirstBlockHeight.TlvType()]; ok && val == nil {
- g.FirstBlockHeight = tlv.SomeRecordT(firstBlock)
- }
- if val, ok := typeMap[g.BlockRange.TlvType()]; ok && val == nil {
- g.BlockRange = tlv.SomeRecordT(blockRange)
+ if val, ok := typeMap[g.BlockHeightRange.TlvType()]; ok && val == nil {
+ g.BlockHeightRange = tlv.SomeRecordT(bhRange)
}
if len(tlvRecords) != 0 {
@@ -121,15 +176,10 @@ func (g *GossipTimestampRange) Encode(w *bytes.Buffer, pver uint32) error {
return err
}
- recordProducers := make([]tlv.RecordProducer, 0, 2)
- g.FirstBlockHeight.WhenSome(
- func(height tlv.RecordT[tlv.TlvType2, uint32]) {
- recordProducers = append(recordProducers, &height)
- },
- )
- g.BlockRange.WhenSome(
- func(blockRange tlv.RecordT[tlv.TlvType4, uint32]) {
- recordProducers = append(recordProducers, &blockRange)
+ recordProducers := make([]tlv.RecordProducer, 0, 1)
+ g.BlockHeightRange.WhenSome(
+ func(bhr tlv.RecordT[tlv.TlvType2, BlockHeightRange]) {
+ recordProducers = append(recordProducers, &bhr)
},
)
err := EncodeMessageExtraData(&g.ExtraData, recordProducers...)
### lnwire/gossip_v2_decode_test.go
@@ -0,0 +1,192 @@
+package lnwire
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+
+ "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// gossipV2Message pairs a gossip v2 message with the records of a well-formed
+// instance of it, so a test can drop one record at a time.
+type gossipV2Message struct {
+ name string
+ new func() Message
+
+ // records is a valid record set for the message.
+ records map[uint64][]byte
+
+ // compulsory lists the types that the reader requires. Every entry is
+ // also present in records.
+ compulsory []uint64
+}
+
+// gossipV2Messages returns the four pure-TLV gossip v2 messages that enforce
+// compulsory-field presence, each with a well-formed record set.
+func gossipV2Messages() []gossipV2Message {
+ return []gossipV2Message{
+ {
+ name: "channel_update_2",
+ new: func() Message { return &ChannelUpdate2{} },
+ records: map[uint64][]byte{
+ 2: make([]byte, sciddirLen),
+ 4: make([]byte, 4),
+ 240: make([]byte, 64),
+ },
+ compulsory: []uint64{2, 4, 240},
+ },
+ {
+ name: "channel_announcement_2",
+ new: func() Message { return &ChannelAnnouncement2{} },
+ records: map[uint64][]byte{
+ 4: make([]byte, 8),
+ 6: {1},
+ 8: make([]byte, 33),
+ 10: make([]byte, 33),
+ 18: make([]byte, 34),
+ 240: make([]byte, 64),
+ },
+ compulsory: []uint64{4, 6, 8, 10, 18, 240},
+ },
+ {
+ name: "node_announcement_2",
+ new: func() Message { return &NodeAnnouncement2{} },
+ records: map[uint64][]byte{
+ 0: {},
+ 2: make([]byte, 4),
+ 4: make([]byte, 33),
+ 240: make([]byte, 64),
+ },
+ compulsory: []uint64{0, 2, 4, 240},
+ },
+ {
+ name: "announcement_signatures_2",
+ new: func() Message {
+ return &AnnounceSignatures2{}
+ },
+ records: map[uint64][]byte{
+ 0: make([]byte, 32),
+ 2: make([]byte, 8),
+ 4: make([]byte, AnnouncementSigPairLen),
+ 6: make([]byte, 32),
+ },
+ compulsory: []uint64{0, 2, 4, 6},
+ },
+ }
+}
+
+// encodeRecordMap serialises a type-to-value map as a TLV stream.
+func encodeRecordMap(t *testing.T, fields map[uint64][]byte) []byte {
+ t.Helper()
+
+ raw, err := EncodeRecords(tlv.MapToRecords(fields))
+ require.NoError(t, err)
+
+ return raw
+}
+
+// TestGossipV2CompulsoryFields tests that the gossip v2 readers reject a
+// message that omits any compulsory TLV, and accept the full record set.
+func TestGossipV2CompulsoryFields(t *testing.T) {
+ t.Parallel()
+
+ for _, msg := range gossipV2Messages() {
+ t.Run(msg.name, func(t *testing.T) {
+ t.Parallel()
+
+ // The unmodified record set must decode, so a later
+ // rejection is attributable to the dropped type.
+ raw := encodeRecordMap(t, msg.records)
+ require.NoError(
+ t, msg.new().Decode(bytes.NewReader(raw), 0),
+ )
+
+ for _, dropped := range msg.compulsory {
+ name := fmt.Sprintf("without %d", dropped)
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+
+ fields := make(map[uint64][]byte)
+ for typ, value := range msg.records {
+ if typ == dropped {
+ continue
+ }
+ fields[typ] = value
+ }
+
+ raw := encodeRecordMap(t, fields)
+ err := msg.new().Decode(
+ bytes.NewReader(raw), 0,
+ )
+ require.ErrorContains(
+ t, err, fmt.Sprintf(
+ "required TLV type "+
+ "%d missing",
+ dropped,
+ ),
+ )
+ })
+ }
+ })
+ }
+}
+
+// TestAnnouncementSigPairRejectsOverflow tests that a partial signature at or
+// above the curve order is rejected rather than silently reduced mod n.
+func TestAnnouncementSigPairRejectsOverflow(t *testing.T) {
+ t.Parallel()
+
+ // A scalar of all 0xff is above the secp256k1 group order.
+ overflow := bytes.Repeat([]byte{0xff}, 32)
+ valid := make([]byte, 32)
+ valid[31] = 1
+
+ tests := []struct {
+ name string
+ raw []byte
+ }{
+ {
+ name: "node sig overflows",
+ raw: append(append([]byte{}, overflow...), valid...),
+ },
+ {
+ name: "bitcoin sig overflows",
+ raw: append(append([]byte{}, valid...), overflow...),
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ records := map[uint64][]byte{
+ 0: make([]byte, 32),
+ 2: make([]byte, 8),
+ 4: test.raw,
+ 6: make([]byte, 32),
+ }
+
+ raw := encodeRecordMap(t, records)
+
+ var msg AnnounceSignatures2
+ err := msg.Decode(bytes.NewReader(raw), 0)
+ require.ErrorIs(t, err, musig2.ErrPartialSigInvalid)
+ })
+ }
+
+ // A pair that is below the order still decodes.
+ records := map[uint64][]byte{
+ 0: make([]byte, 32),
+ 2: make([]byte, 8),
+ 4: append(append([]byte{}, valid...), valid...),
+ 6: make([]byte, 32),
+ }
+
+ var msg AnnounceSignatures2
+ require.NoError(t, msg.Decode(
+ bytes.NewReader(encodeRecordMap(t, records)), 0,
+ ))
+}
### lnwire/intro_node.go
@@ -2,10 +2,12 @@ package lnwire
import (
"bytes"
+ "encoding/binary"
"fmt"
"io"
"github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/tlv"
)
// IntroductionNode is the sealed sum-type for a blinded path's introduction
@@ -179,3 +181,91 @@ func (s SciddirIntro) Bytes() []byte {
return buf.Bytes()
}
+
+// NewSciddirIntroFromSCID builds the sciddir variant from a ShortChannelID.
+// The direction must be 0 for node_id_1 or 1 for node_id_2.
+func NewSciddirIntroFromSCID(direction byte,
+ scid ShortChannelID) (SciddirIntro, error) {
+
+ var b [scidLen]byte
+ binary.BigEndian.PutUint64(b[:], scid.ToUint64())
+
+ return NewSciddirIntro(direction, b)
+}
+
+// ShortChannelID returns the short channel ID that the sciddir refers to.
+func (s SciddirIntro) ShortChannelID() ShortChannelID {
+ return NewShortChanIDFromInt(binary.BigEndian.Uint64(s.SCID[:]))
+}
+
+// sciddirRecord returns a TLV record for a field that the spec types as
+// sciddir_or_pubkey but constrains to the sciddir form, such as the
+// short_channel_id of channel_update_2. It keeps the typed record's type
+// number and rejects the pubkey form. It is a function rather than a method,
+// because the methods of SciddirIntro use value receivers.
+func sciddirRecord[T tlv.TlvType](
+ r *tlv.RecordT[T, SciddirIntro]) *tlv.Record {
+
+ record := tlv.MakeStaticRecord(
+ r.TlvType(), &r.Val, sciddirLen, sciddirIntroEncoder,
+ sciddirIntroDecoder,
+ )
+
+ return &record
+}
+
+// sciddirIntroEncoder encodes the 9-byte sciddir form.
+func sciddirIntroEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
+ v, ok := val.(*SciddirIntro)
+ if !ok {
+ return tlv.NewTypeForEncodingErr(val, "lnwire.SciddirIntro")
+ }
+
+ // validate owns the 0/1 direction rule, so the encoder and the decoder
+ // reject the same byte with the same error.
+ if err := v.validate(); err != nil {
+ return err
+ }
+
+ return v.encode(w)
+}
+
+// sciddirIntroDecoder decodes the sciddir form and rejects the pubkey form of
+// sciddir_or_pubkey.
+func sciddirIntroDecoder(r io.Reader, val interface{}, _ *[8]byte,
+ l uint64) error {
+
+ v, ok := val.(*SciddirIntro)
+ if !ok {
+ return tlv.NewTypeForDecodingErr(
+ val, "lnwire.SciddirIntro", l, sciddirLen,
+ )
+ }
+
+ if l == pubKeyLen {
+ return fmt.Errorf("the pubkey form of sciddir_or_pubkey is " +
+ "not allowed here")
+ }
+ if l != sciddirLen {
+ return tlv.NewTypeForDecodingErr(
+ val, "lnwire.SciddirIntro", l, sciddirLen,
+ )
+ }
+
+ var b [sciddirLen]byte
+ if _, err := io.ReadFull(r, b[:]); err != nil {
+ return err
+ }
+
+ // The constructor applies the 0/1 direction rule, so an invalid
+ // direction has one error identity on every path that produces a
+ // SciddirIntro.
+ intro, err := NewSciddirIntro(b[0], [scidLen]byte(b[1:]))
+ if err != nil {
+ return err
+ }
+
+ *v = intro
+
+ return nil
+}
### lnwire/intro_node_test.go
@@ -0,0 +1,135 @@
+package lnwire
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/lightningnetwork/lnd/tlv"
+ "github.com/stretchr/testify/require"
+)
+
+// TestSciddirIntroCodec tests the sciddir_or_pubkey codec that a
+// channel_update_2 short_channel_id uses. The field is constrained to the
+// sciddir form, so the decoder rejects the pubkey form, a wrong length and an
+// out-of-range direction byte, and the encoder rejects the same direction.
+func TestSciddirIntroCodec(t *testing.T) {
+ t.Parallel()
+
+ encode := func(t *testing.T, intro SciddirIntro) ([]byte, error) {
+ t.Helper()
+
+ var b bytes.Buffer
+ err := sciddirIntroEncoder(&b, &intro, nil)
+
+ return b.Bytes(), err
+ }
+
+ decode := func(t *testing.T, raw []byte) (SciddirIntro, error) {
+ t.Helper()
+
+ var intro SciddirIntro
+ err := sciddirIntroDecoder(
+ bytes.NewReader(raw), &intro, nil, uint64(len(raw)),
+ )
+
+ return intro, err
+ }
+
+ t.Run("round trip", func(t *testing.T) {
+ t.Parallel()
+
+ for _, direction := range []byte{0, 1} {
+ intro := SciddirIntro{
+ Direction: direction,
+ SCID: [scidLen]byte{
+ 1, 2, 3, 4, 5, 6, 7, 8,
+ },
+ }
+
+ raw, err := encode(t, intro)
+ require.NoError(t, err)
+ require.Len(t, raw, sciddirLen)
+
+ got, err := decode(t, raw)
+ require.NoError(t, err)
+ require.Equal(t, intro, got)
+ }
+ })
+
+ t.Run("encode rejects direction", func(t *testing.T) {
+ t.Parallel()
+
+ _, err := encode(t, SciddirIntro{Direction: 2})
+ require.ErrorIs(t, err, ErrInvalidIntroNode)
+ })
+
+ t.Run("decode rejects direction", func(t *testing.T) {
+ t.Parallel()
+
+ raw := make([]byte, sciddirLen)
+ raw[0] = 2
+
+ _, err := decode(t, raw)
+ require.ErrorIs(t, err, ErrInvalidIntroNode)
+ })
+
+ t.Run("decode rejects pubkey form", func(t *testing.T) {
+ t.Parallel()
+
+ _, err := decode(t, make([]byte, pubKeyLen))
+ require.ErrorContains(t, err, "pubkey form")
+ })
+
+ t.Run("decode rejects wrong length", func(t *testing.T) {
+ t.Parallel()
+
+ rangeLen := []int{0, sciddirLen - 1, sciddirLen + 1}
+
+ for _, length := range rangeLen {
+ _, err := decode(t, make([]byte, length))
+ require.ErrorAs(t, err, &tlv.ErrTypeForDecoding{})
+ }
+ })
+}
+
+// TestChannelUpdate2RejectsBadSciddir tests that the public ChannelUpdate2
+// decoder rejects a short_channel_id that is not a well-formed sciddir.
+func TestChannelUpdate2RejectsBadSciddir(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ scid []byte
+ }{
+ {
+ name: "direction out of range",
+ scid: append([]byte{2}, make([]byte, scidLen)...),
+ },
+ {
+ name: "pubkey form",
+ scid: make([]byte, pubKeyLen),
+ },
+ {
+ name: "short",
+ scid: make([]byte, sciddirLen-1),
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ raw, err := EncodeRecords(tlv.MapToRecords(
+ map[uint64][]byte{
+ 2: test.scid,
+ 4: make([]byte, 4),
+ 240: make([]byte, 64),
+ },
+ ))
+ require.NoError(t, err)
+
+ var msg ChannelUpdate2
+ require.Error(t, msg.Decode(bytes.NewReader(raw), 0))
+ })
+ }
+}
### lnwire/node_announcement_2.go
@@ -7,13 +7,20 @@ import (
"fmt"
"image/color"
"io"
+ "math"
"net"
"unicode/utf8"
"github.com/lightningnetwork/lnd/tlv"
"github.com/lightningnetwork/lnd/tor"
)
+// ErrNodeAnn2PortOutOfRange is returned when an address cannot represent its
+// port as the unsigned 16-bit value required on the wire.
+var ErrNodeAnn2PortOutOfRange = errors.New(
+ "node announcement address port outside uint16 range",
+)
+
// NodeAnnouncement2 message is used to announce the presence of a Lightning
// node and also to signal that the node is accepting incoming connections.
// Each NodeAnnouncement2 authenticating the advertised information within the
@@ -53,13 +60,13 @@ type NodeAnnouncement2 struct {
// reachable at.
TorV3Addrs tlv.OptionalRecordT[tlv.TlvType9, TorV3Addrs]
- // DNSHostName is an optional DNS hostname that the node is reachable
- // at.
- DNSHostName tlv.OptionalRecordT[tlv.TlvType11, DNSAddress]
+ // DNSHostNames is an optional list of DNS hostnames that the node is
+ // reachable at.
+ DNSHostNames tlv.OptionalRecordT[tlv.TlvType11, DNSAddrs]
// Signature is used to validate the announced data and prove the
// ownership of node id.
- Signature tlv.RecordT[tlv.TlvType160, Sig]
+ Signature tlv.RecordT[tlv.TlvType240, Sig]
// Any extra fields in the signed range that we do not yet know about,
// but we need to keep them for signature validation and to produce a
@@ -107,7 +114,7 @@ func (n *NodeAnnouncement2) AllRecords() []tlv.Record {
recordProducers = append(recordProducers, &r)
})
- n.DNSHostName.WhenSome(func(r tlv.RecordT[tlv.TlvType11, DNSAddress]) {
+ n.DNSHostNames.WhenSome(func(r tlv.RecordT[tlv.TlvType11, DNSAddrs]) {
recordProducers = append(recordProducers, &r)
})
@@ -129,7 +136,7 @@ func (n *NodeAnnouncement2) Decode(r io.Reader, _ uint32) error {
ipv4 = tlv.ZeroRecordT[tlv.TlvType5, IPV4Addrs]()
ipv6 = tlv.ZeroRecordT[tlv.TlvType7, IPV6Addrs]()
torV3 = tlv.ZeroRecordT[tlv.TlvType9, TorV3Addrs]()
- dns = tlv.ZeroRecordT[tlv.TlvType11, DNSAddress]()
+ dns = tlv.ZeroRecordT[tlv.TlvType11, DNSAddrs]()
)
stream, err := tlv.NewStream(ProduceRecordsSorted(
@@ -154,6 +161,16 @@ func (n *NodeAnnouncement2) Decode(r io.Reader, _ uint32) error {
return err
}
+ if err := assertRequiredPresent(
+ typeMap,
+ n.Features.TlvType(),
+ n.BlockHeight.TlvType(),
+ n.NodeID.TlvType(),
+ n.Signature.TlvType(),
+ ); err != nil {
+ return err
+ }
+
if _, ok := typeMap[n.Alias.TlvType()]; ok {
n.Alias = tlv.SomeRecordT(alias)
}
@@ -174,8 +191,8 @@ func (n *NodeAnnouncement2) Decode(r io.Reader, _ uint32) error {
n.TorV3Addrs = tlv.SomeRecordT(torV3)
}
- if _, ok := typeMap[n.DNSHostName.TlvType()]; ok {
- n.DNSHostName = tlv.SomeRecordT(dns)
+ if _, ok := typeMap[n.DNSHostNames.TlvType()]; ok {
+ n.DNSHostNames = tlv.SomeRecordT(dns)
}
n.ExtraSignedFields = ExtraSignedFieldsFromTypeMap(typeMap)
@@ -213,6 +230,57 @@ func (n *NodeAnnouncement2) NodeFeatures() *FeatureVector {
return NewFeatureVector(&n.Features.Val, Features)
}
+// Addresses returns the addresses that the node can be reached at, with every
+// unusable entry left out. An entry with a zero port is unusable, and so is a
+// DNS entry whose hostname fails ValidateDNSAddr. BOLT 7 tells a receiver to
+// ignore such an address and keep the rest of the announcement, so a
+// consumer uses this method rather than the raw address fields.
+//
+// The filter cannot live in the codec. The address fields are in the signed
+// range, and the signature digest is rebuilt by re-encoding the decoded
+// records, so the codec has to round-trip every entry. For the same reason
+// the codec does not enforce the sender rule that a node must not announce a
+// zero port. That rule belongs where lnd builds its own announcement.
+func (n *NodeAnnouncement2) Addresses() []net.Addr {
+ var addrs []net.Addr
+
+ n.IPV4Addrs.WhenSome(func(r tlv.RecordT[tlv.TlvType5, IPV4Addrs]) {
+ for _, addr := range r.Val {
+ if addr.Port != 0 {
+ addrs = append(addrs, addr)
+ }
+ }
+ })
+
+ n.IPV6Addrs.WhenSome(func(r tlv.RecordT[tlv.TlvType7, IPV6Addrs]) {
+ for _, addr := range r.Val {
+ if addr.Port != 0 {
+ addrs = append(addrs, addr)
+ }
+ }
+ })
+
+ n.TorV3Addrs.WhenSome(func(r tlv.RecordT[tlv.TlvType9, TorV3Addrs]) {
+ for _, addr := range r.Val {
+ if addr.Port != 0 {
+ addrs = append(addrs, addr)
+ }
+ }
+ })
+
+ n.DNSHostNames.WhenSome(func(r tlv.RecordT[tlv.TlvType11, DNSAddrs]) {
+ for _, addr := range r.Val {
+ // ValidateDNSAddr also rejects a zero port.
+ err := ValidateDNSAddr(addr.Hostname, addr.Port)
+ if err == nil {
+ addrs = append(addrs, addr)
+ }
+ }
+ })
+
+ return addrs
+}
+
// TimestampDesc returns a human-readable description of the timestamp of the
// announcement.
//
@@ -377,6 +445,10 @@ func (a *IPV4Addrs) encodedSize() uint64 {
func ipv4AddrsEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
if v, ok := val.(*IPV4Addrs); ok {
for _, ip := range *v {
+ if err := validateNodeAnn2Port(ip.Port); err != nil {
+ return err
+ }
+
_, err := w.Write(ip.IP.To4())
if err != nil {
return err
@@ -473,6 +545,10 @@ func (a *IPV6Addrs) encodedSize() uint64 {
func ipv6AddrsEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
if v, ok := val.(*IPV6Addrs); ok {
for _, ip := range *v {
+ if err := validateNodeAnn2Port(ip.Port); err != nil {
+ return err
+ }
+
_, err := w.Write(ip.IP.To16())
if err != nil {
return err
@@ -556,6 +632,10 @@ func (a *TorV3Addrs) Record() tlv.Record {
func torV3AddrsEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
if v, ok := val.(*TorV3Addrs); ok {
for _, addr := range *v {
+ if err := validateNodeAnn2Port(addr.Port); err != nil {
+ return err
+ }
+
encodedHostLen := tor.V3Len - tor.OnionSuffixLen
host, err := tor.Base32Encoding.DecodeString(
addr.OnionService[:encodedHostLen],
@@ -587,6 +667,17 @@ func torV3AddrsEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
return tlv.NewTypeForEncodingErr(val, "lnwire.TorV3Addrs")
}
+// validateNodeAnn2Port ensures a locally constructed address cannot wrap when
+// converted to its two-byte wire representation. Port zero remains encodable
+// so received signed records can be reproduced byte for byte.
+func validateNodeAnn2Port(port int) error {
+ if port < 0 || port > math.MaxUint16 {
+ return fmt.Errorf("%w: %d", ErrNodeAnn2PortOutOfRange, port)
+ }
+
+ return nil
+}
+
// torV3AddrsDecoder decodes TLV bytes into Tor v3 addresses.
func torV3AddrsDecoder(r io.Reader, val interface{}, _ *[8]byte,
l uint64) error {
### lnwire/node_announcement_2_test.go
@@ -3,12 +3,84 @@ package lnwire
import (
"bytes"
"io"
+ "math"
+ "net"
"testing"
"github.com/lightningnetwork/lnd/tlv"
+ "github.com/lightningnetwork/lnd/tor"
"github.com/stretchr/testify/require"
)
+// TestNodeAnn2AddressPortRange verifies that locally constructed IP and Tor
+// addresses cannot wrap an out-of-range port into a different wire value.
+func TestNodeAnn2AddressPortRange(t *testing.T) {
+ t.Parallel()
+
+ onion := tor.Base32Encoding.EncodeToString(make([]byte, 35)) +
+ tor.OnionSuffix
+ tests := []struct {
+ name string
+ encode func(int) error
+ }{
+ {
+ name: "ipv4",
+ encode: func(port int) error {
+ addrs := IPV4Addrs{{
+ IP: net.IPv4(192, 0, 2, 1), Port: port,
+ }}
+
+ return ipv4AddrsEncoder(
+ &bytes.Buffer{}, &addrs, nil,
+ )
+ },
+ },
+ {
+ name: "ipv6",
+ encode: func(port int) error {
+ addrs := IPV6Addrs{{
+ IP: net.ParseIP("2001:db8::1"),
+ Port: port,
+ }}
+
+ return ipv6AddrsEncoder(
+ &bytes.Buffer{}, &addrs, nil,
+ )
+ },
+ },
+ {
+ name: "tor v3",
+ encode: func(port int) error {
+ addrs := TorV3Addrs{{
+ OnionService: onion, Port: port,
+ }}
+
+ return torV3AddrsEncoder(
+ &bytes.Buffer{}, &addrs, nil,
+ )
+ },
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ for _, port := range []int{0, math.MaxUint16} {
+ require.NoError(t, test.encode(port))
+ }
+
+ require.ErrorIs(
+ t, test.encode(-1), ErrNodeAnn2PortOutOfRange,
+ )
+ require.ErrorIs(
+ t, test.encode(math.MaxUint16+1),
+ ErrNodeAnn2PortOutOfRange,
+ )
+ })
+ }
+}
+
// TestNodeAnn2EncodeDecode tests the encoding and decoding of the
// NodeAnnouncement2 message using hardcoded byte slices.
func TestNodeAnn2EncodeDecode(t *testing.T) {
@@ -75,16 +147,18 @@ func TestNodeAnn2EncodeDecode(t *testing.T) {
0x21, 0x22, 0x23,
0x23, 0x28, // port 9000.
- // DNSHostName record (optional).
- 0x0b, // type (11).
- 0x17, // length (23).
+ // DNSHostNames record (optional): one entry of u16 length,
+ // hostname and u16 port.
+ 0x0b, // type (11).
+ 0x19, // length (25).
+ 0x00, 0x15, // hostname length (21).
0x6c, 0x69, 0x67, 0x68, 0x74, 0x6e, 0x69, 0x6e,
0x67, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, // value.
0x65, 0x2e, 0x63, 0x6f, 0x6d,
0x23, 0x28, // port 9000.
// Signature.
- 0xa0, // type.
+ 0xf0, // type.
0x40, // length.
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb,
0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
@@ -122,6 +196,75 @@ func TestNodeAnn2EncodeDecode(t *testing.T) {
require.Equal(t, rawBytes, b.Bytes())
}
+// TestNodeAnn2AddressesIgnorePortZero tests that an address with a zero port,
+// or a DNS entry with an invalid hostname, drops only that address. The
+// message must still round-trip byte for byte, because the signature digest
+// is rebuilt from the decoded records.
+func TestNodeAnn2AddressesIgnorePortZero(t *testing.T) {
+ t.Parallel()
+
+ onion := tor.Base32Encoding.EncodeToString(make([]byte, 35)) +
+ tor.OnionSuffix
+
+ var (
+ ip4 = &net.TCPAddr{
+ IP: net.IPv4(10, 0, 0, 1).To4(), Port: 9735,
+ }
+ ip4Zero = &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1).To4()}
+ ip6 = &net.TCPAddr{
+ IP: net.ParseIP("2001:db8::1"), Port: 9735,
+ }
+ ip6Zero = &net.TCPAddr{IP: net.ParseIP("2001:db8::2")}
+ onn = &tor.OnionAddr{OnionService: onion, Port: 9735}
+ dns = &DNSAddress{Hostname: "example.com", Port: 9735}
+ )
+
+ // Put a usable address before a distinct zero-port address. This
+ // ensures that decoding the latter cannot overwrite the former's IP
+ // bytes.
+ msg := &NodeAnnouncement2{}
+ msg.Signature.Val = testSchnorrSig
+ msg.IPV4Addrs = tlv.SomeRecordT(tlv.NewRecordT[tlv.TlvType5](
+ IPV4Addrs{
+ ip4,
+ ip4Zero,
+ },
+ ))
+ msg.IPV6Addrs = tlv.SomeRecordT(tlv.NewRecordT[tlv.TlvType7](
+ IPV6Addrs{
+ ip6,
+ ip6Zero,
+ },
+ ))
+ msg.TorV3Addrs = tlv.SomeRecordT(tlv.NewRecordT[tlv.TlvType9](
+ TorV3Addrs{
+ onn,
+ {OnionService: onion, Port: 0},
+ },
+ ))
+ msg.DNSHostNames = tlv.SomeRecordT(tlv.NewRecordT[tlv.TlvType11](
+ DNSAddrs{
+ {Hostname: "example.org", Port: 0},
+ {Hostname: "bad_host", Port: 9735},
+ dns,
+ },
+ ))
+
+ // The codec keeps every entry, including the unusable ones.
+ var b bytes.Buffer
+ require.NoError(t, msg.Encode(&b, 0))
+
+ var decoded NodeAnnouncement2
+ require.NoError(t, decoded.Decode(bytes.NewReader(b.Bytes()), 0))
+
+ var reencoded bytes.Buffer
+ require.NoError(t, decoded.Encode(&reencoded, 0))
+ require.Equal(t, b.Bytes(), reencoded.Bytes())
+
+ // Only the usable addresses remain, in field order.
+ require.Equal(t, []net.Addr{ip4, ip6, onn, dns}, decoded.Addresses())
+}
+
// TestNodeAnn2AddrDecodeTruncated asserts that each fixed width address decoder
// rejects a record that holds fewer bytes than its TLV length declares.
func TestNodeAnn2AddrDecodeTruncated(t *testing.T) {
### lnwire/partial_sig.go
@@ -1,6 +1,7 @@
package lnwire
import (
+ "fmt"
"io"
"github.com/btcsuite/btcd/btcec/v2"
@@ -249,3 +250,99 @@ func MaybePartialSigWithNonce(sig *PartialSigWithNonce,
),
)
}
+
+const (
+ // AnnouncementSigPairLen is the wire length of an AnnouncementSigPair:
+ // two concatenated 32-byte musig2 partial signatures.
+ AnnouncementSigPairLen = 64
+)
+
+// AnnouncementSigPair carries the two raw musig2 partial signatures that a
+// node emits in announcement_signatures_2 -- one over its node_id key and one
+// over its bitcoin key. They are encoded back-to-back as `node || bitcoin`
+// for a total of 64 bytes. Receivers can verify each signature independently
+// with the standard MuSig2 partial-signature verification routine.
+type AnnouncementSigPair struct {
+ // Node is the partial signature produced with the node_id key.
+ Node btcec.ModNScalar
+
+ // Bitcoin is the partial signature produced with the bitcoin key.
+ Bitcoin btcec.ModNScalar
+}
+
+// NewAnnouncementSigPair creates a new AnnouncementSigPair.
+func NewAnnouncementSigPair(node,
+ bitcoin btcec.ModNScalar) AnnouncementSigPair {
+
+ return AnnouncementSigPair{
+ Node: node,
+ Bitcoin: bitcoin,
+ }
+}
+
+// Record returns the tlv record for the announcement-sig pair. The wrapping
+// RecordT supplies the real type number; the zero passed here is overridden.
+func (a *AnnouncementSigPair) Record() tlv.Record {
+ return tlv.MakeStaticRecord(
+ 0, a, AnnouncementSigPairLen,
+ announcementSigPairEncoder, announcementSigPairDecoder,
+ )
+}
+
+// announcementSigPairEncoder encodes the node and bitcoin partial signatures
+// as two consecutive 32-byte scalars.
+func announcementSigPairEncoder(w io.Writer, val interface{},
+ _ *[8]byte) error {
+
+ v, ok := val.(*AnnouncementSigPair)
+ if !ok {
+ return tlv.NewTypeForEncodingErr(
+ val, "lnwire.AnnouncementSigPair",
+ )
+ }
+
+ nodeBytes := v.Node.Bytes()
+ if _, err := w.Write(nodeBytes[:]); err != nil {
+ return err
+ }
+ bitcoinBytes := v.Bitcoin.Bytes()
+ _, err := w.Write(bitcoinBytes[:])
+
+ return err
+}
+
+// announcementSigPairDecoder decodes the node and bitcoin partial signatures
+// and rejects scalars outside the curve order.
+func announcementSigPairDecoder(r io.Reader, val interface{}, buf *[8]byte,
+ l uint64) error {
+
+ v, ok := val.(*AnnouncementSigPair)
+ if !ok || l != AnnouncementSigPairLen {
+ return tlv.NewTypeForDecodingErr(
+ val, "lnwire.AnnouncementSigPair", l,
+ AnnouncementSigPairLen,
+ )
+ }
+
+ var nodeBytes, bitcoinBytes [32]byte
+ if err := tlv.DBytes32(r, &nodeBytes, buf, 32); err != nil {
+ return err
+ }
+ if err := tlv.DBytes32(r, &bitcoinBytes, buf, 32); err != nil {
+ return err
+ }
+
+ // A partial signature must be below the curve order. BIP-327 rejects
+ // one that is not, and so does musig2.PartialSignature.Decode. Without
+ // the check, SetBytes silently reduces it mod n.
+ if v.Node.SetBytes(&nodeBytes) != 0 {
+ return fmt.Errorf("node partial signature: %w",
+ musig2.ErrPartialSigInvalid)
+ }
+ if v.Bitcoin.SetBytes(&bitcoinBytes) != 0 {
+ return fmt.Errorf("bitcoin partial signature: %w",
+ musig2.ErrPartialSigInvalid)
+ }
+
+ return nil
+}
### lnwire/pure_tlv.go
@@ -2,6 +2,7 @@ package lnwire
import (
"bytes"
+ "fmt"
"github.com/lightningnetwork/lnd/tlv"
)
@@ -10,11 +11,11 @@ const (
// pureTLVUnsignedRangeOneStart defines the start of the first unsigned
// TLV range used for pure TLV messages. The range is inclusive of this
// number.
- pureTLVUnsignedRangeOneStart = 160
+ pureTLVUnsignedRangeOneStart = 240
// pureTLVSignedSecondRangeStart defines the start of the second signed
// TLV range used for pure TLV messages. The range is inclusive of this
- // number. Note that the first range is the inclusive range of 0-159.
+ // number. Note that the first range is the inclusive range of 0-239.
pureTLVSignedSecondRangeStart = 1000000000
// pureTLVUnsignedRangeTwoStart defines the start of the second unsigned
@@ -73,14 +74,29 @@ func SerialiseFieldsToSignFn(msg PureTLVMessage,
}
// InUnsignedRange is the BOLT 7 v2 UnsignedRangeFunc: it returns true for types
-// in 160-999_999_999 or 3_000_000_000+, which sit outside the BOLT 7 v2 signed
-// ranges (0-159 and 1_000_000_000-2_999_999_999).
+// in 240-999_999_999 or 3_000_000_000+, which sit outside the BOLT 7 v2 signed
+// ranges (0-239 and 1_000_000_000-2_999_999_999).
func InUnsignedRange(t tlv.Type) bool {
return (t >= pureTLVUnsignedRangeOneStart &&
t < pureTLVSignedSecondRangeStart) ||
t >= pureTLVUnsignedRangeTwoStart
}
+// assertRequiredPresent returns an error if any of the given TLV types is
+// missing from the parsed type map (as returned by the various
+// DecodeWithParsedTypes helpers). It is used to enforce the spec's
+// reader-side requirement that compulsory TLVs are present in a received
+// pure-TLV message.
+func assertRequiredPresent(typeMap tlv.TypeMap, required ...tlv.Type) error {
+ for _, t := range required {
+ if _, ok := typeMap[t]; !ok {
+ return fmt.Errorf("required TLV type %d missing", t)
+ }
+ }
+
+ return nil
+}
+
// ExtraSignedFields is a type that stores a map from TLV types in the signed
// range (for PureMessages) to their corresponding serialised values. This type
// can be used to keep around data that we don't yet understand but that we need
### lnwire/pure_tlv_test.go
@@ -113,7 +113,7 @@ type MsgV1 struct {
Capacity tlv.OptionalRecordT[tlv.TlvType1, MilliSatoshi]
// Signature in the unsigned range.
- Signature tlv.RecordT[tlv.TlvType160, Sig]
+ Signature tlv.RecordT[tlv.TlvType240, Sig]
// Any extra fields in the signed range that we do not yet know about,
// but we need to keep them for signature validation and to produce a
@@ -130,7 +130,7 @@ func newMsgV1(nodeKey *btcec.PublicKey, capacity *MilliSatoshi) *MsgV1 {
NodeKey: tlv.NewPrimitiveRecord[tlv.TlvType0](
nodeKey,
),
- Signature: tlv.NewRecordT[tlv.TlvType160](
+ Signature: tlv.NewRecordT[tlv.TlvType240](
testSchnorrSig,
),
ExtraSignedFields: make(ExtraSignedFields),
@@ -230,11 +230,11 @@ type MsgV2 struct {
SecondPeer tlv.OptionalRecordT[tlv.TlvType5, TrueBoolean]
// Signature in the unsigned range.
- Signature tlv.RecordT[tlv.TlvType160, Sig]
+ Signature tlv.RecordT[tlv.TlvType240, Sig]
// Another field in the unsigned range. An older node can throw this
// away.
- SPVProof tlv.RecordT[tlv.TlvType161, []byte]
+ SPVProof tlv.RecordT[tlv.TlvType241, []byte]
// A new field in the second signed range. An older node should keep
// this since it is part of the serialised message that is signed.
@@ -258,10 +258,10 @@ func newMsgV2(nodeKey *btcec.PublicKey, capacity *MilliSatoshi,
newMsg := &MsgV2{
NodeKey: tlv.NewPrimitiveRecord[tlv.TlvType0](nodeKey),
- SPVProof: tlv.NewPrimitiveRecord[tlv.TlvType161](spvProof),
+ SPVProof: tlv.NewPrimitiveRecord[tlv.TlvType241](spvProof),
Num: tlv.NewPrimitiveRecord[tlv.TlvType1000000000](num),
Other: tlv.NewPrimitiveRecord[tlv.TlvType3000000000](num),
- Signature: tlv.NewRecordT[tlv.TlvType160](
+ Signature: tlv.NewRecordT[tlv.TlvType240](
testSchnorrSig,
),
ExtraSignedFields: make(ExtraSignedFields),
### lnwire/test_message.go
@@ -132,18 +132,25 @@ var _ TestMessage = (*AnnounceSignatures2)(nil)
// This is part of the TestMessage interface.
func (a *AnnounceSignatures2) RandTestMessage(t *rapid.T) Message {
var (
- chanID = RandChannelID(t)
- scid = RandShortChannelID(t)
- pSig = RandPartialSig(t)
+ chanID = RandChannelID(t)
+ scid = RandShortChannelID(t)
+ nodeSig = RandPartialSig(t)
+ bitcoinSig = RandPartialSig(t)
+ fundingTxID = RandChainHash(t)
)
+ sigs := NewAnnouncementSigPair(nodeSig.Sig, bitcoinSig.Sig)
+
msg := &AnnounceSignatures2{
ChannelID: tlv.NewRecordT[tlv.TlvType0, ChannelID](
chanID,
),
ShortChannelID: tlv.NewRecordT[tlv.TlvType2](scid),
- PartialSignature: tlv.NewRecordT[tlv.TlvType4, PartialSig](
- *pSig,
+ PartialSignatures: tlv.NewRecordT[
+ tlv.TlvType4, AnnouncementSigPair,
+ ](sigs),
+ FundingTxID: tlv.NewPrimitiveRecord[tlv.TlvType6](
+ fundingTxID,
),
ExtraSignedFields: make(map[uint64][]byte),
}
@@ -232,11 +239,10 @@ func (c *ChannelAnnouncement2) RandTestMessage(t *rapid.T) Message {
copy(chainHashObj[:], chainHash[:])
msg := &ChannelAnnouncement2{
- ChainHash: tlv.NewPrimitiveRecord[tlv.TlvType0, chainhash.Hash](
- chainHashObj,
- ),
- Features: tlv.NewRecordT[tlv.TlvType2, RawFeatureVector](
- *features,
+ ChainHash: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType0, chainhash.Hash](
+ chainHashObj,
+ ),
),
ShortChannelID: tlv.NewRecordT[tlv.TlvType4, ShortChannelID](
shortChanID,
@@ -262,6 +268,14 @@ func (c *ChannelAnnouncement2) RandTestMessage(t *rapid.T) Message {
}
// Randomly include optional fields
+ if rapid.Bool().Draw(t, "includeFeatures") {
+ msg.Features = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType2, RawFeatureVector](
+ *features,
+ ),
+ )
+ }
+
if rapid.Bool().Draw(t, "includeBitcoinKey1") {
var bitcoinKey1 [33]byte
copy(bitcoinKey1[:], RandPubKey(t).SerializeCompressed())
@@ -564,59 +578,78 @@ func (c *ChannelUpdate2) RandTestMessage(t *rapid.T) Message {
var chainHashObj chainhash.Hash
copy(chainHashObj[:], chainHash[:])
- //nolint:ll
+ var direction byte
+ if rapid.Bool().Draw(t, "isSecondPeer") {
+ direction = 1
+ }
+ sciddir, err := NewSciddirIntroFromSCID(direction, shortChanID)
+ if err != nil {
+ t.Fatalf("unable to build sciddir: %v", err)
+ }
+ scidRecord := tlv.ZeroRecordT[tlv.TlvType2, SciddirIntro]()
+ scidRecord.Val = sciddir
+
msg := &ChannelUpdate2{
- ChainHash: tlv.NewPrimitiveRecord[tlv.TlvType0, chainhash.Hash](
- chainHashObj,
- ),
- ShortChannelID: tlv.NewRecordT[tlv.TlvType2, ShortChannelID](
- shortChanID,
+ ChainHash: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType0, chainhash.Hash](
+ chainHashObj,
+ ),
),
+ ShortChannelID: scidRecord,
BlockHeight: tlv.NewPrimitiveRecord[tlv.TlvType4, uint32](
blockHeight,
),
- DisabledFlags: tlv.NewPrimitiveRecord[tlv.TlvType6, ChanUpdateDisableFlags]( //nolint:ll
- disabledFlags,
+ DisabledFlags: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType6, ChanUpdateDisableFlags]( //nolint:ll
+ disabledFlags,
+ ),
),
- CLTVExpiryDelta: tlv.NewPrimitiveRecord[tlv.TlvType10, uint16](
- cltvExpiryDelta,
+ CLTVExpiryDelta: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType10, uint16](
+ cltvExpiryDelta,
+ ),
),
- HTLCMinimumMsat: tlv.NewPrimitiveRecord[tlv.TlvType12, MilliSatoshi](
- htlcMinMsat,
+ HTLCMinimumMsat: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType12, MilliSatoshi](
+ htlcMinMsat,
+ ),
),
- HTLCMaximumMsat: tlv.NewPrimitiveRecord[tlv.TlvType14, MilliSatoshi](
- htlcMaxMsat,
+ HTLCMaximumMsat: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType14, MilliSatoshi](
+ htlcMaxMsat,
+ ),
),
- FeeBaseMsat: tlv.NewPrimitiveRecord[tlv.TlvType16, uint32](
- feeBaseMsat,
+ FeeBaseMsat: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType16, uint32](
+ feeBaseMsat,
+ ),
),
- FeeProportionalMillionths: tlv.NewPrimitiveRecord[tlv.TlvType18, uint32](
- feeProportionalMillionths,
+ FeeProportionalMillionths: tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType18, uint32](
+ feeProportionalMillionths,
+ ),
),
ExtraSignedFields: make(map[uint64][]byte),
}
if rapid.Bool().Draw(t, "includeInboundFee") {
- base := rapid.IntRange(-1000, 1000).Draw(t, "inFeeBase")
- rate := rapid.IntRange(-1000, 1000).Draw(t, "inFeeProp")
- fee := Fee{
- BaseFee: int32(base),
- FeeRate: int32(rate),
- }
- msg.InboundFee = tlv.SomeRecordT(
- tlv.NewRecordT[tlv.TlvType55555](fee),
+ base := uint32(
+ rapid.IntRange(1, 0x7FFFFFFF).Draw(t, "inFeeBase"),
+ )
+ rate := uint32(
+ rapid.IntRange(1, 0x7FFFFFFF).Draw(t, "inFeeProp"),
+ )
+ msg.InboundFeeBaseMsat = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType20](base),
+ )
+ msg.InboundFeeProportionalMillionths = tlv.SomeRecordT(
+ tlv.NewPrimitiveRecord[tlv.TlvType22](rate),
)
}
msg.Signature.Val = RandSignature(t)
msg.Signature.Val.ForceSchnorr()
- if rapid.Bool().Draw(t, "isSecondPeer") {
- msg.SecondPeer = tlv.SomeRecordT(
- tlv.RecordT[tlv.TlvType8, TrueBoolean]{},
- )
- }
-
return msg
}
@@ -1284,22 +1317,20 @@ func (g *GossipTimestampRange) RandTestMessage(t *rapid.T) Message {
ExtraData: RandExtraOpaqueData(t, nil),
}
- includeFirstBlockHeight := rapid.Bool().Draw(
- t, "includeFirstBlockHeight",
+ includeBlockHeightRange := rapid.Bool().Draw(
+ t, "includeBlockHeightRange",
)
- includeBlockRange := rapid.Bool().Draw(t, "includeBlockRange")
- if includeFirstBlockHeight {
+ if includeBlockHeightRange {
height := rapid.Uint32().Draw(t, "firstBlockHeight")
- msg.FirstBlockHeight = tlv.SomeRecordT(
- tlv.RecordT[tlv.TlvType2, uint32]{Val: height},
- )
- }
-
- if includeBlockRange {
- blockRange := rapid.Uint32().Draw(t, "blockRange")
- msg.BlockRange = tlv.SomeRecordT(
- tlv.RecordT[tlv.TlvType4, uint32]{Val: blockRange},
+ numBlocks := rapid.Uint32().Draw(t, "numBlocks")
+ msg.BlockHeightRange = tlv.SomeRecordT(
+ tlv.RecordT[tlv.TlvType2, BlockHeightRange]{
+ Val: BlockHeightRange{
+ FirstBlockHeight: height,
+ NumBlocks: numBlocks,
+ },
+ },
)
}
@@ -1519,19 +1550,21 @@ func (n *NodeAnnouncement2) RandTestMessage(t *rapid.T) Message {
msg.TorV3Addrs = tlv.SomeRecordT(torV3Record)
}
- if rapid.Bool().Draw(t, "includeDNSHostName") {
- // Generate a valid DNS hostname.
- hostname := genValidHostname(t)
- port := rapid.Uint16Range(1, 65535).Draw(t, "dnsPort")
-
- dnsAddr := DNSAddress{
- Hostname: hostname,
- Port: port,
+ if rapid.Bool().Draw(t, "includeDNSHostNames") {
+ numAddrs := rapid.IntRange(1, 3).Draw(t, "numDNSAddrs")
+ dnsAddrs := make(DNSAddrs, 0, numAddrs)
+ for range numAddrs {
+ dnsAddrs = append(dnsAddrs, &DNSAddress{
+ Hostname: genValidHostname(t),
+ Port: rapid.Uint16Range(1, 65535).Draw(
+ t, "dnsPort",
+ ),
+ })
}
- dnsRecord := tlv.ZeroRecordT[tlv.TlvType11, DNSAddress]()
- dnsRecord.Val = dnsAddr
- msg.DNSHostName = tlv.SomeRecordT(dnsRecord)
+ dnsRecord := tlv.ZeroRecordT[tlv.TlvType11, DNSAddrs]()
+ dnsRecord.Val = dnsAddrs
+ msg.DNSHostNames = tlv.SomeRecordT(dnsRecord)
}
randRecs, _ := RandSignedRangeRecords(t)
### netann/channel_announcement_test.go
@@ -461,9 +461,10 @@ func buildUnsignedChanAnnouncement(node1, node2 *keyRing,
withBtcKeys bool) *lnwire.ChannelAnnouncement2 {
var ann lnwire.ChannelAnnouncement2
- ann.ChainHash.Val = *chaincfg.MainNetParams.GenesisHash
features := lnwire.NewRawFeatureVector()
- ann.Features.Val = *features
+ ann.Features = tlv.SomeRecordT(
+ tlv.NewRecordT[tlv.TlvType2](*features),
+ )
ann.ShortChannelID.Val = lnwire.ShortChannelID{
BlockHeight: 1000,
TxIndex: 100,
### netann/channel_update.go
@@ -305,15 +305,26 @@ func validateChannelUpdate1Fields(capacity btcutil.Amount,
func validateChannelUpdate2Fields(capacity btcutil.Amount,
c *lnwire.ChannelUpdate2) error {
- maxHtlc := c.HTLCMaximumMsat.Val
- if maxHtlc == 0 || maxHtlc < c.HTLCMinimumMsat.Val {
+ policy := c.ForwardingPolicy()
+ capacityMsat := lnwire.NewMSatFromSatoshis(capacity)
+
+ maxHtlcOpt := c.MaxHTLC(capacityMsat)
+ if maxHtlcOpt.IsNone() {
+ // None means the htlc_maximum_msat TLV is absent and the
+ // capacity is unknown, so there are no other constraints to
+ // check.
+ return nil
+ }
+ maxHtlc := maxHtlcOpt.UnwrapOr(0)
+
+ if maxHtlc == 0 || maxHtlc < policy.MinHTLC {
return fmt.Errorf("invalid max htlc for channel update %v",
lnutils.SpewLogClosure(c))
}
- // Checking whether the MaxHTLC value respects the channel's capacity.
- capacityMsat := lnwire.NewMSatFromSatoshis(capacity)
- if maxHtlc > capacityMsat {
+ // For light clients the capacity is not set, so skip the check that
+ // MaxHTLC respects it, as validateChannelUpdate1Fields does.
+ if capacityMsat != 0 && maxHtlc > capacityMsat {
return fmt.Errorf("max_htlc (%v) for channel update greater "+
"than capacity (%v)", maxHtlc, capacityMsat)
}
### netann/channel_update_test.go
@@ -8,6 +8,8 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
+ "github.com/btcsuite/btcd/btcutil/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwire"
@@ -238,3 +240,93 @@ func TestChannelUpdateSignaturePreservesExtraData(t *testing.T) {
// decode, and verify lifecycle while the unknown TLV is preserved.
require.NoError(t, err)
}
+
+// TestValidateChannelUpdate2MaxHTLC tests the handling of htlc_maximum_msat on
+// a gossip v2 channel update. The TLV is optional, and the spec defaults an
+// absent one to half the channel capacity, so a conformant update that omits
+// it must still validate.
+func TestValidateChannelUpdate2MaxHTLC(t *testing.T) {
+ t.Parallel()
+
+ const capacity = btcutil.Amount(1_000_000)
+
+ newUpdate := func(maxHTLC fn.Option[lnwire.MilliSatoshi],
+ ) *lnwire.ChannelUpdate2 {
+
+ upd := &lnwire.ChannelUpdate2{}
+ upd.ShortChannelID.Val = lnwire.SciddirIntro{
+ SCID: [8]byte{0, 0, 0, 0, 0, 0, 0, 1},
+ }
+ upd.BlockHeight.Val = 100
+
+ maxHTLC.WhenSome(func(m lnwire.MilliSatoshi) {
+ upd.HTLCMaximumMsat = tlv.SomeRecordT(
+ tlv.NewRecordT[
+ tlv.TlvType14, lnwire.MilliSatoshi,
+ ](m),
+ )
+ })
+
+ return upd
+ }
+
+ halfCapacity := lnwire.NewMSatFromSatoshis(capacity) / 2
+
+ tests := []struct {
+ name string
+ capacity btcutil.Amount
+ maxHTLC fn.Option[lnwire.MilliSatoshi]
+ wantErr string
+ }{
+ {
+ name: "absent takes the half-capacity default",
+ capacity: capacity,
+ },
+ {
+ name: "absent with unknown capacity",
+ capacity: 0,
+ },
+ {
+ name: "present within capacity",
+ capacity: capacity,
+ maxHTLC: fn.Some(halfCapacity),
+ },
+ {
+ // An unknown capacity cannot bound max_htlc, so the
+ // check is skipped as it is for a v1 update.
+ name: "present with unknown capacity",
+ capacity: 0,
+ maxHTLC: fn.Some(halfCapacity),
+ },
+ {
+ name: "present above capacity",
+ capacity: capacity,
+ maxHTLC: fn.Some(
+ lnwire.NewMSatFromSatoshis(capacity) + 1,
+ ),
+ wantErr: "greater than capacity",
+ },
+ {
+ name: "present zero",
+ capacity: capacity,
+ maxHTLC: fn.Some(lnwire.MilliSatoshi(0)),
+ wantErr: "invalid max htlc",
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ err := netann.ValidateChannelUpdateFields(
+ test.capacity, newUpdate(test.maxHTLC),
+ )
+ if test.wantErr != "" {
+ require.ErrorContains(t, err, test.wantErr)
+
+ return
+ }
+ require.NoError(t, err)
+ })
+ }
+}
### routing/router_test.go
@@ -2998,7 +2998,7 @@ func (m *mockGraphBuilder) ApplyChannelUpdate(msg *lnwire.ChannelUpdate1) bool {
}
update, err := models.ChanEdgePolicyFromWire(
- msg.ShortChannelID.ToUint64(), msg,
+ msg.ShortChannelID.ToUint64(), 0, msg,
)
if err != nil {
return falseWhy this scored 40/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.