• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 17404926758

02 Sep 2025 01:23PM UTC coverage: 66.663% (-0.008%) from 66.671%
17404926758

Pull #10103

github

web-flow
Merge 86a915a77 into 166676469
Pull Request #10103: Rate limit outgoing gossip bandwidth by peer

59 of 71 new or added lines in 5 files covered. (83.1%)

106 existing lines in 24 files now uncovered.

136016 of 204035 relevant lines covered (66.66%)

21441.58 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.65
/discovery/gossiper.go
1
package discovery
2

3
import (
4
        "bytes"
5
        "context"
6
        "errors"
7
        "fmt"
8
        "strings"
9
        "sync"
10
        "sync/atomic"
11
        "time"
12

13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
15
        "github.com/btcsuite/btcd/btcutil"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
17
        "github.com/btcsuite/btcd/wire"
18
        "github.com/davecgh/go-spew/spew"
19
        "github.com/lightninglabs/neutrino/cache"
20
        "github.com/lightninglabs/neutrino/cache/lru"
21
        "github.com/lightningnetwork/lnd/batch"
22
        "github.com/lightningnetwork/lnd/chainntnfs"
23
        "github.com/lightningnetwork/lnd/channeldb"
24
        "github.com/lightningnetwork/lnd/fn/v2"
25
        "github.com/lightningnetwork/lnd/graph"
26
        graphdb "github.com/lightningnetwork/lnd/graph/db"
27
        "github.com/lightningnetwork/lnd/graph/db/models"
28
        "github.com/lightningnetwork/lnd/input"
29
        "github.com/lightningnetwork/lnd/keychain"
30
        "github.com/lightningnetwork/lnd/lnpeer"
31
        "github.com/lightningnetwork/lnd/lnutils"
32
        "github.com/lightningnetwork/lnd/lnwallet"
33
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
34
        "github.com/lightningnetwork/lnd/lnwallet/chanvalidate"
35
        "github.com/lightningnetwork/lnd/lnwire"
36
        "github.com/lightningnetwork/lnd/multimutex"
37
        "github.com/lightningnetwork/lnd/netann"
38
        "github.com/lightningnetwork/lnd/routing/route"
39
        "github.com/lightningnetwork/lnd/ticker"
40
        "golang.org/x/time/rate"
41
)
42

43
const (
44
        // DefaultMaxChannelUpdateBurst is the default maximum number of updates
45
        // for a specific channel and direction that we'll accept over an
46
        // interval.
47
        DefaultMaxChannelUpdateBurst = 10
48

49
        // DefaultChannelUpdateInterval is the default interval we'll use to
50
        // determine how often we should allow a new update for a specific
51
        // channel and direction.
52
        DefaultChannelUpdateInterval = time.Minute
53

54
        // maxPrematureUpdates tracks the max amount of premature channel
55
        // updates that we'll hold onto.
56
        maxPrematureUpdates = 100
57

58
        // maxFutureMessages tracks the max amount of future messages that
59
        // we'll hold onto.
60
        maxFutureMessages = 1000
61

62
        // DefaultSubBatchDelay is the default delay we'll use when
63
        // broadcasting the next announcement batch.
64
        DefaultSubBatchDelay = 5 * time.Second
65

66
        // maxRejectedUpdates tracks the max amount of rejected channel updates
67
        // we'll maintain. This is the global size across all peers. We'll
68
        // allocate ~3 MB max to the cache.
69
        maxRejectedUpdates = 10_000
70

71
        // DefaultProofMatureDelta specifies the default value used for
72
        // ProofMatureDelta, which is the number of confirmations needed before
73
        // processing the announcement signatures.
74
        DefaultProofMatureDelta = 6
75
)
76

77
var (
78
        // ErrGossiperShuttingDown is an error that is returned if the gossiper
79
        // is in the process of being shut down.
80
        ErrGossiperShuttingDown = errors.New("gossiper is shutting down")
81

82
        // ErrGossipSyncerNotFound signals that we were unable to find an active
83
        // gossip syncer corresponding to a gossip query message received from
84
        // the remote peer.
85
        ErrGossipSyncerNotFound = errors.New("gossip syncer not found")
86

87
        // ErrNoFundingTransaction is returned when we are unable to find the
88
        // funding transaction described by the short channel ID on chain.
89
        ErrNoFundingTransaction = errors.New(
90
                "unable to find the funding transaction",
91
        )
92

93
        // ErrInvalidFundingOutput is returned if the channel funding output
94
        // fails validation.
95
        ErrInvalidFundingOutput = errors.New(
96
                "channel funding output validation failed",
97
        )
98

99
        // ErrChannelSpent is returned when we go to validate a channel, but
100
        // the purported funding output has actually already been spent on
101
        // chain.
102
        ErrChannelSpent = errors.New("channel output has been spent")
103

104
        // emptyPubkey is used to compare compressed pubkeys against an empty
105
        // byte array.
106
        emptyPubkey [33]byte
107
)
108

109
// optionalMsgFields is a set of optional message fields that external callers
110
// can provide that serve useful when processing a specific network
111
// announcement.
112
type optionalMsgFields struct {
113
        capacity      *btcutil.Amount
114
        channelPoint  *wire.OutPoint
115
        remoteAlias   *lnwire.ShortChannelID
116
        tapscriptRoot fn.Option[chainhash.Hash]
117
}
118

119
// apply applies the optional fields within the functional options.
120
func (f *optionalMsgFields) apply(optionalMsgFields ...OptionalMsgField) {
50✔
121
        for _, optionalMsgField := range optionalMsgFields {
58✔
122
                optionalMsgField(f)
8✔
123
        }
8✔
124
}
125

126
// OptionalMsgField is a functional option parameter that can be used to provide
127
// external information that is not included within a network message but serves
128
// useful when processing it.
129
type OptionalMsgField func(*optionalMsgFields)
130

131
// ChannelCapacity is an optional field that lets the gossiper know of the
132
// capacity of a channel.
133
func ChannelCapacity(capacity btcutil.Amount) OptionalMsgField {
30✔
134
        return func(f *optionalMsgFields) {
34✔
135
                f.capacity = &capacity
4✔
136
        }
4✔
137
}
138

139
// ChannelPoint is an optional field that lets the gossiper know of the outpoint
140
// of a channel.
141
func ChannelPoint(op wire.OutPoint) OptionalMsgField {
33✔
142
        return func(f *optionalMsgFields) {
40✔
143
                f.channelPoint = &op
7✔
144
        }
7✔
145
}
146

147
// TapscriptRoot is an optional field that lets the gossiper know of the root of
148
// the tapscript tree for a custom channel.
149
func TapscriptRoot(root fn.Option[chainhash.Hash]) OptionalMsgField {
29✔
150
        return func(f *optionalMsgFields) {
32✔
151
                f.tapscriptRoot = root
3✔
152
        }
3✔
153
}
154

155
// RemoteAlias is an optional field that lets the gossiper know that a locally
156
// sent channel update is actually an update for the peer that should replace
157
// the ShortChannelID field with the remote's alias. This is only used for
158
// channels with peers where the option-scid-alias feature bit was negotiated.
159
// The channel update will be added to the graph under the original SCID, but
160
// will be modified and re-signed with this alias.
161
func RemoteAlias(alias *lnwire.ShortChannelID) OptionalMsgField {
29✔
162
        return func(f *optionalMsgFields) {
32✔
163
                f.remoteAlias = alias
3✔
164
        }
3✔
165
}
166

167
// networkMsg couples a routing related wire message with the peer that
168
// originally sent it.
169
type networkMsg struct {
170
        peer              lnpeer.Peer
171
        source            *btcec.PublicKey
172
        msg               lnwire.Message
173
        optionalMsgFields *optionalMsgFields
174

175
        isRemote bool
176

177
        err chan error
178
}
179

180
// chanPolicyUpdateRequest is a request that is sent to the server when a caller
181
// wishes to update a particular set of channels. New ChannelUpdate messages
182
// will be crafted to be sent out during the next broadcast epoch and the fee
183
// updates committed to the lower layer.
184
type chanPolicyUpdateRequest struct {
185
        edgesToUpdate []EdgeWithInfo
186
        errChan       chan error
187
}
188

189
// PinnedSyncers is a set of node pubkeys for which we will maintain an active
190
// syncer at all times.
191
type PinnedSyncers map[route.Vertex]struct{}
192

193
// Config defines the configuration for the service. ALL elements within the
194
// configuration MUST be non-nil for the service to carry out its duties.
195
type Config struct {
196
        // ChainHash is a hash that indicates which resident chain of the
197
        // AuthenticatedGossiper. Any announcements that don't match this
198
        // chain hash will be ignored.
199
        //
200
        // TODO(roasbeef): eventually make into map so can de-multiplex
201
        // incoming announcements
202
        //   * also need to do same for Notifier
203
        ChainHash chainhash.Hash
204

205
        // Graph is the subsystem which is responsible for managing the
206
        // topology of lightning network. After incoming channel, node, channel
207
        // updates announcements are validated they are sent to the router in
208
        // order to be included in the LN graph.
209
        Graph graph.ChannelGraphSource
210

211
        // ChainIO represents an abstraction over a source that can query the
212
        // blockchain.
213
        ChainIO lnwallet.BlockChainIO
214

215
        // ChanSeries is an interfaces that provides access to a time series
216
        // view of the current known channel graph. Each GossipSyncer enabled
217
        // peer will utilize this in order to create and respond to channel
218
        // graph time series queries.
219
        ChanSeries ChannelGraphTimeSeries
220

221
        // Notifier is used for receiving notifications of incoming blocks.
222
        // With each new incoming block found we process previously premature
223
        // announcements.
224
        //
225
        // TODO(roasbeef): could possibly just replace this with an epoch
226
        // channel.
227
        Notifier chainntnfs.ChainNotifier
228

229
        // Broadcast broadcasts a particular set of announcements to all peers
230
        // that the daemon is connected to. If supplied, the exclude parameter
231
        // indicates that the target peer should be excluded from the
232
        // broadcast.
233
        Broadcast func(skips map[route.Vertex]struct{},
234
                msg ...lnwire.Message) error
235

236
        // NotifyWhenOnline is a function that allows the gossiper to be
237
        // notified when a certain peer comes online, allowing it to
238
        // retry sending a peer message.
239
        //
240
        // NOTE: The peerChan channel must be buffered.
241
        NotifyWhenOnline func(peerPubKey [33]byte, peerChan chan<- lnpeer.Peer)
242

243
        // NotifyWhenOffline is a function that allows the gossiper to be
244
        // notified when a certain peer disconnects, allowing it to request a
245
        // notification for when it reconnects.
246
        NotifyWhenOffline func(peerPubKey [33]byte) <-chan struct{}
247

248
        // FetchSelfAnnouncement retrieves our current node announcement, for
249
        // use when determining whether we should update our peers about our
250
        // presence in the network.
251
        FetchSelfAnnouncement func() lnwire.NodeAnnouncement
252

253
        // UpdateSelfAnnouncement produces a new announcement for our node with
254
        // an updated timestamp which can be broadcast to our peers.
255
        UpdateSelfAnnouncement func() (lnwire.NodeAnnouncement, error)
256

257
        // ProofMatureDelta the number of confirmations which is needed before
258
        // exchange the channel announcement proofs.
259
        ProofMatureDelta uint32
260

261
        // TrickleDelay the period of trickle timer which flushes to the
262
        // network the pending batch of new announcements we've received since
263
        // the last trickle tick.
264
        TrickleDelay time.Duration
265

266
        // RetransmitTicker is a ticker that ticks with a period which
267
        // indicates that we should check if we need re-broadcast any of our
268
        // personal channels.
269
        RetransmitTicker ticker.Ticker
270

271
        // RebroadcastInterval is the maximum time we wait between sending out
272
        // channel updates for our active channels and our own node
273
        // announcement. We do this to ensure our active presence on the
274
        // network is known, and we are not being considered a zombie node or
275
        // having zombie channels.
276
        RebroadcastInterval time.Duration
277

278
        // WaitingProofStore is a persistent storage of partial channel proof
279
        // announcement messages. We use it to buffer half of the material
280
        // needed to reconstruct a full authenticated channel announcement.
281
        // Once we receive the other half the channel proof, we'll be able to
282
        // properly validate it and re-broadcast it out to the network.
283
        //
284
        // TODO(wilmer): make interface to prevent channeldb dependency.
285
        WaitingProofStore *channeldb.WaitingProofStore
286

287
        // MessageStore is a persistent storage of gossip messages which we will
288
        // use to determine which messages need to be resent for a given peer.
289
        MessageStore GossipMessageStore
290

291
        // AnnSigner is an instance of the MessageSigner interface which will
292
        // be used to manually sign any outgoing channel updates. The signer
293
        // implementation should be backed by the public key of the backing
294
        // Lightning node.
295
        //
296
        // TODO(roasbeef): extract ann crafting + sign from fundingMgr into
297
        // here?
298
        AnnSigner lnwallet.MessageSigner
299

300
        // ScidCloser is an instance of ClosedChannelTracker that helps the
301
        // gossiper cut down on spam channel announcements for already closed
302
        // channels.
303
        ScidCloser ClosedChannelTracker
304

305
        // NumActiveSyncers is the number of peers for which we should have
306
        // active syncers with. After reaching NumActiveSyncers, any future
307
        // gossip syncers will be passive.
308
        NumActiveSyncers int
309

310
        // NoTimestampQueries will prevent the GossipSyncer from querying
311
        // timestamps of announcement messages from the peer and from replying
312
        // to timestamp queries.
313
        NoTimestampQueries bool
314

315
        // RotateTicker is a ticker responsible for notifying the SyncManager
316
        // when it should rotate its active syncers. A single active syncer with
317
        // a chansSynced state will be exchanged for a passive syncer in order
318
        // to ensure we don't keep syncing with the same peers.
319
        RotateTicker ticker.Ticker
320

321
        // HistoricalSyncTicker is a ticker responsible for notifying the
322
        // syncManager when it should attempt a historical sync with a gossip
323
        // sync peer.
324
        HistoricalSyncTicker ticker.Ticker
325

326
        // ActiveSyncerTimeoutTicker is a ticker responsible for notifying the
327
        // syncManager when it should attempt to start the next pending
328
        // activeSyncer due to the current one not completing its state machine
329
        // within the timeout.
330
        ActiveSyncerTimeoutTicker ticker.Ticker
331

332
        // MinimumBatchSize is minimum size of a sub batch of announcement
333
        // messages.
334
        MinimumBatchSize int
335

336
        // SubBatchDelay is the delay between sending sub batches of
337
        // gossip messages.
338
        SubBatchDelay time.Duration
339

340
        // IgnoreHistoricalFilters will prevent syncers from replying with
341
        // historical data when the remote peer sets a gossip_timestamp_range.
342
        // This prevents ranges with old start times from causing us to dump the
343
        // graph on connect.
344
        IgnoreHistoricalFilters bool
345

346
        // PinnedSyncers is a set of peers that will always transition to
347
        // ActiveSync upon connection. These peers will never transition to
348
        // PassiveSync.
349
        PinnedSyncers PinnedSyncers
350

351
        // MaxChannelUpdateBurst specifies the maximum number of updates for a
352
        // specific channel and direction that we'll accept over an interval.
353
        MaxChannelUpdateBurst int
354

355
        // ChannelUpdateInterval specifies the interval we'll use to determine
356
        // how often we should allow a new update for a specific channel and
357
        // direction.
358
        ChannelUpdateInterval time.Duration
359

360
        // IsAlias returns true if a given ShortChannelID is an alias for
361
        // option_scid_alias channels.
362
        IsAlias func(scid lnwire.ShortChannelID) bool
363

364
        // SignAliasUpdate is used to re-sign a channel update using the
365
        // remote's alias if the option-scid-alias feature bit was negotiated.
366
        SignAliasUpdate func(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
367
                error)
368

369
        // FindBaseByAlias finds the SCID stored in the graph by an alias SCID.
370
        // This is used for channels that have negotiated the option-scid-alias
371
        // feature bit.
372
        FindBaseByAlias func(alias lnwire.ShortChannelID) (
373
                lnwire.ShortChannelID, error)
374

375
        // GetAlias allows the gossiper to look up the peer's alias for a given
376
        // ChannelID. This is used to sign updates for them if the channel has
377
        // no AuthProof and the option-scid-alias feature bit was negotiated.
378
        GetAlias func(lnwire.ChannelID) (lnwire.ShortChannelID, error)
379

380
        // FindChannel allows the gossiper to find a channel that we're party
381
        // to without iterating over the entire set of open channels.
382
        FindChannel func(node *btcec.PublicKey, chanID lnwire.ChannelID) (
383
                *channeldb.OpenChannel, error)
384

385
        // IsStillZombieChannel takes the timestamps of the latest channel
386
        // updates for a channel and returns true if the channel should be
387
        // considered a zombie based on these timestamps.
388
        IsStillZombieChannel func(time.Time, time.Time) bool
389

390
        // AssumeChannelValid toggles whether the gossiper will check for
391
        // spent-ness of channel outpoints. For neutrino, this saves long
392
        // rescans from blocking initial usage of the daemon.
393
        AssumeChannelValid bool
394

395
        // MsgRateBytes is the rate limit for the number of bytes per second
396
        // that we'll allocate to outbound gossip messages.
397
        MsgRateBytes uint64
398

399
        // MsgBurstBytes is the allotted burst amount in bytes. This is the
400
        // number of starting tokens in our token bucket algorithm.
401
        MsgBurstBytes uint64
402

403
        // FilterConcurrency is the maximum number of concurrent gossip filter
404
        // applications that can be processed.
405
        FilterConcurrency int
406

407
        // BanThreshold is the score used to decide whether a given peer is
408
        // banned or not.
409
        BanThreshold uint64
410

411
        // PeerMsgRateBytes is the rate limit for the number of bytes per second
412
        // that we'll allocate to outbound gossip messages for a single peer.
413
        PeerMsgRateBytes uint64
414
}
415

416
// processedNetworkMsg is a wrapper around networkMsg and a boolean. It is
417
// used to let the caller of the lru.Cache know if a message has already been
418
// processed or not.
419
type processedNetworkMsg struct {
420
        processed bool
421
        msg       *networkMsg
422
}
423

424
// cachedNetworkMsg is a wrapper around a network message that can be used with
425
// *lru.Cache.
426
//
427
// NOTE: This struct is not thread safe which means you need to assure no
428
// concurrent read write access to it and all its contents which are pointers
429
// as well.
430
type cachedNetworkMsg struct {
431
        msgs []*processedNetworkMsg
432
}
433

434
// Size returns the "size" of an entry. We return the number of items as we
435
// just want to limit the total amount of entries rather than do accurate size
436
// accounting.
437
func (c *cachedNetworkMsg) Size() (uint64, error) {
5✔
438
        return uint64(len(c.msgs)), nil
5✔
439
}
5✔
440

441
// rejectCacheKey is the cache key that we'll use to track announcements we've
442
// recently rejected.
443
type rejectCacheKey struct {
444
        pubkey [33]byte
445
        chanID uint64
446
}
447

448
// newRejectCacheKey returns a new cache key for the reject cache.
449
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
475✔
450
        k := rejectCacheKey{
475✔
451
                chanID: cid,
475✔
452
                pubkey: pub,
475✔
453
        }
475✔
454

475✔
455
        return k
475✔
456
}
475✔
457

458
// sourceToPub returns a serialized-compressed public key for use in the reject
459
// cache.
460
func sourceToPub(pk *btcec.PublicKey) [33]byte {
489✔
461
        var pub [33]byte
489✔
462
        copy(pub[:], pk.SerializeCompressed())
489✔
463
        return pub
489✔
464
}
489✔
465

466
// cachedReject is the empty value used to track the value for rejects.
467
type cachedReject struct {
468
}
469

470
// Size returns the "size" of an entry. We return 1 as we just want to limit
471
// the total size.
472
func (c *cachedReject) Size() (uint64, error) {
206✔
473
        return 1, nil
206✔
474
}
206✔
475

