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

lightningnetwork / lnd / 16024244444

02 Jul 2025 11:46AM UTC coverage: 57.264% (-0.5%) from 57.803%
16024244444

Pull #10012

github

web-flow
Merge 32af9d5c7 into 1d2e5472b
Pull Request #10012: multi: prevent goroutine leak in brontide

3 of 29 new or added lines in 2 files covered. (10.34%)

1169 existing lines in 16 files now uncovered.

97585 of 170411 relevant lines covered (57.26%)

1.19 hits per line

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

67.95
/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) {
2✔
121
        for _, optionalMsgField := range optionalMsgFields {
4✔
122
                optionalMsgField(f)
2✔
123
        }
2✔
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 {
2✔
134
        return func(f *optionalMsgFields) {
4✔
135
                f.capacity = &capacity
2✔
136
        }
2✔
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 {
2✔
142
        return func(f *optionalMsgFields) {
4✔
143
                f.channelPoint = &op
2✔
144
        }
2✔
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 {
2✔
150
        return func(f *optionalMsgFields) {
4✔
151
                f.tapscriptRoot = root
2✔
152
        }
2✔
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 {
2✔
162
        return func(f *optionalMsgFields) {
4✔
163
                f.remoteAlias = alias
2✔
164
        }
2✔
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

404
// processedNetworkMsg is a wrapper around networkMsg and a boolean. It is
405
// used to let the caller of the lru.Cache know if a message has already been
406
// processed or not.
407
type processedNetworkMsg struct {
408
        processed bool
409
        msg       *networkMsg
410
}
411

412
// cachedNetworkMsg is a wrapper around a network message that can be used with
413
// *lru.Cache.
414
type cachedNetworkMsg struct {
415
        msgs []*processedNetworkMsg
416
}
417

418
// Size returns the "size" of an entry. We return the number of items as we
419
// just want to limit the total amount of entries rather than do accurate size
420
// accounting.
421
func (c *cachedNetworkMsg) Size() (uint64, error) {
2✔
422
        return uint64(len(c.msgs)), nil
2✔
423
}
2✔
424

425
// rejectCacheKey is the cache key that we'll use to track announcements we've
426
// recently rejected.
427
type rejectCacheKey struct {
428
        pubkey [33]byte
429
        chanID uint64
430
}
431

432
// newRejectCacheKey returns a new cache key for the reject cache.
433
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
2✔
434
        k := rejectCacheKey{
2✔
435
                chanID: cid,
2✔
436
                pubkey: pub,
2✔
437
        }
2✔
438

2✔
439
        return k
2✔
440
}
2✔
441

442
// sourceToPub returns a serialized-compressed public key for use in the reject
443
// cache.
444
func sourceToPub(pk *btcec.PublicKey) [33]byte {
2✔
445
        var pub [33]byte
2✔
446
        copy(pub[:], pk.SerializeCompressed())
2✔
447
        return pub
2✔
448
}
2✔
449

450
// cachedReject is the empty value used to track the value for rejects.
451
type cachedReject struct {
452
}
453

454
// Size returns the "size" of an entry. We return 1 as we just want to limit
455
// the total size.
456
func (c *cachedReject) Size() (uint64, error) {
×
457
        return 1, nil
×
458
}
×
459

460
// AuthenticatedGossiper is a subsystem which is responsible for receiving
461
// announcements, validating them and applying the changes to router, syncing
462
// lightning network with newly connected nodes, broadcasting announcements
463
// after validation, negotiating the channel announcement proofs exchange and
464
// handling the premature announcements. All outgoing announcements are
465
// expected to be properly signed as dictated in BOLT#7, additionally, all
466
// incoming message are expected to be well formed and signed. Invalid messages
467
// will be rejected by this struct.
468
type AuthenticatedGossiper struct {
469
        // Parameters which are needed to properly handle the start and stop of
470
        // the service.
471
        started sync.Once
472
        stopped sync.Once
473

474
        // bestHeight is the height of the block at the tip of the main chain
475
        // as we know it. Accesses *MUST* be done with the gossiper's lock
476
        // held.
477
        bestHeight uint32
478

479
        // cfg is a copy of the configuration struct that the gossiper service
480
        // was initialized with.
481
        cfg *Config
482

483
        // blockEpochs encapsulates a stream of block epochs that are sent at
484
        // every new block height.
485
        blockEpochs *chainntnfs.BlockEpochEvent
486

487
        // prematureChannelUpdates is a map of ChannelUpdates we have received
488
        // that wasn't associated with any channel we know about.  We store
489
        // them temporarily, such that we can reprocess them when a
490
        // ChannelAnnouncement for the channel is received.
491
        prematureChannelUpdates *lru.Cache[uint64, *cachedNetworkMsg]
492

493
        // banman tracks our peer's ban status.
494
        banman *banman
495

496
        // networkMsgs is a channel that carries new network broadcasted
497
        // message from outside the gossiper service to be processed by the
498
        // networkHandler.
499
        networkMsgs chan *networkMsg
500

501
        // futureMsgs is a list of premature network messages that have a block
502
        // height specified in the future. We will save them and resend it to
503
        // the chan networkMsgs once the block height has reached. The cached
504
        // map format is,
505
        //   {msgID1: msg1, msgID2: msg2, ...}
506
        futureMsgs *futureMsgCache
507

508
        // chanPolicyUpdates is a channel that requests to update the
509
        // forwarding policy of a set of channels is sent over.
510
        chanPolicyUpdates chan *chanPolicyUpdateRequest
511

512
        // selfKey is the identity public key of the backing Lightning node.
513
        selfKey *btcec.PublicKey
514

515
        // selfKeyLoc is the locator for the identity public key of the backing
516
        // Lightning node.
517
        selfKeyLoc keychain.KeyLocator
518

519
        // channelMtx is used to restrict the database access to one
520
        // goroutine per channel ID. This is done to ensure that when
521
        // the gossiper is handling an announcement, the db state stays
522
        // consistent between when the DB is first read until it's written.
523
        channelMtx *multimutex.Mutex[uint64]
524

525
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
526

527
        // syncMgr is a subsystem responsible for managing the gossip syncers
528
        // for peers currently connected. When a new peer is connected, the
529
        // manager will create its accompanying gossip syncer and determine
530
        // whether it should have an activeSync or passiveSync sync type based
531
        // on how many other gossip syncers are currently active. Any activeSync
532
        // gossip syncers are started in a round-robin manner to ensure we're
533
        // not syncing with multiple peers at the same time.
534
        syncMgr *SyncManager
535

536
        // reliableSender is a subsystem responsible for handling reliable
537
        // message send requests to peers. This should only be used for channels
538
        // that are unadvertised at the time of handling the message since if it
539
        // is advertised, then peers should be able to get the message from the
540
        // network.
541
        reliableSender *reliableSender
542

543
        // chanUpdateRateLimiter contains rate limiters for each direction of
544
        // a channel update we've processed. We'll use these to determine
545
        // whether we should accept a new update for a specific channel and
546
        // direction.
547
        //
548
        // NOTE: This map must be synchronized with the main
549
        // AuthenticatedGossiper lock.
550
        chanUpdateRateLimiter map[uint64][2]*rate.Limiter
551

552
        // vb is used to enforce job dependency ordering of gossip messages.
553
        vb *ValidationBarrier
554

555
        sync.Mutex
556

557
        cancel fn.Option[context.CancelFunc]
558
        quit   chan struct{}
559
        wg     sync.WaitGroup
560
}
561

562
// New creates a new AuthenticatedGossiper instance, initialized with the
563
// passed configuration parameters.
564
func New(cfg Config, selfKeyDesc *keychain.KeyDescriptor) *AuthenticatedGossiper {
2✔
565
        gossiper := &AuthenticatedGossiper{
2✔
566
                selfKey:           selfKeyDesc.PubKey,
2✔
567
                selfKeyLoc:        selfKeyDesc.KeyLocator,
2✔
568
                cfg:               &cfg,
2✔
569
                networkMsgs:       make(chan *networkMsg),
2✔
570
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
2✔
571
                quit:              make(chan struct{}),
2✔
572
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
2✔
573
                prematureChannelUpdates: lru.NewCache(
2✔
574
                        maxPrematureUpdates,
2✔
575
                        lru.WithDeleteCallback(
2✔
576
                                func(k uint64, cmsg *cachedNetworkMsg) {
2✔
NEW
577
                                        // for every network message which is
×
NEW
578
                                        // not processed, send an error to the
×
NEW
579
                                        // channel.
×
NEW
580
                                        cb := func(msg *networkMsg) {
×
NEW
581
                                                err := fmt.Errorf("premature "+
×
NEW
582
                                                        "channel update for "+
×
NEW
583
                                                        "peer %x not "+
×
NEW
584
                                                        "processed, deleting "+
×
NEW
585
                                                        "from LRU cache",
×
NEW
586
                                                        msg.peer.PubKey())
×
NEW
587
                                                msg.err <- err
×
NEW
588
                                        }
×
NEW
589
                                        for _, msg := range cmsg.msgs {
×
NEW
590
                                                cb(msg.msg)
×
NEW
591
                                        }
×
592
                                }),
593
                ),
594
                channelMtx: multimutex.NewMutex[uint64](),
595
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
596
                        maxRejectedUpdates,
597
                ),
598
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
599
                banman:                newBanman(),
600
        }
601

602
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
2✔
603

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

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

2✔
626
        return gossiper
2✔
627
}
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 {
2✔
646

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

2✔
653
        select {
2✔
654
        case d.chanPolicyUpdates <- policyUpdate:
2✔
655
                err := <-errChan
2✔
656
                return err
2✔
UNCOV
657
        case <-d.quit:
×
UNCOV
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 {
2✔
665
        var err error
2✔
666
        d.started.Do(func() {
4✔
667
                ctx, cancel := context.WithCancel(context.Background())
2✔
668
                d.cancel = fn.Some(cancel)
2✔
669

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

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

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

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

699
        d.syncMgr.Start()
2✔
700

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

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

2✔
708
        return nil
2✔
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() {
2✔
716
        defer d.wg.Done()
2✔
717

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

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

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

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

UNCOV
742
                case <-d.quit:
×
UNCOV
743
                        return
×
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 {
2✔
759
        return f.msgID.Add(1)
2✔
760
}
2✔
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 {
2✔
765
        // Create a new cache.
2✔
766
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
2✔
767

2✔
768
        return &futureMsgCache{
2✔
769
                Cache: cache,
2✔
770
        }
2✔
771
}
2✔
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) {
2✔
784
        // Return a constant 1.
2✔
785
        return 1, nil
2✔
786
}
2✔
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) {
2✔
792
        var (
2✔
793
                // msgs are the target messages.
2✔
794
                msgs []*networkMsg
2✔
795

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

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

807
                return true
2✔
808
        }
809

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

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

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

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

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

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

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

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

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

857
        d.syncMgr.Stop()
2✔
858

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

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

2✔
865
        // We'll stop our reliable sender after all of the gossiper's goroutines
2✔
866
        // have exited to ensure nothing can cause it to continue executing.
2✔
867
        d.reliableSender.Stop()
2✔
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 {
2✔
880

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

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

2✔
892
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
2✔
893
                if !ok {
2✔
UNCOV
894
                        log.Warnf("Gossip syncer for peer=%x not found",
×
UNCOV
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())
2✔
904
                if err != nil {
2✔
UNCOV
905
                        log.Errorf("Process query msg from peer %x got %v",
×
UNCOV
906
                                peer.PubKey(), err)
×
907
                }
×
908

909
                errChan <- err
2✔
910
                return errChan
2✔
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:
2✔
915
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
2✔
916
                if !ok {
2✔
UNCOV
917
                        log.Warnf("Gossip syncer for peer=%x not found",
×
UNCOV
918
                                peer.PubKey())
×
919

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

924
                // If we've found the message target, then we'll dispatch the
925
                // message directly to it.
926
                if err := syncer.ApplyGossipFilter(ctx, m); err != nil {
2✔
UNCOV
927
                        log.Warnf("Unable to apply gossip filter for peer=%x: "+
×
UNCOV
928
                                "%v", peer.PubKey(), err)
×
929

×
930
                        errChan <- err
×
931
                        return errChan
×
932
                }
×
933

934
                errChan <- nil
2✔
935
                return errChan
2✔
936

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

2✔
945
                if bytes.Equal(m.NodeID1[:], ownKey) ||
2✔
946
                        bytes.Equal(m.NodeID2[:], ownKey) {
4✔
947

2✔
948
                        log.Warn(ownErr)
2✔
949
                        errChan <- ownErr
2✔
950
                        return errChan
2✔
951
                }
2✔
952
        }
953

954
        nMsg := &networkMsg{
2✔
955
                msg:      msg,
2✔
956
                isRemote: true,
2✔
957
                peer:     peer,
2✔
958
                source:   peer.IdentityKey(),
2✔
959
                err:      errChan,
2✔
960
        }
2✔
961

2✔
962
        select {
2✔
963
        case d.networkMsgs <- nMsg:
2✔
964

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

977
        return nMsg.err
2✔
978
}
979

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

2✔
990
        optionalMsgFields := &optionalMsgFields{}
2✔
991
        optionalMsgFields.apply(optionalFields...)
2✔
992

2✔
993
        nMsg := &networkMsg{
2✔
994
                msg:               msg,
2✔
995
                optionalMsgFields: optionalMsgFields,
2✔
996
                isRemote:          false,
2✔
997
                source:            d.selfKey,
2✔
998
                err:               make(chan error, 1),
2✔
999
        }
2✔
1000

2✔
1001
        select {
2✔
1002
        case d.networkMsgs <- nMsg:
2✔
UNCOV
1003
        case <-d.quit:
×
UNCOV
1004
                nMsg.err <- ErrGossiperShuttingDown
×
1005
        }
1006

1007
        return nMsg.err
2✔
1008
}
1009

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

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

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

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

1037
        // sender is the set of peers that sent us this message.
1038
        senders map[route.Vertex]struct{}
1039
}
1040

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

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

1062
        // channelUpdates are identified by the channel update id field.
1063
        channelUpdates map[channelUpdateID]msgWithSenders
1064

1065
        // nodeAnnouncements are identified by the Vertex field.
1066
        nodeAnnouncements map[route.Vertex]msgWithSenders
1067

1068
        sync.Mutex
1069
}
1070

1071
// Reset operates on deDupedAnnouncements to reset the storage of
1072
// announcements.
1073
func (d *deDupedAnnouncements) Reset() {
2✔
1074
        d.Lock()
2✔
1075
        defer d.Unlock()
2✔
1076

2✔
1077
        d.reset()
2✔
1078
}
2✔
1079

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

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

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

1105
        // Channel announcements are identified by the short channel id field.
1106
        case *lnwire.ChannelAnnouncement1:
2✔
1107
                deDupKey := msg.ShortChannelID
2✔
1108
                sender := route.NewVertex(message.source)
2✔
1109

2✔
1110
                mws, ok := d.channelAnnouncements[deDupKey]
2✔
1111
                if !ok {
4✔
1112
                        mws = msgWithSenders{
2✔
1113
                                msg:     msg,
2✔
1114
                                isLocal: !message.isRemote,
2✔
1115
                                senders: make(map[route.Vertex]struct{}),
2✔
1116
                        }
2✔
1117
                        mws.senders[sender] = struct{}{}
2✔
1118

2✔
1119
                        d.channelAnnouncements[deDupKey] = mws
2✔
1120

2✔
1121
                        return
2✔
1122
                }
2✔
1123

UNCOV
1124
                mws.msg = msg
×
UNCOV
1125
                mws.senders[sender] = struct{}{}
×
1126
                d.channelAnnouncements[deDupKey] = mws
×
1127

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

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

×
1147
                                return
×
1148
                        }
×
1149

1150
                        oldTimestamp = update.Timestamp
×
1151
                }
1152

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

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

2✔
1171
                        // We'll mark the sender of the message in the
2✔
1172
                        // senders map.
2✔
1173
                        mws.senders[sender] = struct{}{}
2✔
1174

2✔
1175
                        d.channelUpdates[deDupKey] = mws
2✔
1176

2✔
1177
                        return
2✔
1178
                }
2✔
1179

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

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

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

1202
                // Discard the message if it's old.
1203
                if oldTimestamp > msg.Timestamp {
4✔
1204
                        return
2✔
1205
                }
2✔
1206

1207
                // Replace if it's newer.
1208
                if oldTimestamp < msg.Timestamp {
4✔
1209
                        mws = msgWithSenders{
2✔
1210
                                msg:     msg,
2✔
1211
                                isLocal: !message.isRemote,
2✔
1212
                                senders: make(map[route.Vertex]struct{}),
2✔
1213
                        }
2✔
1214

2✔
1215
                        mws.senders[sender] = struct{}{}
2✔
1216

2✔
1217
                        d.nodeAnnouncements[deDupKey] = mws
2✔
1218

2✔
1219
                        return
2✔
1220
                }
2✔
1221

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

1229
// AddMsgs is a helper method to add multiple messages to the announcement
1230
// batch.
1231
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
2✔
1232
        d.Lock()
2✔
1233
        defer d.Unlock()
2✔
1234

2✔
1235
        for _, msg := range msgs {
4✔
1236
                d.addMsg(msg)
2✔
1237
        }
2✔
1238
}
1239

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

1247
        // remoteMsgs is the set of messages that we received from a remote
1248
        // party.
1249
        remoteMsgs []msgWithSenders
1250
}
1251

1252
// addMsg adds a new message to the appropriate sub-slice.
1253
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
2✔
1254
        if msg.isLocal {
4✔
1255
                m.localMsgs = append(m.localMsgs, msg)
2✔
1256
        } else {
4✔
1257
                m.remoteMsgs = append(m.remoteMsgs, msg)
2✔
1258
        }
2✔
1259
}
1260

1261
// isEmpty returns true if the batch is empty.
1262
func (m *msgsToBroadcast) isEmpty() bool {
2✔
1263
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
2✔
1264
}
2✔
1265

1266
// length returns the length of the combined message set.
UNCOV
1267
func (m *msgsToBroadcast) length() int {
×
UNCOV
1268
        return len(m.localMsgs) + len(m.remoteMsgs)
×
1269
}
×
1270

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

2✔
1281
        // Get the total number of announcements.
2✔
1282
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
2✔
1283
                len(d.nodeAnnouncements)
2✔
1284

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

2✔
1292
        // Add the channel announcements to the array first.
2✔
1293
        for _, message := range d.channelAnnouncements {
4✔
1294
                msgs.addMsg(message)
2✔
1295
        }
2✔
1296

1297
        // Then add the channel updates.
1298
        for _, message := range d.channelUpdates {
4✔
1299
                msgs.addMsg(message)
2✔
1300
        }
2✔
1301

1302
        // Finally add the node announcements.
1303
        for _, message := range d.nodeAnnouncements {
4✔
1304
                msgs.addMsg(message)
2✔
1305
        }
2✔
1306

1307
        d.reset()
2✔
1308

2✔
1309
        // Return the array of lnwire.messages.
2✔
1310
        return msgs
2✔
1311
}
1312