476
// AuthenticatedGossiper is a subsystem which is responsible for receiving
477
// announcements, validating them and applying the changes to router, syncing
478
// lightning network with newly connected nodes, broadcasting announcements
479
// after validation, negotiating the channel announcement proofs exchange and
480
// handling the premature announcements. All outgoing announcements are
481
// expected to be properly signed as dictated in BOLT#7, additionally, all
482
// incoming message are expected to be well formed and signed. Invalid messages
483
// will be rejected by this struct.
484
type AuthenticatedGossiper struct {
485
        // Parameters which are needed to properly handle the start and stop of
486
        // the service.
487
        started sync.Once
488
        stopped sync.Once
489

490
        // bestHeight is the height of the block at the tip of the main chain
491
        // as we know it. Accesses *MUST* be done with the gossiper's lock
492
        // held.
493
        bestHeight uint32
494

495
        // cfg is a copy of the configuration struct that the gossiper service
496
        // was initialized with.
497
        cfg *Config
498

499
        // blockEpochs encapsulates a stream of block epochs that are sent at
500
        // every new block height.
501
        blockEpochs *chainntnfs.BlockEpochEvent
502

503
        // prematureChannelUpdates is a map of ChannelUpdates we have received
504
        // that wasn't associated with any channel we know about.  We store
505
        // them temporarily, such that we can reprocess them when a
506
        // ChannelAnnouncement for the channel is received.
507
        prematureChannelUpdates *lru.Cache[uint64, *cachedNetworkMsg]
508

509
        // banman tracks our peer's ban status.
510
        banman *banman
511

512
        // networkMsgs is a channel that carries new network broadcasted
513
        // message from outside the gossiper service to be processed by the
514
        // networkHandler.
515
        networkMsgs chan *networkMsg
516

517
        // futureMsgs is a list of premature network messages that have a block
518
        // height specified in the future. We will save them and resend it to
519
        // the chan networkMsgs once the block height has reached. The cached
520
        // map format is,
521
        //   {msgID1: msg1, msgID2: msg2, ...}
522
        futureMsgs *futureMsgCache
523

524
        // chanPolicyUpdates is a channel that requests to update the
525
        // forwarding policy of a set of channels is sent over.
526
        chanPolicyUpdates chan *chanPolicyUpdateRequest
527

528
        // selfKey is the identity public key of the backing Lightning node.
529
        selfKey *btcec.PublicKey
530

531
        // selfKeyLoc is the locator for the identity public key of the backing
532
        // Lightning node.
533
        selfKeyLoc keychain.KeyLocator
534

535
        // channelMtx is used to restrict the database access to one
536
        // goroutine per channel ID. This is done to ensure that when
537
        // the gossiper is handling an announcement, the db state stays
538
        // consistent between when the DB is first read until it's written.
539
        channelMtx *multimutex.Mutex[uint64]
540

541
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
542

543
        // syncMgr is a subsystem responsible for managing the gossip syncers
544
        // for peers currently connected. When a new peer is connected, the
545
        // manager will create its accompanying gossip syncer and determine
546
        // whether it should have an activeSync or passiveSync sync type based
547
        // on how many other gossip syncers are currently active. Any activeSync
548
        // gossip syncers are started in a round-robin manner to ensure we're
549
        // not syncing with multiple peers at the same time.
550
        syncMgr *SyncManager
551

552
        // reliableSender is a subsystem responsible for handling reliable
553
        // message send requests to peers. This should only be used for channels
554
        // that are unadvertised at the time of handling the message since if it
555
        // is advertised, then peers should be able to get the message from the
556
        // network.
557
        reliableSender *reliableSender
558

559
        // chanUpdateRateLimiter contains rate limiters for each direction of
560
        // a channel update we've processed. We'll use these to determine
561
        // whether we should accept a new update for a specific channel and
562
        // direction.
563
        //
564
        // NOTE: This map must be synchronized with the main
565
        // AuthenticatedGossiper lock.
566
        chanUpdateRateLimiter map[uint64][2]*rate.Limiter
567

568
        // vb is used to enforce job dependency ordering of gossip messages.
569
        vb *ValidationBarrier
570

571
        sync.Mutex
572

573
        cancel fn.Option[context.CancelFunc]
574
        quit   chan struct{}
575
        wg     sync.WaitGroup
576
}
577

578
// New creates a new AuthenticatedGossiper instance, initialized with the
579
// passed configuration parameters.
580
func New(cfg Config, selfKeyDesc *keychain.KeyDescriptor) *AuthenticatedGossiper {
33✔
581
        gossiper := &AuthenticatedGossiper{
33✔
582
                selfKey:           selfKeyDesc.PubKey,
33✔
583
                selfKeyLoc:        selfKeyDesc.KeyLocator,
33✔
584
                cfg:               &cfg,
33✔
585
                networkMsgs:       make(chan *networkMsg),
33✔
586
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
33✔
587
                quit:              make(chan struct{}),
33✔
588
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
33✔
589
                prematureChannelUpdates: lru.NewCache[uint64, *cachedNetworkMsg]( //nolint: ll
33✔
590
                        maxPrematureUpdates,
33✔
591
                ),
33✔
592
                channelMtx: multimutex.NewMutex[uint64](),
33✔
593
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
33✔
594
                        maxRejectedUpdates,
33✔
595
                ),
33✔
596
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
33✔
597
                banman:                newBanman(cfg.BanThreshold),
33✔
598
        }
33✔
599

33✔
600
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
33✔
601

33✔
602
        gossiper.syncMgr = newSyncManager(&SyncManagerCfg{
33✔
603
                ChainHash:                cfg.ChainHash,
33✔
604
                ChanSeries:               cfg.ChanSeries,
33✔
605
                RotateTicker:             cfg.RotateTicker,
33✔
606
                HistoricalSyncTicker:     cfg.HistoricalSyncTicker,
33✔
607
                NumActiveSyncers:         cfg.NumActiveSyncers,
33✔
608
                NoTimestampQueries:       cfg.NoTimestampQueries,
33✔
609
                IgnoreHistoricalFilters:  cfg.IgnoreHistoricalFilters,
33✔
610
                BestHeight:               gossiper.latestHeight,
33✔
611
                PinnedSyncers:            cfg.PinnedSyncers,
33✔
612
                IsStillZombieChannel:     cfg.IsStillZombieChannel,
33✔
613
                AllotedMsgBytesPerSecond: cfg.MsgRateBytes,
33✔
614
                AllotedMsgBytesBurst:     cfg.MsgBurstBytes,
33✔
615
                FilterConcurrency:        cfg.FilterConcurrency,
33✔
616
                PeerMsgBytesPerSecond:    cfg.PeerMsgRateBytes,
33✔
617
        })
33✔
618

33✔
619
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
33✔
620
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
33✔
621
                NotifyWhenOffline: cfg.NotifyWhenOffline,
33✔
622
                MessageStore:      cfg.MessageStore,
33✔
623
                IsMsgStale:        gossiper.isMsgStale,
33✔
624
        })
33✔
625

33✔
626
        return gossiper
33✔
627
}
33✔
628

629
// EdgeWithInfo contains the information that is required to update an edge.
630
type EdgeWithInfo struct {
631
        // Info describes the channel.
632
        Info *models.ChannelEdgeInfo
633

634
        // Edge describes the policy in one direction of the channel.
635
        Edge *models.ChannelEdgePolicy
636
}
637

638
// PropagateChanPolicyUpdate signals the AuthenticatedGossiper to perform the
639
// specified edge updates. Updates are done in two stages: first, the
640
// AuthenticatedGossiper ensures the update has been committed by dependent
641
// sub-systems, then it signs and broadcasts new updates to the network. A
642
// mapping between outpoints and updated channel policies is returned, which is
643
// used to update the forwarding policies of the underlying links.
644
func (d *AuthenticatedGossiper) PropagateChanPolicyUpdate(
645
        edgesToUpdate []EdgeWithInfo) error {
4✔
646

4✔
647
        errChan := make(chan error, 1)
4✔
648
        policyUpdate := &chanPolicyUpdateRequest{
4✔
649
                edgesToUpdate: edgesToUpdate,
4✔
650
                errChan:       errChan,
4✔
651
        }
4✔
652

4✔
653
        select {
4✔
654
        case d.chanPolicyUpdates <- policyUpdate:
4✔
655
                err := <-errChan
4✔
656
                return err
4✔
657
        case <-d.quit:
×
658
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
659
        }
660
}
661

662
// Start spawns network messages handler goroutine and registers on new block
663
// notifications in order to properly handle the premature announcements.
664
func (d *AuthenticatedGossiper) Start() error {
33✔
665
        var err error
33✔
666
        d.started.Do(func() {
66✔
667
                ctx, cancel := context.WithCancel(context.Background())
33✔
668
                d.cancel = fn.Some(cancel)
33✔
669

33✔
670
                log.Info("Authenticated Gossiper starting")
33✔
671
                err = d.start(ctx)
33✔
672
        })
33✔
673
        return err
33✔
674
}
675

676
func (d *AuthenticatedGossiper) start(ctx context.Context) error {
33✔
677
        // First we register for new notifications of newly discovered blocks.
33✔
678
        // We do this immediately so we'll later be able to consume any/all
33✔
679
        // blocks which were discovered.
33✔
680
        blockEpochs, err := d.cfg.Notifier.RegisterBlockEpochNtfn(nil)
33✔
681
        if err != nil {
33✔
682
                return err
×
683
        }
×
684
        d.blockEpochs = blockEpochs
33✔
685

33✔
686
        height, err := d.cfg.Graph.CurrentBlockHeight()
33✔
687
        if err != nil {
33✔
688
                return err
×
689
        }
×
690
        d.bestHeight = height
33✔
691

33✔
692
        // Start the reliable sender. In case we had any pending messages ready
33✔
693
        // to be sent when the gossiper was last shut down, we must continue on
33✔
694
        // our quest to deliver them to their respective peers.
33✔
695
        if err := d.reliableSender.Start(); err != nil {
33✔
696
                return err
×
697
        }
×
698

699
        d.syncMgr.Start()
33✔
700

33✔
701
        d.banman.start()
33✔
702

33✔
703
        // Start receiving blocks in its dedicated goroutine.
33✔
704
        d.wg.Add(2)
33✔
705
        go d.syncBlockHeight()
33✔
706
        go d.networkHandler(ctx)
33✔
707

33✔
708
        return nil
33✔
709
}
710

711
// syncBlockHeight syncs the best block height for the gossiper by reading
712
// blockEpochs.
713
//
714
// NOTE: must be run as a goroutine.
715
func (d *AuthenticatedGossiper) syncBlockHeight() {
33✔
716
        defer d.wg.Done()
33✔
717

33✔
718
        for {
66✔
719
                select {
33✔
720
                // A new block has arrived, so we can re-process the previously
721
                // premature announcements.
722
                case newBlock, ok := <-d.blockEpochs.Epochs:
3✔
723
                        // If the channel has been closed, then this indicates
3✔
724
                        // the daemon is shutting down, so we exit ourselves.
3✔
725
                        if !ok {
6✔
726
                                return
3✔
727
                        }
3✔
728

729
                        // Once a new block arrives, we update our running
730
                        // track of the height of the chain tip.
731
                        d.Lock()
3✔
732
                        blockHeight := uint32(newBlock.Height)
3✔
733
                        d.bestHeight = blockHeight
3✔
734
                        d.Unlock()
3✔
735

3✔
736
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
3✔
737
                                newBlock.Hash)
3✔
738

3✔
739
                        // Resend future messages, if any.
3✔
740
                        d.resendFutureMessages(blockHeight)
3✔
741

742
                case <-d.quit:
30✔
743
                        return
30✔
744
                }
745
        }
746
}
747

748
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
749
// the unique ID when saving the message.
750
type futureMsgCache struct {
751
        *lru.Cache[uint64, *cachedFutureMsg]
752

753
        // msgID is a monotonically increased integer.
754
        msgID atomic.Uint64
755
}
756

757
// nextMsgID returns a unique message ID.
758
func (f *futureMsgCache) nextMsgID() uint64 {
6✔
759
        return f.msgID.Add(1)
6✔
760
}
6✔
761

762
// newFutureMsgCache creates a new future message cache with the underlying lru
763
// cache being initialized with the specified capacity.
764
func newFutureMsgCache(capacity uint64) *futureMsgCache {
34✔
765
        // Create a new cache.
34✔
766
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
34✔
767

34✔
768
        return &futureMsgCache{
34✔
769
                Cache: cache,
34✔
770
        }
34✔
771
}
34✔
772

773
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
774
type cachedFutureMsg struct {
775
        // msg is the network message.
776
        msg *networkMsg
777

778
        // height is the block height.
779
        height uint32
780
}
781

782
// Size returns the size of the message.
783
func (c *cachedFutureMsg) Size() (uint64, error) {
7✔
784
        // Return a constant 1.
7✔
785
        return 1, nil
7✔
786
}
7✔
787

788
// resendFutureMessages takes a block height, resends all the future messages
789
// found below and equal to that height and deletes those messages found in the
790
// gossiper's futureMsgs.
791
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
3✔
792
        var (
3✔
793
                // msgs are the target messages.
3✔
794
                msgs []*networkMsg
3✔
795

3✔
796
                // keys are the target messages' caching keys.
3✔
797
                keys []uint64
3✔
798
        )
3✔
799

3✔
800
        // filterMsgs is the visitor used when iterating the future cache.
3✔
801
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
6✔
802
                if cmsg.height <= height {
6✔
803
                        msgs = append(msgs, cmsg.msg)
3✔
804
                        keys = append(keys, k)
3✔
805
                }
3✔
806

807
                return true
3✔
808
        }
809

810
        // Filter out the target messages.
811
        d.futureMsgs.Range(filterMsgs)
3✔
812

3✔
813
        // Return early if no messages found.
3✔
814
        if len(msgs) == 0 {
6✔
815
                return
3✔
816
        }
3✔
817

818
        // Remove the filtered messages.
819
        for _, key := range keys {
6✔
820
                d.futureMsgs.Delete(key)
3✔
821
        }
3✔
822

823
        log.Debugf("Resending %d network messages at height %d",
3✔
824
                len(msgs), height)
3✔
825

3✔
826
        for _, msg := range msgs {
6✔
827
                select {
3✔
828
                case d.networkMsgs <- msg:
3✔
829
                case <-d.quit:
×
830
                        msg.err <- ErrGossiperShuttingDown
×
831
                }
832
        }
833
}
834

835
// Stop signals any active goroutines for a graceful closure.
836
func (d *AuthenticatedGossiper) Stop() error {
34✔
837
        d.stopped.Do(func() {
67✔
838
                log.Info("Authenticated gossiper shutting down...")
33✔
839
                defer log.Debug("Authenticated gossiper shutdown complete")
33✔
840

33✔
841
                d.stop()
33✔
842
        })
33✔
843
        return nil
34✔
844
}
845

846
func (d *AuthenticatedGossiper) stop() {
33✔
847
        log.Debug("Authenticated Gossiper is stopping")
33✔
848
        defer log.Debug("Authenticated Gossiper stopped")
33✔
849

33✔
850
        // `blockEpochs` is only initialized in the start routine so we make
33✔
851
        // sure we don't panic here in the case where the `Stop` method is
33✔
852
        // called when the `Start` method does not complete.
33✔
853
        if d.blockEpochs != nil {
66✔
854
                d.blockEpochs.Cancel()
33✔
855
        }
33✔
856

857
        d.syncMgr.Stop()
33✔
858

33✔
859
        d.banman.stop()
33✔
860

33✔
861
        d.cancel.WhenSome(func(fn context.CancelFunc) { fn() })
66✔
862
        close(d.quit)
33✔
863
        d.wg.Wait()
33✔
864

33✔
865
        // We'll stop our reliable sender after all of the gossiper's goroutines
33✔
866
        // have exited to ensure nothing can cause it to continue executing.
33✔
867
        d.reliableSender.Stop()
33✔
868
}
869

870
// TODO(roasbeef): need method to get current gossip timestamp?
871
//  * using mtx, check time rotate forward is needed?
872

873
// ProcessRemoteAnnouncement sends a new remote announcement message along with
874
// the peer that sent the routing message. The announcement will be processed
875
// then added to a queue for batched trickled announcement to all connected
876
// peers.  Remote channel announcements should contain the announcement proof
877
// and be fully validated.
878
func (d *AuthenticatedGossiper) ProcessRemoteAnnouncement(ctx context.Context,
879
        msg lnwire.Message, peer lnpeer.Peer) chan error {
294✔
880

294✔
881
        errChan := make(chan error, 1)
294✔
882

294✔
883
        // For messages in the known set of channel series queries, we'll
294✔
884
        // dispatch the message directly to the GossipSyncer, and skip the main
294✔
885
        // processing loop.
294✔
886
        switch m := msg.(type) {
294✔
887
        case *lnwire.QueryShortChanIDs,
888
                *lnwire.QueryChannelRange,
889
                *lnwire.ReplyChannelRange,
890
                *lnwire.ReplyShortChanIDsEnd:
3✔
891

3✔
892
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
893
                if !ok {
3✔
894
                        log.Warnf("Gossip syncer for peer=%x not found",
×
895
                                peer.PubKey())
×
896

×
897
                        errChan <- ErrGossipSyncerNotFound
×
898
                        return errChan
×
899
                }
×
900

901
                // If we've found the message target, then we'll dispatch the
902
                // message directly to it.
903
                err := syncer.ProcessQueryMsg(m, peer.QuitSignal())
3✔
904
                if err != nil {
3✔
905
                        log.Errorf("Process query msg from peer %x got %v",
×
906
                                peer.PubKey(), err)
×
907
                }
×
908

909
                errChan <- err
3✔
910
                return errChan
3✔
911

912
        // If a peer is updating its current update horizon, then we'll dispatch
913
        // that directly to the proper GossipSyncer.
914
        case *lnwire.GossipTimestampRange:
3✔
915
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
916
                if !ok {
3✔
917
                        log.Warnf("Gossip syncer for peer=%x not found",
×
918
                                peer.PubKey())
×
919

×
920
                        errChan <- ErrGossipSyncerNotFound
×
921
                        return errChan
×
922
                }
×
923

924
                // Queue the message for asynchronous processing to prevent
925
                // blocking the gossiper when rate limiting is active.
926
                if !syncer.QueueTimestampRange(m) {
3✔
927
                        log.Warnf("Unable to queue gossip filter for peer=%x: "+
×
928
                                "queue full", peer.PubKey())
×
929

×
930
                        // Return nil to indicate we've handled the message,
×
931
                        // even though it was dropped. This prevents the peer
×
932
                        // from being disconnected.
×
933
                        errChan <- nil
×
934
                        return errChan
×
935
                }
×
936

937
                errChan <- nil
3✔
938
                return errChan
3✔
939

940
        // To avoid inserting edges in the graph for our own channels that we
941
        // have already closed, we ignore such channel announcements coming
942
        // from the remote.
943
        case *lnwire.ChannelAnnouncement1:
223✔
944
                ownKey := d.selfKey.SerializeCompressed()
223✔
945
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
223✔
946
                        "for own channel")
223✔
947

223✔
948
                if bytes.Equal(m.NodeID1[:], ownKey) ||
223✔
949
                        bytes.Equal(m.NodeID2[:], ownKey) {
228✔
950

5✔
951
                        log.Warn(ownErr)
5✔
952
                        errChan <- ownErr
5✔
953
                        return errChan
5✔
954
                }
5✔
955
        }
956

957
        nMsg := &networkMsg{
292✔
958
                msg:      msg,
292✔
959
                isRemote: true,
292✔
960
                peer:     peer,
292✔
961
                source:   peer.IdentityKey(),
292✔
962
                err:      errChan,
292✔
963
        }
292✔
964

292✔
965
        select {
292✔
966
        case d.networkMsgs <- nMsg:
292✔
967

968
        // If the peer that sent us this error is quitting, then we don't need
969
        // to send back an error and can return immediately.
970
        // TODO(elle): the peer should now just rely on canceling the passed
971
        //  context.
972
        case <-peer.QuitSignal():
×
973
                return nil
×
974
        case <-ctx.Done():
×
975
                return nil
×
976
        case <-d.quit:
×
977
                nMsg.err <- ErrGossiperShuttingDown
×
978
        }
979

980
        return nMsg.err
292✔
981
}
982

983
// ProcessLocalAnnouncement sends a new remote announcement message along with
984
// the peer that sent the routing message. The announcement will be processed
985
// then added to a queue for batched trickled announcement to all connected
986
// peers.  Local channel announcements don't contain the announcement proof and
987
// will not be fully validated. Once the channel proofs are received, the
988
// entire channel announcement and update messages will be re-constructed and
989
// broadcast to the rest of the network.
990
func (d *AuthenticatedGossiper) ProcessLocalAnnouncement(msg lnwire.Message,
991
        optionalFields ...OptionalMsgField) chan error {
50✔
992

50✔
993
        optionalMsgFields := &optionalMsgFields{}
50✔
994
        optionalMsgFields.apply(optionalFields...)
50✔
995

50✔
996
        nMsg := &networkMsg{
50✔
997
                msg:               msg,
50✔
998
                optionalMsgFields: optionalMsgFields,
50✔
999
                isRemote:          false,
50✔
1000
                source:            d.selfKey,
50✔
1001
                err:               make(chan error, 1),
50✔
1002
        }
50✔
1003

50✔
1004
        select {
50✔
1005
        case d.networkMsgs <- nMsg:
50✔
1006
        case <-d.quit:
×
1007
                nMsg.err <- ErrGossiperShuttingDown
×
1008
        }
1009

1010
        return nMsg.err
50✔
1011
}
1012

1013
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
1014
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
1015
// tuple.
1016
type channelUpdateID struct {
1017
        // channelID represents the set of data which is needed to
1018
        // retrieve all necessary data to validate the channel existence.
1019
        channelID lnwire.ShortChannelID
1020

1021
        // Flags least-significant bit must be set to 0 if the creating node
1022
        // corresponds to the first node in the previously sent channel
1023
        // announcement and 1 otherwise.
1024
        flags lnwire.ChanUpdateChanFlags
1025
}
1026

1027
// msgWithSenders is a wrapper struct around a message, and the set of peers
1028
// that originally sent us this message. Using this struct, we can ensure that
1029
// we don't re-send a message to the peer that sent it to us in the first
1030
// place.
1031
type msgWithSenders struct {
1032
        // msg is the wire message itself.
1033
        msg lnwire.Message
1034

1035
        // isLocal is true if this was a message that originated locally. We'll
1036
        // use this to bypass our normal checks to ensure we prioritize sending
1037
        // out our own updates.
1038
        isLocal bool
1039

1040
        // sender is the set of peers that sent us this message.
1041
        senders map[route.Vertex]struct{}
1042
}
1043

1044
// mergeSyncerMap is used to merge the set of senders of a particular message
1045
// with peers that we have an active GossipSyncer with. We do this to ensure
1046
// that we don't broadcast messages to any peers that we have active gossip
1047
// syncers for.
1048
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
32✔
1049
        for peerPub := range syncers {
35✔
1050
                m.senders[peerPub] = struct{}{}
3✔
1051
        }
3✔
1052
}
1053

1054
// deDupedAnnouncements de-duplicates announcements that have been added to the
1055
// batch. Internally, announcements are stored in three maps
1056
// (one each for channel announcements, channel updates, and node
1057
// announcements). These maps keep track of unique announcements and ensure no
1058
// announcements are duplicated. We keep the three message types separate, such
1059
// that we can send channel announcements first, then channel updates, and
1060
// finally node announcements when it's time to broadcast them.
1061
type deDupedAnnouncements struct {
1062
        // channelAnnouncements are identified by the short channel id field.
1063
        channelAnnouncements map[lnwire.ShortChannelID]msgWithSenders
1064

1065
        // channelUpdates are identified by the channel update id field.
1066
        channelUpdates map[channelUpdateID]msgWithSenders
1067

1068
        // nodeAnnouncements are identified by the Vertex field.
1069
        nodeAnnouncements map[route.Vertex]msgWithSenders
1070

1071
        sync.Mutex
1072
}
1073

1074
// Reset operates on deDupedAnnouncements to reset the storage of
1075
// announcements.
1076
func (d *deDupedAnnouncements) Reset() {
35✔
1077
        d.Lock()
35✔
1078
        defer d.Unlock()
35✔
1079

35✔
1080
        d.reset()
35✔
1081
}
35✔
1082

1083
// reset is the private version of the Reset method. We have this so we can
1084
// call this method within method that are already holding the lock.
1085
func (d *deDupedAnnouncements) reset() {
330✔
1086
        // Storage of each type of announcement (channel announcements, channel
330✔
1087
        // updates, node announcements) is set to an empty map where the
330✔
1088
        // appropriate key points to the corresponding lnwire.Message.
330✔
1089
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
330✔
1090
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
330✔
1091
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
330✔
1092
}
330✔
1093

1094
// addMsg adds a new message to the current batch. If the message is already
1095
// present in the current batch, then this new instance replaces the latter,
1096
// and the set of senders is updated to reflect which node sent us this
1097
// message.
1098
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
94✔
1099
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
94✔
1100

94✔
1101
        // Depending on the message type (channel announcement, channel update,
94✔
1102
        // or node announcement), the message is added to the corresponding map
94✔
1103
        // in deDupedAnnouncements. Because each identifying key can have at
94✔
1104
        // most one value, the announcements are de-duplicated, with newer ones
94✔
1105
        // replacing older ones.
94✔
1106
        switch msg := message.msg.(type) {
94✔
1107

1108
        // Channel announcements are identified by the short channel id field.
1109
        case *lnwire.ChannelAnnouncement1:
26✔
1110
                deDupKey := msg.ShortChannelID
26✔
1111
                sender := route.NewVertex(message.source)
26✔
1112

26✔
1113
                mws, ok := d.channelAnnouncements[deDupKey]
26✔
1114
                if !ok {
51✔
1115
                        mws = msgWithSenders{
25✔
1116
                                msg:     msg,
25✔
1117
                                isLocal: !message.isRemote,
25✔
1118
                                senders: make(map[route.Vertex]struct{}),
25✔
1119
                        }
25✔
1120
                        mws.senders[sender] = struct{}{}
25✔
1121

25✔
1122
                        d.channelAnnouncements[deDupKey] = mws
25✔
1123

25✔
1124
                        return
25✔
1125
                }
25✔
1126

1127
                mws.msg = msg
1✔
1128
                mws.senders[sender] = struct{}{}
1✔
1129
                d.channelAnnouncements[deDupKey] = mws
1✔
1130

1131
        // Channel updates are identified by the (short channel id,
1132
        // channelflags) tuple.
1133
        case *lnwire.ChannelUpdate1:
49✔
1134
                sender := route.NewVertex(message.source)
49✔
1135
                deDupKey := channelUpdateID{
49✔
1136
                        msg.ShortChannelID,
49✔
1137
                        msg.ChannelFlags,
49✔
1138
                }
49✔
1139

49✔
1140
                oldTimestamp := uint32(0)
49✔
1141
                mws, ok := d.channelUpdates[deDupKey]
49✔
1142
                if ok {
52✔
1143
                        // If we already have seen this message, record its
3✔
1144
                        // timestamp.
3✔
1145
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1146
                        if !ok {
3✔
1147
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1148
                                        "got: %T", mws.msg)
×
1149

×
1150
                                return
×
1151
                        }
×
1152

1153
                        oldTimestamp = update.Timestamp
3✔
1154
                }
1155

1156
                // If we already had this message with a strictly newer
1157
                // timestamp, then we'll just discard the message we got.
1158
                if oldTimestamp > msg.Timestamp {
50✔
1159
                        log.Debugf("Ignored outdated network message: "+
1✔
1160
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1161
                        return
1✔
1162
                }
1✔
1163

1164
                // If the message we just got is newer than what we previously
1165
                // have seen, or this is the first time we see it, then we'll
1166
                // add it to our map of announcements.
1167
                if oldTimestamp < msg.Timestamp {
95✔
1168
                        mws = msgWithSenders{
47✔
1169
                                msg:     msg,
47✔
1170
                                isLocal: !message.isRemote,
47✔
1171
                                senders: make(map[route.Vertex]struct{}),
47✔
1172
                        }
47✔
1173

47✔
1174
                        // We'll mark the sender of the message in the
47✔
1175
                        // senders map.
47✔
1176
                        mws.senders[sender] = struct{}{}
47✔
1177

47✔
1178
                        d.channelUpdates[deDupKey] = mws
47✔
1179

47✔
1180
                        return
47✔
1181
                }
47✔
1182

1183
                // Lastly, if we had seen this exact message from before, with
1184
                // the same timestamp, we'll add the sender to the map of
1185
                // senders, such that we can skip sending this message back in
1186
                // the next batch.
1187
                mws.msg = msg
1✔
1188
                mws.senders[sender] = struct{}{}
1✔
1189
                d.channelUpdates[deDupKey] = mws
1✔
1190

1191
        // Node announcements are identified by the Vertex field.  Use the
1192
        // NodeID to create the corresponding Vertex.
1193
        case *lnwire.NodeAnnouncement:
25✔
1194
                sender := route.NewVertex(message.source)
25✔
1195
                deDupKey := route.Vertex(msg.NodeID)
25✔
1196

25✔
1197
                // We do the same for node announcements as we did for channel
25✔
1198
                // updates, as they also carry a timestamp.
25✔
1199
                oldTimestamp := uint32(0)
25✔
1200
                mws, ok := d.nodeAnnouncements[deDupKey]
25✔
1201
                if ok {
33✔
1202
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
8✔
1203
                }
8✔
1204

1205
                // Discard the message if it's old.
1206
                if oldTimestamp > msg.Timestamp {
28✔
1207
                        return
3✔
1208
                }
3✔
1209

1210
                // Replace if it's newer.
1211
                if oldTimestamp < msg.Timestamp {
46✔
1212
                        mws = msgWithSenders{
21✔
1213
                                msg:     msg,
21✔
1214
                                isLocal: !message.isRemote,
21✔
1215
                                senders: make(map[route.Vertex]struct{}),
21✔
1216
                        }
21✔
1217

21✔
1218
                        mws.senders[sender] = struct{}{}
21✔
1219

21✔
1220
                        d.nodeAnnouncements[deDupKey] = mws
21✔
1221

21✔
1222
                        return
21✔
1223
                }
21✔
1224

1225
                // Add to senders map if it's the same as we had.
1226
                mws.msg = msg
7✔
1227
                mws.senders[sender] = struct{}{}
7✔
1228
                d.nodeAnnouncements[deDupKey] = mws
7✔
1229
        }
1230
}
1231

1232
// AddMsgs is a helper method to add multiple messages to the announcement
1233
// batch.
1234
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
62✔
1235
        d.Lock()
62✔
1236
        defer d.Unlock()
62✔
1237

62✔
1238
        for _, msg := range msgs {
156✔
1239
                d.addMsg(msg)
94✔
1240
        }
94✔
1241
}
1242

1243
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1244
// to broadcast next into messages that are locally sourced and those that are
1245
// sourced remotely.
1246
type msgsToBroadcast struct {
1247
        // localMsgs is the set of messages we created locally.
1248
        localMsgs []msgWithSenders
1249

1250
        // remoteMsgs is the set of messages that we received from a remote
1251
        // party.
1252
        remoteMsgs []msgWithSenders
1253
}
1254

1255
// addMsg adds a new message to the appropriate sub-slice.
1256
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
79✔
1257
        if msg.isLocal {
129✔
1258
                m.localMsgs = append(m.localMsgs, msg)
50✔
1259
        } else {
82✔
1260
                m.remoteMsgs = append(m.remoteMsgs, msg)
32✔
1261
        }
32✔
1262
}
1263

1264
// isEmpty returns true if the batch is empty.
1265
func (m *msgsToBroadcast) isEmpty() bool {
297✔
1266
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
297✔
1267
}
297✔
1268

1269
// length returns the length of the combined message set.
1270
func (m *msgsToBroadcast) length() int {
1✔
1271
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1272
}
1✔
1273

1274
// Emit returns the set of de-duplicated announcements to be sent out during
1275
// the next announcement epoch, in the order of channel announcements, channel
1276
// updates, and node announcements. Each message emitted, contains the set of
1277
// peers that sent us the message. This way, we can ensure that we don't waste
1278
// bandwidth by re-sending a message to the peer that sent it to us in the
1279
// first place. Additionally, the set of stored messages are reset.
1280
func (d *deDupedAnnouncements) Emit() msgsToBroadcast {
298✔
1281
        d.Lock()
298✔
1282
        defer d.Unlock()
298✔
1283

298✔
1284
        // Get the total number of announcements.
298✔
1285
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
298✔
1286
                len(d.nodeAnnouncements)
298✔
1287

298✔
1288
        // Create an empty array of lnwire.Messages with a length equal to
298✔
1289
        // the total number of announcements.
298✔
1290
        msgs := msgsToBroadcast{
298✔
1291
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
298✔
1292
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
298✔
1293
        }
298✔
1294

298✔
1295
        // Add the channel announcements to the array first.
298✔
1296
        for _, message := range d.channelAnnouncements {
320✔
1297
                msgs.addMsg(message)
22✔
1298
        }
22✔
1299

1300
        // Then add the channel updates.
1301
        for _, message := range d.channelUpdates {
341✔
1302
                msgs.addMsg(message)
43✔
1303
        }
43✔
1304

1305
        // Finally add the node announcements.
1306
        for _, message := range d.nodeAnnouncements {
318✔
1307
                msgs.addMsg(message)
20✔
1308
        }
20✔
1309

1310
        d.reset()
298✔
1311

298✔
1312
        // Return the array of lnwire.messages.
298✔
1313
        return msgs
298✔
1314
}
1315

1316
// calculateSubBatchSize is a helper function that calculates the size to break
1317
// down the batchSize into.
1318
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1319
        minimumBatchSize, batchSize int) int {
16✔
1320
        if subBatchDelay > totalDelay {
18✔
1321
                return batchSize
2✔
1322
        }
2✔
1323

1324
        subBatchSize := (batchSize*int(subBatchDelay) +
14✔
1325
                int(totalDelay) - 1) / int(totalDelay)
14✔
1326

14✔
1327
        if subBatchSize < minimumBatchSize {
18✔
1328
                return minimumBatchSize
4✔
1329
        }
4✔
1330

1331
        return subBatchSize
10✔
1332
}
1333

1334
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1335
// this variable so the function can be mocked in our test.
1336
var batchSizeCalculator = calculateSubBatchSize
1337

1338
// splitAnnouncementBatches takes an exiting list of announcements and
1339
// decomposes it into sub batches controlled by the `subBatchSize`.
1340
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1341
        announcementBatch []msgWithSenders) [][]msgWithSenders {
78✔
1342

78✔
1343
        subBatchSize := batchSizeCalculator(
78✔
1344
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
78✔
1345
                d.cfg.MinimumBatchSize, len(announcementBatch),
78✔
1346
        )
78✔
1347

78✔
1348
        var splitAnnouncementBatch [][]msgWithSenders
78✔
1349

78✔
1350
        for subBatchSize < len(announcementBatch) {
202✔
1351
                // For slicing with minimal allocation
124✔
1352
                // https://github.com/golang/go/wiki/SliceTricks
124✔
1353
                announcementBatch, splitAnnouncementBatch =
124✔
1354
                        announcementBatch[subBatchSize:],
124✔
1355
                        append(splitAnnouncementBatch,
124✔
1356
                                announcementBatch[0:subBatchSize:subBatchSize])
124✔
1357
        }
124✔
1358
        splitAnnouncementBatch = append(
78✔
1359
                splitAnnouncementBatch, announcementBatch,
78✔
1360
        )
78✔
1361

78✔
1362
        return splitAnnouncementBatch
78✔
1363
}
1364

1365
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1366
// split size, and then sends out all items to the set of target peers. Locally
1367
// generated announcements are always sent before remotely generated
1368
// announcements.
1369
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(ctx context.Context,
1370
        annBatch msgsToBroadcast) {
37✔
1371

37✔
1372
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
37✔
1373
        // duration to delay the sending of next announcement batch.
37✔
1374
        delayNextBatch := func() {
108✔
1375
                select {
71✔
1376
                case <-time.After(d.cfg.SubBatchDelay):
54✔
1377
                case <-d.quit:
17✔
1378
                        return
17✔
1379
                }
1380
        }
1381

1382
        // Fetch the local and remote announcements.
1383
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
37✔
1384
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
37✔
1385

37✔
1386
        d.wg.Add(1)
37✔
1387
        go func() {
74✔
1388
                defer d.wg.Done()
37✔
1389

37✔
1390
                log.Debugf("Broadcasting %v new local announcements in %d "+
37✔
1391
                        "sub batches", len(annBatch.localMsgs),
37✔
1392
                        len(localBatches))
37✔
1393

37✔
1394
                // Send out the local announcements first.
37✔
1395
                for _, annBatch := range localBatches {
74✔
1396
                        d.sendLocalBatch(annBatch)
37✔
1397
                        delayNextBatch()
37✔
1398
                }
37✔
1399

1400
                log.Debugf("Broadcasting %v new remote announcements in %d "+
37✔
1401
                        "sub batches", len(annBatch.remoteMsgs),
37✔
1402
                        len(remoteBatches))
37✔
1403

37✔
1404
                // Now send the remote announcements.
37✔
1405
                for _, annBatch := range remoteBatches {
74✔
1406
                        d.sendRemoteBatch(ctx, annBatch)
37✔
1407
                        delayNextBatch()
37✔
1408
                }
37✔
1409
        }()
1410
}
1411

1412
// sendLocalBatch broadcasts a list of locally generated announcements to our
1413
// peers. For local announcements, we skip the filter and dedup logic and just
1414
// send the announcements out to all our coonnected peers.
1415
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
37✔
1416
        msgsToSend := lnutils.Map(
37✔
1417
                annBatch, func(m msgWithSenders) lnwire.Message {
83✔
1418
                        return m.msg
46✔
1419
                },
46✔
1420
        )
1421

1422
        err := d.cfg.Broadcast(nil, msgsToSend...)
37✔
1423
        if err != nil {
37✔
1424
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1425
        }
×
1426
}
1427

1428
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1429
// peers.
1430
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1431
        annBatch []msgWithSenders) {
37✔
1432

37✔
1433
        syncerPeers := d.syncMgr.GossipSyncers()
37✔
1434

37✔
1435
        // We'll first attempt to filter out this new message for all peers
37✔
1436
        // that have active gossip syncers active.
37✔
1437
        for pub, syncer := range syncerPeers {
40✔
1438
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
3✔
1439
                syncer.FilterGossipMsgs(ctx, annBatch...)
3✔
1440
        }
3✔
1441

1442
        for _, msgChunk := range annBatch {
69✔
1443
                msgChunk := msgChunk
32✔
1444

32✔
1445
                // With the syncers taken care of, we'll merge the sender map
32✔
1446
                // with the set of syncers, so we don't send out duplicate
32✔
1447
                // messages.
32✔
1448
                msgChunk.mergeSyncerMap(syncerPeers)
32✔
1449

32✔
1450
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
32✔
1451
                if err != nil {
32✔
1452
                        log.Errorf("Unable to send batch "+
×
1453
                                "announcements: %v", err)
×
1454
                        continue
×
1455
                }
1456
        }
1457
}
1458