1313
// calculateSubBatchSize is a helper function that calculates the size to break
1314
// down the batchSize into.
1315
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1316
        minimumBatchSize, batchSize int) int {
2✔
1317
        if subBatchDelay > totalDelay {
2✔
UNCOV
1318
                return batchSize
×
UNCOV
1319
        }
×
1320

1321
        subBatchSize := (batchSize*int(subBatchDelay) +
2✔
1322
                int(totalDelay) - 1) / int(totalDelay)
2✔
1323

2✔
1324
        if subBatchSize < minimumBatchSize {
4✔
1325
                return minimumBatchSize
2✔
1326
        }
2✔
1327

UNCOV
1328
        return subBatchSize
×
1329
}
1330

1331
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1332
// this variable so the function can be mocked in our test.
1333
var batchSizeCalculator = calculateSubBatchSize
1334

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

2✔
1340
        subBatchSize := batchSizeCalculator(
2✔
1341
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
2✔
1342
                d.cfg.MinimumBatchSize, len(announcementBatch),
2✔
1343
        )
2✔
1344

2✔
1345
        var splitAnnouncementBatch [][]msgWithSenders
2✔
1346

2✔
1347
        for subBatchSize < len(announcementBatch) {
4✔
1348
                // For slicing with minimal allocation
2✔
1349
                // https://github.com/golang/go/wiki/SliceTricks
2✔
1350
                announcementBatch, splitAnnouncementBatch =
2✔
1351
                        announcementBatch[subBatchSize:],
2✔
1352
                        append(splitAnnouncementBatch,
2✔
1353
                                announcementBatch[0:subBatchSize:subBatchSize])
2✔
1354
        }
2✔
1355
        splitAnnouncementBatch = append(
2✔
1356
                splitAnnouncementBatch, announcementBatch,
2✔
1357
        )
2✔
1358

2✔
1359
        return splitAnnouncementBatch
2✔
1360
}
1361

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

2✔
1369
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
2✔
1370
        // duration to delay the sending of next announcement batch.
2✔
1371
        delayNextBatch := func() {
4✔
1372
                select {
2✔
1373
                case <-time.After(d.cfg.SubBatchDelay):
2✔
UNCOV
1374
                case <-d.quit:
×
UNCOV
1375
                        return
×
1376
                }
1377
        }
1378

1379
        // Fetch the local and remote announcements.
1380
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
2✔
1381
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
2✔
1382

2✔
1383
        d.wg.Add(1)
2✔
1384
        go func() {
4✔
1385
                defer d.wg.Done()
2✔
1386

2✔
1387
                log.Debugf("Broadcasting %v new local announcements in %d "+
2✔
1388
                        "sub batches", len(annBatch.localMsgs),
2✔
1389
                        len(localBatches))
2✔
1390

2✔
1391
                // Send out the local announcements first.
2✔
1392
                for _, annBatch := range localBatches {
4✔
1393
                        d.sendLocalBatch(annBatch)
2✔
1394
                        delayNextBatch()
2✔
1395
                }
2✔
1396

1397
                log.Debugf("Broadcasting %v new remote announcements in %d "+
2✔
1398
                        "sub batches", len(annBatch.remoteMsgs),
2✔
1399
                        len(remoteBatches))
2✔
1400

2✔
1401
                // Now send the remote announcements.
2✔
1402
                for _, annBatch := range remoteBatches {
4✔
1403
                        d.sendRemoteBatch(ctx, annBatch)
2✔
1404
                        delayNextBatch()
2✔
1405
                }
2✔
1406
        }()
1407
}
1408

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

1419
        err := d.cfg.Broadcast(nil, msgsToSend...)
2✔
1420
        if err != nil {
2✔
UNCOV
1421
                log.Errorf("Unable to send local batch announcements: %v", err)
×
UNCOV
1422
        }
×
1423
}
1424

1425
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1426
// peers.
1427
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1428
        annBatch []msgWithSenders) {
2✔
1429

2✔
1430
        syncerPeers := d.syncMgr.GossipSyncers()
2✔
1431

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

1439
        for _, msgChunk := range annBatch {
4✔
1440
                msgChunk := msgChunk
2✔
1441

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

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

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

2✔
1465
        // Initialize empty deDupedAnnouncements to store announcement batch.
2✔
1466
        announcements := deDupedAnnouncements{}
2✔
1467
        announcements.Reset()
2✔
1468

2✔
1469
        d.cfg.RetransmitTicker.Resume()
2✔
1470
        defer d.cfg.RetransmitTicker.Stop()
2✔
1471

2✔
1472
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
2✔
1473
        defer trickleTimer.Stop()
2✔
1474

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

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

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

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

1508
                case announcement := <-d.networkMsgs:
2✔
1509
                        log.Tracef("Received network message: "+
2✔
1510
                                "peer=%v, msg=%s, is_remote=%v",
2✔
1511
                                announcement.peer, announcement.msg.MsgType(),
2✔
1512
                                announcement.isRemote)
2✔
1513

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

2✔
1526
                                if emittedAnnouncements != nil {
4✔
1527
                                        announcements.AddMsgs(
2✔
1528
                                                emittedAnnouncements...,
2✔
1529
                                        )
2✔
1530
                                }
2✔
1531
                                continue
2✔
1532
                        }
1533

1534
                        // If this message was recently rejected, then we won't
1535
                        // attempt to re-process it.
1536
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
2✔
1537
                                announcement.msg,
2✔
1538
                                sourceToPub(announcement.source),
2✔
1539
                        ) {
2✔
UNCOV
1540

×
UNCOV
1541
                                announcement.err <- fmt.Errorf("recently " +
×
1542
                                        "rejected")
×
1543
                                continue
×
1544
                        }
1545

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

1557
                        d.wg.Add(1)
2✔
1558
                        go d.handleNetworkMessages(
2✔
1559
                                ctx, announcement, &announcements, annJobID,
2✔
1560
                        )
2✔
1561

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

2✔
1570
                        // If the current announcements batch is nil, then we
2✔
1571
                        // have no further work here.
2✔
1572
                        if announcementBatch.isEmpty() {
4✔
1573
                                continue
2✔
1574
                        }
1575

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

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

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

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

2✔
1612
        defer d.wg.Done()
2✔
1613
        defer d.vb.CompleteJob()
2✔
1614

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

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

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

×
1632
                return
×
1633
        }
1634

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

2✔
1640
        log.Tracef("Processed network message %s, returned "+
2✔
1641
                "len(announcements)=%v, allowDependents=%v",
2✔
1642
                nMsg.msg.MsgType(), len(newAnns), allow)
2✔
1643

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

×
1652
                nMsg.err <- err
×
1653

×
1654
                return
×
1655
        }
×
1656

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

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

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

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

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

2✔
1691
        var scid uint64