1459
// networkHandler is the primary goroutine that drives this service. The roles
1460
// of this goroutine includes answering queries related to the state of the
1461
// network, syncing up newly connected peers, and also periodically
1462
// broadcasting our latest topology state to all connected peers.
1463
//
1464
// NOTE: This MUST be run as a goroutine.
1465
func (d *AuthenticatedGossiper) networkHandler(ctx context.Context) {
33✔
1466
        defer d.wg.Done()
33✔
1467

33✔
1468
        // Initialize empty deDupedAnnouncements to store announcement batch.
33✔
1469
        announcements := deDupedAnnouncements{}
33✔
1470
        announcements.Reset()
33✔
1471

33✔
1472
        d.cfg.RetransmitTicker.Resume()
33✔
1473
        defer d.cfg.RetransmitTicker.Stop()
33✔
1474

33✔
1475
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
33✔
1476
        defer trickleTimer.Stop()
33✔
1477

33✔
1478
        // To start, we'll first check to see if there are any stale channel or
33✔
1479
        // node announcements that we need to re-transmit.
33✔
1480
        if err := d.retransmitStaleAnns(ctx, time.Now()); err != nil {
33✔
1481
                log.Errorf("Unable to rebroadcast stale announcements: %v", err)
×
1482
        }
×
1483

1484
        for {
700✔
1485
                select {
667✔
1486
                // A new policy update has arrived. We'll commit it to the
1487
                // sub-systems below us, then craft, sign, and broadcast a new
1488
                // ChannelUpdate for the set of affected clients.
1489
                case policyUpdate := <-d.chanPolicyUpdates:
4✔
1490
                        log.Tracef("Received channel %d policy update requests",
4✔
1491
                                len(policyUpdate.edgesToUpdate))
4✔
1492

4✔
1493
                        // First, we'll now create new fully signed updates for
4✔
1494
                        // the affected channels and also update the underlying
4✔
1495
                        // graph with the new state.
4✔
1496
                        newChanUpdates, err := d.processChanPolicyUpdate(
4✔
1497
                                ctx, policyUpdate.edgesToUpdate,
4✔
1498
                        )
4✔
1499
                        policyUpdate.errChan <- err
4✔
1500
                        if err != nil {
4✔
1501
                                log.Errorf("Unable to craft policy updates: %v",
×
1502
                                        err)
×
1503
                                continue
×
1504
                        }
1505

1506
                        // Finally, with the updates committed, we'll now add
1507
                        // them to the announcement batch to be flushed at the
1508
                        // start of the next epoch.
1509
                        announcements.AddMsgs(newChanUpdates...)
4✔
1510

1511
                case announcement := <-d.networkMsgs:
341✔
1512
                        log.Tracef("Received network message: "+
341✔
1513
                                "peer=%v, msg=%s, is_remote=%v",
341✔
1514
                                announcement.peer, announcement.msg.MsgType(),
341✔
1515
                                announcement.isRemote)
341✔
1516

341✔
1517
                        switch announcement.msg.(type) {
341✔
1518
                        // Channel announcement signatures are amongst the only
1519
                        // messages that we'll process serially.
1520
                        case *lnwire.AnnounceSignatures1:
24✔
1521
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
24✔
1522
                                        ctx, announcement,
24✔
1523
                                )
24✔
1524
                                log.Debugf("Processed network message %s, "+
24✔
1525
                                        "returned len(announcements)=%v",
24✔
1526
                                        announcement.msg.MsgType(),
24✔
1527
                                        len(emittedAnnouncements))
24✔
1528

24✔
1529
                                if emittedAnnouncements != nil {
37✔
1530
                                        announcements.AddMsgs(
13✔
1531
                                                emittedAnnouncements...,
13✔
1532
                                        )
13✔
1533
                                }
13✔
1534
                                continue
24✔
1535
                        }
1536

1537
                        // If this message was recently rejected, then we won't
1538
                        // attempt to re-process it.
1539
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
320✔
1540
                                announcement.msg,
320✔
1541
                                sourceToPub(announcement.source),
320✔
1542
                        ) {
321✔
1543

1✔
1544
                                announcement.err <- fmt.Errorf("recently " +
1✔
1545
                                        "rejected")
1✔
1546
                                continue
1✔
1547
                        }
1548

1549
                        // We'll set up any dependent, and wait until a free
1550
                        // slot for this job opens up, this allow us to not
1551
                        // have thousands of goroutines active.
1552
                        annJobID, err := d.vb.InitJobDependencies(
319✔
1553
                                announcement.msg,
319✔
1554
                        )
319✔
1555
                        if err != nil {
319✔
1556
                                announcement.err <- err
×
1557
                                continue
×
1558
                        }
1559

1560
                        d.wg.Add(1)
319✔
1561
                        go d.handleNetworkMessages(
319✔
1562
                                ctx, announcement, &announcements, annJobID,
319✔
1563
                        )
319✔
1564

1565
                // The trickle timer has ticked, which indicates we should
1566
                // flush to the network the pending batch of new announcements
1567
                // we've received since the last trickle tick.
1568
                case <-trickleTimer.C:
297✔
1569
                        // Emit the current batch of announcements from
297✔
1570
                        // deDupedAnnouncements.
297✔
1571
                        announcementBatch := announcements.Emit()
297✔
1572

297✔
1573
                        // If the current announcements batch is nil, then we
297✔
1574
                        // have no further work here.
297✔
1575
                        if announcementBatch.isEmpty() {
560✔
1576
                                continue
263✔
1577
                        }
1578

1579
                        // At this point, we have the set of local and remote
1580
                        // announcements we want to send out. We'll do the
1581
                        // batching as normal for both, but for local
1582
                        // announcements, we'll blast them out w/o regard for
1583
                        // our peer's policies so we ensure they propagate
1584
                        // properly.
1585
                        d.splitAndSendAnnBatch(ctx, announcementBatch)
37✔
1586

1587
                // The retransmission timer has ticked which indicates that we
1588
                // should check if we need to prune or re-broadcast any of our
1589
                // personal channels or node announcement. This addresses the
1590
                // case of "zombie" channels and channel advertisements that
1591
                // have been dropped, or not properly propagated through the
1592
                // network.
1593
                case tick := <-d.cfg.RetransmitTicker.Ticks():
1✔
1594
                        if err := d.retransmitStaleAnns(ctx, tick); err != nil {
1✔
1595
                                log.Errorf("unable to rebroadcast stale "+
×
1596
                                        "announcements: %v", err)
×
1597
                        }
×
1598

1599
                // The gossiper has been signalled to exit, to we exit our
1600
                // main loop so the wait group can be decremented.
1601
                case <-d.quit:
33✔
1602
                        return
33✔
1603
                }
1604
        }
1605
}
1606

1607
// handleNetworkMessages is responsible for waiting for dependencies for a
1608
// given network message and processing the message. Once processed, it will
1609
// signal its dependants and add the new announcements to the announce batch.
1610
//
1611
// NOTE: must be run as a goroutine.
1612
func (d *AuthenticatedGossiper) handleNetworkMessages(ctx context.Context,
1613
        nMsg *networkMsg, deDuped *deDupedAnnouncements, jobID JobID) {
319✔
1614

319✔
1615
        defer d.wg.Done()
319✔
1616
        defer d.vb.CompleteJob()
319✔
1617

319✔
1618
        // We should only broadcast this message forward if it originated from
319✔
1619
        // us or it wasn't received as part of our initial historical sync.
319✔
1620
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
319✔
1621

319✔
1622
        // If this message has an existing dependency, then we'll wait until
319✔
1623
        // that has been fully validated before we proceed.
319✔
1624
        err := d.vb.WaitForParents(jobID, nMsg.msg)
319✔
1625
        if err != nil {
319✔
1626
                log.Debugf("Validating network message %s got err: %v",
×
1627
                        nMsg.msg.MsgType(), err)
×
1628

×
1629
                if errors.Is(err, ErrVBarrierShuttingDown) {
×
1630
                        log.Warnf("unexpected error during validation "+
×
1631
                                "barrier shutdown: %v", err)
×
1632
                }
×
1633
                nMsg.err <- err
×
1634

×
1635
                return
×
1636
        }
1637

1638
        // Process the network announcement to determine if this is either a
1639
        // new announcement from our PoV or an edges to a prior vertex/edge we
1640
        // previously proceeded.
1641
        newAnns, allow := d.processNetworkAnnouncement(ctx, nMsg)
319✔
1642

319✔
1643
        log.Tracef("Processed network message %s, returned "+
319✔
1644
                "len(announcements)=%v, allowDependents=%v",
319✔
1645
                nMsg.msg.MsgType(), len(newAnns), allow)
319✔
1646

319✔
1647
        // If this message had any dependencies, then we can now signal them to
319✔
1648
        // continue.
319✔
1649
        err = d.vb.SignalDependents(nMsg.msg, jobID)
319✔
1650
        if err != nil {
319✔
1651
                // Something is wrong if SignalDependents returns an error.
×
1652
                log.Errorf("SignalDependents returned error for msg=%v with "+
×
1653
                        "JobID=%v", spew.Sdump(nMsg.msg), jobID)
×
1654

×
1655
                nMsg.err <- err
×
1656

×
1657
                return
×
1658
        }
×
1659

1660
        // If the announcement was accepted, then add the emitted announcements
1661
        // to our announce batch to be broadcast once the trickle timer ticks
1662
        // gain.
1663
        if newAnns != nil && shouldBroadcast {
359✔
1664
                // TODO(roasbeef): exclude peer that sent.
40✔
1665
                deDuped.AddMsgs(newAnns...)
40✔
1666
        } else if newAnns != nil {
326✔
1667
                log.Trace("Skipping broadcast of announcements received " +
4✔
1668
                        "during initial graph sync")
4✔
1669
        }
4✔
1670
}
1671

1672
// TODO(roasbeef): d/c peers that send updates not on our chain
1673

1674
// InitSyncState is called by outside sub-systems when a connection is
1675
// established to a new peer that understands how to perform channel range
1676
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1677
// needed to handle new queries.
1678
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
3✔
1679
        d.syncMgr.InitSyncState(syncPeer)
3✔
1680
}
3✔
1681

1682
// PruneSyncState is called by outside sub-systems once a peer that we were
1683
// previously connected to has been disconnected. In this case we can stop the
1684
// existing GossipSyncer assigned to the peer and free up resources.
1685
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
3✔
1686
        d.syncMgr.PruneSyncState(peer)
3✔
1687
}
3✔
1688

1689
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1690
// false otherwise, This avoids expensive reprocessing of the message.
1691
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1692
        peerPub [33]byte) bool {
283✔
1693

283✔
1694
        var scid uint64
283✔
1695
        switch m := msg.(type) {
283✔
1696
        case *lnwire.ChannelUpdate1:
51✔
1697
                scid = m.ShortChannelID.ToUint64()
51✔
1698

1699
        case *lnwire.ChannelAnnouncement1:
221✔
1700
                scid = m.ShortChannelID.ToUint64()
221✔
1701

1702
        default:
17✔
1703
                return false
17✔
1704
        }
1705

1706
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
269✔
1707
        return err != cache.ErrElementNotFound
269✔
1708
}
1709

1710
// retransmitStaleAnns examines all outgoing channels that the source node is
1711
// known to maintain to check to see if any of them are "stale". A channel is
1712
// stale iff, the last timestamp of its rebroadcast is older than the
1713
// RebroadcastInterval. We also check if a refreshed node announcement should
1714
// be resent.
1715
func (d *AuthenticatedGossiper) retransmitStaleAnns(ctx context.Context,
1716
        now time.Time) error {
34✔
1717

34✔
1718
        // Iterate over all of our channels and check if any of them fall
34✔
1719
        // within the prune interval or re-broadcast interval.
34✔
1720
        type updateTuple struct {
34✔
1721
                info *models.ChannelEdgeInfo
34✔
1722
                edge *models.ChannelEdgePolicy
34✔
1723
        }
34✔
1724

34✔
1725
        var (
34✔
1726
                havePublicChannels bool
34✔
1727
                edgesToUpdate      []updateTuple
34✔
1728
        )
34✔
1729
        err := d.cfg.Graph.ForAllOutgoingChannels(ctx, func(
34✔
1730
                info *models.ChannelEdgeInfo,
34✔
1731
                edge *models.ChannelEdgePolicy) error {
39✔
1732

5✔
1733
                // If there's no auth proof attached to this edge, it means
5✔
1734
                // that it is a private channel not meant to be announced to
5✔
1735
                // the greater network, so avoid sending channel updates for
5✔
1736
                // this channel to not leak its
5✔
1737
                // existence.
5✔
1738
                if info.AuthProof == nil {
9✔
1739
                        log.Debugf("Skipping retransmission of channel "+
4✔
1740
                                "without AuthProof: %v", info.ChannelID)
4✔
1741
                        return nil
4✔
1742
                }
4✔
1743

1744
                // We make a note that we have at least one public channel. We
1745
                // use this to determine whether we should send a node
1746
                // announcement below.
1747
                havePublicChannels = true
4✔
1748

4✔
1749
                // If this edge has a ChannelUpdate that was created before the
4✔
1750
                // introduction of the MaxHTLC field, then we'll update this
4✔
1751
                // edge to propagate this information in the network.
4✔
1752
                if !edge.MessageFlags.HasMaxHtlc() {
4✔
1753
                        // We'll make sure we support the new max_htlc field if
×
1754
                        // not already present.
×
1755
                        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
×
1756
                        edge.MaxHTLC = lnwire.NewMSatFromSatoshis(info.Capacity)
×
1757

×
1758
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1759
                                info: info,
×
1760
                                edge: edge,
×
1761
                        })
×
1762
                        return nil
×
1763
                }
×
1764

1765
                timeElapsed := now.Sub(edge.LastUpdate)
4✔
1766

4✔
1767
                // If it's been longer than RebroadcastInterval since we've
4✔
1768
                // re-broadcasted the channel, add the channel to the set of
4✔
1769
                // edges we need to update.
4✔
1770
                if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1771
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1772
                                info: info,
1✔
1773
                                edge: edge,
1✔
1774
                        })
1✔
1775
                }
1✔
1776

1777
                return nil
4✔
1778
        }, func() {
3✔
1779
                havePublicChannels = false
3✔
1780
                edgesToUpdate = nil
3✔
1781
        })
3✔
1782
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
34✔
1783
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1784
                        err)
×
1785
        }
×
1786

1787
        var signedUpdates []lnwire.Message
34✔
1788
        for _, chanToUpdate := range edgesToUpdate {
35✔
1789
                // Re-sign and update the channel on disk and retrieve our
1✔
1790
                // ChannelUpdate to broadcast.
1✔
1791
                chanAnn, chanUpdate, err := d.updateChannel(
1✔
1792
                        ctx, chanToUpdate.info, chanToUpdate.edge,
1✔
1793
                )
1✔
1794
                if err != nil {
1✔
1795
                        return fmt.Errorf("unable to update channel: %w", err)
×
1796
                }
×
1797

1798
                // If we have a valid announcement to transmit, then we'll send
1799
                // that along with the update.
1800
                if chanAnn != nil {
2✔
1801
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1802
                }
1✔
1803

1804
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1805
        }
1806

1807
        // If we don't have any public channels, we return as we don't want to
1808
        // broadcast anything that would reveal our existence.
1809
        if !havePublicChannels {
67✔
1810
                return nil
33✔
1811
        }
33✔
1812

1813
        // We'll also check that our NodeAnnouncement is not too old.
1814
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
4✔
1815
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
4✔
1816
        timeElapsed := now.Sub(timestamp)
4✔
1817

4✔
1818
        // If it's been a full day since we've re-broadcasted the
4✔
1819
        // node announcement, refresh it and resend it.
4✔
1820
        nodeAnnStr := ""
4✔
1821
        if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1822
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
1✔
1823
                if err != nil {
1✔
1824
                        return fmt.Errorf("unable to get refreshed node "+
×
1825
                                "announcement: %v", err)
×
1826
                }
×
1827

1828
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1829
                nodeAnnStr = " and our refreshed node announcement"
1✔
1830

1✔
1831
                // Before broadcasting the refreshed node announcement, add it
1✔
1832
                // to our own graph.
1✔
1833
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
2✔
1834
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1835
                                "to graph: %v", err)
1✔
1836
                }
1✔
1837
        }
1838

1839
        // If we don't have any updates to re-broadcast, then we'll exit
1840
        // early.
1841
        if len(signedUpdates) == 0 {
7✔
1842
                return nil
3✔
1843
        }
3✔
1844

1845
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1846
                len(edgesToUpdate), nodeAnnStr)
1✔
1847

1✔
1848
        // With all the wire announcements properly crafted, we'll broadcast
1✔
1849
        // our known outgoing channels to all our immediate peers.
1✔
1850
        if err := d.cfg.Broadcast(nil, signedUpdates...); err != nil {
1✔
1851
                return fmt.Errorf("unable to re-broadcast channels: %w", err)
×
1852
        }
×
1853

1854
        return nil
1✔
1855
}
1856

1857
// processChanPolicyUpdate generates a new set of channel updates for the
1858
// provided list of edges and updates the backing ChannelGraphSource.
1859
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1860
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
4✔
1861

4✔
1862
        var chanUpdates []networkMsg
4✔
1863
        for _, edgeInfo := range edgesToUpdate {
10✔
1864
                // Now that we've collected all the channels we need to update,
6✔
1865
                // we'll re-sign and update the backing ChannelGraphSource, and
6✔
1866
                // retrieve our ChannelUpdate to broadcast.
6✔
1867
                _, chanUpdate, err := d.updateChannel(
6✔
1868
                        ctx, edgeInfo.Info, edgeInfo.Edge,
6✔
1869
                )
6✔
1870
                if err != nil {
6✔
1871
                        return nil, err
×
1872
                }
×
1873

1874
                // We'll avoid broadcasting any updates for private channels to
1875
                // avoid directly giving away their existence. Instead, we'll
1876
                // send the update directly to the remote party.
1877
                if edgeInfo.Info.AuthProof == nil {
10✔
1878
                        // If AuthProof is nil and an alias was found for this
4✔
1879
                        // ChannelID (meaning the option-scid-alias feature was
4✔
1880
                        // negotiated), we'll replace the ShortChannelID in the
4✔
1881
                        // update with the peer's alias. We do this after
4✔
1882
                        // updateChannel so that the alias isn't persisted to
4✔
1883
                        // the database.
4✔
1884
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1885
                                edgeInfo.Info.ChannelPoint,
4✔
1886
                        )
4✔
1887

4✔
1888
                        var defaultAlias lnwire.ShortChannelID
4✔
1889
                        foundAlias, _ := d.cfg.GetAlias(chanID)
4✔
1890
                        if foundAlias != defaultAlias {
7✔
1891
                                chanUpdate.ShortChannelID = foundAlias
3✔
1892

3✔
1893
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
3✔
1894
                                if err != nil {
3✔
1895
                                        log.Errorf("Unable to sign alias "+
×
1896
                                                "update: %v", err)
×
1897
                                        continue
×
1898
                                }
1899

1900
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1901
                                if err != nil {
3✔
1902
                                        log.Errorf("Unable to create sig: %v",
×
1903
                                                err)
×
1904
                                        continue
×
1905
                                }
1906

1907
                                chanUpdate.Signature = lnSig
3✔
1908
                        }
1909

1910
                        remotePubKey := remotePubFromChanInfo(
4✔
1911
                                edgeInfo.Info, chanUpdate.ChannelFlags,
4✔
1912
                        )
4✔
1913
                        err := d.reliableSender.sendMessage(
4✔
1914
                                ctx, chanUpdate, remotePubKey,
4✔
1915
                        )
4✔
1916
                        if err != nil {
4✔
1917
                                log.Errorf("Unable to reliably send %v for "+
×
1918
                                        "channel=%v to peer=%x: %v",
×
1919
                                        chanUpdate.MsgType(),
×
1920
                                        chanUpdate.ShortChannelID,
×
1921
                                        remotePubKey, err)
×
1922
                        }
×
1923
                        continue
4✔
1924
                }
1925

1926
                // We set ourselves as the source of this message to indicate
1927
                // that we shouldn't skip any peers when sending this message.
1928
                chanUpdates = append(chanUpdates, networkMsg{
5✔
1929
                        source:   d.selfKey,
5✔
1930
                        isRemote: false,
5✔
1931
                        msg:      chanUpdate,
5✔
1932
                })
5✔
1933
        }
1934

1935
        return chanUpdates, nil
4✔
1936
}
1937

1938
// remotePubFromChanInfo returns the public key of the remote peer given a
1939
// ChannelEdgeInfo that describe a channel we have with them.
1940
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1941
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
15✔
1942

15✔
1943
        var remotePubKey [33]byte
15✔
1944
        switch {
15✔
1945
        case chanFlags&lnwire.ChanUpdateDirection == 0:
15✔
1946
                remotePubKey = chanInfo.NodeKey2Bytes
15✔
1947
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1948
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1949
        }
1950

1951
        return remotePubKey
15✔
1952
}
1953

1954
// processRejectedEdge examines a rejected edge to see if we can extract any
1955
// new announcements from it.  An edge will get rejected if we already added
1956
// the same edge without AuthProof to the graph. If the received announcement
1957
// contains a proof, we can add this proof to our edge.  We can end up in this
1958
// situation in the case where we create a channel, but for some reason fail
1959
// to receive the remote peer's proof, while the remote peer is able to fully
1960
// assemble the proof and craft the ChannelAnnouncement.
1961
func (d *AuthenticatedGossiper) processRejectedEdge(_ context.Context,
1962
        chanAnnMsg *lnwire.ChannelAnnouncement1,
1963
        proof *models.ChannelAuthProof) ([]networkMsg, error) {
3✔
1964

3✔
1965
        // First, we'll fetch the state of the channel as we know if from the
3✔
1966
        // database.
3✔
1967
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
1968
                chanAnnMsg.ShortChannelID,
3✔
1969
        )
3✔
1970
        if err != nil {
3✔
1971
                return nil, err
×
1972
        }
×
1973

1974
        // The edge is in the graph, and has a proof attached, then we'll just
1975
        // reject it as normal.
1976
        if chanInfo.AuthProof != nil {
6✔
1977
                return nil, nil
3✔
1978
        }
3✔
1979

1980
        // Otherwise, this means that the edge is within the graph, but it
1981
        // doesn't yet have a proper proof attached. If we did not receive
1982
        // the proof such that we now can add it, there's nothing more we
1983
        // can do.
1984
        if proof == nil {
×
1985
                return nil, nil
×
1986
        }
×
1987

1988
        // We'll then create then validate the new fully assembled
1989
        // announcement.
1990
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
×
1991
                proof, chanInfo, e1, e2,
×
1992
        )
×
1993
        if err != nil {
×
1994
                return nil, err
×
1995
        }
×
1996
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
×
1997
        if err != nil {
×
1998
                err := fmt.Errorf("assembled channel announcement proof "+
×
1999
                        "for shortChanID=%v isn't valid: %v",
×
2000
                        chanAnnMsg.ShortChannelID, err)
×
2001
                log.Error(err)
×
2002
                return nil, err
×
2003
        }
×
2004

2005
        // If everything checks out, then we'll add the fully assembled proof
2006
        // to the database.
2007
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
2008
        if err != nil {
×
2009
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
2010
                        chanAnnMsg.ShortChannelID, err)
×
2011
                log.Error(err)
×
2012
                return nil, err
×
2013
        }
×
2014

2015
        // As we now have a complete channel announcement for this channel,
2016
        // we'll construct the announcement so they can be broadcast out to all
2017
        // our peers.
2018
        announcements := make([]networkMsg, 0, 3)
×
2019
        announcements = append(announcements, networkMsg{
×
2020
                source: d.selfKey,
×
2021
                msg:    chanAnn,
×
2022
        })
×
2023
        if e1Ann != nil {
×
2024
                announcements = append(announcements, networkMsg{
×
2025
                        source: d.selfKey,
×
2026
                        msg:    e1Ann,
×
2027
                })
×
2028
        }
×
2029
        if e2Ann != nil {
×
2030
                announcements = append(announcements, networkMsg{
×
2031
                        source: d.selfKey,
×
2032
                        msg:    e2Ann,
×
2033
                })
×
2034

×
2035
        }
×
2036

2037
        return announcements, nil
×
2038
}
2039

2040
// fetchPKScript fetches the output script for the given SCID.
2041
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2042
        []byte, error) {
×
2043

×
2044
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2045
}
×
2046

2047
// addNode processes the given node announcement, and adds it to our channel
2048
// graph.
2049
func (d *AuthenticatedGossiper) addNode(ctx context.Context,
2050
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
20✔
2051

20✔
2052
        if err := netann.ValidateNodeAnn(msg); err != nil {
21✔
2053
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
2054
                        err)
1✔
2055
        }
1✔
2056

2057
        return d.cfg.Graph.AddNode(
19✔
2058
                ctx, models.NodeFromWireAnnouncement(msg), op...,
19✔
2059
        )
19✔
2060
}
2061

2062
// isPremature decides whether a given network message has a block height+delta
2063
// value specified in the future. If so, the message will be added to the
2064
// future message map and be processed when the block height as reached.
2065
//
2066
// NOTE: must be used inside a lock.
2067
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2068
        delta uint32, msg *networkMsg) bool {
292✔
2069

292✔
2070
        // The channel is already confirmed at chanID.BlockHeight so we minus
292✔
2071
        // one block. For instance, if the required confirmation for this
292✔
2072
        // channel announcement is 6, we then only need to wait for 5 more
292✔
2073
        // blocks once the funding tx is confirmed.
292✔
2074
        if delta > 0 {
295✔
2075
                delta--
3✔
2076
        }
3✔
2077

2078
        msgHeight := chanID.BlockHeight + delta
292✔
2079

292✔
2080
        // The message height is smaller or equal to our best known height,
292✔
2081
        // thus the message is mature.
292✔
2082
        if msgHeight <= d.bestHeight {
583✔
2083
                return false
291✔
2084
        }
291✔
2085

2086
        // Add the premature message to our future messages which will be
2087
        // resent once the block height has reached.
2088
        //
2089
        // Copy the networkMsgs since the old message's err chan will be
2090
        // consumed.
2091
        copied := &networkMsg{
4✔
2092
                peer:              msg.peer,
4✔
2093
                source:            msg.source,
4✔
2094
                msg:               msg.msg,
4✔
2095
                optionalMsgFields: msg.optionalMsgFields,
4✔
2096
                isRemote:          msg.isRemote,
4✔
2097
                err:               make(chan error, 1),
4✔
2098
        }
4✔
2099

4✔
2100
        // Create the cached message.
4✔
2101
        cachedMsg := &cachedFutureMsg{
4✔
2102
                msg:    copied,
4✔
2103
                height: msgHeight,
4✔
2104
        }
4✔
2105

4✔
2106
        // Increment the msg ID and add it to the cache.
4✔
2107
        nextMsgID := d.futureMsgs.nextMsgID()
4✔
2108
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
4✔
2109
        if err != nil {
4✔
2110
                log.Errorf("Adding future message got error: %v", err)
×
2111
        }
×
2112

2113
        log.Debugf("Network message: %v added to future messages for "+
4✔
2114
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
4✔
2115
                msgHeight, d.bestHeight)
4✔
2116

4✔
2117
        return true
4✔
2118
}
2119

2120
// processNetworkAnnouncement processes a new network relate authenticated
2121
// channel or node announcement or announcements proofs. If the announcement
2122
// didn't affect the internal state due to either being out of date, invalid,
2123
// or redundant, then nil is returned. Otherwise, the set of announcements will
2124
// be returned which should be broadcasted to the rest of the network. The
2125
// boolean returned indicates whether any dependents of the announcement should
2126
// attempt to be processed as well.
2127
func (d *AuthenticatedGossiper) processNetworkAnnouncement(ctx context.Context,
2128
        nMsg *networkMsg) ([]networkMsg, bool) {
340✔
2129

340✔
2130
        // If this is a remote update, we set the scheduler option to lazily
340✔
2131
        // add it to the graph.
340✔
2132
        var schedulerOp []batch.SchedulerOption
340✔
2133
        if nMsg.isRemote {
633✔
2134
                schedulerOp = append(schedulerOp, batch.LazyAdd())
293✔
2135
        }
293✔
2136

2137
        switch msg := nMsg.msg.(type) {
340✔
2138
        // A new node announcement has arrived which either presents new
2139
        // information about a node in one of the channels we know about, or a
2140
        // updating previously advertised information.
2141
        case *lnwire.NodeAnnouncement:
27✔
2142
                return d.handleNodeAnnouncement(ctx, nMsg, msg, schedulerOp)
27✔
2143

2144
        // A new channel announcement has arrived, this indicates the
2145
        // *creation* of a new channel within the network. This only advertises
2146
        // the existence of a channel and not yet the routing policies in
2147
        // either direction of the channel.
2148
        case *lnwire.ChannelAnnouncement1:
234✔
2149
                return d.handleChanAnnouncement(ctx, nMsg, msg, schedulerOp...)
234✔
2150

2151
        // A new authenticated channel edge update has arrived. This indicates
2152
        // that the directional information for an already known channel has
2153
        // been updated.
2154
        case *lnwire.ChannelUpdate1:
64✔
2155
                return d.handleChanUpdate(ctx, nMsg, msg, schedulerOp)
64✔
2156

2157
        // A new signature announcement has been received. This indicates
2158
        // willingness of nodes involved in the funding of a channel to
2159
        // announce this new channel to the rest of the world.
2160
        case *lnwire.AnnounceSignatures1:
24✔
2161
                return d.handleAnnSig(ctx, nMsg, msg)
24✔
2162

2163
        default:
×
2164
                err := errors.New("wrong type of the announcement")
×
2165
                nMsg.err <- err
×
2166
                return nil, false
×
2167
        }
2168
}
2169

2170
// processZombieUpdate determines whether the provided channel update should
2171
// resurrect a given zombie edge.
2172
//
2173
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2174
// should be inspected.
2175
func (d *AuthenticatedGossiper) processZombieUpdate(_ context.Context,
2176
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2177
        msg *lnwire.ChannelUpdate1) error {
3✔
2178

3✔
2179
        // The least-significant bit in the flag on the channel update tells us
3✔
2180
        // which edge is being updated.
3✔
2181
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2182

3✔
2183
        // Since we've deemed the update as not stale above, before marking it
3✔
2184
        // live, we'll make sure it has been signed by the correct party. If we
3✔
2185
        // have both pubkeys, either party can resurrect the channel. If we've
3✔
2186
        // already marked this with the stricter, single-sided resurrection we
3✔
2187
        // will only have the pubkey of the node with the oldest timestamp.
3✔
2188
        var pubKey *btcec.PublicKey
3✔
2189
        switch {
3✔
2190
        case isNode1 && chanInfo.NodeKey1Bytes != emptyPubkey:
×
2191
                pubKey, _ = chanInfo.NodeKey1()
×
2192
        case !isNode1 && chanInfo.NodeKey2Bytes != emptyPubkey:
2✔
2193
                pubKey, _ = chanInfo.NodeKey2()
2✔
2194
        }
2195
        if pubKey == nil {
4✔
2196
                return fmt.Errorf("incorrect pubkey to resurrect zombie "+
1✔
2197
                        "with chan_id=%v", msg.ShortChannelID)
1✔
2198
        }
1✔
2199

2200
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2201
        if err != nil {
3✔
2202
                return fmt.Errorf("unable to verify channel "+
1✔
2203
                        "update signature: %v", err)
1✔
2204
        }
1✔
2205

2206
        // With the signature valid, we'll proceed to mark the
2207
        // edge as live and wait for the channel announcement to
2208
        // come through again.
2209
        err = d.cfg.Graph.MarkEdgeLive(scid)
1✔
2210
        switch {
1✔
2211
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2212
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2213
                        "zombie index: %v", err)
×
2214

×
2215
                return nil
×
2216

2217
        case err != nil:
×
2218
                return fmt.Errorf("unable to remove edge with "+
×
2219
                        "chan_id=%v from zombie index: %v",
×
2220
                        msg.ShortChannelID, err)
×
2221

2222
        default:
1✔
2223
        }
2224

2225
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2226
                "index", msg.ShortChannelID)
1✔
2227

1✔
2228
        return nil
1✔
2229
}
2230

2231
// fetchNodeAnn fetches the latest signed node announcement from our point of
2232
// view for the node with the given public key.
2233
func (d *AuthenticatedGossiper) fetchNodeAnn(ctx context.Context,
2234
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
23✔
2235

23✔
2236
        node, err := d.cfg.Graph.FetchLightningNode(ctx, pubKey)
23✔
2237
        if err != nil {
29✔
2238
                return nil, err
6✔
2239
        }
6✔
2240

2241
        return node.NodeAnnouncement(true)
17✔
2242
}
2243

2244
// isMsgStale determines whether a message retrieved from the backing
2245
// MessageStore is seen as stale by the current graph.
2246
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2247
        msg lnwire.Message) bool {
15✔
2248

15✔
2249
        switch msg := msg.(type) {
15✔
2250
        case *lnwire.AnnounceSignatures1:
5✔
2251
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
5✔
2252
                        msg.ShortChannelID,
5✔
2253
                )
5✔
2254

5✔
2255
                // If the channel cannot be found, it is most likely a leftover
5✔
2256
                // message for a channel that was closed, so we can consider it
5✔
2257
                // stale.
5✔
2258
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
8✔
2259
                        return true
3✔
2260
                }
3✔
2261
                if err != nil {
5✔
2262
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2263
                                "%v", msg.ShortChannelID, err)
×
2264
                        return false
×
2265
                }
×
2266

2267
                // If the proof exists in the graph, then we have successfully
2268
                // received the remote proof and assembled the full proof, so we
2269
                // can safely delete the local proof from the database.
2270
                return chanInfo.AuthProof != nil
5✔
2271

2272
        case *lnwire.ChannelUpdate1:
13✔
2273
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
13✔
2274

13✔
2275
                // If the channel cannot be found, it is most likely a leftover
13✔
2276
                // message for a channel that was closed, so we can consider it
13✔
2277
                // stale.
13✔
2278
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
16✔
2279
                        return true
3✔
2280
                }
3✔
2281
                if err != nil {
13✔
2282
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2283
                                "%v", msg.ShortChannelID, err)
×
2284
                        return false
×
2285
                }
×
2286

2287
                // Otherwise, we'll retrieve the correct policy that we
2288
                // currently have stored within our graph to check if this
2289
                // message is stale by comparing its timestamp.
2290
                var p *models.ChannelEdgePolicy
13✔
2291
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
26✔
2292
                        p = p1
13✔
2293
                } else {
16✔
2294
                        p = p2
3✔
2295
                }
3✔
2296

2297
                // If the policy is still unknown, then we can consider this
2298
                // policy fresh.
2299
                if p == nil {
13✔
2300
                        return false
×
2301
                }
×
2302

2303
                timestamp := time.Unix(int64(msg.Timestamp), 0)
13✔
2304
                return p.LastUpdate.After(timestamp)
13✔
2305

2306
        default:
×
2307
                // We'll make sure to not mark any unsupported messages as stale
×
2308
                // to ensure they are not removed.
×
2309
                return false
×
2310
        }
2311
}
2312

2313
// updateChannel creates a new fully signed update for the channel, and updates
2314
// the underlying graph with the new state.
2315
func (d *AuthenticatedGossiper) updateChannel(ctx context.Context,
2316
        info *models.ChannelEdgeInfo,
2317
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2318
        *lnwire.ChannelUpdate1, error) {
7✔
2319

7✔
2320
        // Parse the unsigned edge into a channel update.
7✔
2321
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
7✔
2322

7✔
2323
        // We'll generate a new signature over a digest of the channel
7✔
2324
        // announcement itself and update the timestamp to ensure it propagate.
7✔
2325
        err := netann.SignChannelUpdate(
7✔
2326
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
7✔
2327
                netann.ChanUpdSetTimestamp,
7✔
2328
        )
7✔
2329
        if err != nil {
7✔
2330
                return nil, nil, err
×
2331
        }
×
2332

2333
        // Next, we'll set the new signature in place, and update the reference
2334
        // in the backing slice.
2335
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
7✔
2336
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
7✔
2337

7✔
2338
        // To ensure that our signature is valid, we'll verify it ourself
7✔
2339
        // before committing it to the slice returned.
7✔
2340
        err = netann.ValidateChannelUpdateAnn(
7✔
2341
                d.selfKey, info.Capacity, chanUpdate,
7✔
2342
        )
7✔
2343
        if err != nil {
7✔
2344
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2345
                        "update sig: %v", err)
×
2346
        }
×
2347

2348
        // Finally, we'll write the new edge policy to disk.
2349
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
7✔
2350
                return nil, nil, err
×
2351
        }
×
2352

2353
        // We'll also create the original channel announcement so the two can
2354
        // be broadcast along side each other (if necessary), but only if we
2355
        // have a full channel announcement for this channel.
2356
        var chanAnn *lnwire.ChannelAnnouncement1
7✔
2357
        if info.AuthProof != nil {
13✔
2358
                chanID := lnwire.NewShortChanIDFromInt(info.ChannelID)
6✔
2359
                chanAnn = &lnwire.ChannelAnnouncement1{
6✔
2360
                        ShortChannelID:  chanID,
6✔
2361
                        NodeID1:         info.NodeKey1Bytes,
6✔
2362
                        NodeID2:         info.NodeKey2Bytes,
6✔
2363
                        ChainHash:       info.ChainHash,
6✔
2364
                        BitcoinKey1:     info.BitcoinKey1Bytes,
6✔
2365
                        Features:        lnwire.NewRawFeatureVector(),
6✔
2366
                        BitcoinKey2:     info.BitcoinKey2Bytes,
6✔
2367
                        ExtraOpaqueData: info.ExtraOpaqueData,
6✔
2368
                }
6✔
2369
                chanAnn.NodeSig1, err = lnwire.NewSigFromECDSARawSignature(
6✔
2370
                        info.AuthProof.NodeSig1Bytes,
6✔
2371
                )
6✔
2372
                if err != nil {
6✔
2373
                        return nil, nil, err
×
2374
                }
×
2375
                chanAnn.NodeSig2, err = lnwire.NewSigFromECDSARawSignature(
6✔
2376
                        info.AuthProof.NodeSig2Bytes,
6✔
2377
                )
6✔
2378
                if err != nil {
6✔
2379
                        return nil, nil, err
×
2380
                }
×
2381
                chanAnn.BitcoinSig1, err = lnwire.NewSigFromECDSARawSignature(
6✔
2382
                        info.AuthProof.BitcoinSig1Bytes,
6✔
2383
                )
6✔
2384
                if err != nil {
6✔
2385
                        return nil, nil, err
×
2386
                }
×
2387
                chanAnn.BitcoinSig2, err = lnwire.NewSigFromECDSARawSignature(
6✔
2388
                        info.AuthProof.BitcoinSig2Bytes,
6✔
2389
                )
6✔
2390
                if err != nil {
6✔
2391
                        return nil, nil, err
×
2392
                }
×
2393
        }
2394

2395
        return chanAnn, chanUpdate, err
7✔
2396
}
2397

2398
// SyncManager returns the gossiper's SyncManager instance.
2399
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2400
        return d.syncMgr
3✔
2401
}
3✔
2402

2403
// IsKeepAliveUpdate determines whether this channel update is considered a
2404
// keep-alive update based on the previous channel update processed for the same
2405
// direction.
2406
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2407
        prev *models.ChannelEdgePolicy) bool {
20✔
2408

20✔
2409
        // Both updates should be from the same direction.
20✔
2410
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
20✔
2411
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
20✔
2412

×
2413
                return false
×
2414
        }
×
2415

2416
        // The timestamp should always increase for a keep-alive update.
2417
        timestamp := time.Unix(int64(update.Timestamp), 0)
20✔
2418
        if !timestamp.After(prev.LastUpdate) {
20✔
2419
                return false
×
2420
        }
×
2421

2422
        // None of the remaining fields should change for a keep-alive update.
2423
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
23✔
2424
                return false
3✔
2425
        }
3✔
2426
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
38✔
2427
                return false
18✔
2428
        }
18✔
2429
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
8✔
2430
                return false
3✔
2431
        }
3✔
2432
        if update.TimeLockDelta != prev.TimeLockDelta {
5✔
2433
                return false
×
2434
        }
×
2435
        if update.HtlcMinimumMsat != prev.MinHTLC {
5✔
2436
                return false
×
2437
        }
×
2438
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
5✔
2439
                return false
×
2440
        }
×
2441
        if update.HtlcMaximumMsat != prev.MaxHTLC {
5✔
2442
                return false
×
2443
        }
×
2444
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
8✔
2445
                return false
3✔
2446
        }
3✔
2447
        return true
5✔
2448
}
2449

2450
// latestHeight returns the gossiper's latest height known of the chain.
2451
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2452
        d.Lock()
3✔
2453
        defer d.Unlock()