2✔
1692
        switch m := msg.(type) {
2✔
1693
        case *lnwire.ChannelUpdate1:
2✔
1694
                scid = m.ShortChannelID.ToUint64()
2✔
1695

1696
        case *lnwire.ChannelAnnouncement1:
2✔
1697
                scid = m.ShortChannelID.ToUint64()
2✔
1698

1699
        default:
2✔
1700
                return false
2✔
1701
        }
1702

1703
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
2✔
1704
        return err != cache.ErrElementNotFound
2✔
1705
}
1706

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

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

2✔
1722
        var (
2✔
1723
                havePublicChannels bool
2✔
1724
                edgesToUpdate      []updateTuple
2✔
1725
        )
2✔
1726
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
2✔
1727
                info *models.ChannelEdgeInfo,
2✔
1728
                edge *models.ChannelEdgePolicy) error {
4✔
1729

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

1741
                // We make a note that we have at least one public channel. We
1742
                // use this to determine whether we should send a node
1743
                // announcement below.
1744
                havePublicChannels = true
2✔
1745

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

×
1755
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1756
                                info: info,
×
1757
                                edge: edge,
×
1758
                        })
×
1759
                        return nil
×
1760
                }
×
1761

1762
                timeElapsed := now.Sub(edge.LastUpdate)
2✔
1763

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

1774
                return nil
2✔
1775
        })
1776
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
2✔
UNCOV
1777
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
UNCOV
1778
                        err)
×
1779
        }
×
1780

1781
        var signedUpdates []lnwire.Message
2✔
1782
        for _, chanToUpdate := range edgesToUpdate {
2✔
UNCOV
1783
                // Re-sign and update the channel on disk and retrieve our
×
UNCOV
1784
                // ChannelUpdate to broadcast.
×
1785
                chanAnn, chanUpdate, err := d.updateChannel(
×
1786
                        ctx, chanToUpdate.info, chanToUpdate.edge,
×
1787
                )
×
1788
                if err != nil {
×
1789
                        return fmt.Errorf("unable to update channel: %w", err)
×
1790
                }
×
1791

1792
                // If we have a valid announcement to transmit, then we'll send
1793
                // that along with the update.
UNCOV
1794
                if chanAnn != nil {
×
UNCOV
1795
                        signedUpdates = append(signedUpdates, chanAnn)
×
1796
                }
×
1797

1798
                signedUpdates = append(signedUpdates, chanUpdate)
×
1799
        }
1800

1801
        // If we don't have any public channels, we return as we don't want to
1802
        // broadcast anything that would reveal our existence.
1803
        if !havePublicChannels {
4✔
1804
                return nil
2✔
1805
        }
2✔
1806

1807
        // We'll also check that our NodeAnnouncement is not too old.
1808
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
2✔
1809
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
2✔
1810
        timeElapsed := now.Sub(timestamp)
2✔
1811

2✔
1812
        // If it's been a full day since we've re-broadcasted the
2✔
1813
        // node announcement, refresh it and resend it.
2✔
1814
        nodeAnnStr := ""
2✔
1815
        if timeElapsed >= d.cfg.RebroadcastInterval {
2✔
UNCOV
1816
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
×
UNCOV
1817
                if err != nil {
×
1818
                        return fmt.Errorf("unable to get refreshed node "+
×
1819
                                "announcement: %v", err)
×
1820
                }
×
1821

1822
                signedUpdates = append(signedUpdates, &newNodeAnn)
×
UNCOV
1823
                nodeAnnStr = " and our refreshed node announcement"
×
1824

×
1825
                // Before broadcasting the refreshed node announcement, add it
×
1826
                // to our own graph.
×
1827
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
×
1828
                        log.Errorf("Unable to add refreshed node announcement "+
×
1829
                                "to graph: %v", err)
×
1830
                }
×
1831
        }
1832

1833
        // If we don't have any updates to re-broadcast, then we'll exit
1834
        // early.
1835
        if len(signedUpdates) == 0 {
4✔
1836
                return nil
2✔
1837
        }
2✔
1838

UNCOV
1839
        log.Infof("Retransmitting %v outgoing channels%v",
×
UNCOV
1840
                len(edgesToUpdate), nodeAnnStr)
×
1841

×
1842
        // With all the wire announcements properly crafted, we'll broadcast
×
1843
        // our known outgoing channels to all our immediate peers.
×
1844
        if err := d.cfg.Broadcast(nil, signedUpdates...); err != nil {
×
1845
                return fmt.Errorf("unable to re-broadcast channels: %w", err)
×
1846
        }
×
1847

1848
        return nil
×
1849
}
1850

1851
// processChanPolicyUpdate generates a new set of channel updates for the
1852
// provided list of edges and updates the backing ChannelGraphSource.
1853
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1854
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
2✔
1855

2✔
1856
        var chanUpdates []networkMsg
2✔
1857
        for _, edgeInfo := range edgesToUpdate {
4✔
1858
                // Now that we've collected all the channels we need to update,
2✔
1859
                // we'll re-sign and update the backing ChannelGraphSource, and
2✔
1860
                // retrieve our ChannelUpdate to broadcast.
2✔
1861
                _, chanUpdate, err := d.updateChannel(
2✔
1862
                        ctx, edgeInfo.Info, edgeInfo.Edge,
2✔
1863
                )
2✔
1864
                if err != nil {
2✔
UNCOV
1865
                        return nil, err
×
UNCOV
1866
                }
×
1867

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

2✔
1882
                        var defaultAlias lnwire.ShortChannelID
2✔
1883
                        foundAlias, _ := d.cfg.GetAlias(chanID)
2✔
1884
                        if foundAlias != defaultAlias {
4✔
1885
                                chanUpdate.ShortChannelID = foundAlias
2✔
1886

2✔
1887
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
2✔
1888
                                if err != nil {
2✔
UNCOV
1889
                                        log.Errorf("Unable to sign alias "+
×
UNCOV
1890
                                                "update: %v", err)
×
1891
                                        continue
×
1892
                                }
1893

1894
                                lnSig, err := lnwire.NewSigFromSignature(sig)
2✔
1895
                                if err != nil {
2✔
UNCOV
1896
                                        log.Errorf("Unable to create sig: %v",
×
UNCOV
1897
                                                err)
×
1898
                                        continue
×
1899
                                }
1900

1901
                                chanUpdate.Signature = lnSig
2✔
1902
                        }
1903

1904
                        remotePubKey := remotePubFromChanInfo(
2✔
1905
                                edgeInfo.Info, chanUpdate.ChannelFlags,
2✔
1906
                        )
2✔
1907
                        err := d.reliableSender.sendMessage(
2✔
1908
                                ctx, chanUpdate, remotePubKey,
2✔
1909
                        )
2✔
1910
                        if err != nil {
2✔
UNCOV
1911
                                log.Errorf("Unable to reliably send %v for "+
×
UNCOV
1912
                                        "channel=%v to peer=%x: %v",
×
1913
                                        chanUpdate.MsgType(),
×
1914
                                        chanUpdate.ShortChannelID,
×
1915
                                        remotePubKey, err)
×
1916
                        }
×
1917
                        continue
2✔
1918
                }
1919

1920
                // We set ourselves as the source of this message to indicate
1921
                // that we shouldn't skip any peers when sending this message.
1922
                chanUpdates = append(chanUpdates, networkMsg{
2✔
1923
                        source:   d.selfKey,
2✔
1924
                        isRemote: false,
2✔
1925
                        msg:      chanUpdate,
2✔
1926
                })
2✔
1927
        }
1928

1929
        return chanUpdates, nil
2✔
1930
}
1931

1932
// remotePubFromChanInfo returns the public key of the remote peer given a
1933
// ChannelEdgeInfo that describe a channel we have with them.
1934
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1935
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
2✔
1936

2✔
1937
        var remotePubKey [33]byte
2✔
1938
        switch {
2✔
1939
        case chanFlags&lnwire.ChanUpdateDirection == 0:
2✔
1940
                remotePubKey = chanInfo.NodeKey2Bytes
2✔
1941
        case chanFlags&lnwire.ChanUpdateDirection == 1:
2✔
1942
                remotePubKey = chanInfo.NodeKey1Bytes
2✔
1943
        }
1944

1945
        return remotePubKey
2✔
1946
}
1947

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

2✔
1959
        // First, we'll fetch the state of the channel as we know if from the
2✔
1960
        // database.
2✔
1961
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
2✔
1962
                chanAnnMsg.ShortChannelID,
2✔
1963
        )
2✔
1964
        if err != nil {
2✔
UNCOV
1965
                return nil, err
×
UNCOV
1966
        }
×
1967

1968
        // The edge is in the graph, and has a proof attached, then we'll just
1969
        // reject it as normal.
1970
        if chanInfo.AuthProof != nil {
4✔
1971
                return nil, nil
2✔
1972
        }
2✔
1973

1974
        // Otherwise, this means that the edge is within the graph, but it
1975
        // doesn't yet have a proper proof attached. If we did not receive
1976
        // the proof such that we now can add it, there's nothing more we
1977
        // can do.
UNCOV
1978
        if proof == nil {
×
UNCOV
1979
                return nil, nil
×
1980
        }
×
1981

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

1999
        // If everything checks out, then we'll add the fully assembled proof
2000
        // to the database.
UNCOV
2001
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
UNCOV
2002
        if err != nil {
×
2003
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
2004
                        chanAnnMsg.ShortChannelID, err)
×
2005
                log.Error(err)
×
2006
                return nil, err
×
2007
        }
×
2008

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

×
2029
        }
×
2030

2031
        return announcements, nil
×
2032
}
2033

2034
// fetchPKScript fetches the output script for the given SCID.
2035
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
UNCOV
2036
        []byte, error) {
×
UNCOV
2037

×
2038
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2039
}
×
2040

2041
// addNode processes the given node announcement, and adds it to our channel
2042
// graph.
2043
func (d *AuthenticatedGossiper) addNode(ctx context.Context,
2044
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
2✔
2045

2✔
2046
        if err := netann.ValidateNodeAnn(msg); err != nil {
2✔
UNCOV
2047
                return fmt.Errorf("unable to validate node announcement: %w",
×
UNCOV
2048
                        err)
×
2049
        }
×
2050

2051
        return d.cfg.Graph.AddNode(
2✔
2052
                ctx, models.NodeFromWireAnnouncement(msg), op...,
2✔
2053
        )
2✔
2054
}
2055

2056
// isPremature decides whether a given network message has a block height+delta
2057
// value specified in the future. If so, the message will be added to the
2058
// future message map and be processed when the block height as reached.
2059
//
2060
// NOTE: must be used inside a lock.
2061
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2062
        delta uint32, msg *networkMsg) bool {
2✔
2063

2✔
2064
        // The channel is already confirmed at chanID.BlockHeight so we minus
2✔
2065
        // one block. For instance, if the required confirmation for this
2✔
2066
        // channel announcement is 6, we then only need to wait for 5 more
2✔
2067
        // blocks once the funding tx is confirmed.
2✔
2068
        if delta > 0 {
4✔
2069
                delta--
2✔
2070
        }
2✔
2071

2072
        msgHeight := chanID.BlockHeight + delta
2✔
2073

2✔
2074
        // The message height is smaller or equal to our best known height,
2✔
2075
        // thus the message is mature.
2✔
2076
        if msgHeight <= d.bestHeight {
4✔
2077
                return false
2✔
2078
        }
2✔
2079

2080
        // Add the premature message to our future messages which will be
2081
        // resent once the block height has reached.
2082
        //
2083
        // Copy the networkMsgs since the old message's err chan will be
2084
        // consumed.
2085
        copied := &networkMsg{
2✔
2086
                peer:              msg.peer,
2✔
2087
                source:            msg.source,
2✔
2088
                msg:               msg.msg,
2✔
2089
                optionalMsgFields: msg.optionalMsgFields,
2✔
2090
                isRemote:          msg.isRemote,
2✔
2091
                err:               make(chan error, 1),
2✔
2092
        }
2✔
2093

2✔
2094
        // Create the cached message.
2✔
2095
        cachedMsg := &cachedFutureMsg{
2✔
2096
                msg:    copied,
2✔
2097
                height: msgHeight,
2✔
2098
        }
2✔
2099

2✔
2100
        // Increment the msg ID and add it to the cache.
2✔
2101
        nextMsgID := d.futureMsgs.nextMsgID()
2✔
2102
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
2✔
2103
        if err != nil {
2✔
UNCOV
2104
                log.Errorf("Adding future message got error: %v", err)
×
UNCOV
2105
        }
×
2106

2107
        log.Debugf("Network message: %v added to future messages for "+
2✔
2108
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
2✔
2109
                msgHeight, d.bestHeight)
2✔
2110

2✔
2111
        return true
2✔
2112
}
2113

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

2✔
2124
        // If this is a remote update, we set the scheduler option to lazily
2✔
2125
        // add it to the graph.
2✔
2126
        var schedulerOp []batch.SchedulerOption
2✔
2127
        if nMsg.isRemote {
4✔
2128
                schedulerOp = append(schedulerOp, batch.LazyAdd())
2✔
2129
        }
2✔
2130