3✔
2454
        return d.bestHeight
3✔
2455
}
3✔
2456

2457
// handleNodeAnnouncement processes a new node announcement.
2458
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2459
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2460
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
27✔
2461

27✔
2462
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
27✔
2463

27✔
2464
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
27✔
2465
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
27✔
2466
                nMsg.source.SerializeCompressed())
27✔
2467

27✔
2468
        // We'll quickly ask the router if it already has a newer update for
27✔
2469
        // this node so we can skip validating signatures if not required.
27✔
2470
        if d.cfg.Graph.IsStaleNode(ctx, nodeAnn.NodeID, timestamp) {
38✔
2471
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
11✔
2472
                nMsg.err <- nil
11✔
2473
                return nil, true
11✔
2474
        }
11✔
2475

2476
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
22✔
2477
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2478
                        err)
3✔
2479

3✔
2480
                if !graph.IsError(
3✔
2481
                        err,
3✔
2482
                        graph.ErrOutdated,
3✔
2483
                        graph.ErrIgnored,
3✔
2484
                ) {
3✔
2485

×
2486
                        log.Error(err)
×
2487
                }
×
2488

2489
                nMsg.err <- err
3✔
2490
                return nil, false
3✔
2491
        }
2492

2493
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2494
        // quick check to ensure this node intends to publicly advertise itself
2495
        // to the network.
2496
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
19✔
2497
        if err != nil {
19✔
2498
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2499
                        nodeAnn.NodeID, err)
×
2500
                nMsg.err <- err
×
2501
                return nil, false
×
2502
        }
×
2503

2504
        var announcements []networkMsg
19✔
2505

19✔
2506
        // If it does, we'll add their announcement to our batch so that it can
19✔
2507
        // be broadcast to the rest of our peers.
19✔
2508
        if isPublic {
25✔
2509
                announcements = append(announcements, networkMsg{
6✔
2510
                        peer:     nMsg.peer,
6✔
2511
                        isRemote: nMsg.isRemote,
6✔
2512
                        source:   nMsg.source,
6✔
2513
                        msg:      nodeAnn,
6✔
2514
                })
6✔
2515
        } else {
22✔
2516
                log.Tracef("Skipping broadcasting node announcement for %x "+
16✔
2517
                        "due to being unadvertised", nodeAnn.NodeID)
16✔
2518
        }
16✔
2519

2520
        nMsg.err <- nil
19✔
2521
        // TODO(roasbeef): get rid of the above
19✔
2522

19✔
2523
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
19✔
2524
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
19✔
2525
                nMsg.source.SerializeCompressed())
19✔
2526

19✔
2527
        return announcements, true
19✔
2528
}
2529

2530
// handleChanAnnouncement processes a new channel announcement.
2531
//
2532
//nolint:funlen
2533
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2534
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2535
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
237✔
2536

237✔
2537
        scid := ann.ShortChannelID
237✔
2538

237✔
2539
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
237✔
2540
                nMsg.peer, scid.ToUint64())
237✔
2541

237✔
2542
        // We'll ignore any channel announcements that target any chain other
237✔
2543
        // than the set of chains we know of.
237✔
2544
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
237✔
2545
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2546
                        ", gossiper on chain=%v", ann.ChainHash,
×
2547
                        d.cfg.ChainHash)
×
2548
                log.Errorf(err.Error())
×
2549

×
2550
                key := newRejectCacheKey(
×
2551
                        scid.ToUint64(),
×
2552
                        sourceToPub(nMsg.source),
×
2553
                )
×
2554
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2555

×
2556
                nMsg.err <- err
×
2557
                return nil, false
×
2558
        }
×
2559

2560
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2561
        // reject the announcement. Since the router accepts alias SCIDs,
2562
        // not erroring out would be a DoS vector.
2563
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
237✔
2564
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2565
                log.Errorf(err.Error())
×
2566

×
2567
                key := newRejectCacheKey(
×
2568
                        scid.ToUint64(),
×
2569
                        sourceToPub(nMsg.source),
×
2570
                )
×
2571
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2572

×
2573
                nMsg.err <- err
×
2574
                return nil, false
×
2575
        }
×
2576

2577
        // If the advertised inclusionary block is beyond our knowledge of the
2578
        // chain tip, then we'll ignore it for now.
2579
        d.Lock()
237✔
2580
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
238✔
2581
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2582
                        "advertises height %v, only height %v is known",
1✔
2583
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2584
                d.Unlock()
1✔
2585
                nMsg.err <- nil
1✔
2586
                return nil, false
1✔
2587
        }
1✔
2588
        d.Unlock()
236✔
2589

236✔
2590
        // At this point, we'll now ask the router if this is a zombie/known
236✔
2591
        // edge. If so we can skip all the processing below.
236✔
2592
        if d.cfg.Graph.IsKnownEdge(scid) {
240✔
2593
                nMsg.err <- nil
4✔
2594
                return nil, true
4✔
2595
        }
4✔
2596

2597
        // Check if the channel is already closed in which case we can ignore
2598
        // it.
2599
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
235✔
2600
        if err != nil {
235✔
2601
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2602
                        err)
×
2603
                nMsg.err <- err
×
2604

×
2605
                return nil, false
×
2606
        }
×
2607

2608
        if closed {
236✔
2609
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2610

1✔
2611
                // If this is an announcement from us, we'll just ignore it.
1✔
2612
                if !nMsg.isRemote {
1✔
2613
                        nMsg.err <- err
×
2614
                        return nil, false
×
2615
                }
×
2616

2617
                log.Warnf("Increasing ban score for peer=%v due to outdated "+
1✔
2618
                        "channel announcement for channel %v", nMsg.peer, scid)
1✔
2619

1✔
2620
                // Increment the peer's ban score if they are sending closed
1✔
2621
                // channel announcements.
1✔
2622
                dcErr := d.handleBadPeer(nMsg.peer)
1✔
2623
                if dcErr != nil {
1✔
2624
                        err = dcErr
×
2625
                }
×
2626

2627
                nMsg.err <- err
1✔
2628

1✔
2629
                return nil, false
1✔
2630
        }
2631

2632
        // If this is a remote channel announcement, then we'll validate all
2633
        // the signatures within the proof as it should be well formed.
2634
        var proof *models.ChannelAuthProof
234✔
2635
        if nMsg.isRemote {
454✔
2636
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
220✔
2637
                if err != nil {
220✔
2638
                        err := fmt.Errorf("unable to validate announcement: "+
×
2639
                                "%v", err)
×
2640

×
2641
                        key := newRejectCacheKey(
×
2642
                                scid.ToUint64(),
×
2643
                                sourceToPub(nMsg.source),
×
2644
                        )
×
2645
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2646

×
2647
                        log.Error(err)
×
2648
                        nMsg.err <- err
×
2649
                        return nil, false
×
2650
                }
×
2651

2652
                // If the proof checks out, then we'll save the proof itself to
2653
                // the database so we can fetch it later when gossiping with
2654
                // other nodes.
2655
                proof = &models.ChannelAuthProof{
220✔
2656
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
220✔
2657
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
220✔
2658
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
220✔
2659
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
220✔
2660
                }
220✔
2661
        }
2662

2663
        // With the proof validated (if necessary), we can now store it within
2664
        // the database for our path finding and syncing needs.
2665
        edge := &models.ChannelEdgeInfo{
234✔
2666
                ChannelID:        scid.ToUint64(),
234✔
2667
                ChainHash:        ann.ChainHash,
234✔
2668
                NodeKey1Bytes:    ann.NodeID1,
234✔
2669
                NodeKey2Bytes:    ann.NodeID2,
234✔
2670
                BitcoinKey1Bytes: ann.BitcoinKey1,
234✔
2671
                BitcoinKey2Bytes: ann.BitcoinKey2,
234✔
2672
                AuthProof:        proof,
234✔
2673
                Features: lnwire.NewFeatureVector(
234✔
2674
                        ann.Features, lnwire.Features,
234✔
2675
                ),
234✔
2676
                ExtraOpaqueData: ann.ExtraOpaqueData,
234✔
2677
        }
234✔
2678

234✔
2679
        // If there were any optional message fields provided, we'll include
234✔
2680
        // them in its serialized disk representation now.
234✔
2681
        var tapscriptRoot fn.Option[chainhash.Hash]
234✔
2682
        if nMsg.optionalMsgFields != nil {
251✔
2683
                if nMsg.optionalMsgFields.capacity != nil {
21✔
2684
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
4✔
2685
                }
4✔
2686
                if nMsg.optionalMsgFields.channelPoint != nil {
24✔
2687
                        cp := *nMsg.optionalMsgFields.channelPoint
7✔
2688
                        edge.ChannelPoint = cp
7✔
2689
                }
7✔
2690

2691
                // Optional tapscript root for custom channels.
2692
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
17✔
2693
        }
2694

2695
        // Before we start validation or add the edge to the database, we obtain
2696
        // the mutex for this channel ID. We do this to ensure no other
2697
        // goroutine has read the database and is now making decisions based on
2698
        // this DB state, before it writes to the DB. It also ensures that we
2699
        // don't perform the expensive validation check on the same channel
2700
        // announcement at the same time.
2701
        d.channelMtx.Lock(scid.ToUint64())
234✔
2702

234✔
2703
        // If AssumeChannelValid is present, then we are unable to perform any
234✔
2704
        // of the expensive checks below, so we'll short-circuit our path
234✔
2705
        // straight to adding the edge to our graph. If the passed
234✔
2706
        // ShortChannelID is an alias, then we'll skip validation as it will
234✔
2707
        // not map to a legitimate tx. This is not a DoS vector as only we can
234✔
2708
        // add an alias ChannelAnnouncement from the gossiper.
234✔
2709
        if !(d.cfg.AssumeChannelValid || d.cfg.IsAlias(scid)) {
466✔
2710
                op, capacity, script, err := d.validateFundingTransaction(
232✔
2711
                        ctx, ann, tapscriptRoot,
232✔
2712
                )
232✔
2713
                if err != nil {
436✔
2714
                        defer d.channelMtx.Unlock(scid.ToUint64())
204✔
2715

204✔
2716
                        switch {
204✔
2717
                        case errors.Is(err, ErrNoFundingTransaction),
2718
                                errors.Is(err, ErrInvalidFundingOutput):
202✔
2719

202✔
2720
                                key := newRejectCacheKey(
202✔
2721
                                        scid.ToUint64(),
202✔
2722
                                        sourceToPub(nMsg.source),
202✔
2723
                                )
202✔
2724
                                _, _ = d.recentRejects.Put(
202✔
2725
                                        key, &cachedReject{},
202✔
2726
                                )
202✔
2727

2728
                        case errors.Is(err, ErrChannelSpent):
2✔
2729
                                key := newRejectCacheKey(
2✔
2730
                                        scid.ToUint64(),
2✔
2731
                                        sourceToPub(nMsg.source),
2✔
2732
                                )
2✔
2733
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
2✔
2734

2✔
2735
                                // Since this channel has already been closed,
2✔
2736
                                // we'll add it to the graph's closed channel
2✔
2737
                                // index such that we won't attempt to do
2✔
2738
                                // expensive validation checks on it again.
2✔
2739
                                // TODO: Populate the ScidCloser by using closed
2✔
2740
                                // channel notifications.
2✔
2741
                                dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
2✔
2742
                                if dbErr != nil {
2✔
2743
                                        log.Errorf("failed to mark scid(%v) "+
×
2744
                                                "as closed: %v", scid, dbErr)
×
2745

×
2746
                                        nMsg.err <- dbErr
×
2747

×
2748
                                        return nil, false
×
2749
                                }
×
2750

2751
                        default:
×
2752
                                // Otherwise, this is just a regular rejected
×
2753
                                // edge. We won't increase the ban score for the
×
2754
                                // remote peer.
×
2755
                                key := newRejectCacheKey(
×
2756
                                        scid.ToUint64(),
×
2757
                                        sourceToPub(nMsg.source),
×
2758
                                )
×
2759
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2760

×
2761
                                nMsg.err <- err
×
2762

×
2763
                                return nil, false
×
2764
                        }
2765

2766
                        if !nMsg.isRemote {
204✔
2767
                                log.Errorf("failed to add edge for local "+
×
2768
                                        "channel: %v", err)
×
2769
                                nMsg.err <- err
×
2770

×
2771
                                return nil, false
×
2772
                        }
×
2773

2774
                        log.Warnf("Increasing ban score for peer=%v due to "+
204✔
2775
                                "invalid channel announcement for channel %v",
204✔
2776
                                nMsg.peer, scid)
204✔
2777

204✔
2778
                        // Increment the peer's ban score if they are sending
204✔
2779
                        // us invalid channel announcements.
204✔
2780
                        dcErr := d.handleBadPeer(nMsg.peer)
204✔
2781
                        if dcErr != nil {
204✔
2782
                                err = dcErr
×
2783
                        }
×
2784

2785
                        nMsg.err <- err
204✔
2786

204✔
2787
                        return nil, false
204✔
2788
                }
2789

2790
                edge.FundingScript = fn.Some(script)
28✔
2791

28✔
2792
                // TODO(roasbeef): this is a hack, needs to be removed after
28✔
2793
                //  commitment fees are dynamic.
28✔
2794
                edge.Capacity = capacity
28✔
2795
                edge.ChannelPoint = op
28✔
2796
        }
2797

2798
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
30✔
2799

30✔
2800
        // We will add the edge to the channel router. If the nodes present in
30✔
2801
        // this channel are not present in the database, a partial node will be
30✔
2802
        // added to represent each node while we wait for a node announcement.
30✔
2803
        err = d.cfg.Graph.AddEdge(ctx, edge, ops...)
30✔
2804
        if err != nil {
34✔
2805
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
4✔
2806
                        scid.ToUint64(), err)
4✔
2807

4✔
2808
                defer d.channelMtx.Unlock(scid.ToUint64())
4✔
2809

4✔
2810
                // If the edge was rejected due to already being known, then it
4✔
2811
                // may be the case that this new message has a fresh channel
4✔
2812
                // proof, so we'll check.
4✔
2813
                if graph.IsError(err, graph.ErrIgnored) {
7✔
2814
                        // Attempt to process the rejected message to see if we
3✔
2815
                        // get any new announcements.
3✔
2816
                        anns, rErr := d.processRejectedEdge(ctx, ann, proof)
3✔
2817
                        if rErr != nil {
3✔
2818
                                key := newRejectCacheKey(
×
2819
                                        scid.ToUint64(),
×
2820
                                        sourceToPub(nMsg.source),
×
2821
                                )
×
2822
                                cr := &cachedReject{}
×
2823
                                _, _ = d.recentRejects.Put(key, cr)
×
2824

×
2825
                                nMsg.err <- rErr
×
2826

×
2827
                                return nil, false
×
2828
                        }
×
2829

2830
                        log.Debugf("Extracted %v announcements from rejected "+
3✔
2831
                                "msgs", len(anns))
3✔
2832

3✔
2833
                        // If while processing this rejected edge, we realized
3✔
2834
                        // there's a set of announcements we could extract,
3✔
2835
                        // then we'll return those directly.
3✔
2836
                        //
3✔
2837
                        // NOTE: since this is an ErrIgnored, we can return
3✔
2838
                        // true here to signal "allow" to its dependants.
3✔
2839
                        nMsg.err <- nil
3✔
2840

3✔
2841
                        return anns, true
3✔
2842
                }
2843

2844
                // Otherwise, this is just a regular rejected edge.
2845
                key := newRejectCacheKey(
1✔
2846
                        scid.ToUint64(),
1✔
2847
                        sourceToPub(nMsg.source),
1✔
2848
                )
1✔
2849
                _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2850

1✔
2851
                if !nMsg.isRemote {
1✔
2852
                        log.Errorf("failed to add edge for local channel: %v",
×
2853
                                err)
×
2854
                        nMsg.err <- err
×
2855

×
2856
                        return nil, false
×
2857
                }
×
2858

2859
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2860
                if dcErr != nil {
1✔
2861
                        log.Errorf("failed to check if we should disconnect "+
×
2862
                                "peer: %v", dcErr)
×
2863
                        nMsg.err <- dcErr
×
2864

×
2865
                        return nil, false
×
2866
                }
×
2867

2868
                if shouldDc {
1✔
2869
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2870
                }
×
2871

2872
                nMsg.err <- err
1✔
2873

1✔
2874
                return nil, false
1✔
2875
        }
2876

2877
        // If err is nil, release the lock immediately.
2878
        d.channelMtx.Unlock(scid.ToUint64())
29✔
2879

29✔
2880
        log.Debugf("Finish adding edge for short_chan_id: %v", scid.ToUint64())
29✔
2881

29✔
2882
        // If we earlier received any ChannelUpdates for this channel, we can
29✔
2883
        // now process them, as the channel is added to the graph.
29✔
2884
        var channelUpdates []*processedNetworkMsg
29✔
2885

29✔
2886
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
29✔
2887
        if err == nil {
34✔
2888
                // There was actually an entry in the map, so we'll accumulate
5✔
2889
                // it. We don't worry about deletion, since it'll eventually
5✔
2890
                // fall out anyway.
5✔
2891
                chanMsgs := earlyChanUpdates
5✔
2892
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
5✔
2893
        }
5✔
2894

2895
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2896
        // ensure we don't block here, as we can handle only one announcement
2897
        // at a time.
2898
        for _, cu := range channelUpdates {
34✔
2899
                // Skip if already processed.
5✔
2900
                if cu.processed {
8✔
2901
                        continue
3✔
2902
                }
2903

2904
                // Mark the ChannelUpdate as processed. This ensures that a
2905
                // subsequent announcement in the option-scid-alias case does
2906
                // not re-use an old ChannelUpdate.
2907
                cu.processed = true
5✔
2908

5✔
2909
                d.wg.Add(1)
5✔
2910
                go func(updMsg *networkMsg) {
10✔
2911
                        defer d.wg.Done()
5✔
2912

5✔
2913
                        switch msg := updMsg.msg.(type) {
5✔
2914
                        // Reprocess the message, making sure we return an
2915
                        // error to the original caller in case the gossiper
2916
                        // shuts down.
2917
                        case *lnwire.ChannelUpdate1:
5✔
2918
                                log.Debugf("Reprocessing ChannelUpdate for "+
5✔
2919
                                        "shortChanID=%v", scid.ToUint64())
5✔
2920

5✔
2921
                                select {
5✔
2922
                                case d.networkMsgs <- updMsg:
5✔
2923
                                case <-d.quit:
×
2924
                                        updMsg.err <- ErrGossiperShuttingDown
×
2925
                                }
2926

2927
                        // We don't expect any other message type than
2928
                        // ChannelUpdate to be in this cache.
2929
                        default:
×
2930
                                log.Errorf("Unsupported message type found "+
×
2931
                                        "among ChannelUpdates: %T", msg)
×
2932
                        }
2933
                }(cu.msg)
2934
        }
2935

2936
        // Channel announcement was successfully processed and now it might be
2937
        // broadcast to other connected nodes if it was an announcement with
2938
        // proof (remote).
2939
        var announcements []networkMsg
29✔
2940

29✔
2941
        if proof != nil {
44✔
2942
                announcements = append(announcements, networkMsg{
15✔
2943
                        peer:     nMsg.peer,
15✔
2944
                        isRemote: nMsg.isRemote,
15✔
2945
                        source:   nMsg.source,
15✔
2946
                        msg:      ann,
15✔
2947
                })
15✔
2948
        }
15✔
2949

2950
        nMsg.err <- nil
29✔
2951

29✔
2952
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
29✔
2953
                nMsg.peer, scid.ToUint64())
29✔
2954

29✔
2955
        return announcements, true
29✔
2956
}
2957

2958
// handleChanUpdate processes a new channel update.
2959
//
2960
//nolint:funlen
2961
func (d *AuthenticatedGossiper) handleChanUpdate(ctx context.Context,
2962
        nMsg *networkMsg, upd *lnwire.ChannelUpdate1,
2963
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
64✔
2964

64✔
2965
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
64✔
2966
                nMsg.peer, upd.ShortChannelID.ToUint64())
64✔
2967

64✔
2968
        // We'll ignore any channel updates that target any chain other than
64✔
2969
        // the set of chains we know of.
64✔
2970
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
64✔
2971
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2972
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2973
                log.Errorf(err.Error())
×
2974

×
2975
                key := newRejectCacheKey(
×
2976
                        upd.ShortChannelID.ToUint64(),
×
2977
                        sourceToPub(nMsg.source),
×
2978
                )
×
2979
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2980

×
2981
                nMsg.err <- err
×
2982
                return nil, false
×
2983
        }
×
2984

2985
        blockHeight := upd.ShortChannelID.BlockHeight
64✔
2986
        shortChanID := upd.ShortChannelID.ToUint64()
64✔
2987

64✔
2988
        // If the advertised inclusionary block is beyond our knowledge of the
64✔
2989
        // chain tip, then we'll put the announcement in limbo to be fully
64✔
2990
        // verified once we advance forward in the chain. If the update has an
64✔
2991
        // alias SCID, we'll skip the isPremature check. This is necessary
64✔
2992
        // since aliases start at block height 16_000_000.
64✔
2993
        d.Lock()
64✔
2994
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
64✔
2995
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
64✔
UNCOV
2996

×
UNCOV
2997
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
UNCOV
2998
                        "premature: advertises height %v, only height %v is "+
×
UNCOV
2999
                        "known", shortChanID, blockHeight, d.bestHeight)
×
UNCOV
3000
                d.Unlock()
×
UNCOV
3001
                nMsg.err <- nil
×
UNCOV
3002
                return nil, false
×
UNCOV
3003
        }
×
3004
        d.Unlock()
64✔
3005

64✔
3006
        // Before we perform any of the expensive checks below, we'll check
64✔
3007
        // whether this update is stale or is for a zombie channel in order to
64✔
3008
        // quickly reject it.
64✔
3009
        timestamp := time.Unix(int64(upd.Timestamp), 0)
64✔
3010

64✔
3011
        // Fetch the SCID we should be using to lock the channelMtx and make
64✔
3012
        // graph queries with.
64✔
3013
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
64✔
3014
        if err != nil {
128✔
3015
                // Fallback and set the graphScid to the peer-provided SCID.
64✔
3016
                // This will occur for non-option-scid-alias channels and for
64✔
3017
                // public option-scid-alias channels after 6 confirmations.
64✔
3018
                // Once public option-scid-alias channels have 6 confs, we'll
64✔
3019
                // ignore ChannelUpdates with one of their aliases.
64✔
3020
                graphScid = upd.ShortChannelID
64✔
3021
        }
64✔
3022

3023
        // We make sure to obtain the mutex for this channel ID before we access
3024
        // the database. This ensures the state we read from the database has
3025
        // not changed between this point and when we call UpdateEdge() later.
3026
        d.channelMtx.Lock(graphScid.ToUint64())
64✔
3027
        defer d.channelMtx.Unlock(graphScid.ToUint64())
64✔
3028

64✔
3029
        if d.cfg.Graph.IsStaleEdgePolicy(
64✔
3030
                graphScid, timestamp, upd.ChannelFlags,
64✔
3031
        ) {
70✔
3032

6✔
3033
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
6✔
3034
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
6✔
3035
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
6✔
3036
                )
6✔
3037

6✔
3038
                nMsg.err <- nil
6✔
3039
                return nil, true
6✔
3040
        }
6✔
3041

3042
        // Check that the ChanUpdate is not too far into the future, this could
3043
        // reveal some faulty implementation therefore we log an error.
3044
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
61✔
3045
                err := fmt.Errorf("skewed timestamp of edge policy, "+
×
3046
                        "timestamp too far in the future: %v", timestamp.Unix())
×
3047

×
3048
                // If this is a channel_update from us, we'll just ignore it.
×
3049
                if !nMsg.isRemote {
×
3050
                        nMsg.err <- err
×
3051
                        return nil, false
×
3052
                }
×
3053

3054
                log.Errorf("Increasing ban score for peer=%v due to bad "+
×
3055
                        "channel_update with short_chan_id(%v): timestamp(%v) "+
×
3056
                        "too far in the future", nMsg.peer, shortChanID,
×
3057
                        timestamp.Unix())
×
3058

×
3059
                // Increment the peer's ban score if they are skewed channel
×
3060
                // updates.
×
3061
                dcErr := d.handleBadPeer(nMsg.peer)
×
3062
                if dcErr != nil {
×
3063
                        err = dcErr
×
3064
                }
×
3065

3066
                nMsg.err <- err
×
3067

×
3068
                return nil, false
×
3069
        }
3070

3071
        // Get the node pub key as far since we don't have it in the channel
3072
        // update announcement message. We'll need this to properly verify the
3073
        // message's signature.
3074
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
61✔
3075
        switch {
61✔
3076
        // No error, break.
3077
        case err == nil:
57✔
3078
                break
57✔
3079

3080
        case errors.Is(err, graphdb.ErrZombieEdge):
3✔
3081
                err = d.processZombieUpdate(ctx, chanInfo, graphScid, upd)
3✔
3082
                if err != nil {
5✔
3083
                        log.Debug(err)
2✔
3084
                        nMsg.err <- err
2✔
3085
                        return nil, false
2✔
3086
                }
2✔
3087

3088
                // We'll fallthrough to ensure we stash the update until we
3089
                // receive its corresponding ChannelAnnouncement. This is
3090
                // needed to ensure the edge exists in the graph before
3091
                // applying the update.
3092
                fallthrough
1✔
3093
        case errors.Is(err, graphdb.ErrGraphNotFound):
1✔
3094
                fallthrough
1✔
3095
        case errors.Is(err, graphdb.ErrGraphNoEdgesFound):
1✔
3096
                fallthrough
1✔
3097
        case errors.Is(err, graphdb.ErrEdgeNotFound):
5✔
3098
                // If the edge corresponding to this ChannelUpdate was not
5✔
3099
                // found in the graph, this might be a channel in the process
5✔
3100
                // of being opened, and we haven't processed our own
5✔
3101
                // ChannelAnnouncement yet, hence it is not not found in the
5✔
3102
                // graph. This usually gets resolved after the channel proofs
5✔
3103
                // are exchanged and the channel is broadcasted to the rest of
5✔
3104
                // the network, but in case this is a private channel this
5✔
3105
                // won't ever happen. This can also happen in the case of a
5✔
3106
                // zombie channel with a fresh update for which we don't have a
5✔
3107
                // ChannelAnnouncement for since we reject them. Because of
5✔
3108
                // this, we temporarily add it to a map, and reprocess it after
5✔
3109
                // our own ChannelAnnouncement has been processed.
5✔
3110
                //
5✔
3111
                // The shortChanID may be an alias, but it is fine to use here
5✔
3112
                // since we don't have an edge in the graph and if the peer is
5✔
3113
                // not buggy, we should be able to use it once the gossiper
5✔
3114
                // receives the local announcement.
5✔
3115
                pMsg := &processedNetworkMsg{msg: nMsg}
5✔
3116

5✔
3117
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
5✔
3118
                switch {
5✔
3119
                // Nothing in the cache yet, we can just directly insert this
3120
                // element.
3121
                case err == cache.ErrElementNotFound:
5✔
3122
                        _, _ = d.prematureChannelUpdates.Put(
5✔
3123
                                shortChanID, &cachedNetworkMsg{
5✔
3124
                                        msgs: []*processedNetworkMsg{pMsg},
5✔
3125
                                })
5✔
3126

3127
                // There's already something in the cache, so we'll combine the
3128
                // set of messages into a single value.
3129
                default:
3✔
3130
                        msgs := earlyMsgs.msgs
3✔
3131
                        msgs = append(msgs, pMsg)
3✔
3132
                        _, _ = d.prematureChannelUpdates.Put(
3✔
3133
                                shortChanID, &cachedNetworkMsg{
3✔
3134
                                        msgs: msgs,
3✔
3135
                                })
3✔
3136
                }
3137

3138
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
5✔
3139
                        "(shortChanID=%v), saving for reprocessing later",
5✔
3140
                        shortChanID)
5✔
3141

5✔
3142
                // NOTE: We don't return anything on the error channel for this
5✔
3143
                // message, as we expect that will be done when this
5✔
3144
                // ChannelUpdate is later reprocessed. This might never happen
5✔
3145
                // if the corresponding ChannelAnnouncement is never received
5✔
3146
                // or the LRU cache is filled up and the entry is evicted.
5✔
3147
                return nil, false
5✔
3148

3149
        default:
×
3150
                err := fmt.Errorf("unable to validate channel update "+
×
3151
                        "short_chan_id=%v: %v", shortChanID, err)
×
3152
                log.Error(err)
×
3153
                nMsg.err <- err
×
3154

×
3155
                key := newRejectCacheKey(
×
3156
                        upd.ShortChannelID.ToUint64(),
×
3157
                        sourceToPub(nMsg.source),
×
3158
                )
×
3159
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3160

×
3161
                return nil, false
×
3162
        }
3163

3164
        // The least-significant bit in the flag on the channel update
3165
        // announcement tells us "which" side of the channels directed edge is
3166
        // being updated.
3167
        var (
57✔
3168
                pubKey       *btcec.PublicKey
57✔
3169
                edgeToUpdate *models.ChannelEdgePolicy
57✔
3170
        )
57✔
3171
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
57✔
3172
        switch direction {
57✔
3173
        case 0:
41✔
3174
                pubKey, _ = chanInfo.NodeKey1()
41✔
3175
                edgeToUpdate = e1
41✔
3176
        case 1:
19✔
3177
                pubKey, _ = chanInfo.NodeKey2()
19✔
3178
                edgeToUpdate = e2
19✔
3179
        }
3180

3181
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
57✔
3182
                "edge policy=%v", chanInfo.ChannelID,
57✔
3183
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
57✔
3184

57✔
3185
        // Validate the channel announcement with the expected public key and
57✔
3186
        // channel capacity. In the case of an invalid channel update, we'll
57✔
3187
        // return an error to the caller and exit early.
57✔
3188
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
57✔
3189
        if err != nil {
61✔
3190
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3191
                        "announcement for short_chan_id=%v: %v",
4✔
3192
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3193

4✔
3194
                log.Error(rErr)
4✔
3195
                nMsg.err <- rErr
4✔
3196
                return nil, false
4✔
3197
        }
4✔
3198

3199
        // If we have a previous version of the edge being updated, we'll want
3200
        // to rate limit its updates to prevent spam throughout the network.
3201
        if nMsg.isRemote && edgeToUpdate != nil {
73✔
3202
                // If it's a keep-alive update, we'll only propagate one if
20✔
3203
                // it's been a day since the previous. This follows our own
20✔
3204
                // heuristic of sending keep-alive updates after the same
20✔
3205
                // duration (see retransmitStaleAnns).
20✔
3206
                timeSinceLastUpdate := timestamp.Sub(edgeToUpdate.LastUpdate)
20✔
3207
                if IsKeepAliveUpdate(upd, edgeToUpdate) {
25✔
3208
                        if timeSinceLastUpdate < d.cfg.RebroadcastInterval {
9✔
3209
                                log.Debugf("Ignoring keep alive update not "+
4✔
3210
                                        "within %v period for channel %v",
4✔
3211
                                        d.cfg.RebroadcastInterval, shortChanID)
4✔
3212
                                nMsg.err <- nil
4✔
3213
                                return nil, false
4✔
3214
                        }
4✔
3215
                } else {
18✔
3216
                        // If it's not, we'll allow an update per minute with a
18✔
3217
                        // maximum burst of 10. If we haven't seen an update
18✔
3218
                        // for this channel before, we'll need to initialize a
18✔
3219
                        // rate limiter for each direction.
18✔
3220
                        //
18✔
3221
                        // Since the edge exists in the graph, we'll create a
18✔
3222
                        // rate limiter for chanInfo.ChannelID rather then the
18✔
3223
                        // SCID the peer sent. This is because there may be
18✔
3224
                        // multiple aliases for a channel and we may otherwise
18✔
3225
                        // rate-limit only a single alias of the channel,
18✔
3226
                        // instead of the whole channel.
18✔
3227
                        baseScid := chanInfo.ChannelID
18✔
3228
                        d.Lock()
18✔
3229
                        rls, ok := d.chanUpdateRateLimiter[baseScid]
18✔
3230
                        if !ok {
23✔
3231
                                r := rate.Every(d.cfg.ChannelUpdateInterval)
5✔
3232
                                b := d.cfg.MaxChannelUpdateBurst
5✔
3233
                                rls = [2]*rate.Limiter{
5✔
3234
                                        rate.NewLimiter(r, b),
5✔
3235
                                        rate.NewLimiter(r, b),
5✔
3236
                                }
5✔
3237
                                d.chanUpdateRateLimiter[baseScid] = rls
5✔
3238
                        }
5✔
3239
                        d.Unlock()
18✔
3240

18✔
3241
                        if !rls[direction].Allow() {
27✔
3242
                                log.Debugf("Rate limiting update for channel "+
9✔
3243
                                        "%v from direction %x", shortChanID,
9✔
3244
                                        pubKey.SerializeCompressed())
9✔
3245
                                nMsg.err <- nil
9✔
3246
                                return nil, false
9✔
3247
                        }
9✔
3248
                }
3249
        }
3250

3251
        // We'll use chanInfo.ChannelID rather than the peer-supplied
3252
        // ShortChannelID in the ChannelUpdate to avoid the router having to
3253
        // lookup the stored SCID. If we're sending the update, we'll always
3254
        // use the SCID stored in the database rather than a potentially
3255
        // different alias. This might mean that SigBytes is incorrect as it
3256
        // signs a different SCID than the database SCID, but since there will
3257
        // only be a difference if AuthProof == nil, this is fine.
3258
        update := &models.ChannelEdgePolicy{
46✔
3259
                SigBytes:                  upd.Signature.ToSignatureBytes(),
46✔
3260
                ChannelID:                 chanInfo.ChannelID,
46✔
3261
                LastUpdate:                timestamp,
46✔
3262
                MessageFlags:              upd.MessageFlags,
46✔
3263
                ChannelFlags:              upd.ChannelFlags,
46✔
3264
                TimeLockDelta:             upd.TimeLockDelta,
46✔
3265
                MinHTLC:                   upd.HtlcMinimumMsat,
46✔
3266
                MaxHTLC:                   upd.HtlcMaximumMsat,
46✔
3267
                FeeBaseMSat:               lnwire.MilliSatoshi(upd.BaseFee),
46✔
3268
                FeeProportionalMillionths: lnwire.MilliSatoshi(upd.FeeRate),
46✔
3269
                InboundFee:                upd.InboundFee.ValOpt(),
46✔
3270
                ExtraOpaqueData:           upd.ExtraOpaqueData,
46✔
3271
        }
46✔
3272

46✔
3273
        if err := d.cfg.Graph.UpdateEdge(ctx, update, ops...); err != nil {
46✔
3274
                if graph.IsError(
×
3275
                        err, graph.ErrOutdated,
×
3276
                        graph.ErrIgnored,
×
3277
                ) {
×
3278

×
3279
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
×
3280
                                shortChanID, err)
×
3281
                } else {
×
3282
                        // Since we know the stored SCID in the graph, we'll
×
3283
                        // cache that SCID.
×
3284
                        key := newRejectCacheKey(
×
3285
                                chanInfo.ChannelID,
×
3286
                                sourceToPub(nMsg.source),
×
3287
                        )
×
3288
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3289

×
3290
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3291
                                shortChanID, err)
×
3292
                }
×
3293

3294
                nMsg.err <- err
×
3295
                return nil, false
×
3296
        }
3297

3298
        // If this is a local ChannelUpdate without an AuthProof, it means it
3299
        // is an update to a channel that is not (yet) supposed to be announced
3300
        // to the greater network. However, our channel counter party will need
3301
        // to be given the update, so we'll try sending the update directly to
3302
        // the remote peer.
3303
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
60✔
3304
                if nMsg.optionalMsgFields != nil {
28✔
3305
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
14✔
3306
                        if remoteAlias != nil {
17✔
3307
                                // The remoteAlias field was specified, meaning
3✔
3308
                                // that we should replace the SCID in the
3✔
3309
                                // update with the remote's alias. We'll also
3✔
3310
                                // need to re-sign the channel update. This is
3✔
3311
                                // required for option-scid-alias feature-bit
3✔
3312
                                // negotiated channels.
3✔
3313
                                upd.ShortChannelID = *remoteAlias
3✔
3314

3✔
3315
                                sig, err := d.cfg.SignAliasUpdate(upd)
3✔
3316
                                if err != nil {
3✔
3317
                                        log.Error(err)
×
3318
                                        nMsg.err <- err
×
3319
                                        return nil, false
×
3320
                                }
×
3321

3322
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
3323
                                if err != nil {
3✔
3324
                                        log.Error(err)
×
3325
                                        nMsg.err <- err
×
3326
                                        return nil, false
×
3327
                                }
×
3328

3329
                                upd.Signature = lnSig
3✔
3330
                        }
3331
                }
3332

3333
                // Get our peer's public key.
3334
                remotePubKey := remotePubFromChanInfo(
14✔
3335
                        chanInfo, upd.ChannelFlags,
14✔
3336
                )
14✔
3337

14✔
3338
                log.Debugf("The message %v has no AuthProof, sending the "+
14✔
3339
                        "update to remote peer %x", upd.MsgType(), remotePubKey)
14✔
3340

14✔
3341
                // Now we'll attempt to send the channel update message
14✔
3342
                // reliably to the remote peer in the background, so that we
14✔
3343
                // don't block if the peer happens to be offline at the moment.
14✔
3344
                err := d.reliableSender.sendMessage(ctx, upd, remotePubKey)
14✔
3345
                if err != nil {
14✔
3346
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3347
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3348
                                upd.ShortChannelID, remotePubKey, err)
×
3349
                        nMsg.err <- err
×
3350
                        return nil, false
×
3351
                }
×
3352
        }
3353

3354
        // Channel update announcement was successfully processed and now it
3355
        // can be broadcast to the rest of the network. However, we'll only
3356
        // broadcast the channel update announcement if it has an attached
3357
        // authentication proof. We also won't broadcast the update if it
3358
        // contains an alias because the network would reject this.
3359
        var announcements []networkMsg
46✔
3360
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
72✔
3361
                announcements = append(announcements, networkMsg{
26✔
3362
                        peer:     nMsg.peer,
26✔
3363
                        source:   nMsg.source,
26✔
3364
                        isRemote: nMsg.isRemote,
26✔
3365
                        msg:      upd,
26✔
3366
                })
26✔
3367
        }
26✔
3368

3369
        nMsg.err <- nil
46✔
3370

46✔
3371
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
46✔
3372
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
46✔
3373
                timestamp)
46✔
3374
        return announcements, true
46✔
3375
}
3376

3377
// handleAnnSig processes a new announcement signatures message.
3378
//
3379
//nolint:funlen
3380
func (d *AuthenticatedGossiper) handleAnnSig(ctx context.Context,
3381
        nMsg *networkMsg, ann *lnwire.AnnounceSignatures1) ([]networkMsg,
3382
        bool) {
24✔
3383

24✔
3384
        needBlockHeight := ann.ShortChannelID.BlockHeight +
24✔
3385
                d.cfg.ProofMatureDelta
24✔
3386
        shortChanID := ann.ShortChannelID.ToUint64()
24✔
3387

24✔
3388
        prefix := "local"
24✔
3389
        if nMsg.isRemote {
38✔
3390
                prefix = "remote"
14✔
3391
        }
14✔
3392

3393
        log.Infof("Received new %v announcement signature for %v", prefix,
24✔
3394
                ann.ShortChannelID)
24✔
3395

24✔
3396
        // By the specification, channel announcement proofs should be sent
24✔
3397
        // after some number of confirmations after channel was registered in
24✔
3398
        // bitcoin blockchain. Therefore, we check if the proof is mature.
24✔
3399
        d.Lock()
24✔
3400
        premature := d.isPremature(
24✔
3401
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
24✔
3402
        )
24✔
3403
        if premature {
27✔
3404
                log.Warnf("Premature proof announcement, current block height"+
3✔
3405
                        "lower than needed: %v < %v", d.bestHeight,
3✔
3406
                        needBlockHeight)
3✔
3407
                d.Unlock()
3✔
3408
                nMsg.err <- nil
3✔
3409
                return nil, false
3✔
3410
        }
3✔
3411
        d.Unlock()
24✔
3412

24✔
3413
        // Ensure that we know of a channel with the target channel ID before
24✔
3414
        // proceeding further.
24✔
3415
        //
24✔
3416
        // We must acquire the mutex for this channel ID before getting the
24✔
3417
        // channel from the database, to ensure what we read does not change
24✔
3418
        // before we call AddProof() later.
24✔
3419
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
24✔
3420
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
24✔
3421

24✔
3422
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
24✔
3423
                ann.ShortChannelID,
24✔
3424
        )