2131
        switch msg := nMsg.msg.(type) {
2✔
2132
        // A new node announcement has arrived which either presents new
2133
        // information about a node in one of the channels we know about, or a
2134
        // updating previously advertised information.
2135
        case *lnwire.NodeAnnouncement:
2✔
2136
                return d.handleNodeAnnouncement(ctx, nMsg, msg, schedulerOp)
2✔
2137

2138
        // A new channel announcement has arrived, this indicates the
2139
        // *creation* of a new channel within the network. This only advertises
2140
        // the existence of a channel and not yet the routing policies in
2141
        // either direction of the channel.
2142
        case *lnwire.ChannelAnnouncement1:
2✔
2143
                return d.handleChanAnnouncement(ctx, nMsg, msg, schedulerOp...)
2✔
2144

2145
        // A new authenticated channel edge update has arrived. This indicates
2146
        // that the directional information for an already known channel has
2147
        // been updated.
2148
        case *lnwire.ChannelUpdate1:
2✔
2149
                return d.handleChanUpdate(ctx, nMsg, msg, schedulerOp)
2✔
2150

2151
        // A new signature announcement has been received. This indicates
2152
        // willingness of nodes involved in the funding of a channel to
2153
        // announce this new channel to the rest of the world.
2154
        case *lnwire.AnnounceSignatures1:
2✔
2155
                return d.handleAnnSig(ctx, nMsg, msg)
2✔
2156

UNCOV
2157
        default:
×
UNCOV
2158
                err := errors.New("wrong type of the announcement")
×
2159
                nMsg.err <- err
×
2160
                return nil, false
×
2161
        }
2162
}
2163

2164
// processZombieUpdate determines whether the provided channel update should
2165
// resurrect a given zombie edge.
2166
//
2167
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2168
// should be inspected.
2169
func (d *AuthenticatedGossiper) processZombieUpdate(_ context.Context,
2170
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
UNCOV
2171
        msg *lnwire.ChannelUpdate1) error {
×
UNCOV
2172

×
2173
        // The least-significant bit in the flag on the channel update tells us
×
2174
        // which edge is being updated.
×
2175
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
×
2176

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

2194
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
×
UNCOV
2195
        if err != nil {
×
2196
                return fmt.Errorf("unable to verify channel "+
×
2197
                        "update signature: %v", err)
×
2198
        }
×
2199

2200
        // With the signature valid, we'll proceed to mark the
2201
        // edge as live and wait for the channel announcement to
2202
        // come through again.
UNCOV
2203
        err = d.cfg.Graph.MarkEdgeLive(scid)
×
UNCOV
2204
        switch {
×
2205
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2206
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2207
                        "zombie index: %v", err)
×
2208

×
2209
                return nil
×
2210

2211
        case err != nil:
×
UNCOV
2212
                return fmt.Errorf("unable to remove edge with "+
×
2213
                        "chan_id=%v from zombie index: %v",
×
2214
                        msg.ShortChannelID, err)
×
2215

2216
        default:
×
2217
        }
2218

UNCOV
2219
        log.Debugf("Removed edge with chan_id=%v from zombie "+
×
UNCOV
2220
                "index", msg.ShortChannelID)
×
2221

×
2222
        return nil
×
2223
}
2224

2225
// fetchNodeAnn fetches the latest signed node announcement from our point of
2226
// view for the node with the given public key.
2227
func (d *AuthenticatedGossiper) fetchNodeAnn(ctx context.Context,
2228
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
2✔
2229

2✔
2230
        node, err := d.cfg.Graph.FetchLightningNode(ctx, pubKey)
2✔
2231
        if err != nil {
2✔
UNCOV
2232
                return nil, err
×
UNCOV
2233
        }
×
2234

2235
        return node.NodeAnnouncement(true)
2✔
2236
}
2237

2238
// isMsgStale determines whether a message retrieved from the backing
2239
// MessageStore is seen as stale by the current graph.
2240
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2241
        msg lnwire.Message) bool {
2✔
2242

2✔
2243
        switch msg := msg.(type) {
2✔
2244
        case *lnwire.AnnounceSignatures1:
2✔
2245
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
2✔
2246
                        msg.ShortChannelID,
2✔
2247
                )
2✔
2248

2✔
2249
                // If the channel cannot be found, it is most likely a leftover
2✔
2250
                // message for a channel that was closed, so we can consider it
2✔
2251
                // stale.
2✔
2252
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
4✔
2253
                        return true
2✔
2254
                }
2✔
2255
                if err != nil {
2✔
UNCOV
2256
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
UNCOV
2257
                                "%v", msg.ShortChannelID, err)
×
2258
                        return false
×
2259
                }
×
2260

2261
                // If the proof exists in the graph, then we have successfully
2262
                // received the remote proof and assembled the full proof, so we
2263
                // can safely delete the local proof from the database.
2264
                return chanInfo.AuthProof != nil
2✔
2265

2266
        case *lnwire.ChannelUpdate1:
2✔
2267
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
2✔
2268

2✔
2269
                // If the channel cannot be found, it is most likely a leftover
2✔
2270
                // message for a channel that was closed, so we can consider it
2✔
2271
                // stale.
2✔
2272
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
4✔
2273
                        return true
2✔
2274
                }
2✔
2275
                if err != nil {
2✔
UNCOV
2276
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
UNCOV
2277
                                "%v", msg.ShortChannelID, err)
×
2278
                        return false
×
2279
                }
×
2280

2281
                // Otherwise, we'll retrieve the correct policy that we
2282
                // currently have stored within our graph to check if this
2283
                // message is stale by comparing its timestamp.
2284
                var p *models.ChannelEdgePolicy
2✔
2285
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4✔
2286
                        p = p1
2✔
2287
                } else {
4✔
2288
                        p = p2
2✔
2289
                }
2✔
2290

2291
                // If the policy is still unknown, then we can consider this
2292
                // policy fresh.
2293
                if p == nil {
2✔
UNCOV
2294
                        return false
×
UNCOV
2295
                }
×
2296

2297
                timestamp := time.Unix(int64(msg.Timestamp), 0)
2✔
2298
                return p.LastUpdate.After(timestamp)
2✔
2299

UNCOV
2300
        default:
×
UNCOV
2301
                // We'll make sure to not mark any unsupported messages as stale
×
2302
                // to ensure they are not removed.
×
2303
                return false
×
2304
        }
2305
}
2306

2307
// updateChannel creates a new fully signed update for the channel, and updates
2308
// the underlying graph with the new state.
2309
func (d *AuthenticatedGossiper) updateChannel(ctx context.Context,
2310
        info *models.ChannelEdgeInfo,
2311
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2312
        *lnwire.ChannelUpdate1, error) {
2✔
2313

2✔
2314
        // Parse the unsigned edge into a channel update.
2✔
2315
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
2✔
2316

2✔
2317
        // We'll generate a new signature over a digest of the channel
2✔
2318
        // announcement itself and update the timestamp to ensure it propagate.
2✔
2319
        err := netann.SignChannelUpdate(
2✔
2320
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
2✔
2321
                netann.ChanUpdSetTimestamp,
2✔
2322
        )
2✔
2323
        if err != nil {
2✔
UNCOV
2324
                return nil, nil, err
×
UNCOV
2325
        }
×
2326

2327
        // Next, we'll set the new signature in place, and update the reference
2328
        // in the backing slice.
2329
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
2✔
2330
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
2✔
2331

2✔
2332
        // To ensure that our signature is valid, we'll verify it ourself
2✔
2333
        // before committing it to the slice returned.
2✔
2334
        err = netann.ValidateChannelUpdateAnn(
2✔
2335
                d.selfKey, info.Capacity, chanUpdate,
2✔
2336
        )
2✔
2337
        if err != nil {
2✔
UNCOV
2338
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
UNCOV
2339
                        "update sig: %v", err)
×
2340
        }
×
2341

2342
        // Finally, we'll write the new edge policy to disk.
2343
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
2✔
UNCOV
2344
                return nil, nil, err
×
UNCOV
2345
        }
×
2346

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

2389
        return chanAnn, chanUpdate, err
2✔
2390
}
2391

2392
// SyncManager returns the gossiper's SyncManager instance.
2393
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
2✔
2394
        return d.syncMgr
2✔
2395
}
2✔
2396

2397
// IsKeepAliveUpdate determines whether this channel update is considered a
2398
// keep-alive update based on the previous channel update processed for the same
2399
// direction.
2400
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2401
        prev *models.ChannelEdgePolicy) bool {
2✔
2402

2✔
2403
        // Both updates should be from the same direction.
2✔
2404
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
2✔
2405
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
2✔
UNCOV
2406

×
UNCOV
2407
                return false
×
2408
        }
×
2409

2410
        // The timestamp should always increase for a keep-alive update.
2411
        timestamp := time.Unix(int64(update.Timestamp), 0)
2✔
2412
        if !timestamp.After(prev.LastUpdate) {
2✔
UNCOV
2413
                return false
×
UNCOV
2414
        }
×
2415

2416
        // None of the remaining fields should change for a keep-alive update.
2417
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
4✔
2418
                return false
2✔
2419
        }
2✔
2420
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
4✔
2421
                return false
2✔
2422
        }
2✔
2423
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
4✔
2424
                return false
2✔
2425
        }
2✔
2426
        if update.TimeLockDelta != prev.TimeLockDelta {
2✔
UNCOV
2427
                return false
×
UNCOV
2428
        }
×
2429
        if update.HtlcMinimumMsat != prev.MinHTLC {
2✔
2430
                return false
×
UNCOV
2431
        }
×
2432
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
2✔
2433
                return false
×
UNCOV
2434
        }
×
2435
        if update.HtlcMaximumMsat != prev.MaxHTLC {
2✔
2436
                return false
×
UNCOV
2437
        }
×
2438
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
4✔
2439
                return false
2✔
2440
        }
2✔
2441
        return true
2✔
2442
}
2443

2444
// latestHeight returns the gossiper's latest height known of the chain.
2445
func (d *AuthenticatedGossiper) latestHeight() uint32 {
2✔
2446
        d.Lock()
2✔
2447
        defer d.Unlock()
2✔
2448
        return d.bestHeight
2✔
2449
}
2✔
2450

2451
// handleNodeAnnouncement processes a new node announcement.
2452
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2453
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2454
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
2✔
2455

2✔
2456
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
2✔
2457

2✔
2458
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
2✔
2459
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
2✔
2460
                nMsg.source.SerializeCompressed())
2✔
2461

2✔
2462
        // We'll quickly ask the router if it already has a newer update for
2✔
2463
        // this node so we can skip validating signatures if not required.
2✔
2464
        if d.cfg.Graph.IsStaleNode(ctx, nodeAnn.NodeID, timestamp) {
4✔
2465
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
2✔
2466
                nMsg.err <- nil
2✔
2467
                return nil, true
2✔
2468
        }
2✔
2469

2470
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
4✔
2471
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
2✔
2472
                        err)
2✔
2473

2✔
2474
                if !graph.IsError(
2✔
2475
                        err,
2✔
2476
                        graph.ErrOutdated,
2✔
2477
                        graph.ErrIgnored,
2✔
2478
                ) {
2✔
UNCOV
2479

×
UNCOV
2480
                        log.Error(err)
×
2481
                }
×
2482

2483
                nMsg.err <- err
2✔
2484
                return nil, false
2✔
2485
        }
2486

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

2498
        var announcements []networkMsg
2✔
2499

2✔
2500
        // If it does, we'll add their announcement to our batch so that it can
2✔
2501
        // be broadcast to the rest of our peers.
2✔
2502
        if isPublic {
4✔
2503
                announcements = append(announcements, networkMsg{
2✔
2504
                        peer:     nMsg.peer,
2✔
2505
                        isRemote: nMsg.isRemote,
2✔
2506
                        source:   nMsg.source,
2✔
2507
                        msg:      nodeAnn,
2✔
2508
                })
2✔
2509
        } else {
4✔
2510
                log.Tracef("Skipping broadcasting node announcement for %x "+
2✔
2511
                        "due to being unadvertised", nodeAnn.NodeID)
2✔
2512
        }
2✔
2513

2514
        nMsg.err <- nil
2✔
2515
        // TODO(roasbeef): get rid of the above
2✔
2516

2✔
2517
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
2✔
2518
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
2✔
2519
                nMsg.source.SerializeCompressed())
2✔
2520

2✔
2521
        return announcements, true
2✔
2522
}
2523

2524
// handleChanAnnouncement processes a new channel announcement.
2525
//
2526
//nolint:funlen
2527
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2528
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2529
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
2✔
2530

2✔
2531
        scid := ann.ShortChannelID
2✔
2532

2✔
2533
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
2✔
2534
                nMsg.peer, scid.ToUint64())
2✔
2535

2✔
2536
        // We'll ignore any channel announcements that target any chain other
2✔
2537
        // than the set of chains we know of.
2✔
2538
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
2✔
UNCOV
2539
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
UNCOV
2540
                        ", gossiper on chain=%v", ann.ChainHash,
×
2541
                        d.cfg.ChainHash)
×
2542
                log.Errorf(err.Error())
×
2543

×
2544
                key := newRejectCacheKey(
×
2545
                        scid.ToUint64(),
×
2546
                        sourceToPub(nMsg.source),
×
2547
                )
×
2548
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2549

×
2550
                nMsg.err <- err
×
2551
                return nil, false
×
2552
        }
×
2553

2554
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2555
        // reject the announcement. Since the router accepts alias SCIDs,
2556
        // not erroring out would be a DoS vector.
2557
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
2✔
UNCOV
2558
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
UNCOV
2559
                log.Errorf(err.Error())
×
2560

×
2561
                key := newRejectCacheKey(
×
2562
                        scid.ToUint64(),
×
2563
                        sourceToPub(nMsg.source),
×
2564
                )
×
2565
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2566

×
2567
                nMsg.err <- err
×
2568
                return nil, false
×
2569
        }
×
2570

2571
        // If the advertised inclusionary block is beyond our knowledge of the
2572
        // chain tip, then we'll ignore it for now.
2573
        d.Lock()
2✔
2574
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
2✔
UNCOV
2575
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
×
UNCOV
2576
                        "advertises height %v, only height %v is known",
×
2577
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
×
2578
                d.Unlock()
×
2579
                nMsg.err <- nil
×
2580
                return nil, false
×
2581
        }
×
2582
        d.Unlock()
2✔
2583

2✔
2584
        // At this point, we'll now ask the router if this is a zombie/known
2✔
2585
        // edge. If so we can skip all the processing below.
2✔
2586
        if d.cfg.Graph.IsKnownEdge(scid) {
4✔
2587
                nMsg.err <- nil
2✔
2588
                return nil, true
2✔
2589
        }
2✔
2590

2591
        // Check if the channel is already closed in which case we can ignore
2592
        // it.
2593
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
2✔
2594
        if err != nil {
2✔
UNCOV
2595
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
UNCOV
2596
                        err)
×
2597
                nMsg.err <- err
×
2598

×
2599
                return nil, false
×
2600
        }
×
2601

2602
        if closed {
2✔
UNCOV
2603
                err = fmt.Errorf("ignoring closed channel %v", scid)
×
UNCOV
2604
                log.Error(err)
×
2605

×
2606
                // If this is an announcement from us, we'll just ignore it.
×
2607
                if !nMsg.isRemote {
×
2608
                        nMsg.err <- err
×
2609
                        return nil, false
×
2610
                }
×
2611

2612
                // Increment the peer's ban score if they are sending closed
2613
                // channel announcements.
UNCOV
2614
                d.banman.incrementBanScore(nMsg.peer.PubKey())
×
UNCOV
2615

×
2616
                // If the peer is banned and not a channel peer, we'll
×
2617
                // disconnect them.
×
2618
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
×
2619
                if dcErr != nil {
×
2620
                        log.Errorf("failed to check if we should disconnect "+
×
2621
                                "peer: %v", dcErr)
×
2622
                        nMsg.err <- dcErr
×
2623

×
2624
                        return nil, false
×
2625
                }
×
2626

2627
                if shouldDc {
×
UNCOV
2628
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2629
                }
×
2630

2631
                nMsg.err <- err
×
UNCOV
2632

×
2633
                return nil, false
×
2634
        }
2635

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

×
2645
                        key := newRejectCacheKey(
×
2646
                                scid.ToUint64(),
×
2647
                                sourceToPub(nMsg.source),
×
2648
                        )
×
2649
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2650

×
2651
                        log.Error(err)
×
2652
                        nMsg.err <- err
×
2653
                        return nil, false
×
2654
                }
×
2655

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

2667
        // With the proof validated (if necessary), we can now store it within
2668
        // the database for our path finding and syncing needs.
2669
        var featureBuf bytes.Buffer
2✔
2670
        if err := ann.Features.Encode(&featureBuf); err != nil {
2✔
UNCOV
2671
                log.Errorf("unable to encode features: %v", err)
×
UNCOV
2672
                nMsg.err <- err
×
2673
                return nil, false
×
2674
        }
×
2675

2676
        edge := &models.ChannelEdgeInfo{
2✔
2677
                ChannelID:        scid.ToUint64(),
2✔
2678
                ChainHash:        ann.ChainHash,
2✔
2679
                NodeKey1Bytes:    ann.NodeID1,
2✔
2680
                NodeKey2Bytes:    ann.NodeID2,
2✔
2681
                BitcoinKey1Bytes: ann.BitcoinKey1,
2✔
2682
                BitcoinKey2Bytes: ann.BitcoinKey2,
2✔
2683
                AuthProof:        proof,
2✔
2684
                Features:         featureBuf.Bytes(),
2✔
2685
                ExtraOpaqueData:  ann.ExtraOpaqueData,
2✔
2686
        }
2✔
2687

2✔
2688
        // If there were any optional message fields provided, we'll include
2✔
2689
        // them in its serialized disk representation now.
2✔
2690
        var tapscriptRoot fn.Option[chainhash.Hash]
2✔
2691
        if nMsg.optionalMsgFields != nil {
4✔
2692
                if nMsg.optionalMsgFields.capacity != nil {
4✔
2693
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
2✔
2694
                }
2✔
2695
                if nMsg.optionalMsgFields.channelPoint != nil {
4✔
2696
                        cp := *nMsg.optionalMsgFields.channelPoint
2✔
2697
                        edge.ChannelPoint = cp
2✔
2698
                }
2✔
2699

2700
                // Optional tapscript root for custom channels.
2701
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
2✔
2702
        }
2703

2704
        // Before we start validation or add the edge to the database, we obtain
2705
        // the mutex for this channel ID. We do this to ensure no other
2706
        // goroutine has read the database and is now making decisions based on
2707
        // this DB state, before it writes to the DB. It also ensures that we
2708
        // don't perform the expensive validation check on the same channel
2709
        // announcement at the same time.
2710
        d.channelMtx.Lock(scid.ToUint64())
2✔
2711

2✔
2712
        // If AssumeChannelValid is present, then we are unable to perform any
2✔
2713
        // of the expensive checks below, so we'll short-circuit our path
2✔
2714
        // straight to adding the edge to our graph. If the passed
2✔
2715
        // ShortChannelID is an alias, then we'll skip validation as it will
2✔
2716
        // not map to a legitimate tx. This is not a DoS vector as only we can
2✔
2717
        // add an alias ChannelAnnouncement from the gossiper.
2✔
2718
        if !(d.cfg.AssumeChannelValid || d.cfg.IsAlias(scid)) { //nolint:nestif
4✔
2719
                op, capacity, script, err := d.validateFundingTransaction(
2✔
2720
                        ctx, ann, tapscriptRoot,
2✔
2721
                )
2✔
2722
                if err != nil {
2✔
UNCOV
2723
                        defer d.channelMtx.Unlock(scid.ToUint64())
×
UNCOV
2724

×
2725
                        switch {
×
2726
                        case errors.Is(err, ErrNoFundingTransaction),
2727
                                errors.Is(err, ErrInvalidFundingOutput):
×
UNCOV
2728

×
2729
                                key := newRejectCacheKey(
×
2730
                                        scid.ToUint64(),
×
2731
                                        sourceToPub(nMsg.source),
×
2732
                                )
×
2733
                                _, _ = d.recentRejects.Put(
×
2734
                                        key, &cachedReject{},
×
2735
                                )
×
2736

×
2737
                                // Increment the peer's ban score. We check
×
2738
                                // isRemote so we don't actually ban the peer in
×
2739
                                // case of a local bug.
×
2740
                                if nMsg.isRemote {
×
2741
                                        d.banman.incrementBanScore(
×
2742
                                                nMsg.peer.PubKey(),
×
2743
                                        )
×
2744
                                }
×
2745

2746
                        case errors.Is(err, ErrChannelSpent):
×
UNCOV
2747
                                key := newRejectCacheKey(
×
2748
                                        scid.ToUint64(),
×
2749
                                        sourceToPub(nMsg.source),
×
2750
                                )
×
2751
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2752

×
2753
                                // Since this channel has already been closed,
×
2754
                                // we'll add it to the graph's closed channel
×
2755
                                // index such that we won't attempt to do
×
2756
                                // expensive validation checks on it again.
×
2757
                                // TODO: Populate the ScidCloser by using closed
×
2758
                                // channel notifications.
×
2759
                                dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
×
2760
                                if dbErr != nil {
×
2761
                                        log.Errorf("failed to mark scid(%v) "+
×
2762
                                                "as closed: %v", scid, dbErr)
×
2763

×
2764
                                        nMsg.err <- dbErr
×
2765

×
2766
                                        return nil, false
×
2767
                                }
×
2768

2769
                                // Increment the peer's ban score. We check
2770
                                // isRemote so we don't accidentally ban
2771
                                // ourselves in case of a bug.
UNCOV
2772
                                if nMsg.isRemote {
×
UNCOV
2773
                                        d.banman.incrementBanScore(
×
2774
                                                nMsg.peer.PubKey(),
×
2775
                                        )
×
2776
                                }
×
2777

2778
                        default:
×
UNCOV
2779
                                // Otherwise, this is just a regular rejected
×
2780
                                // edge.
×
2781
                                key := newRejectCacheKey(
×
2782
                                        scid.ToUint64(),
×
2783
                                        sourceToPub(nMsg.source),
×
2784
                                )
×
2785
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2786
                        }
2787

UNCOV
2788
                        if !nMsg.isRemote {
×
UNCOV
2789
                                log.Errorf("failed to add edge for local "+
×
2790
                                        "channel: %v", err)
×
2791
                                nMsg.err <- err
×
2792

×
2793
                                return nil, false
×
2794
                        }
×
2795

2796
                        shouldDc, dcErr := d.ShouldDisconnect(
×
UNCOV
2797
                                nMsg.peer.IdentityKey(),
×
2798
                        )
×
2799
                        if dcErr != nil {
×
2800
                                log.Errorf("failed to check if we should "+
×
2801
                                        "disconnect peer: %v", dcErr)
×
2802
                                nMsg.err <- dcErr
×
2803

×
2804
                                return nil, false
×
2805
                        }
×
2806

2807
                        if shouldDc {
×
UNCOV
2808
                                nMsg.peer.Disconnect(ErrPeerBanned)
×
2809
                        }
×
2810

2811
                        nMsg.err <- err
×
UNCOV
2812

×
2813
                        return nil, false
×
2814
                }
2815

2816
                edge.FundingScript = fn.Some(script)
2✔
2817

2✔
2818
                // TODO(roasbeef): this is a hack, needs to be removed after
2✔
2819
                //  commitment fees are dynamic.
2✔
2820
                edge.Capacity = capacity
2✔
2821
                edge.ChannelPoint = op
2✔
2822
        }
2823

2824
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
2✔
2825

2✔
2826
        // We will add the edge to the channel router. If the nodes present in
2✔
2827
        // this channel are not present in the database, a partial node will be
2✔
2828
        // added to represent each node while we wait for a node announcement.
2✔
2829
        err = d.cfg.Graph.AddEdge(ctx, edge, ops...)
2✔
2830
        if err != nil {
4✔
2831
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
2✔
2832
                        scid.ToUint64(), err)
2✔
2833

2✔
2834
                defer d.channelMtx.Unlock(scid.ToUint64())
2✔
2835

2✔
2836
                // If the edge was rejected due to already being known, then it
2✔
2837
                // may be the case that this new message has a fresh channel
2✔
2838
                // proof, so we'll check.
2✔
2839
                if graph.IsError(err, graph.ErrIgnored) {
4✔
2840
                        // Attempt to process the rejected message to see if we
2✔
2841
                        // get any new announcements.
2✔
2842
                        anns, rErr := d.processRejectedEdge(ctx, ann, proof)
2✔
2843
                        if rErr != nil {
2✔
UNCOV
2844
                                key := newRejectCacheKey(
×
UNCOV
2845
                                        scid.ToUint64(),
×
2846
                                        sourceToPub(nMsg.source),
×
2847
                                )
×
2848
                                cr := &cachedReject{}
×
2849
                                _, _ = d.recentRejects.Put(key, cr)
×
2850

×
2851
                                nMsg.err <- rErr
×
2852

×
2853
                                return nil, false
×
2854
                        }
×
2855

2856
                        log.Debugf("Extracted %v announcements from rejected "+
2✔
2857
                                "msgs", len(anns))
2✔
2858

2✔
2859
                        // If while processing this rejected edge, we realized
2✔
2860
                        // there's a set of announcements we could extract,
2✔
2861
                        // then we'll return those directly.
2✔
2862
                        //
2✔
2863
                        // NOTE: since this is an ErrIgnored, we can return
2✔
2864
                        // true here to signal "allow" to its dependants.
2✔
2865
                        nMsg.err <- nil
2✔
2866

2✔
2867
                        return anns, true
2✔
2868
                }
2869

2870
                // Otherwise, this is just a regular rejected edge.
UNCOV
2871
                key := newRejectCacheKey(
×
UNCOV
2872
                        scid.ToUint64(),
×
2873
                        sourceToPub(nMsg.source),
×
2874
                )
×
2875
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2876

×
2877
                if !nMsg.isRemote {
×
2878
                        log.Errorf("failed to add edge for local channel: %v",
×
2879
                                err)
×
2880
                        nMsg.err <- err
×
2881

×
2882
                        return nil, false
×
2883
                }
×
2884

2885
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
×
UNCOV
2886
                if dcErr != nil {
×
2887
                        log.Errorf("failed to check if we should disconnect "+
×
2888
                                "peer: %v", dcErr)
×
2889
                        nMsg.err <- dcErr
×
2890

×
2891
                        return nil, false
×
2892
                }
×
2893

2894
                if shouldDc {
×
UNCOV
2895
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2896
                }
×
2897

2898
                nMsg.err <- err
×
UNCOV
2899

×
2900
                return nil, false
×
2901
        }
2902

2903
        // If err is nil, release the lock immediately.
2904
        d.channelMtx.Unlock(scid.ToUint64())
2✔
2905

2✔
2906
        log.Debugf("Finish adding edge for short_chan_id: %v", scid.ToUint64())
2✔
2907

2✔
2908
        // If we earlier received any ChannelUpdates for this channel, we can
2✔
2909
        // now process them, as the channel is added to the graph.
2✔
2910
        var channelUpdates []*processedNetworkMsg
2✔
2911

2✔
2912
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
2✔
2913
        if err == nil {
4✔
2914
                // There was actually an entry in the map, so we'll accumulate
2✔
2915
                // it. We don't worry about deletion, since it'll eventually
2✔
2916
                // fall out anyway.
2✔
2917
                chanMsgs := earlyChanUpdates
2✔
2918
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
2✔
2919
        }
2✔
2920

2921
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2922
        // ensure we don't block here, as we can handle only one announcement
2923
        // at a time.
2924
        for _, cu := range channelUpdates {
4✔
2925
                // Skip if already processed.
2✔
2926
                if cu.processed {
2✔
UNCOV
2927
                        continue
×
2928
                }
2929

2930
                // Mark the ChannelUpdate as processed. This ensures that a
2931
                // subsequent announcement in the option-scid-alias case does
2932
                // not re-use an old ChannelUpdate.
2933
                cu.processed = true
2✔
2934

2✔
2935
                d.wg.Add(1)
2✔
2936
                go func(updMsg *networkMsg) {
4✔
2937
                        defer d.wg.Done()
2✔
2938

2✔
2939
                        switch msg := updMsg.msg.(type) {
2✔
2940
                        // Reprocess the message, making sure we return an
2941
                        // error to the original caller in case the gossiper
2942
                        // shuts down.
2943
                        case *lnwire.ChannelUpdate1:
2✔
2944
                                log.Debugf("Reprocessing ChannelUpdate for "+
2✔
2945
                                        "shortChanID=%v", scid.ToUint64())
2✔
2946

2✔
2947
                                select {
2✔
2948
                                case d.networkMsgs <- updMsg:
2✔
UNCOV
2949
                                case <-d.quit:
×
UNCOV
2950
                                        updMsg.err <- ErrGossiperShuttingDown
×
2951
                                }
2952

2953
                        // We don't expect any other message type than
2954
                        // ChannelUpdate to be in this cache.
UNCOV
2955
                        default:
×
UNCOV
2956
                                log.Errorf("Unsupported message type found "+
×
2957
                                        "among ChannelUpdates: %T", msg)
×
2958
                        }
2959
                }(cu.msg)
2960
        }
2961

2962
        // Channel announcement was successfully processed and now it might be
2963
        // broadcast to other connected nodes if it was an announcement with
2964
        // proof (remote).
2965
        var announcements []networkMsg
2✔
2966

2✔
2967
        if proof != nil {
4✔
2968
                announcements = append(announcements, networkMsg{
2✔
2969
                        peer:     nMsg.peer,
2✔
2970
                        isRemote: nMsg.isRemote,
2✔
2971
                        source:   nMsg.source,
2✔
2972
                        msg:      ann,
2✔
2973
                })
2✔
2974
        }
2✔
2975

2976
        nMsg.err <- nil
2✔
2977

2✔
2978
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
2✔
2979
                nMsg.peer, scid.ToUint64())
2✔
2980

2✔
2981
        return announcements, true
2✔
2982
}
2983

2984
// handleChanUpdate processes a new channel update.
2985
//
2986
//nolint:funlen
2987
func (d *AuthenticatedGossiper) handleChanUpdate(ctx context.Context,
2988
        nMsg *networkMsg, upd *lnwire.ChannelUpdate1,
2989
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
2✔
2990

2✔
2991
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
2✔
2992
                nMsg.peer, upd.ShortChannelID.ToUint64())
2✔
2993

2✔
2994
        // We'll ignore any channel updates that target any chain other than
2✔
2995
        // the set of chains we know of.
2✔
2996
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
2✔
UNCOV
2997
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
UNCOV
2998
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2999
                log.Errorf(err.Error())
×
3000

×
3001
                key := newRejectCacheKey(
×
3002
                        upd.ShortChannelID.ToUint64(),
×
3003
                        sourceToPub(nMsg.source),
×
3004
                )
×
3005
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3006

×
3007
                nMsg.err <- err
×
3008
                return nil, false
×
3009
        }
×
3010

3011
        blockHeight := upd.ShortChannelID.BlockHeight
2✔
3012
        shortChanID := upd.ShortChannelID.ToUint64()
2✔
3013

2✔
3014
        // If the advertised inclusionary block is beyond our knowledge of the
2✔
3015
        // chain tip, then we'll put the announcement in limbo to be fully
2✔
3016
        // verified once we advance forward in the chain. If the update has an
2✔
3017
        // alias SCID, we'll skip the isPremature check. This is necessary
2✔
3018
        // since aliases start at block height 16_000_000.
2✔
3019
        d.Lock()
2✔
3020
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
2✔
3021
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
2✔
UNCOV
3022

×
UNCOV
3023
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
UNCOV
3024
                        "premature: advertises height %v, only height %v is "+
×
UNCOV
3025
                        "known", shortChanID, blockHeight, d.bestHeight)
×
UNCOV
3026
                d.Unlock()
×
UNCOV
3027
                nMsg.err <- nil
×
UNCOV
3028
                return nil, false
×
UNCOV
3029
        }
×
3030
        d.Unlock()
2✔
3031

2✔
3032
        // Before we perform any of the expensive checks below, we'll check
2✔
3033
        // whether this update is stale or is for a zombie channel in order to
2✔
3034
        // quickly reject it.
2✔
3035
        timestamp := time.Unix(int64(upd.Timestamp), 0)
2✔
3036

2✔
3037
        // Fetch the SCID we should be using to lock the channelMtx and make
2✔
3038
        // graph queries with.
2✔
3039
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
2✔
3040
        if err != nil {
4✔
3041
                // Fallback and set the graphScid to the peer-provided SCID.
2✔
3042
                // This will occur for non-option-scid-alias channels and for
2✔
3043
                // public option-scid-alias channels after 6 confirmations.
2✔
3044
                // Once public option-scid-alias channels have 6 confs, we'll
2✔
3045
                // ignore ChannelUpdates with one of their aliases.
2✔
3046
                graphScid = upd.ShortChannelID
2✔
3047
        }
2✔
3048

3049
        // We make sure to obtain the mutex for this channel ID before we access
3050
        // the database. This ensures the state we read from the database has
3051
        // not changed between this point and when we call UpdateEdge() later.
3052
        d.channelMtx.Lock(graphScid.ToUint64())
2✔
3053
        defer d.channelMtx.Unlock(graphScid.ToUint64())
2✔
3054

2✔
3055
        if d.cfg.Graph.IsStaleEdgePolicy(
2✔
3056
                graphScid, timestamp, upd.ChannelFlags,
2✔
3057
        ) {
4✔
3058

2✔
3059
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
2✔
3060
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
2✔
3061
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
2✔
3062
                )
2✔
3063

2✔
3064
                nMsg.err <- nil
2✔
3065
                return nil, true
2✔
3066
        }
2✔
3067

3068
        // Check that the ChanUpdate is not too far into the future, this could
3069
        // reveal some faulty implementation therefore we log an error.
3070
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
2✔
UNCOV
3071
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
UNCOV
3072
                        "short_chan_id(%v), timestamp too far in the future: "+
×
3073
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
3074
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
3075
                        nMsg.isRemote,
×
3076
                )
×
3077

×
3078
                nMsg.err <- fmt.Errorf("skewed timestamp of edge policy, "+
×
3079
                        "timestamp too far in the future: %v", timestamp.Unix())
×
3080

×
3081
                return nil, false
×
3082
        }
×
3083

3084
        // Get the node pub key as far since we don't have it in the channel
3085
        // update announcement message. We'll need this to properly verify the
3086
        // message's signature.
3087
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
2✔
3088
        switch {
2✔
3089
        // No error, break.
3090
        case err == nil:
2✔
3091
                break
2✔
3092

UNCOV
3093
        case errors.Is(err, graphdb.ErrZombieEdge):
×
UNCOV
3094
                err = d.processZombieUpdate(ctx, chanInfo, graphScid, upd)
×
3095
                if err != nil {
×
3096
                        log.Debug(err)
×
3097
                        nMsg.err <- err
×
3098
                        return nil, false
×
3099
                }
×
3100

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

2✔
3130
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
2✔
3131
                switch {
2✔
3132
                // Nothing in the cache yet, we can just directly insert this
3133
                // element.
3134
                case err == cache.ErrElementNotFound:
2✔
3135
                        _, _ = d.prematureChannelUpdates.Put(
2✔
3136
                                shortChanID, &cachedNetworkMsg{
2✔
3137
                                        msgs: []*processedNetworkMsg{pMsg},
2✔
3138
                                })
2✔
3139

3140
                // There's already something in the cache, so we'll combine the
3141
                // set of messages into a single value.
3142
                default:
2✔
3143
                        msgs := earlyMsgs.msgs
2✔
3144
                        msgs = append(msgs, pMsg)
2✔
3145
                        _, _ = d.prematureChannelUpdates.Put(
2✔
3146
                                shortChanID, &cachedNetworkMsg{
2✔
3147
                                        msgs: msgs,
2✔
3148
                                })
2✔
3149
                }
3150

3151
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
2✔
3152
                        "(shortChanID=%v), saving for reprocessing later",
2✔
3153
                        shortChanID)
2✔
3154

2✔
3155
                // NOTE: We don't return anything on the error channel for this
2✔
3156
                // message, as we expect that will be done when this
2✔
3157
                // ChannelUpdate is later reprocessed.
2✔
3158
                return nil, false
2✔
3159

UNCOV
3160
        default:
×
UNCOV
3161
                err := fmt.Errorf("unable to validate channel update "+
×
3162
                        "short_chan_id=%v: %v", shortChanID, err)
×
3163
                log.Error(err)
×
3164
                nMsg.err <- err
×
3165

×
3166
                key := newRejectCacheKey(
×
3167
                        upd.ShortChannelID.ToUint64(),
×
3168
                        sourceToPub(nMsg.source),
×
3169
                )
×
3170
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3171

×
3172
                return nil, false
×
3173
        }
3174

3175
        // The least-significant bit in the flag on the channel update
3176
        // announcement tells us "which" side of the channels directed edge is
3177
        // being updated.
3178
        var (
2✔
3179
                pubKey       *btcec.PublicKey
2✔
3180
                edgeToUpdate *models.ChannelEdgePolicy
2✔
3181
        )
2✔
3182
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
2✔
3183
        switch direction {
2✔
3184
        case 0:
2✔
3185
                pubKey, _ = chanInfo.NodeKey1()
2✔
3186
                edgeToUpdate = e1
2✔
3187
        case 1:
2✔
3188
                pubKey, _ = chanInfo.NodeKey2()
2✔
3189
                edgeToUpdate = e2
2✔
3190
        }
3191

3192
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
2✔
3193
                "edge policy=%v", chanInfo.ChannelID,
2✔
3194
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
2✔
3195

2✔
3196
        // Validate the channel announcement with the expected public key and
2✔
3197
        // channel capacity. In the case of an invalid channel update, we'll
2✔
3198
        // return an error to the caller and exit early.
2✔
3199
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
2✔
3200
        if err != nil {
2✔
UNCOV
3201
                rErr := fmt.Errorf("unable to validate channel update "+
×
UNCOV
3202
                        "announcement for short_chan_id=%v: %v",
×
3203
                        spew.Sdump(upd.ShortChannelID), err)
×
3204

×
3205
                log.Error(rErr)
×
3206
                nMsg.err <- rErr
×
3207
                return nil, false
×
3208
        }
×
3209

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

2✔
3252
                        if !rls[direction].Allow() {
4✔
3253
                                log.Debugf("Rate limiting update for channel "+
2✔
3254
                                        "%v from direction %x", shortChanID,
2✔
3255
                                        pubKey.SerializeCompressed())
2✔
3256
                                nMsg.err <- nil
2✔
3257
                                return nil, false
2✔
3258
                        }
2✔
3259
                }
3260
        }
3261

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

2✔
3284
        if err := d.cfg.Graph.UpdateEdge(ctx, update, ops...); err != nil {
2✔
UNCOV
3285
                if graph.IsError(
×
UNCOV
3286
                        err, graph.ErrOutdated,
×
3287
                        graph.ErrIgnored,
×
3288
                ) {
×
3289

×
3290
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
×
3291
                                shortChanID, err)
×
3292
                } else {
×
3293
                        // Since we know the stored SCID in the graph, we'll
×
3294
                        // cache that SCID.
×
3295
                        key := newRejectCacheKey(
×
3296
                                chanInfo.ChannelID,
×
3297
                                sourceToPub(nMsg.source),
×
3298
                        )
×
3299
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3300

×
3301
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3302
                                shortChanID, err)
×
3303
                }
×
3304

3305
                nMsg.err <- err
×
UNCOV
3306
                return nil, false
×
3307
        }
3308

3309
        // If this is a local ChannelUpdate without an AuthProof, it means it
3310
        // is an update to a channel that is not (yet) supposed to be announced
3311
        // to the greater network. However, our channel counter party will need
3312
        // to be given the update, so we'll try sending the update directly to
3313
        // the remote peer.
3314
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
4✔
3315
                if nMsg.optionalMsgFields != nil {
4✔
3316
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
2✔
3317
                        if remoteAlias != nil {
4✔
3318
                                // The remoteAlias field was specified, meaning
2✔
3319
                                // that we should replace the SCID in the
2✔
3320
                                // update with the remote's alias. We'll also
2✔
3321
                                // need to re-sign the channel update. This is
2✔
3322
                                // required for option-scid-alias feature-bit
2✔
3323
                                // negotiated channels.
2✔
3324
                                upd.ShortChannelID = *remoteAlias
2✔
3325

2✔
3326
                                sig, err := d.cfg.SignAliasUpdate(upd)
2✔
3327
                                if err != nil {
2✔
UNCOV
3328
                                        log.Error(err)
×
UNCOV
3329
                                        nMsg.err <- err
×
3330
                                        return nil, false
×
3331
                                }
×
3332

3333
                                lnSig, err := lnwire.NewSigFromSignature(sig)
2✔
3334
                                if err != nil {
2✔
UNCOV
3335
                                        log.Error(err)
×
UNCOV
3336
                                        nMsg.err <- err
×
3337
                                        return nil, false
×
3338
                                }
×
3339

3340
                                upd.Signature = lnSig
2✔
3341
                        }
3342
                }
3343

3344
                // Get our peer's public key.
3345
                remotePubKey := remotePubFromChanInfo(
2✔
3346
                        chanInfo, upd.ChannelFlags,
2✔
3347
                )
2✔
3348

2✔
3349
                log.Debugf("The message %v has no AuthProof, sending the "+
2✔
3350
                        "update to remote peer %x", upd.MsgType(), remotePubKey)
2✔
3351

2✔
3352
                // Now we'll attempt to send the channel update message
2✔
3353
                // reliably to the remote peer in the background, so that we
2✔
3354
                // don't block if the peer happens to be offline at the moment.
2✔
3355
                err := d.reliableSender.sendMessage(ctx, upd, remotePubKey)
2✔
3356
                if err != nil {
2✔
UNCOV
3357
                        err := fmt.Errorf("unable to reliably send %v for "+
×
UNCOV
3358
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3359
                                upd.ShortChannelID, remotePubKey, err)
×
3360
                        nMsg.err <- err
×
3361
                        return nil, false
×
3362
                }
×
3363
        }
3364

3365
        // Channel update announcement was successfully processed and now it
3366
        // can be broadcast to the rest of the network. However, we'll only
3367
        // broadcast the channel update announcement if it has an attached
3368
        // authentication proof. We also won't broadcast the update if it
3369
        // contains an alias because the network would reject this.
3370
        var announcements []networkMsg
2✔
3371
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
4✔
3372
                announcements = append(announcements, networkMsg{
2✔
3373
                        peer:     nMsg.peer,
2✔
3374
                        source:   nMsg.source,
2✔
3375
                        isRemote: nMsg.isRemote,
2✔
3376
                        msg:      upd,
2✔
3377
                })
2✔
3378
        }
2✔
3379

3380
        nMsg.err <- nil
2✔
3381

2✔
3382
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
2✔
3383
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
2✔
3384
                timestamp)
2✔
3385
        return announcements, true
2✔
3386
}
3387

3388
// handleAnnSig processes a new announcement signatures message.
3389
//
3390
//nolint:funlen
3391
func (d *AuthenticatedGossiper) handleAnnSig(ctx context.Context,
3392
        nMsg *networkMsg, ann *lnwire.AnnounceSignatures1) ([]networkMsg,
3393
        bool) {
2✔
3394

2✔
3395
        needBlockHeight := ann.ShortChannelID.BlockHeight +
2✔
3396
                d.cfg.ProofMatureDelta
2✔
3397
        shortChanID := ann.ShortChannelID.ToUint64()
2✔
3398

2✔
3399
        prefix := "local"
2✔
3400
        if nMsg.isRemote {
4✔
3401
                prefix = "remote"
2✔
3402
        }
2✔
3403

3404
        log.Infof("Received new %v announcement signature for %v", prefix,
2✔
3405
                ann.ShortChannelID)
2✔
3406

2✔
3407
        // By the specification, channel announcement proofs should be sent
2✔
3408
        // after some number of confirmations after channel was registered in
2✔
3409
        // bitcoin blockchain. Therefore, we check if the proof is mature.
2✔
3410
        d.Lock()
2✔
3411
        premature := d.isPremature(
2✔
3412
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
2✔
3413
        )
2✔
3414
        if premature {
4✔
3415
                log.Warnf("Premature proof announcement, current block height"+
2✔
3416
                        "lower than needed: %v < %v", d.bestHeight,
2✔
3417
                        needBlockHeight)
2✔
3418
                d.Unlock()
2✔
3419
                nMsg.err <- nil
2✔
3420
                return nil, false
2✔
3421
        }
2✔
3422
        d.Unlock()
2✔
3423

2✔
3424
        // Ensure that we know of a channel with the target channel ID before
2✔
3425
        // proceeding further.
2✔
3426
        //
2✔
3427
        // We must acquire the mutex for this channel ID before getting the
2✔
3428
        // channel from the database, to ensure what we read does not change
2✔
3429
        // before we call AddProof() later.
2✔
3430
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
2✔
3431
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
2✔
3432

2✔
3433
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
2✔
3434
                ann.ShortChannelID,
2✔
3435
        )
2✔
3436
        if err != nil {
4✔
3437
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
2✔
3438
                if err != nil {
4✔
3439
                        err := fmt.Errorf("unable to store the proof for "+
2✔
3440
                                "short_chan_id=%v: %v", shortChanID, err)
2✔
3441
                        log.Error(err)
2✔
3442
                        nMsg.err <- err
2✔
3443

2✔
3444
                        return nil, false
2✔
3445
                }
2✔
3446

3447
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
2✔
3448
                err := d.cfg.WaitingProofStore.Add(proof)
2✔
3449
                if err != nil {
2✔
UNCOV
3450
                        err := fmt.Errorf("unable to store the proof for "+
×
UNCOV
3451
                                "short_chan_id=%v: %v", shortChanID, err)
×
3452
                        log.Error(err)
×
3453
                        nMsg.err <- err
×
3454
                        return nil, false
×
3455
                }
×
3456

3457
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
2✔
3458
                        ", adding to waiting batch", prefix, shortChanID)
2✔
3459
                nMsg.err <- nil
2✔
3460
                return nil, false
2✔
3461
        }
3462

3463
        nodeID := nMsg.source.SerializeCompressed()
2✔
3464
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
2✔
3465
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
2✔
3466

2✔
3467
        // Ensure that channel that was retrieved belongs to the peer which
2✔
3468
        // sent the proof announcement.
2✔
3469
        if !(isFirstNode || isSecondNode) {
2✔
UNCOV
3470
                err := fmt.Errorf("channel that was received doesn't belong "+
×
UNCOV
3471
                        "to the peer which sent the proof, short_chan_id=%v",
×
3472
                        shortChanID)
×
3473
                log.Error(err)
×
3474
                nMsg.err <- err
×
3475
                return nil, false
×
3476
        }
×
3477

3478
        // If proof was sent by a local sub-system, then we'll send the
3479
        // announcement signature to the remote node so they can also
3480
        // reconstruct the full channel announcement.
3481
        if !nMsg.isRemote {
4✔
3482
                var remotePubKey [33]byte
2✔
3483
                if isFirstNode {
4✔
3484
                        remotePubKey = chanInfo.NodeKey2Bytes
2✔
3485
                } else {
4✔
3486
                        remotePubKey = chanInfo.NodeKey1Bytes
2✔
3487
                }
2✔
3488

3489
                // Since the remote peer might not be online we'll call a
3490
                // method that will attempt to deliver the proof when it comes
3491
                // online.
3492
                err := d.reliableSender.sendMessage(ctx, ann, remotePubKey)
2✔
3493
                if err != nil {
2✔
UNCOV
3494
                        err := fmt.Errorf("unable to reliably send %v for "+
×
UNCOV
3495
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3496
                                ann.ShortChannelID, remotePubKey, err)
×
3497
                        nMsg.err <- err
×
3498
                        return nil, false
×
3499
                }
×
3500
        }
3501

3502
        // Check if we already have the full proof for this channel.
3503
        if chanInfo.AuthProof != nil {
4✔
3504
                // If we already have the fully assembled proof, then the peer
2✔
3505
                // sending us their proof has probably not received our local
2✔
3506
                // proof yet. So be kind and send them the full proof.
2✔
3507
                if nMsg.isRemote {
4✔
3508
                        peerID := nMsg.source.SerializeCompressed()
2✔
3509
                        log.Debugf("Got AnnounceSignatures for channel with " +
2✔
3510
                                "full proof.")
2✔
3511

2✔
3512
                        d.wg.Add(1)
2✔
3513
                        go func() {
4✔
3514
                                defer d.wg.Done()
2✔
3515

2✔
3516
                                log.Debugf("Received half proof for channel "+
2✔
3517
                                        "%v with existing full proof. Sending"+
2✔
3518
                                        " full proof to peer=%x",
2✔
3519
                                        ann.ChannelID, peerID)
2✔
3520

2✔
3521
                                ca, _, _, err := netann.CreateChanAnnouncement(
2✔
3522
                                        chanInfo.AuthProof, chanInfo, e1, e2,
2✔
3523
                                )
2✔
3524
                                if err != nil {
2✔
UNCOV
3525
                                        log.Errorf("unable to gen ann: %v",
×
UNCOV
3526
                                                err)
×
3527
                                        return
×
3528
                                }
×
3529

3530
                                err = nMsg.peer.SendMessage(false, ca)
2✔
3531
                                if err != nil {
2✔
UNCOV
3532
                                        log.Errorf("Failed sending full proof"+
×
UNCOV
3533
                                                " to peer=%x: %v", peerID, err)
×
3534
                                        return
×
3535
                                }
×
3536

3537
                                log.Debugf("Full proof sent to peer=%x for "+
2✔
3538
                                        "chanID=%v", peerID, ann.ChannelID)
2✔
3539
                        }()
3540
                }
3541

3542
                log.Debugf("Already have proof for channel with chanID=%v",
2✔
3543
                        ann.ChannelID)
2✔
3544
                nMsg.err <- nil
2✔
3545
                return nil, true
2✔
3546
        }
3547

3548
        // Check that we received the opposite proof. If so, then we're now
3549
        // able to construct the full proof, and create the channel
3550
        // announcement. If we didn't receive the opposite half of the proof
3551
        // then we should store this one, and wait for the opposite to be
3552
        // received.
3553
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
2✔
3554
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
2✔
3555
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
2✔
UNCOV
3556
                err := fmt.Errorf("unable to get the opposite proof for "+
×
UNCOV
3557
                        "short_chan_id=%v: %v", shortChanID, err)
×
3558
                log.Error(err)
×
3559
                nMsg.err <- err
×
3560
                return nil, false
×
3561
        }
×
3562

3563
        if err == channeldb.ErrWaitingProofNotFound {
4✔
3564
                err := d.cfg.WaitingProofStore.Add(proof)
2✔
3565
                if err != nil {
2✔
UNCOV
3566
                        err := fmt.Errorf("unable to store the proof for "+
×
UNCOV
3567
                                "short_chan_id=%v: %v", shortChanID, err)
×
3568
                        log.Error(err)
×
3569
                        nMsg.err <- err
×
3570
                        return nil, false
×
3571
                }
×
3572

3573
                log.Infof("1/2 of channel ann proof received for "+
2✔
3574
                        "short_chan_id=%v, waiting for other half",
2✔
3575
                        shortChanID)
2✔
3576

2✔
3577
                nMsg.err <- nil
2✔
3578
                return nil, false
2✔
3579
        }
3580

3581
        // We now have both halves of the channel announcement proof, then
3582
        // we'll reconstruct the initial announcement so we can validate it
3583
        // shortly below.
3584
        var dbProof models.ChannelAuthProof
2✔
3585
        if isFirstNode {
4✔
3586
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
2✔
3587
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
2✔
3588
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
2✔
3589
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
2✔
3590
        } else {
4✔
3591
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
2✔
3592
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
2✔
3593
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
2✔
3594
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
2✔
3595
        }
2✔
3596

3597
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
2✔
3598
                &dbProof, chanInfo, e1, e2,
2✔
3599
        )
2✔
3600
        if err != nil {
2✔
UNCOV
3601
                log.Error(err)
×
UNCOV
3602
                nMsg.err <- err
×
3603
                return nil, false
×
3604
        }
×
3605

3606
        // With all the necessary components assembled validate the full
3607
        // channel announcement proof.
3608
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
2✔
3609
        if err != nil {
2✔
UNCOV
3610
                err := fmt.Errorf("channel announcement proof for "+
×
UNCOV
3611
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3612

×
3613
                log.Error(err)
×
3614
                nMsg.err <- err
×
3615
                return nil, false
×
3616
        }
×
3617

3618
        // If the channel was returned by the router it means that existence of
3619
        // funding point and inclusion of nodes bitcoin keys in it already
3620
        // checked by the router. In this stage we should check that node keys
3621
        // attest to the bitcoin keys by validating the signatures of
3622
        // announcement. If proof is valid then we'll populate the channel edge
3623
        // with it, so we can announce it on peer connect.
3624
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
2✔
3625
        if err != nil {
2✔
UNCOV
3626
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
UNCOV
3627
                        " %v", ann.ChannelID, err)
×
3628
                log.Error(err)
×
3629
                nMsg.err <- err
×
3630
                return nil, false
×
3631
        }
×
3632

3633
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
2✔
3634
        if err != nil {
2✔
UNCOV
3635
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
UNCOV
3636
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3637
                log.Error(err)
×
3638
                nMsg.err <- err
×
3639
                return nil, false
×
3640
        }
×
3641

3642
        // Proof was successfully created and now can announce the channel to
3643
        // the remain network.
3644
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
2✔
3645
                ", adding to next ann batch", shortChanID)
2✔
3646

2✔
3647
        // Assemble the necessary announcements to add to the next broadcasting
2✔
3648
        // batch.
2✔
3649
        var announcements []networkMsg
2✔
3650
        announcements = append(announcements, networkMsg{
2✔
3651
                peer:   nMsg.peer,
2✔
3652
                source: nMsg.source,
2✔
3653
                msg:    chanAnn,
2✔
3654
        })
2✔
3655
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
4✔
3656
                announcements = append(announcements, networkMsg{
2✔
3657
                        peer:   nMsg.peer,
2✔
3658
                        source: src,
2✔
3659
                        msg:    e1Ann,
2✔
3660
                })
2✔
3661
        }
2✔
3662
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
4✔
3663
                announcements = append(announcements, networkMsg{
2✔
3664
                        peer:   nMsg.peer,
2✔
3665
                        source: src,
2✔
3666
                        msg:    e2Ann,
2✔
3667
                })
2✔
3668
        }
2✔
3669

3670
        // We'll also send along the node announcements for each channel
3671
        // participant if we know of them. To ensure our node announcement
3672
        // propagates to our channel counterparty, we'll set the source for
3673
        // each announcement to the node it belongs to, otherwise we won't send
3674
        // it since the source gets skipped. This isn't necessary for channel
3675
        // updates and announcement signatures since we send those directly to
3676
        // our channel counterparty through the gossiper's reliable sender.
3677
        node1Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey1Bytes)
2✔
3678
        if err != nil {
4✔
3679
                log.Debugf("Unable to fetch node announcement for %x: %v",
2✔
3680
                        chanInfo.NodeKey1Bytes, err)
2✔
3681
        } else {
4✔
3682
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
4✔
3683
                        announcements = append(announcements, networkMsg{
2✔
3684
                                peer:   nMsg.peer,
2✔
3685
                                source: nodeKey1,
2✔
3686
                                msg:    node1Ann,
2✔
3687
                        })
2✔
3688
                }
2✔
3689
        }
3690

3691
        node2Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey2Bytes)
2✔
3692
        if err != nil {
4✔
3693
                log.Debugf("Unable to fetch node announcement for %x: %v",
2✔
3694
                        chanInfo.NodeKey2Bytes, err)
2✔
3695
        } else {
4✔
3696
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
4✔
3697
                        announcements = append(announcements, networkMsg{
2✔
3698
                                peer:   nMsg.peer,
2✔
3699
                                source: nodeKey2,
2✔
3700
                                msg:    node2Ann,
2✔
3701
                        })
2✔
3702
                }
2✔
3703
        }
3704

3705
        nMsg.err <- nil
2✔
3706
        return announcements, true
2✔
3707
}
3708

3709
// isBanned returns true if the peer identified by pubkey is banned for sending
3710
// invalid channel announcements.
3711
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
2✔
3712
        return d.banman.isBanned(pubkey)
2✔
3713
}
2✔
3714

3715
// ShouldDisconnect returns true if we should disconnect the peer identified by
3716
// pubkey.
3717
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3718
        bool, error) {
2✔
3719

2✔
3720
        pubkeySer := pubkey.SerializeCompressed()
2✔
3721

2✔
3722
        var pubkeyBytes [33]byte
2✔
3723
        copy(pubkeyBytes[:], pubkeySer)
2✔
3724

2✔
3725
        // If the public key is banned, check whether or not this is a channel
2✔
3726
        // peer.
2✔
3727
        if d.isBanned(pubkeyBytes) {
2✔
UNCOV
3728
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
×
UNCOV
3729
                if err != nil {
×
3730
                        return false, err
×
3731
                }
×
3732

3733
                // We should only disconnect non-channel peers.
UNCOV
3734
                if !isChanPeer {
×
UNCOV
3735
                        return true, nil
×
3736
                }
×
3737
        }
3738

3739
        return false, nil
2✔
3740
}
3741

3742
// validateFundingTransaction fetches the channel announcements claimed funding
3743
// transaction from chain to ensure that it exists, is not spent and matches
3744
// the channel announcement proof. The transaction's outpoint and value are
3745
// returned if we can glean them from the work done in this method.
3746
func (d *AuthenticatedGossiper) validateFundingTransaction(_ context.Context,
3747
        ann *lnwire.ChannelAnnouncement1,
3748
        tapscriptRoot fn.Option[chainhash.Hash]) (wire.OutPoint, btcutil.Amount,
3749
        []byte, error) {
2✔
3750

2✔
3751
        scid := ann.ShortChannelID
2✔
3752

2✔
3753
        // Before we can add the channel to the channel graph, we need to obtain
2✔
3754
        // the full funding outpoint that's encoded within the channel ID.
2✔
3755
        fundingTx, err := lnwallet.FetchFundingTxWrapper(
2✔
3756
                d.cfg.ChainIO, &scid, d.quit,
2✔
3757
        )
2✔
3758
        if err != nil {
2✔
UNCOV
3759
                //nolint:ll
×
UNCOV
3760
                //
×
3761
                // In order to ensure we don't erroneously mark a channel as a
×
3762
                // zombie due to an RPC failure, we'll attempt to string match
×
3763
                // for the relevant errors.
×
3764
                //
×
3765
                // * btcd:
×
3766
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
×
3767
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
×
3768
                // * bitcoind:
×
3769
                //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
×
3770
                //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
×
3771
                switch {
×
3772
                case strings.Contains(err.Error(), "not found"):
×
3773
                        fallthrough
×
3774

3775
                case strings.Contains(err.Error(), "out of range"):
×
UNCOV
3776
                        // If the funding transaction isn't found at all, then
×
3777
                        // we'll mark the edge itself as a zombie so we don't
×
3778
                        // continue to request it. We use the "zero key" for
×
3779
                        // both node pubkeys so this edge can't be resurrected.
×
3780
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
×
3781
                        if zErr != nil {
×
3782
                                return wire.OutPoint{}, 0, nil, zErr
×
3783
                        }
×
3784

3785
                default:
×
3786
                }
3787

UNCOV
3788
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
×
UNCOV
3789
                        ErrNoFundingTransaction, err)
×
3790
        }
3791

3792
        // Recreate witness output to be sure that declared in channel edge
3793
        // bitcoin keys and channel value corresponds to the reality.
3794
        fundingPkScript, err := makeFundingScript(
2✔
3795
                ann.BitcoinKey1[:], ann.BitcoinKey2[:], ann.Features,
2✔
3796
                tapscriptRoot,
2✔
3797
        )
2✔
3798
        if err != nil {
2✔
UNCOV
3799
                return wire.OutPoint{}, 0, nil, err
×
UNCOV
3800
        }
×
3801

3802
        // Next we'll validate that this channel is actually well formed. If
3803
        // this check fails, then this channel either doesn't exist, or isn't
3804
        // the one that was meant to be created according to the passed channel
3805
        // proofs.
3806
        fundingPoint, err := chanvalidate.Validate(
2✔
3807
                &chanvalidate.Context{
2✔
3808
                        Locator: &chanvalidate.ShortChanIDChanLocator{
2✔
3809
                                ID: scid,
2✔
3810
                        },
2✔
3811
                        MultiSigPkScript: fundingPkScript,
2✔
3812
                        FundingTx:        fundingTx,
2✔
3813
                },
2✔
3814
        )
2✔
3815
        if err != nil {
2✔
UNCOV
3816
                // Mark the edge as a zombie so we won't try to re-validate it
×
UNCOV
3817
                // on start up.
×
3818
                zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
×
3819
                if zErr != nil {
×
3820
                        return wire.OutPoint{}, 0, nil, zErr
×
3821
                }
×
3822

3823
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
×
UNCOV
3824
                        ErrInvalidFundingOutput, err)
×
3825
        }
3826

3827
        // Now that we have the funding outpoint of the channel, ensure
3828
        // that it hasn't yet been spent. If so, then this channel has
3829
        // been closed so we'll ignore it.
3830
        chanUtxo, err := d.cfg.ChainIO.GetUtxo(
2✔
3831
                fundingPoint, fundingPkScript, scid.BlockHeight, d.quit,
2✔
3832
        )
2✔
3833
        if err != nil {
2✔
UNCOV
3834
                if errors.Is(err, btcwallet.ErrOutputSpent) {
×
UNCOV
3835
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
×
3836
                        if zErr != nil {
×
3837
                                return wire.OutPoint{}, 0, nil, zErr
×
3838
                        }
×
3839
                }
3840

UNCOV
3841
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: unable to "+
×
UNCOV
3842
                        "fetch utxo for chan_id=%v, chan_point=%v: %w",
×
3843
                        ErrChannelSpent, scid.ToUint64(), fundingPoint, err)
×
3844
        }
3845

3846
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
2✔
3847
                nil
2✔
3848
}
3849

3850
// makeFundingScript is used to make the funding script for both segwit v0 and
3851
// segwit v1 (taproot) channels.
3852
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3853
        features *lnwire.RawFeatureVector,
3854
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
2✔
3855

2✔
3856
        legacyFundingScript := func() ([]byte, error) {
4✔
3857
                witnessScript, err := input.GenMultiSigScript(
2✔
3858
                        bitcoinKey1, bitcoinKey2,
2✔
3859
                )
2✔
3860
                if err != nil {
2✔
UNCOV
3861
                        return nil, err
×
UNCOV
3862
                }
×
3863
                pkScript, err := input.WitnessScriptHash(witnessScript)
2✔
3864
                if err != nil {
2✔
UNCOV
3865
                        return nil, err
×
UNCOV
3866
                }
×
3867

3868
                return pkScript, nil
2✔
3869
        }
3870

3871
        if features.IsEmpty() {
4✔
3872
                return legacyFundingScript()
2✔
3873
        }
2✔
3874

3875
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
2✔
3876
        if chanFeatureBits.HasFeature(
2✔
3877
                lnwire.SimpleTaprootChannelsOptionalStaging,
2✔
3878
        ) {
4✔
3879

2✔
3880
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
2✔
3881
                if err != nil {
2✔
UNCOV
3882
                        return nil, err
×
UNCOV
3883
                }
×
3884
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
2✔
3885
                if err != nil {
2✔
UNCOV
3886
                        return nil, err
×
UNCOV
3887
                }
×
3888

3889
                fundingScript, _, err := input.GenTaprootFundingScript(
2✔
3890
                        pubKey1, pubKey2, 0, tapscriptRoot,
2✔
3891
                )
2✔
3892
                if err != nil {
2✔
UNCOV
3893
                        return nil, err
×
UNCOV
3894
                }
×
3895

3896
                // TODO(roasbeef): add tapscript root to gossip v1.5
3897

3898
                return fundingScript, nil
2✔
3899
        }
3900

UNCOV
3901
        return legacyFundingScript()
×
3902
}
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