24✔
3425
        if err != nil {
28✔
3426
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
4✔
3427
                if err != nil {
7✔
3428
                        err := fmt.Errorf("unable to store the proof for "+
3✔
3429
                                "short_chan_id=%v: %v", shortChanID, err)
3✔
3430
                        log.Error(err)
3✔
3431
                        nMsg.err <- err
3✔
3432

3✔
3433
                        return nil, false
3✔
3434
                }
3✔
3435

3436
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
4✔
3437
                err := d.cfg.WaitingProofStore.Add(proof)
4✔
3438
                if err != nil {
4✔
3439
                        err := fmt.Errorf("unable to store the proof for "+
×
3440
                                "short_chan_id=%v: %v", shortChanID, err)
×
3441
                        log.Error(err)
×
3442
                        nMsg.err <- err
×
3443
                        return nil, false
×
3444
                }
×
3445

3446
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
4✔
3447
                        ", adding to waiting batch", prefix, shortChanID)
4✔
3448
                nMsg.err <- nil
4✔
3449
                return nil, false
4✔
3450
        }
3451

3452
        nodeID := nMsg.source.SerializeCompressed()
23✔
3453
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
23✔
3454
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
23✔
3455

23✔
3456
        // Ensure that channel that was retrieved belongs to the peer which
23✔
3457
        // sent the proof announcement.
23✔
3458
        if !(isFirstNode || isSecondNode) {
23✔
3459
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3460
                        "to the peer which sent the proof, short_chan_id=%v",
×
3461
                        shortChanID)
×
3462
                log.Error(err)
×
3463
                nMsg.err <- err
×
3464
                return nil, false
×
3465
        }
×
3466

3467
        // If proof was sent by a local sub-system, then we'll send the
3468
        // announcement signature to the remote node so they can also
3469
        // reconstruct the full channel announcement.
3470
        if !nMsg.isRemote {
36✔
3471
                var remotePubKey [33]byte
13✔
3472
                if isFirstNode {
26✔
3473
                        remotePubKey = chanInfo.NodeKey2Bytes
13✔
3474
                } else {
16✔
3475
                        remotePubKey = chanInfo.NodeKey1Bytes
3✔
3476
                }
3✔
3477

3478
                // Since the remote peer might not be online we'll call a
3479
                // method that will attempt to deliver the proof when it comes
3480
                // online.
3481
                err := d.reliableSender.sendMessage(ctx, ann, remotePubKey)
13✔
3482
                if err != nil {
13✔
3483
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3484
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3485
                                ann.ShortChannelID, remotePubKey, err)
×
3486
                        nMsg.err <- err
×
3487
                        return nil, false
×
3488
                }
×
3489
        }
3490

3491
        // Check if we already have the full proof for this channel.
3492
        if chanInfo.AuthProof != nil {
27✔
3493
                // If we already have the fully assembled proof, then the peer
4✔
3494
                // sending us their proof has probably not received our local
4✔
3495
                // proof yet. So be kind and send them the full proof.
4✔
3496
                if nMsg.isRemote {
8✔
3497
                        peerID := nMsg.source.SerializeCompressed()
4✔
3498
                        log.Debugf("Got AnnounceSignatures for channel with " +
4✔
3499
                                "full proof.")
4✔
3500

4✔
3501
                        d.wg.Add(1)
4✔
3502
                        go func() {
8✔
3503
                                defer d.wg.Done()
4✔
3504

4✔
3505
                                log.Debugf("Received half proof for channel "+
4✔
3506
                                        "%v with existing full proof. Sending"+
4✔
3507
                                        " full proof to peer=%x",
4✔
3508
                                        ann.ChannelID, peerID)
4✔
3509

4✔
3510
                                ca, _, _, err := netann.CreateChanAnnouncement(
4✔
3511
                                        chanInfo.AuthProof, chanInfo, e1, e2,
4✔
3512
                                )
4✔
3513
                                if err != nil {
4✔
3514
                                        log.Errorf("unable to gen ann: %v",
×
3515
                                                err)
×
3516
                                        return
×
3517
                                }
×
3518

3519
                                err = nMsg.peer.SendMessage(false, ca)
4✔
3520
                                if err != nil {
4✔
3521
                                        log.Errorf("Failed sending full proof"+
×
3522
                                                " to peer=%x: %v", peerID, err)
×
3523
                                        return
×
3524
                                }
×
3525

3526
                                log.Debugf("Full proof sent to peer=%x for "+
4✔
3527
                                        "chanID=%v", peerID, ann.ChannelID)
4✔
3528
                        }()
3529
                }
3530

3531
                log.Debugf("Already have proof for channel with chanID=%v",
4✔
3532
                        ann.ChannelID)
4✔
3533
                nMsg.err <- nil
4✔
3534
                return nil, true
4✔
3535
        }
3536

3537
        // Check that we received the opposite proof. If so, then we're now
3538
        // able to construct the full proof, and create the channel
3539
        // announcement. If we didn't receive the opposite half of the proof
3540
        // then we should store this one, and wait for the opposite to be
3541
        // received.
3542
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
22✔
3543
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
22✔
3544
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
22✔
3545
                err := fmt.Errorf("unable to get the opposite proof for "+
×
3546
                        "short_chan_id=%v: %v", shortChanID, err)
×
3547
                log.Error(err)
×
3548
                nMsg.err <- err
×
3549
                return nil, false
×
3550
        }
×
3551

3552
        if err == channeldb.ErrWaitingProofNotFound {
34✔
3553
                err := d.cfg.WaitingProofStore.Add(proof)
12✔
3554
                if err != nil {
12✔
3555
                        err := fmt.Errorf("unable to store the proof for "+
×
3556
                                "short_chan_id=%v: %v", shortChanID, err)
×
3557
                        log.Error(err)
×
3558
                        nMsg.err <- err
×
3559
                        return nil, false
×
3560
                }
×
3561

3562
                log.Infof("1/2 of channel ann proof received for "+
12✔
3563
                        "short_chan_id=%v, waiting for other half",
12✔
3564
                        shortChanID)
12✔
3565

12✔
3566
                nMsg.err <- nil
12✔
3567
                return nil, false
12✔
3568
        }
3569

3570
        // We now have both halves of the channel announcement proof, then
3571
        // we'll reconstruct the initial announcement so we can validate it
3572
        // shortly below.
3573
        var dbProof models.ChannelAuthProof
13✔
3574
        if isFirstNode {
17✔
3575
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
4✔
3576
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
4✔
3577
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
4✔
3578
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
4✔
3579
        } else {
16✔
3580
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
12✔
3581
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
12✔
3582
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
12✔
3583
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
12✔
3584
        }
12✔
3585

3586
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
13✔
3587
                &dbProof, chanInfo, e1, e2,
13✔
3588
        )
13✔
3589
        if err != nil {
13✔
3590
                log.Error(err)
×
3591
                nMsg.err <- err
×
3592
                return nil, false
×
3593
        }
×
3594

3595
        // With all the necessary components assembled validate the full
3596
        // channel announcement proof.
3597
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
13✔
3598
        if err != nil {
13✔
3599
                err := fmt.Errorf("channel announcement proof for "+
×
3600
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3601

×
3602
                log.Error(err)
×
3603
                nMsg.err <- err
×
3604
                return nil, false
×
3605
        }
×
3606

3607
        // If the channel was returned by the router it means that existence of
3608
        // funding point and inclusion of nodes bitcoin keys in it already
3609
        // checked by the router. In this stage we should check that node keys
3610
        // attest to the bitcoin keys by validating the signatures of
3611
        // announcement. If proof is valid then we'll populate the channel edge
3612
        // with it, so we can announce it on peer connect.
3613
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
13✔
3614
        if err != nil {
13✔
3615
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
3616
                        " %v", ann.ChannelID, err)
×
3617
                log.Error(err)
×
3618
                nMsg.err <- err
×
3619
                return nil, false
×
3620
        }
×
3621

3622
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
13✔
3623
        if err != nil {
13✔
3624
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3625
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3626
                log.Error(err)
×
3627
                nMsg.err <- err
×
3628
                return nil, false
×
3629
        }
×
3630

3631
        // Proof was successfully created and now can announce the channel to
3632
        // the remain network.
3633
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
13✔
3634
                ", adding to next ann batch", shortChanID)
13✔
3635

13✔
3636
        // Assemble the necessary announcements to add to the next broadcasting
13✔
3637
        // batch.
13✔
3638
        var announcements []networkMsg
13✔
3639
        announcements = append(announcements, networkMsg{
13✔
3640
                peer:   nMsg.peer,
13✔
3641
                source: nMsg.source,
13✔
3642
                msg:    chanAnn,
13✔
3643
        })
13✔
3644
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
25✔
3645
                announcements = append(announcements, networkMsg{
12✔
3646
                        peer:   nMsg.peer,
12✔
3647
                        source: src,
12✔
3648
                        msg:    e1Ann,
12✔
3649
                })
12✔
3650
        }
12✔
3651
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
24✔
3652
                announcements = append(announcements, networkMsg{
11✔
3653
                        peer:   nMsg.peer,
11✔
3654
                        source: src,
11✔
3655
                        msg:    e2Ann,
11✔
3656
                })
11✔
3657
        }
11✔
3658

3659
        // We'll also send along the node announcements for each channel
3660
        // participant if we know of them. To ensure our node announcement
3661
        // propagates to our channel counterparty, we'll set the source for
3662
        // each announcement to the node it belongs to, otherwise we won't send
3663
        // it since the source gets skipped. This isn't necessary for channel
3664
        // updates and announcement signatures since we send those directly to
3665
        // our channel counterparty through the gossiper's reliable sender.
3666
        node1Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey1Bytes)
13✔
3667
        if err != nil {
18✔
3668
                log.Debugf("Unable to fetch node announcement for %x: %v",
5✔
3669
                        chanInfo.NodeKey1Bytes, err)
5✔
3670
        } else {
16✔
3671
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
22✔
3672
                        announcements = append(announcements, networkMsg{
11✔
3673
                                peer:   nMsg.peer,
11✔
3674
                                source: nodeKey1,
11✔
3675
                                msg:    node1Ann,
11✔
3676
                        })
11✔
3677
                }
11✔
3678
        }
3679

3680
        node2Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey2Bytes)
13✔
3681
        if err != nil {
20✔
3682
                log.Debugf("Unable to fetch node announcement for %x: %v",
7✔
3683
                        chanInfo.NodeKey2Bytes, err)
7✔
3684
        } else {
16✔
3685
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
18✔
3686
                        announcements = append(announcements, networkMsg{
9✔
3687
                                peer:   nMsg.peer,
9✔
3688
                                source: nodeKey2,
9✔
3689
                                msg:    node2Ann,
9✔
3690
                        })
9✔
3691
                }
9✔
3692
        }
3693

3694
        nMsg.err <- nil
13✔
3695
        return announcements, true
13✔
3696
}
3697

3698
// isBanned returns true if the peer identified by pubkey is banned for sending
3699
// invalid channel announcements.
3700
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
211✔
3701
        return d.banman.isBanned(pubkey)
211✔
3702
}
211✔
3703

3704
// ShouldDisconnect returns true if we should disconnect the peer identified by
3705
// pubkey.
3706
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3707
        bool, error) {
209✔
3708

209✔
3709
        pubkeySer := pubkey.SerializeCompressed()
209✔
3710

209✔
3711
        var pubkeyBytes [33]byte
209✔
3712
        copy(pubkeyBytes[:], pubkeySer)
209✔
3713

209✔
3714
        // If the public key is banned, check whether or not this is a channel
209✔
3715
        // peer.
209✔
3716
        if d.isBanned(pubkeyBytes) {
211✔
3717
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3718
                if err != nil {
2✔
3719
                        return false, err
×
3720
                }
×
3721

3722
                // We should only disconnect non-channel peers.
3723
                if !isChanPeer {
3✔
3724
                        return true, nil
1✔
3725
                }
1✔
3726
        }
3727

3728
        return false, nil
208✔
3729
}
3730

3731
// validateFundingTransaction fetches the channel announcements claimed funding
3732
// transaction from chain to ensure that it exists, is not spent and matches
3733
// the channel announcement proof. The transaction's outpoint and value are
3734
// returned if we can glean them from the work done in this method.
3735
func (d *AuthenticatedGossiper) validateFundingTransaction(_ context.Context,
3736
        ann *lnwire.ChannelAnnouncement1,
3737
        tapscriptRoot fn.Option[chainhash.Hash]) (wire.OutPoint, btcutil.Amount,
3738
        []byte, error) {
232✔
3739

232✔
3740
        scid := ann.ShortChannelID
232✔
3741

232✔
3742
        // Before we can add the channel to the channel graph, we need to obtain
232✔
3743
        // the full funding outpoint that's encoded within the channel ID.
232✔
3744
        fundingTx, err := lnwallet.FetchFundingTxWrapper(
232✔
3745
                d.cfg.ChainIO, &scid, d.quit,
232✔
3746
        )
232✔
3747
        if err != nil {
233✔
3748
                //nolint:ll
1✔
3749
                //
1✔
3750
                // In order to ensure we don't erroneously mark a channel as a
1✔
3751
                // zombie due to an RPC failure, we'll attempt to string match
1✔
3752
                // for the relevant errors.
1✔
3753
                //
1✔
3754
                // * btcd:
1✔
3755
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
1✔
3756
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
1✔
3757
                // * bitcoind:
1✔
3758
                //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
1✔
3759
                //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
1✔
3760
                switch {
1✔
3761
                case strings.Contains(err.Error(), "not found"):
1✔
3762
                        fallthrough
1✔
3763

3764
                case strings.Contains(err.Error(), "out of range"):
1✔
3765
                        // If the funding transaction isn't found at all, then
1✔
3766
                        // we'll mark the edge itself as a zombie so we don't
1✔
3767
                        // continue to request it. We use the "zero key" for
1✔
3768
                        // both node pubkeys so this edge can't be resurrected.
1✔
3769
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
1✔
3770
                        if zErr != nil {
1✔
3771
                                return wire.OutPoint{}, 0, nil, zErr
×
3772
                        }
×
3773

3774
                default:
×
3775
                }
3776

3777
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
1✔
3778
                        ErrNoFundingTransaction, err)
1✔
3779
        }
3780

3781
        // Recreate witness output to be sure that declared in channel edge
3782
        // bitcoin keys and channel value corresponds to the reality.
3783
        fundingPkScript, err := makeFundingScript(
231✔
3784
                ann.BitcoinKey1[:], ann.BitcoinKey2[:], ann.Features,
231✔
3785
                tapscriptRoot,
231✔
3786
        )
231✔
3787
        if err != nil {
231✔
3788
                return wire.OutPoint{}, 0, nil, err
×
3789
        }
×
3790

3791
        // Next we'll validate that this channel is actually well formed. If
3792
        // this check fails, then this channel either doesn't exist, or isn't
3793
        // the one that was meant to be created according to the passed channel
3794
        // proofs.
3795
        fundingPoint, err := chanvalidate.Validate(
231✔
3796
                &chanvalidate.Context{
231✔
3797
                        Locator: &chanvalidate.ShortChanIDChanLocator{
231✔
3798
                                ID: scid,
231✔
3799
                        },
231✔
3800
                        MultiSigPkScript: fundingPkScript,
231✔
3801
                        FundingTx:        fundingTx,
231✔
3802
                },
231✔
3803
        )
231✔
3804
        if err != nil {
432✔
3805
                // Mark the edge as a zombie so we won't try to re-validate it
201✔
3806
                // on start up.
201✔
3807
                zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
201✔
3808
                if zErr != nil {
201✔
3809
                        return wire.OutPoint{}, 0, nil, zErr
×
3810
                }
×
3811

3812
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
201✔
3813
                        ErrInvalidFundingOutput, err)
201✔
3814
        }
3815

3816
        // Now that we have the funding outpoint of the channel, ensure
3817
        // that it hasn't yet been spent. If so, then this channel has
3818
        // been closed so we'll ignore it.
3819
        chanUtxo, err := d.cfg.ChainIO.GetUtxo(
30✔
3820
                fundingPoint, fundingPkScript, scid.BlockHeight, d.quit,
30✔
3821
        )
30✔
3822
        if err != nil {
32✔
3823
                if errors.Is(err, btcwallet.ErrOutputSpent) {
4✔
3824
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
2✔
3825
                        if zErr != nil {
2✔
3826
                                return wire.OutPoint{}, 0, nil, zErr
×
3827
                        }
×
3828
                }
3829

3830
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: unable to "+
2✔
3831
                        "fetch utxo for chan_id=%v, chan_point=%v: %w",
2✔
3832
                        ErrChannelSpent, scid.ToUint64(), fundingPoint, err)
2✔
3833
        }
3834

3835
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
28✔
3836
                nil
28✔
3837
}
3838

3839
// handleBadPeer takes a misbehaving peer and increases its ban score. Once
3840
// increased, it will disconnect the peer if its ban score has reached
3841
// `banThreshold` and it doesn't have a channel with us.
3842
func (d *AuthenticatedGossiper) handleBadPeer(peer lnpeer.Peer) error {
205✔
3843
        // Increment the peer's ban score for misbehavior.
205✔
3844
        d.banman.incrementBanScore(peer.PubKey())
205✔
3845

205✔
3846
        // If the peer is banned and not a channel peer, we'll disconnect them.
205✔
3847
        shouldDc, dcErr := d.ShouldDisconnect(peer.IdentityKey())
205✔
3848
        if dcErr != nil {
205✔
3849
                log.Errorf("failed to check if we should disconnect peer: %v",
×
3850
                        dcErr)
×
3851

×
3852
                return dcErr
×
3853
        }
×
3854

3855
        if shouldDc {
206✔
3856
                peer.Disconnect(ErrPeerBanned)
1✔
3857
        }
1✔
3858

3859
        return nil
205✔
3860
}
3861

3862
// makeFundingScript is used to make the funding script for both segwit v0 and
3863
// segwit v1 (taproot) channels.
3864
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3865
        features *lnwire.RawFeatureVector,
3866
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
231✔
3867

231✔
3868
        legacyFundingScript := func() ([]byte, error) {
462✔
3869
                witnessScript, err := input.GenMultiSigScript(
231✔
3870
                        bitcoinKey1, bitcoinKey2,
231✔
3871
                )
231✔
3872
                if err != nil {
231✔
3873
                        return nil, err
×
3874
                }
×
3875
                pkScript, err := input.WitnessScriptHash(witnessScript)
231✔
3876
                if err != nil {
231✔
3877
                        return nil, err
×
3878
                }
×
3879

3880
                return pkScript, nil
231✔
3881
        }
3882

3883
        if features.IsEmpty() {
462✔
3884
                return legacyFundingScript()
231✔
3885
        }
231✔
3886

3887
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
3✔
3888
        if chanFeatureBits.HasFeature(
3✔
3889
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
3890
        ) {
6✔
3891

3✔
3892
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
3893
                if err != nil {
3✔
3894
                        return nil, err
×
3895
                }
×
3896
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
3897
                if err != nil {
3✔
3898
                        return nil, err
×
3899
                }
×
3900

3901
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
3902
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
3903
                )
3✔
3904
                if err != nil {
3✔
3905
                        return nil, err
×
3906
                }
×
3907

3908
                // TODO(roasbeef): add tapscript root to gossip v1.5
3909

3910
                return fundingScript, nil
3✔
3911
        }
3912

3913
        return legacyFundingScript()
×
3914
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc