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

lightningnetwork / lnd / 12947350568

24 Jan 2025 09:58AM UTC coverage: 58.706% (-0.09%) from 58.795%
12947350568

Pull #9232

github

Abdulkbk
docs: add release note
Pull Request #9232: chanbackup: archive old channel backup files

52 of 69 new or added lines in 2 files covered. (75.36%)

244 existing lines in 26 files now uncovered.

135827 of 231369 relevant lines covered (58.71%)

19284.67 hits per line

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

80.08
/discovery/gossiper.go
1
package discovery
2

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

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

38
const (
39
        // DefaultMaxChannelUpdateBurst is the default maximum number of updates
40
        // for a specific channel and direction that we'll accept over an
41
        // interval.
42
        DefaultMaxChannelUpdateBurst = 10
43

44
        // DefaultChannelUpdateInterval is the default interval we'll use to
45
        // determine how often we should allow a new update for a specific
46
        // channel and direction.
47
        DefaultChannelUpdateInterval = time.Minute
48

49
        // maxPrematureUpdates tracks the max amount of premature channel
50
        // updates that we'll hold onto.
51
        maxPrematureUpdates = 100
52

53
        // maxFutureMessages tracks the max amount of future messages that
54
        // we'll hold onto.
55
        maxFutureMessages = 1000
56

57
        // DefaultSubBatchDelay is the default delay we'll use when
58
        // broadcasting the next announcement batch.
59
        DefaultSubBatchDelay = 5 * time.Second
60

61
        // maxRejectedUpdates tracks the max amount of rejected channel updates
62
        // we'll maintain. This is the global size across all peers. We'll
63
        // allocate ~3 MB max to the cache.
64
        maxRejectedUpdates = 10_000
65

66
        // DefaultProofMatureDelta specifies the default value used for
67
        // ProofMatureDelta, which is the number of confirmations needed before
68
        // processing the announcement signatures.
69
        DefaultProofMatureDelta = 6
70
)
71

72
var (
73
        // ErrGossiperShuttingDown is an error that is returned if the gossiper
74
        // is in the process of being shut down.
75
        ErrGossiperShuttingDown = errors.New("gossiper is shutting down")
76

77
        // ErrGossipSyncerNotFound signals that we were unable to find an active
78
        // gossip syncer corresponding to a gossip query message received from
79
        // the remote peer.
80
        ErrGossipSyncerNotFound = errors.New("gossip syncer not found")
81

82
        // emptyPubkey is used to compare compressed pubkeys against an empty
83
        // byte array.
84
        emptyPubkey [33]byte
85
)
86

87
// optionalMsgFields is a set of optional message fields that external callers
88
// can provide that serve useful when processing a specific network
89
// announcement.
90
type optionalMsgFields struct {
91
        capacity      *btcutil.Amount
92
        channelPoint  *wire.OutPoint
93
        remoteAlias   *lnwire.ShortChannelID
94
        tapscriptRoot fn.Option[chainhash.Hash]
95
}
96

97
// apply applies the optional fields within the functional options.
98
func (f *optionalMsgFields) apply(optionalMsgFields ...OptionalMsgField) {
49✔
99
        for _, optionalMsgField := range optionalMsgFields {
56✔
100
                optionalMsgField(f)
7✔
101
        }
7✔
102
}
103

104
// OptionalMsgField is a functional option parameter that can be used to provide
105
// external information that is not included within a network message but serves
106
// useful when processing it.
107
type OptionalMsgField func(*optionalMsgFields)
108

109
// ChannelCapacity is an optional field that lets the gossiper know of the
110
// capacity of a channel.
111
func ChannelCapacity(capacity btcutil.Amount) OptionalMsgField {
29✔
112
        return func(f *optionalMsgFields) {
32✔
113
                f.capacity = &capacity
3✔
114
        }
3✔
115
}
116

117
// ChannelPoint is an optional field that lets the gossiper know of the outpoint
118
// of a channel.
119
func ChannelPoint(op wire.OutPoint) OptionalMsgField {
32✔
120
        return func(f *optionalMsgFields) {
38✔
121
                f.channelPoint = &op
6✔
122
        }
6✔
123
}
124

125
// TapscriptRoot is an optional field that lets the gossiper know of the root of
126
// the tapscript tree for a custom channel.
127
func TapscriptRoot(root fn.Option[chainhash.Hash]) OptionalMsgField {
28✔
128
        return func(f *optionalMsgFields) {
30✔
129
                f.tapscriptRoot = root
2✔
130
        }
2✔
131
}
132

133
// RemoteAlias is an optional field that lets the gossiper know that a locally
134
// sent channel update is actually an update for the peer that should replace
135
// the ShortChannelID field with the remote's alias. This is only used for
136
// channels with peers where the option-scid-alias feature bit was negotiated.
137
// The channel update will be added to the graph under the original SCID, but
138
// will be modified and re-signed with this alias.
139
func RemoteAlias(alias *lnwire.ShortChannelID) OptionalMsgField {
28✔
140
        return func(f *optionalMsgFields) {
30✔
141
                f.remoteAlias = alias
2✔
142
        }
2✔
143
}
144

145
// networkMsg couples a routing related wire message with the peer that
146
// originally sent it.
147
type networkMsg struct {
148
        peer              lnpeer.Peer
149
        source            *btcec.PublicKey
150
        msg               lnwire.Message
151
        optionalMsgFields *optionalMsgFields
152

153
        isRemote bool
154

155
        err chan error
156
}
157

158
// chanPolicyUpdateRequest is a request that is sent to the server when a caller
159
// wishes to update a particular set of channels. New ChannelUpdate messages
160
// will be crafted to be sent out during the next broadcast epoch and the fee
161
// updates committed to the lower layer.
162
type chanPolicyUpdateRequest struct {
163
        edgesToUpdate []EdgeWithInfo
164
        errChan       chan error
165
}
166

167
// PinnedSyncers is a set of node pubkeys for which we will maintain an active
168
// syncer at all times.
169
type PinnedSyncers map[route.Vertex]struct{}
170

171
// Config defines the configuration for the service. ALL elements within the
172
// configuration MUST be non-nil for the service to carry out its duties.
173
type Config struct {
174
        // ChainHash is a hash that indicates which resident chain of the
175
        // AuthenticatedGossiper. Any announcements that don't match this
176
        // chain hash will be ignored.
177
        //
178
        // TODO(roasbeef): eventually make into map so can de-multiplex
179
        // incoming announcements
180
        //   * also need to do same for Notifier
181
        ChainHash chainhash.Hash
182

183
        // Graph is the subsystem which is responsible for managing the
184
        // topology of lightning network. After incoming channel, node, channel
185
        // updates announcements are validated they are sent to the router in
186
        // order to be included in the LN graph.
187
        Graph graph.ChannelGraphSource
188

189
        // ChainIO represents an abstraction over a source that can query the
190
        // blockchain.
191
        ChainIO lnwallet.BlockChainIO
192

193
        // ChanSeries is an interfaces that provides access to a time series
194
        // view of the current known channel graph. Each GossipSyncer enabled
195
        // peer will utilize this in order to create and respond to channel
196
        // graph time series queries.
197
        ChanSeries ChannelGraphTimeSeries
198

199
        // Notifier is used for receiving notifications of incoming blocks.
200
        // With each new incoming block found we process previously premature
201
        // announcements.
202
        //
203
        // TODO(roasbeef): could possibly just replace this with an epoch
204
        // channel.
205
        Notifier chainntnfs.ChainNotifier
206

207
        // Broadcast broadcasts a particular set of announcements to all peers
208
        // that the daemon is connected to. If supplied, the exclude parameter
209
        // indicates that the target peer should be excluded from the
210
        // broadcast.
211
        Broadcast func(skips map[route.Vertex]struct{},
212
                msg ...lnwire.Message) error
213

214
        // NotifyWhenOnline is a function that allows the gossiper to be
215
        // notified when a certain peer comes online, allowing it to
216
        // retry sending a peer message.
217
        //
218
        // NOTE: The peerChan channel must be buffered.
219
        NotifyWhenOnline func(peerPubKey [33]byte, peerChan chan<- lnpeer.Peer)
220

221
        // NotifyWhenOffline is a function that allows the gossiper to be
222
        // notified when a certain peer disconnects, allowing it to request a
223
        // notification for when it reconnects.
224
        NotifyWhenOffline func(peerPubKey [33]byte) <-chan struct{}
225

226
        // FetchSelfAnnouncement retrieves our current node announcement, for
227
        // use when determining whether we should update our peers about our
228
        // presence in the network.
229
        FetchSelfAnnouncement func() lnwire.NodeAnnouncement
230

231
        // UpdateSelfAnnouncement produces a new announcement for our node with
232
        // an updated timestamp which can be broadcast to our peers.
233
        UpdateSelfAnnouncement func() (lnwire.NodeAnnouncement, error)
234

235
        // ProofMatureDelta the number of confirmations which is needed before
236
        // exchange the channel announcement proofs.
237
        ProofMatureDelta uint32
238

239
        // TrickleDelay the period of trickle timer which flushes to the
240
        // network the pending batch of new announcements we've received since
241
        // the last trickle tick.
242
        TrickleDelay time.Duration
243

244
        // RetransmitTicker is a ticker that ticks with a period which
245
        // indicates that we should check if we need re-broadcast any of our
246
        // personal channels.
247
        RetransmitTicker ticker.Ticker
248

249
        // RebroadcastInterval is the maximum time we wait between sending out
250
        // channel updates for our active channels and our own node
251
        // announcement. We do this to ensure our active presence on the
252
        // network is known, and we are not being considered a zombie node or
253
        // having zombie channels.
254
        RebroadcastInterval time.Duration
255

256
        // WaitingProofStore is a persistent storage of partial channel proof
257
        // announcement messages. We use it to buffer half of the material
258
        // needed to reconstruct a full authenticated channel announcement.
259
        // Once we receive the other half the channel proof, we'll be able to
260
        // properly validate it and re-broadcast it out to the network.
261
        //
262
        // TODO(wilmer): make interface to prevent channeldb dependency.
263
        WaitingProofStore *channeldb.WaitingProofStore
264

265
        // MessageStore is a persistent storage of gossip messages which we will
266
        // use to determine which messages need to be resent for a given peer.
267
        MessageStore GossipMessageStore
268

269
        // AnnSigner is an instance of the MessageSigner interface which will
270
        // be used to manually sign any outgoing channel updates. The signer
271
        // implementation should be backed by the public key of the backing
272
        // Lightning node.
273
        //
274
        // TODO(roasbeef): extract ann crafting + sign from fundingMgr into
275
        // here?
276
        AnnSigner lnwallet.MessageSigner
277

278
        // ScidCloser is an instance of ClosedChannelTracker that helps the
279
        // gossiper cut down on spam channel announcements for already closed
280
        // channels.
281
        ScidCloser ClosedChannelTracker
282

283
        // NumActiveSyncers is the number of peers for which we should have
284
        // active syncers with. After reaching NumActiveSyncers, any future
285
        // gossip syncers will be passive.
286
        NumActiveSyncers int
287

288
        // NoTimestampQueries will prevent the GossipSyncer from querying
289
        // timestamps of announcement messages from the peer and from replying
290
        // to timestamp queries.
291
        NoTimestampQueries bool
292

293
        // RotateTicker is a ticker responsible for notifying the SyncManager
294
        // when it should rotate its active syncers. A single active syncer with
295
        // a chansSynced state will be exchanged for a passive syncer in order
296
        // to ensure we don't keep syncing with the same peers.
297
        RotateTicker ticker.Ticker
298

299
        // HistoricalSyncTicker is a ticker responsible for notifying the
300
        // syncManager when it should attempt a historical sync with a gossip
301
        // sync peer.
302
        HistoricalSyncTicker ticker.Ticker
303

304
        // ActiveSyncerTimeoutTicker is a ticker responsible for notifying the
305
        // syncManager when it should attempt to start the next pending
306
        // activeSyncer due to the current one not completing its state machine
307
        // within the timeout.
308
        ActiveSyncerTimeoutTicker ticker.Ticker
309

310
        // MinimumBatchSize is minimum size of a sub batch of announcement
311
        // messages.
312
        MinimumBatchSize int
313

314
        // SubBatchDelay is the delay between sending sub batches of
315
        // gossip messages.
316
        SubBatchDelay time.Duration
317

318
        // IgnoreHistoricalFilters will prevent syncers from replying with
319
        // historical data when the remote peer sets a gossip_timestamp_range.
320
        // This prevents ranges with old start times from causing us to dump the
321
        // graph on connect.
322
        IgnoreHistoricalFilters bool
323

324
        // PinnedSyncers is a set of peers that will always transition to
325
        // ActiveSync upon connection. These peers will never transition to
326
        // PassiveSync.
327
        PinnedSyncers PinnedSyncers
328

329
        // MaxChannelUpdateBurst specifies the maximum number of updates for a
330
        // specific channel and direction that we'll accept over an interval.
331
        MaxChannelUpdateBurst int
332

333
        // ChannelUpdateInterval specifies the interval we'll use to determine
334
        // how often we should allow a new update for a specific channel and
335
        // direction.
336
        ChannelUpdateInterval time.Duration
337

338
        // IsAlias returns true if a given ShortChannelID is an alias for
339
        // option_scid_alias channels.
340
        IsAlias func(scid lnwire.ShortChannelID) bool
341

342
        // SignAliasUpdate is used to re-sign a channel update using the
343
        // remote's alias if the option-scid-alias feature bit was negotiated.
344
        SignAliasUpdate func(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
345
                error)
346

347
        // FindBaseByAlias finds the SCID stored in the graph by an alias SCID.
348
        // This is used for channels that have negotiated the option-scid-alias
349
        // feature bit.
350
        FindBaseByAlias func(alias lnwire.ShortChannelID) (
351
                lnwire.ShortChannelID, error)
352

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

358
        // FindChannel allows the gossiper to find a channel that we're party
359
        // to without iterating over the entire set of open channels.
360
        FindChannel func(node *btcec.PublicKey, chanID lnwire.ChannelID) (
361
                *channeldb.OpenChannel, error)
362

363
        // IsStillZombieChannel takes the timestamps of the latest channel
364
        // updates for a channel and returns true if the channel should be
365
        // considered a zombie based on these timestamps.
366
        IsStillZombieChannel func(time.Time, time.Time) bool
367
}
368

369
// processedNetworkMsg is a wrapper around networkMsg and a boolean. It is
370
// used to let the caller of the lru.Cache know if a message has already been
371
// processed or not.
372
type processedNetworkMsg struct {
373
        processed bool
374
        msg       *networkMsg
375
}
376

377
// cachedNetworkMsg is a wrapper around a network message that can be used with
378
// *lru.Cache.
379
type cachedNetworkMsg struct {
380
        msgs []*processedNetworkMsg
381
}
382

383
// Size returns the "size" of an entry. We return the number of items as we
384
// just want to limit the total amount of entries rather than do accurate size
385
// accounting.
386
func (c *cachedNetworkMsg) Size() (uint64, error) {
4✔
387
        return uint64(len(c.msgs)), nil
4✔
388
}
4✔
389

390
// rejectCacheKey is the cache key that we'll use to track announcements we've
391
// recently rejected.
392
type rejectCacheKey struct {
393
        pubkey [33]byte
394
        chanID uint64
395
}
396

397
// newRejectCacheKey returns a new cache key for the reject cache.
398
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
464✔
399
        k := rejectCacheKey{
464✔
400
                chanID: cid,
464✔
401
                pubkey: pub,
464✔
402
        }
464✔
403

464✔
404
        return k
464✔
405
}
464✔
406

407
// sourceToPub returns a serialized-compressed public key for use in the reject
408
// cache.
409
func sourceToPub(pk *btcec.PublicKey) [33]byte {
478✔
410
        var pub [33]byte
478✔
411
        copy(pub[:], pk.SerializeCompressed())
478✔
412
        return pub
478✔
413
}
478✔
414

415
// cachedReject is the empty value used to track the value for rejects.
416
type cachedReject struct {
417
}
418

419
// Size returns the "size" of an entry. We return 1 as we just want to limit
420
// the total size.
421
func (c *cachedReject) Size() (uint64, error) {
203✔
422
        return 1, nil
203✔
423
}
203✔
424

425
// AuthenticatedGossiper is a subsystem which is responsible for receiving
426
// announcements, validating them and applying the changes to router, syncing
427
// lightning network with newly connected nodes, broadcasting announcements
428
// after validation, negotiating the channel announcement proofs exchange and
429
// handling the premature announcements. All outgoing announcements are
430
// expected to be properly signed as dictated in BOLT#7, additionally, all
431
// incoming message are expected to be well formed and signed. Invalid messages
432
// will be rejected by this struct.
433
type AuthenticatedGossiper struct {
434
        // Parameters which are needed to properly handle the start and stop of
435
        // the service.
436
        started sync.Once
437
        stopped sync.Once
438

439
        // bestHeight is the height of the block at the tip of the main chain
440
        // as we know it. Accesses *MUST* be done with the gossiper's lock
441
        // held.
442
        bestHeight uint32
443

444
        quit chan struct{}
445
        wg   sync.WaitGroup
446

447
        // cfg is a copy of the configuration struct that the gossiper service
448
        // was initialized with.
449
        cfg *Config
450

451
        // blockEpochs encapsulates a stream of block epochs that are sent at
452
        // every new block height.
453
        blockEpochs *chainntnfs.BlockEpochEvent
454

455
        // prematureChannelUpdates is a map of ChannelUpdates we have received
456
        // that wasn't associated with any channel we know about.  We store
457
        // them temporarily, such that we can reprocess them when a
458
        // ChannelAnnouncement for the channel is received.
459
        prematureChannelUpdates *lru.Cache[uint64, *cachedNetworkMsg]
460

461
        // banman tracks our peer's ban status.
462
        banman *banman
463

464
        // networkMsgs is a channel that carries new network broadcasted
465
        // message from outside the gossiper service to be processed by the
466
        // networkHandler.
467
        networkMsgs chan *networkMsg
468

469
        // futureMsgs is a list of premature network messages that have a block
470
        // height specified in the future. We will save them and resend it to
471
        // the chan networkMsgs once the block height has reached. The cached
472
        // map format is,
473
        //   {msgID1: msg1, msgID2: msg2, ...}
474
        futureMsgs *futureMsgCache
475

476
        // chanPolicyUpdates is a channel that requests to update the
477
        // forwarding policy of a set of channels is sent over.
478
        chanPolicyUpdates chan *chanPolicyUpdateRequest
479

480
        // selfKey is the identity public key of the backing Lightning node.
481
        selfKey *btcec.PublicKey
482

483
        // selfKeyLoc is the locator for the identity public key of the backing
484
        // Lightning node.
485
        selfKeyLoc keychain.KeyLocator
486

487
        // channelMtx is used to restrict the database access to one
488
        // goroutine per channel ID. This is done to ensure that when
489
        // the gossiper is handling an announcement, the db state stays
490
        // consistent between when the DB is first read until it's written.
491
        channelMtx *multimutex.Mutex[uint64]
492

493
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
494

495
        // syncMgr is a subsystem responsible for managing the gossip syncers
496
        // for peers currently connected. When a new peer is connected, the
497
        // manager will create its accompanying gossip syncer and determine
498
        // whether it should have an activeSync or passiveSync sync type based
499
        // on how many other gossip syncers are currently active. Any activeSync
500
        // gossip syncers are started in a round-robin manner to ensure we're
501
        // not syncing with multiple peers at the same time.
502
        syncMgr *SyncManager
503

504
        // reliableSender is a subsystem responsible for handling reliable
505
        // message send requests to peers. This should only be used for channels
506
        // that are unadvertised at the time of handling the message since if it
507
        // is advertised, then peers should be able to get the message from the
508
        // network.
509
        reliableSender *reliableSender
510

511
        // chanUpdateRateLimiter contains rate limiters for each direction of
512
        // a channel update we've processed. We'll use these to determine
513
        // whether we should accept a new update for a specific channel and
514
        // direction.
515
        //
516
        // NOTE: This map must be synchronized with the main
517
        // AuthenticatedGossiper lock.
518
        chanUpdateRateLimiter map[uint64][2]*rate.Limiter
519

520
        sync.Mutex
521
}
522

523
// New creates a new AuthenticatedGossiper instance, initialized with the
524
// passed configuration parameters.
525
func New(cfg Config, selfKeyDesc *keychain.KeyDescriptor) *AuthenticatedGossiper {
29✔
526
        gossiper := &AuthenticatedGossiper{
29✔
527
                selfKey:           selfKeyDesc.PubKey,
29✔
528
                selfKeyLoc:        selfKeyDesc.KeyLocator,
29✔
529
                cfg:               &cfg,
29✔
530
                networkMsgs:       make(chan *networkMsg),
29✔
531
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
29✔
532
                quit:              make(chan struct{}),
29✔
533
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
29✔
534
                prematureChannelUpdates: lru.NewCache[uint64, *cachedNetworkMsg]( //nolint: ll
29✔
535
                        maxPrematureUpdates,
29✔
536
                ),
29✔
537
                channelMtx: multimutex.NewMutex[uint64](),
29✔
538
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
29✔
539
                        maxRejectedUpdates,
29✔
540
                ),
29✔
541
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
29✔
542
                banman:                newBanman(),
29✔
543
        }
29✔
544

29✔
545
        gossiper.syncMgr = newSyncManager(&SyncManagerCfg{
29✔
546
                ChainHash:               cfg.ChainHash,
29✔
547
                ChanSeries:              cfg.ChanSeries,
29✔
548
                RotateTicker:            cfg.RotateTicker,
29✔
549
                HistoricalSyncTicker:    cfg.HistoricalSyncTicker,
29✔
550
                NumActiveSyncers:        cfg.NumActiveSyncers,
29✔
551
                NoTimestampQueries:      cfg.NoTimestampQueries,
29✔
552
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalFilters,
29✔
553
                BestHeight:              gossiper.latestHeight,
29✔
554
                PinnedSyncers:           cfg.PinnedSyncers,
29✔
555
                IsStillZombieChannel:    cfg.IsStillZombieChannel,
29✔
556
        })
29✔
557

29✔
558
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
29✔
559
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
29✔
560
                NotifyWhenOffline: cfg.NotifyWhenOffline,
29✔
561
                MessageStore:      cfg.MessageStore,
29✔
562
                IsMsgStale:        gossiper.isMsgStale,
29✔
563
        })
29✔
564

29✔
565
        return gossiper
29✔
566
}
29✔
567

568
// EdgeWithInfo contains the information that is required to update an edge.
569
type EdgeWithInfo struct {
570
        // Info describes the channel.
571
        Info *models.ChannelEdgeInfo
572

573
        // Edge describes the policy in one direction of the channel.
574
        Edge *models.ChannelEdgePolicy
575
}
576

577
// PropagateChanPolicyUpdate signals the AuthenticatedGossiper to perform the
578
// specified edge updates. Updates are done in two stages: first, the
579
// AuthenticatedGossiper ensures the update has been committed by dependent
580
// sub-systems, then it signs and broadcasts new updates to the network. A
581
// mapping between outpoints and updated channel policies is returned, which is
582
// used to update the forwarding policies of the underlying links.
583
func (d *AuthenticatedGossiper) PropagateChanPolicyUpdate(
584
        edgesToUpdate []EdgeWithInfo) error {
3✔
585

3✔
586
        errChan := make(chan error, 1)
3✔
587
        policyUpdate := &chanPolicyUpdateRequest{
3✔
588
                edgesToUpdate: edgesToUpdate,
3✔
589
                errChan:       errChan,
3✔
590
        }
3✔
591

3✔
592
        select {
3✔
593
        case d.chanPolicyUpdates <- policyUpdate:
3✔
594
                err := <-errChan
3✔
595
                return err
3✔
596
        case <-d.quit:
×
597
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
598
        }
599
}
600

601
// Start spawns network messages handler goroutine and registers on new block
602
// notifications in order to properly handle the premature announcements.
603
func (d *AuthenticatedGossiper) Start() error {
29✔
604
        var err error
29✔
605
        d.started.Do(func() {
58✔
606
                log.Info("Authenticated Gossiper starting")
29✔
607
                err = d.start()
29✔
608
        })
29✔
609
        return err
29✔
610
}
611

612
func (d *AuthenticatedGossiper) start() error {
29✔
613
        // First we register for new notifications of newly discovered blocks.
29✔
614
        // We do this immediately so we'll later be able to consume any/all
29✔
615
        // blocks which were discovered.
29✔
616
        blockEpochs, err := d.cfg.Notifier.RegisterBlockEpochNtfn(nil)
29✔
617
        if err != nil {
29✔
618
                return err
×
619
        }
×
620
        d.blockEpochs = blockEpochs
29✔
621

29✔
622
        height, err := d.cfg.Graph.CurrentBlockHeight()
29✔
623
        if err != nil {
29✔
624
                return err
×
625
        }
×
626
        d.bestHeight = height
29✔
627

29✔
628
        // Start the reliable sender. In case we had any pending messages ready
29✔
629
        // to be sent when the gossiper was last shut down, we must continue on
29✔
630
        // our quest to deliver them to their respective peers.
29✔
631
        if err := d.reliableSender.Start(); err != nil {
29✔
632
                return err
×
633
        }
×
634

635
        d.syncMgr.Start()
29✔
636

29✔
637
        d.banman.start()
29✔
638

29✔
639
        // Start receiving blocks in its dedicated goroutine.
29✔
640
        d.wg.Add(2)
29✔
641
        go d.syncBlockHeight()
29✔
642
        go d.networkHandler()
29✔
643

29✔
644
        return nil
29✔
645
}
646

647
// syncBlockHeight syncs the best block height for the gossiper by reading
648
// blockEpochs.
649
//
650
// NOTE: must be run as a goroutine.
651
func (d *AuthenticatedGossiper) syncBlockHeight() {
29✔
652
        defer d.wg.Done()
29✔
653

29✔
654
        for {
58✔
655
                select {
29✔
656
                // A new block has arrived, so we can re-process the previously
657
                // premature announcements.
658
                case newBlock, ok := <-d.blockEpochs.Epochs:
2✔
659
                        // If the channel has been closed, then this indicates
2✔
660
                        // the daemon is shutting down, so we exit ourselves.
2✔
661
                        if !ok {
4✔
662
                                return
2✔
663
                        }
2✔
664

665
                        // Once a new block arrives, we update our running
666
                        // track of the height of the chain tip.
667
                        d.Lock()
2✔
668
                        blockHeight := uint32(newBlock.Height)
2✔
669
                        d.bestHeight = blockHeight
2✔
670
                        d.Unlock()
2✔
671

2✔
672
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
2✔
673
                                newBlock.Hash)
2✔
674

2✔
675
                        // Resend future messages, if any.
2✔
676
                        d.resendFutureMessages(blockHeight)
2✔
677

678
                case <-d.quit:
27✔
679
                        return
27✔
680
                }
681
        }
682
}
683

684
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
685
// the unique ID when saving the message.
686
type futureMsgCache struct {
687
        *lru.Cache[uint64, *cachedFutureMsg]
688

689
        // msgID is a monotonically increased integer.
690
        msgID atomic.Uint64
691
}
692

693
// nextMsgID returns a unique message ID.
694
func (f *futureMsgCache) nextMsgID() uint64 {
5✔
695
        return f.msgID.Add(1)
5✔
696
}
5✔
697

698
// newFutureMsgCache creates a new future message cache with the underlying lru
699
// cache being initialized with the specified capacity.
700
func newFutureMsgCache(capacity uint64) *futureMsgCache {
30✔
701
        // Create a new cache.
30✔
702
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
30✔
703

30✔
704
        return &futureMsgCache{
30✔
705
                Cache: cache,
30✔
706
        }
30✔
707
}
30✔
708

709
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
710
type cachedFutureMsg struct {
711
        // msg is the network message.
712
        msg *networkMsg
713

714
        // height is the block height.
715
        height uint32
716
}
717

718
// Size returns the size of the message.
719
func (c *cachedFutureMsg) Size() (uint64, error) {
6✔
720
        // Return a constant 1.
6✔
721
        return 1, nil
6✔
722
}
6✔
723

724
// resendFutureMessages takes a block height, resends all the future messages
725
// found below and equal to that height and deletes those messages found in the
726
// gossiper's futureMsgs.
727
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
2✔
728
        var (
2✔
729
                // msgs are the target messages.
2✔
730
                msgs []*networkMsg
2✔
731

2✔
732
                // keys are the target messages' caching keys.
2✔
733
                keys []uint64
2✔
734
        )
2✔
735

2✔
736
        // filterMsgs is the visitor used when iterating the future cache.
2✔
737
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
4✔
738
                if cmsg.height <= height {
4✔
739
                        msgs = append(msgs, cmsg.msg)
2✔
740
                        keys = append(keys, k)
2✔
741
                }
2✔
742

743
                return true
2✔
744
        }
745

746
        // Filter out the target messages.
747
        d.futureMsgs.Range(filterMsgs)
2✔
748

2✔
749
        // Return early if no messages found.
2✔
750
        if len(msgs) == 0 {
4✔
751
                return
2✔
752
        }
2✔
753

754
        // Remove the filtered messages.
755
        for _, key := range keys {
4✔
756
                d.futureMsgs.Delete(key)
2✔
757
        }
2✔
758

759
        log.Debugf("Resending %d network messages at height %d",
2✔
760
                len(msgs), height)
2✔
761

2✔
762
        for _, msg := range msgs {
4✔
763
                select {
2✔
764
                case d.networkMsgs <- msg:
2✔
765
                case <-d.quit:
×
766
                        msg.err <- ErrGossiperShuttingDown
×
767
                }
768
        }
769
}
770

771
// Stop signals any active goroutines for a graceful closure.
772
func (d *AuthenticatedGossiper) Stop() error {
30✔
773
        d.stopped.Do(func() {
59✔
774
                log.Info("Authenticated gossiper shutting down...")
29✔
775
                defer log.Debug("Authenticated gossiper shutdown complete")
29✔
776

29✔
777
                d.stop()
29✔
778
        })
29✔
779
        return nil
30✔
780
}
781

782
func (d *AuthenticatedGossiper) stop() {
29✔
783
        log.Debug("Authenticated Gossiper is stopping")
29✔
784
        defer log.Debug("Authenticated Gossiper stopped")
29✔
785

29✔
786
        // `blockEpochs` is only initialized in the start routine so we make
29✔
787
        // sure we don't panic here in the case where the `Stop` method is
29✔
788
        // called when the `Start` method does not complete.
29✔
789
        if d.blockEpochs != nil {
58✔
790
                d.blockEpochs.Cancel()
29✔
791
        }
29✔
792

793
        d.syncMgr.Stop()
29✔
794

29✔
795
        d.banman.stop()
29✔
796

29✔
797
        close(d.quit)
29✔
798
        d.wg.Wait()
29✔
799

29✔
800
        // We'll stop our reliable sender after all of the gossiper's goroutines
29✔
801
        // have exited to ensure nothing can cause it to continue executing.
29✔
802
        d.reliableSender.Stop()
29✔
803
}
804

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

808
// ProcessRemoteAnnouncement sends a new remote announcement message along with
809
// the peer that sent the routing message. The announcement will be processed
810
// then added to a queue for batched trickled announcement to all connected
811
// peers.  Remote channel announcements should contain the announcement proof
812
// and be fully validated.
813
func (d *AuthenticatedGossiper) ProcessRemoteAnnouncement(msg lnwire.Message,
814
        peer lnpeer.Peer) chan error {
286✔
815

286✔
816
        log.Debugf("Processing remote msg %T from peer=%x", msg, peer.PubKey())
286✔
817

286✔
818
        errChan := make(chan error, 1)
286✔
819

286✔
820
        // For messages in the known set of channel series queries, we'll
286✔
821
        // dispatch the message directly to the GossipSyncer, and skip the main
286✔
822
        // processing loop.
286✔
823
        switch m := msg.(type) {
286✔
824
        case *lnwire.QueryShortChanIDs,
825
                *lnwire.QueryChannelRange,
826
                *lnwire.ReplyChannelRange,
827
                *lnwire.ReplyShortChanIDsEnd:
2✔
828

2✔
829
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
2✔
830
                if !ok {
2✔
831
                        log.Warnf("Gossip syncer for peer=%x not found",
×
832
                                peer.PubKey())
×
833

×
834
                        errChan <- ErrGossipSyncerNotFound
×
835
                        return errChan
×
836
                }
×
837

838
                // If we've found the message target, then we'll dispatch the
839
                // message directly to it.
840
                err := syncer.ProcessQueryMsg(m, peer.QuitSignal())
2✔
841
                if err != nil {
2✔
842
                        log.Errorf("Process query msg from peer %x got %v",
×
843
                                peer.PubKey(), err)
×
844
                }
×
845

846
                errChan <- err
2✔
847
                return errChan
2✔
848

849
        // If a peer is updating its current update horizon, then we'll dispatch
850
        // that directly to the proper GossipSyncer.
851
        case *lnwire.GossipTimestampRange:
2✔
852
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
2✔
853
                if !ok {
2✔
854
                        log.Warnf("Gossip syncer for peer=%x not found",
×
855
                                peer.PubKey())
×
856

×
857
                        errChan <- ErrGossipSyncerNotFound
×
858
                        return errChan
×
859
                }
×
860

861
                // If we've found the message target, then we'll dispatch the
862
                // message directly to it.
863
                if err := syncer.ApplyGossipFilter(m); err != nil {
2✔
864
                        log.Warnf("Unable to apply gossip filter for peer=%x: "+
×
865
                                "%v", peer.PubKey(), err)
×
866

×
867
                        errChan <- err
×
868
                        return errChan
×
869
                }
×
870

871
                errChan <- nil
2✔
872
                return errChan
2✔
873

874
        // To avoid inserting edges in the graph for our own channels that we
875
        // have already closed, we ignore such channel announcements coming
876
        // from the remote.
877
        case *lnwire.ChannelAnnouncement1:
221✔
878
                ownKey := d.selfKey.SerializeCompressed()
221✔
879
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
221✔
880
                        "for own channel")
221✔
881

221✔
882
                if bytes.Equal(m.NodeID1[:], ownKey) ||
221✔
883
                        bytes.Equal(m.NodeID2[:], ownKey) {
225✔
884

4✔
885
                        log.Warn(ownErr)
4✔
886
                        errChan <- ownErr
4✔
887
                        return errChan
4✔
888
                }
4✔
889
        }
890

891
        nMsg := &networkMsg{
284✔
892
                msg:      msg,
284✔
893
                isRemote: true,
284✔
894
                peer:     peer,
284✔
895
                source:   peer.IdentityKey(),
284✔
896
                err:      errChan,
284✔
897
        }
284✔
898

284✔
899
        select {
284✔
900
        case d.networkMsgs <- nMsg:
284✔
901

902
        // If the peer that sent us this error is quitting, then we don't need
903
        // to send back an error and can return immediately.
904
        case <-peer.QuitSignal():
×
905
                return nil
×
906
        case <-d.quit:
×
907
                nMsg.err <- ErrGossiperShuttingDown
×
908
        }
909

910
        return nMsg.err
284✔
911
}
912

913
// ProcessLocalAnnouncement sends a new remote announcement message along with
914
// the peer that sent the routing message. The announcement will be processed
915
// then added to a queue for batched trickled announcement to all connected
916
// peers.  Local channel announcements don't contain the announcement proof and
917
// will not be fully validated. Once the channel proofs are received, the
918
// entire channel announcement and update messages will be re-constructed and
919
// broadcast to the rest of the network.
920
func (d *AuthenticatedGossiper) ProcessLocalAnnouncement(msg lnwire.Message,
921
        optionalFields ...OptionalMsgField) chan error {
49✔
922

49✔
923
        optionalMsgFields := &optionalMsgFields{}
49✔
924
        optionalMsgFields.apply(optionalFields...)
49✔
925

49✔
926
        nMsg := &networkMsg{
49✔
927
                msg:               msg,
49✔
928
                optionalMsgFields: optionalMsgFields,
49✔
929
                isRemote:          false,
49✔
930
                source:            d.selfKey,
49✔
931
                err:               make(chan error, 1),
49✔
932
        }
49✔
933

49✔
934
        select {
49✔
935
        case d.networkMsgs <- nMsg:
49✔
936
        case <-d.quit:
×
937
                nMsg.err <- ErrGossiperShuttingDown
×
938
        }
939

940
        return nMsg.err
49✔
941
}
942

943
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
944
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
945
// tuple.
946
type channelUpdateID struct {
947
        // channelID represents the set of data which is needed to
948
        // retrieve all necessary data to validate the channel existence.
949
        channelID lnwire.ShortChannelID
950

951
        // Flags least-significant bit must be set to 0 if the creating node
952
        // corresponds to the first node in the previously sent channel
953
        // announcement and 1 otherwise.
954
        flags lnwire.ChanUpdateChanFlags
955
}
956

957
// msgWithSenders is a wrapper struct around a message, and the set of peers
958
// that originally sent us this message. Using this struct, we can ensure that
959
// we don't re-send a message to the peer that sent it to us in the first
960
// place.
961
type msgWithSenders struct {
962
        // msg is the wire message itself.
963
        msg lnwire.Message
964

965
        // isLocal is true if this was a message that originated locally. We'll
966
        // use this to bypass our normal checks to ensure we prioritize sending
967
        // out our own updates.
968
        isLocal bool
969

970
        // sender is the set of peers that sent us this message.
971
        senders map[route.Vertex]struct{}
972
}
973

974
// mergeSyncerMap is used to merge the set of senders of a particular message
975
// with peers that we have an active GossipSyncer with. We do this to ensure
976
// that we don't broadcast messages to any peers that we have active gossip
977
// syncers for.
978
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
26✔
979
        for peerPub := range syncers {
28✔
980
                m.senders[peerPub] = struct{}{}
2✔
981
        }
2✔
982
}
983

984
// deDupedAnnouncements de-duplicates announcements that have been added to the
985
// batch. Internally, announcements are stored in three maps
986
// (one each for channel announcements, channel updates, and node
987
// announcements). These maps keep track of unique announcements and ensure no
988
// announcements are duplicated. We keep the three message types separate, such
989
// that we can send channel announcements first, then channel updates, and
990
// finally node announcements when it's time to broadcast them.
991
type deDupedAnnouncements struct {
992
        // channelAnnouncements are identified by the short channel id field.
993
        channelAnnouncements map[lnwire.ShortChannelID]msgWithSenders
994

995
        // channelUpdates are identified by the channel update id field.
996
        channelUpdates map[channelUpdateID]msgWithSenders
997

998
        // nodeAnnouncements are identified by the Vertex field.
999
        nodeAnnouncements map[route.Vertex]msgWithSenders
1000

1001
        sync.Mutex
1002
}
1003

1004
// Reset operates on deDupedAnnouncements to reset the storage of
1005
// announcements.
1006
func (d *deDupedAnnouncements) Reset() {
31✔
1007
        d.Lock()
31✔
1008
        defer d.Unlock()
31✔
1009

31✔
1010
        d.reset()
31✔
1011
}
31✔
1012

1013
// reset is the private version of the Reset method. We have this so we can
1014
// call this method within method that are already holding the lock.
1015
func (d *deDupedAnnouncements) reset() {
318✔
1016
        // Storage of each type of announcement (channel announcements, channel
318✔
1017
        // updates, node announcements) is set to an empty map where the
318✔
1018
        // appropriate key points to the corresponding lnwire.Message.
318✔
1019
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
318✔
1020
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
318✔
1021
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
318✔
1022
}
318✔
1023

1024
// addMsg adds a new message to the current batch. If the message is already
1025
// present in the current batch, then this new instance replaces the latter,
1026
// and the set of senders is updated to reflect which node sent us this
1027
// message.
1028
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
88✔
1029
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
88✔
1030

88✔
1031
        // Depending on the message type (channel announcement, channel update,
88✔
1032
        // or node announcement), the message is added to the corresponding map
88✔
1033
        // in deDupedAnnouncements. Because each identifying key can have at
88✔
1034
        // most one value, the announcements are de-duplicated, with newer ones
88✔
1035
        // replacing older ones.
88✔
1036
        switch msg := message.msg.(type) {
88✔
1037

1038
        // Channel announcements are identified by the short channel id field.
1039
        case *lnwire.ChannelAnnouncement1:
24✔
1040
                deDupKey := msg.ShortChannelID
24✔
1041
                sender := route.NewVertex(message.source)
24✔
1042

24✔
1043
                mws, ok := d.channelAnnouncements[deDupKey]
24✔
1044
                if !ok {
47✔
1045
                        mws = msgWithSenders{
23✔
1046
                                msg:     msg,
23✔
1047
                                isLocal: !message.isRemote,
23✔
1048
                                senders: make(map[route.Vertex]struct{}),
23✔
1049
                        }
23✔
1050
                        mws.senders[sender] = struct{}{}
23✔
1051

23✔
1052
                        d.channelAnnouncements[deDupKey] = mws
23✔
1053

23✔
1054
                        return
23✔
1055
                }
23✔
1056

1057
                mws.msg = msg
1✔
1058
                mws.senders[sender] = struct{}{}
1✔
1059
                d.channelAnnouncements[deDupKey] = mws
1✔
1060

1061
        // Channel updates are identified by the (short channel id,
1062
        // channelflags) tuple.
1063
        case *lnwire.ChannelUpdate1:
44✔
1064
                sender := route.NewVertex(message.source)
44✔
1065
                deDupKey := channelUpdateID{
44✔
1066
                        msg.ShortChannelID,
44✔
1067
                        msg.ChannelFlags,
44✔
1068
                }
44✔
1069

44✔
1070
                oldTimestamp := uint32(0)
44✔
1071
                mws, ok := d.channelUpdates[deDupKey]
44✔
1072
                if ok {
47✔
1073
                        // If we already have seen this message, record its
3✔
1074
                        // timestamp.
3✔
1075
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1076
                        if !ok {
3✔
1077
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1078
                                        "got: %T", mws.msg)
×
1079

×
1080
                                return
×
1081
                        }
×
1082

1083
                        oldTimestamp = update.Timestamp
3✔
1084
                }
1085

1086
                // If we already had this message with a strictly newer
1087
                // timestamp, then we'll just discard the message we got.
1088
                if oldTimestamp > msg.Timestamp {
45✔
1089
                        log.Debugf("Ignored outdated network message: "+
1✔
1090
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1091
                        return
1✔
1092
                }
1✔
1093

1094
                // If the message we just got is newer than what we previously
1095
                // have seen, or this is the first time we see it, then we'll
1096
                // add it to our map of announcements.
1097
                if oldTimestamp < msg.Timestamp {
85✔
1098
                        mws = msgWithSenders{
42✔
1099
                                msg:     msg,
42✔
1100
                                isLocal: !message.isRemote,
42✔
1101
                                senders: make(map[route.Vertex]struct{}),
42✔
1102
                        }
42✔
1103

42✔
1104
                        // We'll mark the sender of the message in the
42✔
1105
                        // senders map.
42✔
1106
                        mws.senders[sender] = struct{}{}
42✔
1107

42✔
1108
                        d.channelUpdates[deDupKey] = mws
42✔
1109

42✔
1110
                        return
42✔
1111
                }
42✔
1112

1113
                // Lastly, if we had seen this exact message from before, with
1114
                // the same timestamp, we'll add the sender to the map of
1115
                // senders, such that we can skip sending this message back in
1116
                // the next batch.
1117
                mws.msg = msg
1✔
1118
                mws.senders[sender] = struct{}{}
1✔
1119
                d.channelUpdates[deDupKey] = mws
1✔
1120

1121
        // Node announcements are identified by the Vertex field.  Use the
1122
        // NodeID to create the corresponding Vertex.
1123
        case *lnwire.NodeAnnouncement:
24✔
1124
                sender := route.NewVertex(message.source)
24✔
1125
                deDupKey := route.Vertex(msg.NodeID)
24✔
1126

24✔
1127
                // We do the same for node announcements as we did for channel
24✔
1128
                // updates, as they also carry a timestamp.
24✔
1129
                oldTimestamp := uint32(0)
24✔
1130
                mws, ok := d.nodeAnnouncements[deDupKey]
24✔
1131
                if ok {
31✔
1132
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
7✔
1133
                }
7✔
1134

1135
                // Discard the message if it's old.
1136
                if oldTimestamp > msg.Timestamp {
26✔
1137
                        return
2✔
1138
                }
2✔
1139

1140
                // Replace if it's newer.
1141
                if oldTimestamp < msg.Timestamp {
44✔
1142
                        mws = msgWithSenders{
20✔
1143
                                msg:     msg,
20✔
1144
                                isLocal: !message.isRemote,
20✔
1145
                                senders: make(map[route.Vertex]struct{}),
20✔
1146
                        }
20✔
1147

20✔
1148
                        mws.senders[sender] = struct{}{}
20✔
1149

20✔
1150
                        d.nodeAnnouncements[deDupKey] = mws
20✔
1151

20✔
1152
                        return
20✔
1153
                }
20✔
1154

1155
                // Add to senders map if it's the same as we had.
1156
                mws.msg = msg
6✔
1157
                mws.senders[sender] = struct{}{}
6✔
1158
                d.nodeAnnouncements[deDupKey] = mws
6✔
1159
        }
1160
}
1161

1162
// AddMsgs is a helper method to add multiple messages to the announcement
1163
// batch.
1164
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
56✔
1165
        d.Lock()
56✔
1166
        defer d.Unlock()
56✔
1167

56✔
1168
        for _, msg := range msgs {
144✔
1169
                d.addMsg(msg)
88✔
1170
        }
88✔
1171
}
1172

1173
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1174
// to broadcast next into messages that are locally sourced and those that are
1175
// sourced remotely.
1176
type msgsToBroadcast struct {
1177
        // localMsgs is the set of messages we created locally.
1178
        localMsgs []msgWithSenders
1179

1180
        // remoteMsgs is the set of messages that we received from a remote
1181
        // party.
1182
        remoteMsgs []msgWithSenders
1183
}
1184

1185
// addMsg adds a new message to the appropriate sub-slice.
1186
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
73✔
1187
        if msg.isLocal {
122✔
1188
                m.localMsgs = append(m.localMsgs, msg)
49✔
1189
        } else {
75✔
1190
                m.remoteMsgs = append(m.remoteMsgs, msg)
26✔
1191
        }
26✔
1192
}
1193

1194
// isEmpty returns true if the batch is empty.
1195
func (m *msgsToBroadcast) isEmpty() bool {
288✔
1196
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
288✔
1197
}
288✔
1198

1199
// length returns the length of the combined message set.
1200
func (m *msgsToBroadcast) length() int {
1✔
1201
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1202
}
1✔
1203

1204
// Emit returns the set of de-duplicated announcements to be sent out during
1205
// the next announcement epoch, in the order of channel announcements, channel
1206
// updates, and node announcements. Each message emitted, contains the set of
1207
// peers that sent us the message. This way, we can ensure that we don't waste
1208
// bandwidth by re-sending a message to the peer that sent it to us in the
1209
// first place. Additionally, the set of stored messages are reset.
1210
func (d *deDupedAnnouncements) Emit() msgsToBroadcast {
289✔
1211
        d.Lock()
289✔
1212
        defer d.Unlock()
289✔
1213

289✔
1214
        // Get the total number of announcements.
289✔
1215
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
289✔
1216
                len(d.nodeAnnouncements)
289✔
1217

289✔
1218
        // Create an empty array of lnwire.Messages with a length equal to
289✔
1219
        // the total number of announcements.
289✔
1220
        msgs := msgsToBroadcast{
289✔
1221
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
289✔
1222
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
289✔
1223
        }
289✔
1224

289✔
1225
        // Add the channel announcements to the array first.
289✔
1226
        for _, message := range d.channelAnnouncements {
309✔
1227
                msgs.addMsg(message)
20✔
1228
        }
20✔
1229

1230
        // Then add the channel updates.
1231
        for _, message := range d.channelUpdates {
327✔
1232
                msgs.addMsg(message)
38✔
1233
        }
38✔
1234

1235
        // Finally add the node announcements.
1236
        for _, message := range d.nodeAnnouncements {
308✔
1237
                msgs.addMsg(message)
19✔
1238
        }
19✔
1239

1240
        d.reset()
289✔
1241

289✔
1242
        // Return the array of lnwire.messages.
289✔
1243
        return msgs
289✔
1244
}
1245

1246
// calculateSubBatchSize is a helper function that calculates the size to break
1247
// down the batchSize into.
1248
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1249
        minimumBatchSize, batchSize int) int {
15✔
1250
        if subBatchDelay > totalDelay {
17✔
1251
                return batchSize
2✔
1252
        }
2✔
1253

1254
        subBatchSize := (batchSize*int(subBatchDelay) +
13✔
1255
                int(totalDelay) - 1) / int(totalDelay)
13✔
1256

13✔
1257
        if subBatchSize < minimumBatchSize {
16✔
1258
                return minimumBatchSize
3✔
1259
        }
3✔
1260

1261
        return subBatchSize
10✔
1262
}
1263

1264
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1265
// this variable so the function can be mocked in our test.
1266
var batchSizeCalculator = calculateSubBatchSize
1267

1268
// splitAnnouncementBatches takes an exiting list of announcements and
1269
// decomposes it into sub batches controlled by the `subBatchSize`.
1270
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1271
        announcementBatch []msgWithSenders) [][]msgWithSenders {
71✔
1272

71✔
1273
        subBatchSize := batchSizeCalculator(
71✔
1274
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
71✔
1275
                d.cfg.MinimumBatchSize, len(announcementBatch),
71✔
1276
        )
71✔
1277

71✔
1278
        var splitAnnouncementBatch [][]msgWithSenders
71✔
1279

71✔
1280
        for subBatchSize < len(announcementBatch) {
194✔
1281
                // For slicing with minimal allocation
123✔
1282
                // https://github.com/golang/go/wiki/SliceTricks
123✔
1283
                announcementBatch, splitAnnouncementBatch =
123✔
1284
                        announcementBatch[subBatchSize:],
123✔
1285
                        append(splitAnnouncementBatch,
123✔
1286
                                announcementBatch[0:subBatchSize:subBatchSize])
123✔
1287
        }
123✔
1288
        splitAnnouncementBatch = append(
71✔
1289
                splitAnnouncementBatch, announcementBatch,
71✔
1290
        )
71✔
1291

71✔
1292
        return splitAnnouncementBatch
71✔
1293
}
1294

1295
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1296
// split size, and then sends out all items to the set of target peers. Locally
1297
// generated announcements are always sent before remotely generated
1298
// announcements.
1299
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(
1300
        annBatch msgsToBroadcast) {
33✔
1301

33✔
1302
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
33✔
1303
        // duration to delay the sending of next announcement batch.
33✔
1304
        delayNextBatch := func() {
97✔
1305
                select {
64✔
1306
                case <-time.After(d.cfg.SubBatchDelay):
47✔
1307
                case <-d.quit:
17✔
1308
                        return
17✔
1309
                }
1310
        }
1311

1312
        // Fetch the local and remote announcements.
1313
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
33✔
1314
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
33✔
1315

33✔
1316
        d.wg.Add(1)
33✔
1317
        go func() {
66✔
1318
                defer d.wg.Done()
33✔
1319

33✔
1320
                log.Debugf("Broadcasting %v new local announcements in %d "+
33✔
1321
                        "sub batches", len(annBatch.localMsgs),
33✔
1322
                        len(localBatches))
33✔
1323

33✔
1324
                // Send out the local announcements first.
33✔
1325
                for _, annBatch := range localBatches {
66✔
1326
                        d.sendLocalBatch(annBatch)
33✔
1327
                        delayNextBatch()
33✔
1328
                }
33✔
1329

1330
                log.Debugf("Broadcasting %v new remote announcements in %d "+
33✔
1331
                        "sub batches", len(annBatch.remoteMsgs),
33✔
1332
                        len(remoteBatches))
33✔
1333

33✔
1334
                // Now send the remote announcements.
33✔
1335
                for _, annBatch := range remoteBatches {
66✔
1336
                        d.sendRemoteBatch(annBatch)
33✔
1337
                        delayNextBatch()
33✔
1338
                }
33✔
1339
        }()
1340
}
1341

1342
// sendLocalBatch broadcasts a list of locally generated announcements to our
1343
// peers. For local announcements, we skip the filter and dedup logic and just
1344
// send the announcements out to all our coonnected peers.
1345
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
33✔
1346
        msgsToSend := lnutils.Map(
33✔
1347
                annBatch, func(m msgWithSenders) lnwire.Message {
78✔
1348
                        return m.msg
45✔
1349
                },
45✔
1350
        )
1351

1352
        err := d.cfg.Broadcast(nil, msgsToSend...)
33✔
1353
        if err != nil {
33✔
1354
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1355
        }
×
1356
}
1357

1358
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1359
// peers.
1360
func (d *AuthenticatedGossiper) sendRemoteBatch(annBatch []msgWithSenders) {
33✔
1361
        syncerPeers := d.syncMgr.GossipSyncers()
33✔
1362

33✔
1363
        // We'll first attempt to filter out this new message for all peers
33✔
1364
        // that have active gossip syncers active.
33✔
1365
        for pub, syncer := range syncerPeers {
35✔
1366
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
2✔
1367
                syncer.FilterGossipMsgs(annBatch...)
2✔
1368
        }
2✔
1369

1370
        for _, msgChunk := range annBatch {
59✔
1371
                msgChunk := msgChunk
26✔
1372

26✔
1373
                // With the syncers taken care of, we'll merge the sender map
26✔
1374
                // with the set of syncers, so we don't send out duplicate
26✔
1375
                // messages.
26✔
1376
                msgChunk.mergeSyncerMap(syncerPeers)
26✔
1377

26✔
1378
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
26✔
1379
                if err != nil {
26✔
1380
                        log.Errorf("Unable to send batch "+
×
1381
                                "announcements: %v", err)
×
1382
                        continue
×
1383
                }
1384
        }
1385
}
1386

1387
// networkHandler is the primary goroutine that drives this service. The roles
1388
// of this goroutine includes answering queries related to the state of the
1389
// network, syncing up newly connected peers, and also periodically
1390
// broadcasting our latest topology state to all connected peers.
1391
//
1392
// NOTE: This MUST be run as a goroutine.
1393
func (d *AuthenticatedGossiper) networkHandler() {
29✔
1394
        defer d.wg.Done()
29✔
1395

29✔
1396
        // Initialize empty deDupedAnnouncements to store announcement batch.
29✔
1397
        announcements := deDupedAnnouncements{}
29✔
1398
        announcements.Reset()
29✔
1399

29✔
1400
        d.cfg.RetransmitTicker.Resume()
29✔
1401
        defer d.cfg.RetransmitTicker.Stop()
29✔
1402

29✔
1403
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
29✔
1404
        defer trickleTimer.Stop()
29✔
1405

29✔
1406
        // To start, we'll first check to see if there are any stale channel or
29✔
1407
        // node announcements that we need to re-transmit.
29✔
1408
        if err := d.retransmitStaleAnns(time.Now()); err != nil {
29✔
1409
                log.Errorf("Unable to rebroadcast stale announcements: %v", err)
×
1410
        }
×
1411

1412
        // We'll use this validation to ensure that we process jobs in their
1413
        // dependency order during parallel validation.
1414
        validationBarrier := graph.NewValidationBarrier(1000, d.quit)
29✔
1415

29✔
1416
        for {
677✔
1417
                select {
648✔
1418
                // A new policy update has arrived. We'll commit it to the
1419
                // sub-systems below us, then craft, sign, and broadcast a new
1420
                // ChannelUpdate for the set of affected clients.
1421
                case policyUpdate := <-d.chanPolicyUpdates:
3✔
1422
                        log.Tracef("Received channel %d policy update requests",
3✔
1423
                                len(policyUpdate.edgesToUpdate))
3✔
1424

3✔
1425
                        // First, we'll now create new fully signed updates for
3✔
1426
                        // the affected channels and also update the underlying
3✔
1427
                        // graph with the new state.
3✔
1428
                        newChanUpdates, err := d.processChanPolicyUpdate(
3✔
1429
                                policyUpdate.edgesToUpdate,
3✔
1430
                        )
3✔
1431
                        policyUpdate.errChan <- err
3✔
1432
                        if err != nil {
3✔
1433
                                log.Errorf("Unable to craft policy updates: %v",
×
1434
                                        err)
×
1435
                                continue
×
1436
                        }
1437

1438
                        // Finally, with the updates committed, we'll now add
1439
                        // them to the announcement batch to be flushed at the
1440
                        // start of the next epoch.
1441
                        announcements.AddMsgs(newChanUpdates...)
3✔
1442

1443
                case announcement := <-d.networkMsgs:
333✔
1444
                        log.Tracef("Received network message: "+
333✔
1445
                                "peer=%v, msg=%s, is_remote=%v",
333✔
1446
                                announcement.peer, announcement.msg.MsgType(),
333✔
1447
                                announcement.isRemote)
333✔
1448

333✔
1449
                        switch announcement.msg.(type) {
333✔
1450
                        // Channel announcement signatures are amongst the only
1451
                        // messages that we'll process serially.
1452
                        case *lnwire.AnnounceSignatures1:
23✔
1453
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
23✔
1454
                                        announcement,
23✔
1455
                                )
23✔
1456
                                log.Debugf("Processed network message %s, "+
23✔
1457
                                        "returned len(announcements)=%v",
23✔
1458
                                        announcement.msg.MsgType(),
23✔
1459
                                        len(emittedAnnouncements))
23✔
1460

23✔
1461
                                if emittedAnnouncements != nil {
35✔
1462
                                        announcements.AddMsgs(
12✔
1463
                                                emittedAnnouncements...,
12✔
1464
                                        )
12✔
1465
                                }
12✔
1466
                                continue
23✔
1467
                        }
1468

1469
                        // If this message was recently rejected, then we won't
1470
                        // attempt to re-process it.
1471
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
312✔
1472
                                announcement.msg,
312✔
1473
                                sourceToPub(announcement.source),
312✔
1474
                        ) {
313✔
1475

1✔
1476
                                announcement.err <- fmt.Errorf("recently " +
1✔
1477
                                        "rejected")
1✔
1478
                                continue
1✔
1479
                        }
1480

1481
                        // We'll set up any dependent, and wait until a free
1482
                        // slot for this job opens up, this allow us to not
1483
                        // have thousands of goroutines active.
1484
                        validationBarrier.InitJobDependencies(announcement.msg)
311✔
1485

311✔
1486
                        d.wg.Add(1)
311✔
1487
                        go d.handleNetworkMessages(
311✔
1488
                                announcement, &announcements, validationBarrier,
311✔
1489
                        )
311✔
1490

1491
                // The trickle timer has ticked, which indicates we should
1492
                // flush to the network the pending batch of new announcements
1493
                // we've received since the last trickle tick.
1494
                case <-trickleTimer.C:
288✔
1495
                        // Emit the current batch of announcements from
288✔
1496
                        // deDupedAnnouncements.
288✔
1497
                        announcementBatch := announcements.Emit()
288✔
1498

288✔
1499
                        // If the current announcements batch is nil, then we
288✔
1500
                        // have no further work here.
288✔
1501
                        if announcementBatch.isEmpty() {
545✔
1502
                                continue
257✔
1503
                        }
1504

1505
                        // At this point, we have the set of local and remote
1506
                        // announcements we want to send out. We'll do the
1507
                        // batching as normal for both, but for local
1508
                        // announcements, we'll blast them out w/o regard for
1509
                        // our peer's policies so we ensure they propagate
1510
                        // properly.
1511
                        d.splitAndSendAnnBatch(announcementBatch)
33✔
1512

1513
                // The retransmission timer has ticked which indicates that we
1514
                // should check if we need to prune or re-broadcast any of our
1515
                // personal channels or node announcement. This addresses the
1516
                // case of "zombie" channels and channel advertisements that
1517
                // have been dropped, or not properly propagated through the
1518
                // network.
1519
                case tick := <-d.cfg.RetransmitTicker.Ticks():
1✔
1520
                        if err := d.retransmitStaleAnns(tick); err != nil {
1✔
1521
                                log.Errorf("unable to rebroadcast stale "+
×
1522
                                        "announcements: %v", err)
×
1523
                        }
×
1524

1525
                // The gossiper has been signalled to exit, to we exit our
1526
                // main loop so the wait group can be decremented.
1527
                case <-d.quit:
29✔
1528
                        return
29✔
1529
                }
1530
        }
1531
}
1532

1533
// handleNetworkMessages is responsible for waiting for dependencies for a
1534
// given network message and processing the message. Once processed, it will
1535
// signal its dependants and add the new announcements to the announce batch.
1536
//
1537
// NOTE: must be run as a goroutine.
1538
func (d *AuthenticatedGossiper) handleNetworkMessages(nMsg *networkMsg,
1539
        deDuped *deDupedAnnouncements, vb *graph.ValidationBarrier) {
311✔
1540

311✔
1541
        defer d.wg.Done()
311✔
1542
        defer vb.CompleteJob()
311✔
1543

311✔
1544
        // We should only broadcast this message forward if it originated from
311✔
1545
        // us or it wasn't received as part of our initial historical sync.
311✔
1546
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
311✔
1547

311✔
1548
        // If this message has an existing dependency, then we'll wait until
311✔
1549
        // that has been fully validated before we proceed.
311✔
1550
        err := vb.WaitForDependants(nMsg.msg)
311✔
1551
        if err != nil {
311✔
1552
                log.Debugf("Validating network message %s got err: %v",
×
1553
                        nMsg.msg.MsgType(), err)
×
1554

×
1555
                if !graph.IsError(
×
1556
                        err,
×
1557
                        graph.ErrVBarrierShuttingDown,
×
1558
                        graph.ErrParentValidationFailed,
×
1559
                ) {
×
1560

×
1561
                        log.Warnf("unexpected error during validation "+
×
1562
                                "barrier shutdown: %v", err)
×
1563
                }
×
1564
                nMsg.err <- err
×
1565

×
1566
                return
×
1567
        }
1568

1569
        // Process the network announcement to determine if this is either a
1570
        // new announcement from our PoV or an edges to a prior vertex/edge we
1571
        // previously proceeded.
1572
        newAnns, allow := d.processNetworkAnnouncement(nMsg)
311✔
1573

311✔
1574
        log.Tracef("Processed network message %s, returned "+
311✔
1575
                "len(announcements)=%v, allowDependents=%v",
311✔
1576
                nMsg.msg.MsgType(), len(newAnns), allow)
311✔
1577

311✔
1578
        // If this message had any dependencies, then we can now signal them to
311✔
1579
        // continue.
311✔
1580
        vb.SignalDependants(nMsg.msg, allow)
311✔
1581

311✔
1582
        // If the announcement was accepted, then add the emitted announcements
311✔
1583
        // to our announce batch to be broadcast once the trickle timer ticks
311✔
1584
        // gain.
311✔
1585
        if newAnns != nil && shouldBroadcast {
345✔
1586
                // TODO(roasbeef): exclude peer that sent.
34✔
1587
                deDuped.AddMsgs(newAnns...)
34✔
1588
        } else if newAnns != nil {
316✔
1589
                log.Trace("Skipping broadcast of announcements received " +
3✔
1590
                        "during initial graph sync")
3✔
1591
        }
3✔
1592
}
1593

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

1596
// InitSyncState is called by outside sub-systems when a connection is
1597
// established to a new peer that understands how to perform channel range
1598
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1599
// needed to handle new queries.
1600
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
2✔
1601
        d.syncMgr.InitSyncState(syncPeer)
2✔
1602
}
2✔
1603

1604
// PruneSyncState is called by outside sub-systems once a peer that we were
1605
// previously connected to has been disconnected. In this case we can stop the
1606
// existing GossipSyncer assigned to the peer and free up resources.
1607
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
2✔
1608
        d.syncMgr.PruneSyncState(peer)
2✔
1609
}
2✔
1610

1611
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1612
// false otherwise, This avoids expensive reprocessing of the message.
1613
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1614
        peerPub [33]byte) bool {
275✔
1615

275✔
1616
        var scid uint64
275✔
1617
        switch m := msg.(type) {
275✔
1618
        case *lnwire.ChannelUpdate1:
44✔
1619
                scid = m.ShortChannelID.ToUint64()
44✔
1620

1621
        case *lnwire.ChannelAnnouncement1:
219✔
1622
                scid = m.ShortChannelID.ToUint64()
219✔
1623

1624
        default:
16✔
1625
                return false
16✔
1626
        }
1627

1628
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
261✔
1629
        return err != cache.ErrElementNotFound
261✔
1630
}
1631

1632
// retransmitStaleAnns examines all outgoing channels that the source node is
1633
// known to maintain to check to see if any of them are "stale". A channel is
1634
// stale iff, the last timestamp of its rebroadcast is older than the
1635
// RebroadcastInterval. We also check if a refreshed node announcement should
1636
// be resent.
1637
func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error {
30✔
1638
        // Iterate over all of our channels and check if any of them fall
30✔
1639
        // within the prune interval or re-broadcast interval.
30✔
1640
        type updateTuple struct {
30✔
1641
                info *models.ChannelEdgeInfo
30✔
1642
                edge *models.ChannelEdgePolicy
30✔
1643
        }
30✔
1644

30✔
1645
        var (
30✔
1646
                havePublicChannels bool
30✔
1647
                edgesToUpdate      []updateTuple
30✔
1648
        )
30✔
1649
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
30✔
1650
                info *models.ChannelEdgeInfo,
30✔
1651
                edge *models.ChannelEdgePolicy) error {
34✔
1652

4✔
1653
                // If there's no auth proof attached to this edge, it means
4✔
1654
                // that it is a private channel not meant to be announced to
4✔
1655
                // the greater network, so avoid sending channel updates for
4✔
1656
                // this channel to not leak its
4✔
1657
                // existence.
4✔
1658
                if info.AuthProof == nil {
7✔
1659
                        log.Debugf("Skipping retransmission of channel "+
3✔
1660
                                "without AuthProof: %v", info.ChannelID)
3✔
1661
                        return nil
3✔
1662
                }
3✔
1663

1664
                // We make a note that we have at least one public channel. We
1665
                // use this to determine whether we should send a node
1666
                // announcement below.
1667
                havePublicChannels = true
3✔
1668

3✔
1669
                // If this edge has a ChannelUpdate that was created before the
3✔
1670
                // introduction of the MaxHTLC field, then we'll update this
3✔
1671
                // edge to propagate this information in the network.
3✔
1672
                if !edge.MessageFlags.HasMaxHtlc() {
3✔
1673
                        // We'll make sure we support the new max_htlc field if
×
1674
                        // not already present.
×
1675
                        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
×
1676
                        edge.MaxHTLC = lnwire.NewMSatFromSatoshis(info.Capacity)
×
1677

×
1678
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1679
                                info: info,
×
1680
                                edge: edge,
×
1681
                        })
×
1682
                        return nil
×
1683
                }
×
1684

1685
                timeElapsed := now.Sub(edge.LastUpdate)
3✔
1686

3✔
1687
                // If it's been longer than RebroadcastInterval since we've
3✔
1688
                // re-broadcasted the channel, add the channel to the set of
3✔
1689
                // edges we need to update.
3✔
1690
                if timeElapsed >= d.cfg.RebroadcastInterval {
4✔
1691
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1692
                                info: info,
1✔
1693
                                edge: edge,
1✔
1694
                        })
1✔
1695
                }
1✔
1696

1697
                return nil
3✔
1698
        })
1699
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
30✔
1700
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1701
                        err)
×
1702
        }
×
1703

1704
        var signedUpdates []lnwire.Message
30✔
1705
        for _, chanToUpdate := range edgesToUpdate {
31✔
1706
                // Re-sign and update the channel on disk and retrieve our
1✔
1707
                // ChannelUpdate to broadcast.
1✔
1708
                chanAnn, chanUpdate, err := d.updateChannel(
1✔
1709
                        chanToUpdate.info, chanToUpdate.edge,
1✔
1710
                )
1✔
1711
                if err != nil {
1✔
1712
                        return fmt.Errorf("unable to update channel: %w", err)
×
1713
                }
×
1714

1715
                // If we have a valid announcement to transmit, then we'll send
1716
                // that along with the update.
1717
                if chanAnn != nil {
2✔
1718
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1719
                }
1✔
1720

1721
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1722
        }
1723

1724
        // If we don't have any public channels, we return as we don't want to
1725
        // broadcast anything that would reveal our existence.
1726
        if !havePublicChannels {
59✔
1727
                return nil
29✔
1728
        }
29✔
1729

1730
        // We'll also check that our NodeAnnouncement is not too old.
1731
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
3✔
1732
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
3✔
1733
        timeElapsed := now.Sub(timestamp)
3✔
1734

3✔
1735
        // If it's been a full day since we've re-broadcasted the
3✔
1736
        // node announcement, refresh it and resend it.
3✔
1737
        nodeAnnStr := ""
3✔
1738
        if timeElapsed >= d.cfg.RebroadcastInterval {
4✔
1739
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
1✔
1740
                if err != nil {
1✔
1741
                        return fmt.Errorf("unable to get refreshed node "+
×
1742
                                "announcement: %v", err)
×
1743
                }
×
1744

1745
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1746
                nodeAnnStr = " and our refreshed node announcement"
1✔
1747

1✔
1748
                // Before broadcasting the refreshed node announcement, add it
1✔
1749
                // to our own graph.
1✔
1750
                if err := d.addNode(&newNodeAnn); err != nil {
2✔
1751
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1752
                                "to graph: %v", err)
1✔
1753
                }
1✔
1754
        }
1755

1756
        // If we don't have any updates to re-broadcast, then we'll exit
1757
        // early.
1758
        if len(signedUpdates) == 0 {
5✔
1759
                return nil
2✔
1760
        }
2✔
1761

1762
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1763
                len(edgesToUpdate), nodeAnnStr)
1✔
1764

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

1771
        return nil
1✔
1772
}
1773

1774
// processChanPolicyUpdate generates a new set of channel updates for the
1775
// provided list of edges and updates the backing ChannelGraphSource.
1776
func (d *AuthenticatedGossiper) processChanPolicyUpdate(
1777
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
3✔
1778

3✔
1779
        var chanUpdates []networkMsg
3✔
1780
        for _, edgeInfo := range edgesToUpdate {
8✔
1781
                // Now that we've collected all the channels we need to update,
5✔
1782
                // we'll re-sign and update the backing ChannelGraphSource, and
5✔
1783
                // retrieve our ChannelUpdate to broadcast.
5✔
1784
                _, chanUpdate, err := d.updateChannel(
5✔
1785
                        edgeInfo.Info, edgeInfo.Edge,
5✔
1786
                )
5✔
1787
                if err != nil {
5✔
1788
                        return nil, err
×
1789
                }
×
1790

1791
                // We'll avoid broadcasting any updates for private channels to
1792
                // avoid directly giving away their existence. Instead, we'll
1793
                // send the update directly to the remote party.
1794
                if edgeInfo.Info.AuthProof == nil {
8✔
1795
                        // If AuthProof is nil and an alias was found for this
3✔
1796
                        // ChannelID (meaning the option-scid-alias feature was
3✔
1797
                        // negotiated), we'll replace the ShortChannelID in the
3✔
1798
                        // update with the peer's alias. We do this after
3✔
1799
                        // updateChannel so that the alias isn't persisted to
3✔
1800
                        // the database.
3✔
1801
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1802
                                edgeInfo.Info.ChannelPoint,
3✔
1803
                        )
3✔
1804

3✔
1805
                        var defaultAlias lnwire.ShortChannelID
3✔
1806
                        foundAlias, _ := d.cfg.GetAlias(chanID)
3✔
1807
                        if foundAlias != defaultAlias {
5✔
1808
                                chanUpdate.ShortChannelID = foundAlias
2✔
1809

2✔
1810
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
2✔
1811
                                if err != nil {
2✔
1812
                                        log.Errorf("Unable to sign alias "+
×
1813
                                                "update: %v", err)
×
1814
                                        continue
×
1815
                                }
1816

1817
                                lnSig, err := lnwire.NewSigFromSignature(sig)
2✔
1818
                                if err != nil {
2✔
1819
                                        log.Errorf("Unable to create sig: %v",
×
1820
                                                err)
×
1821
                                        continue
×
1822
                                }
1823

1824
                                chanUpdate.Signature = lnSig
2✔
1825
                        }
1826

1827
                        remotePubKey := remotePubFromChanInfo(
3✔
1828
                                edgeInfo.Info, chanUpdate.ChannelFlags,
3✔
1829
                        )
3✔
1830
                        err := d.reliableSender.sendMessage(
3✔
1831
                                chanUpdate, remotePubKey,
3✔
1832
                        )
3✔
1833
                        if err != nil {
3✔
1834
                                log.Errorf("Unable to reliably send %v for "+
×
1835
                                        "channel=%v to peer=%x: %v",
×
1836
                                        chanUpdate.MsgType(),
×
1837
                                        chanUpdate.ShortChannelID,
×
1838
                                        remotePubKey, err)
×
1839
                        }
×
1840
                        continue
3✔
1841
                }
1842

1843
                // We set ourselves as the source of this message to indicate
1844
                // that we shouldn't skip any peers when sending this message.
1845
                chanUpdates = append(chanUpdates, networkMsg{
4✔
1846
                        source:   d.selfKey,
4✔
1847
                        isRemote: false,
4✔
1848
                        msg:      chanUpdate,
4✔
1849
                })
4✔
1850
        }
1851

1852
        return chanUpdates, nil
3✔
1853
}
1854

1855
// remotePubFromChanInfo returns the public key of the remote peer given a
1856
// ChannelEdgeInfo that describe a channel we have with them.
1857
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1858
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
14✔
1859

14✔
1860
        var remotePubKey [33]byte
14✔
1861
        switch {
14✔
1862
        case chanFlags&lnwire.ChanUpdateDirection == 0:
14✔
1863
                remotePubKey = chanInfo.NodeKey2Bytes
14✔
1864
        case chanFlags&lnwire.ChanUpdateDirection == 1:
2✔
1865
                remotePubKey = chanInfo.NodeKey1Bytes
2✔
1866
        }
1867

1868
        return remotePubKey
14✔
1869
}
1870

1871
// processRejectedEdge examines a rejected edge to see if we can extract any
1872
// new announcements from it.  An edge will get rejected if we already added
1873
// the same edge without AuthProof to the graph. If the received announcement
1874
// contains a proof, we can add this proof to our edge.  We can end up in this
1875
// situation in the case where we create a channel, but for some reason fail
1876
// to receive the remote peer's proof, while the remote peer is able to fully
1877
// assemble the proof and craft the ChannelAnnouncement.
1878
func (d *AuthenticatedGossiper) processRejectedEdge(
1879
        chanAnnMsg *lnwire.ChannelAnnouncement1,
1880
        proof *models.ChannelAuthProof) ([]networkMsg, error) {
2✔
1881

2✔
1882
        // First, we'll fetch the state of the channel as we know if from the
2✔
1883
        // database.
2✔
1884
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
2✔
1885
                chanAnnMsg.ShortChannelID,
2✔
1886
        )
2✔
1887
        if err != nil {
2✔
1888
                return nil, err
×
1889
        }
×
1890

1891
        // The edge is in the graph, and has a proof attached, then we'll just
1892
        // reject it as normal.
1893
        if chanInfo.AuthProof != nil {
4✔
1894
                return nil, nil
2✔
1895
        }
2✔
1896

1897
        // Otherwise, this means that the edge is within the graph, but it
1898
        // doesn't yet have a proper proof attached. If we did not receive
1899
        // the proof such that we now can add it, there's nothing more we
1900
        // can do.
1901
        if proof == nil {
×
1902
                return nil, nil
×
1903
        }
×
1904

1905
        // We'll then create then validate the new fully assembled
1906
        // announcement.
1907
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
×
1908
                proof, chanInfo, e1, e2,
×
1909
        )
×
1910
        if err != nil {
×
1911
                return nil, err
×
1912
        }
×
1913
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
×
1914
        if err != nil {
×
1915
                err := fmt.Errorf("assembled channel announcement proof "+
×
1916
                        "for shortChanID=%v isn't valid: %v",
×
1917
                        chanAnnMsg.ShortChannelID, err)
×
1918
                log.Error(err)
×
1919
                return nil, err
×
1920
        }
×
1921

1922
        // If everything checks out, then we'll add the fully assembled proof
1923
        // to the database.
1924
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
1925
        if err != nil {
×
1926
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
1927
                        chanAnnMsg.ShortChannelID, err)
×
1928
                log.Error(err)
×
1929
                return nil, err
×
1930
        }
×
1931

1932
        // As we now have a complete channel announcement for this channel,
1933
        // we'll construct the announcement so they can be broadcast out to all
1934
        // our peers.
1935
        announcements := make([]networkMsg, 0, 3)
×
1936
        announcements = append(announcements, networkMsg{
×
1937
                source: d.selfKey,
×
1938
                msg:    chanAnn,
×
1939
        })
×
1940
        if e1Ann != nil {
×
1941
                announcements = append(announcements, networkMsg{
×
1942
                        source: d.selfKey,
×
1943
                        msg:    e1Ann,
×
1944
                })
×
1945
        }
×
1946
        if e2Ann != nil {
×
1947
                announcements = append(announcements, networkMsg{
×
1948
                        source: d.selfKey,
×
1949
                        msg:    e2Ann,
×
1950
                })
×
1951

×
1952
        }
×
1953

1954
        return announcements, nil
×
1955
}
1956

1957
// fetchPKScript fetches the output script for the given SCID.
1958
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
1959
        []byte, error) {
×
1960

×
1961
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
1962
}
×
1963

1964
// addNode processes the given node announcement, and adds it to our channel
1965
// graph.
1966
func (d *AuthenticatedGossiper) addNode(msg *lnwire.NodeAnnouncement,
1967
        op ...batch.SchedulerOption) error {
19✔
1968

19✔
1969
        if err := graph.ValidateNodeAnn(msg); err != nil {
20✔
1970
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
1971
                        err)
1✔
1972
        }
1✔
1973

1974
        timestamp := time.Unix(int64(msg.Timestamp), 0)
18✔
1975
        features := lnwire.NewFeatureVector(msg.Features, lnwire.Features)
18✔
1976
        node := &models.LightningNode{
18✔
1977
                HaveNodeAnnouncement: true,
18✔
1978
                LastUpdate:           timestamp,
18✔
1979
                Addresses:            msg.Addresses,
18✔
1980
                PubKeyBytes:          msg.NodeID,
18✔
1981
                Alias:                msg.Alias.String(),
18✔
1982
                AuthSigBytes:         msg.Signature.ToSignatureBytes(),
18✔
1983
                Features:             features,
18✔
1984
                Color:                msg.RGBColor,
18✔
1985
                ExtraOpaqueData:      msg.ExtraOpaqueData,
18✔
1986
        }
18✔
1987

18✔
1988
        return d.cfg.Graph.AddNode(node, op...)
18✔
1989
}
1990

1991
// isPremature decides whether a given network message has a block height+delta
1992
// value specified in the future. If so, the message will be added to the
1993
// future message map and be processed when the block height as reached.
1994
//
1995
// NOTE: must be used inside a lock.
1996
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
1997
        delta uint32, msg *networkMsg) bool {
281✔
1998

281✔
1999
        // The channel is already confirmed at chanID.BlockHeight so we minus
281✔
2000
        // one block. For instance, if the required confirmation for this
281✔
2001
        // channel announcement is 6, we then only need to wait for 5 more
281✔
2002
        // blocks once the funding tx is confirmed.
281✔
2003
        if delta > 0 {
283✔
2004
                delta--
2✔
2005
        }
2✔
2006

2007
        msgHeight := chanID.BlockHeight + delta
281✔
2008

281✔
2009
        // The message height is smaller or equal to our best known height,
281✔
2010
        // thus the message is mature.
281✔
2011
        if msgHeight <= d.bestHeight {
561✔
2012
                return false
280✔
2013
        }
280✔
2014

2015
        // Add the premature message to our future messages which will be
2016
        // resent once the block height has reached.
2017
        //
2018
        // Copy the networkMsgs since the old message's err chan will be
2019
        // consumed.
2020
        copied := &networkMsg{
3✔
2021
                peer:              msg.peer,
3✔
2022
                source:            msg.source,
3✔
2023
                msg:               msg.msg,
3✔
2024
                optionalMsgFields: msg.optionalMsgFields,
3✔
2025
                isRemote:          msg.isRemote,
3✔
2026
                err:               make(chan error, 1),
3✔
2027
        }
3✔
2028

3✔
2029
        // Create the cached message.
3✔
2030
        cachedMsg := &cachedFutureMsg{
3✔
2031
                msg:    copied,
3✔
2032
                height: msgHeight,
3✔
2033
        }
3✔
2034

3✔
2035
        // Increment the msg ID and add it to the cache.
3✔
2036
        nextMsgID := d.futureMsgs.nextMsgID()
3✔
2037
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
3✔
2038
        if err != nil {
3✔
2039
                log.Errorf("Adding future message got error: %v", err)
×
2040
        }
×
2041

2042
        log.Debugf("Network message: %v added to future messages for "+
3✔
2043
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
3✔
2044
                msgHeight, d.bestHeight)
3✔
2045

3✔
2046
        return true
3✔
2047
}
2048

2049
// processNetworkAnnouncement processes a new network relate authenticated
2050
// channel or node announcement or announcements proofs. If the announcement
2051
// didn't affect the internal state due to either being out of date, invalid,
2052
// or redundant, then nil is returned. Otherwise, the set of announcements will
2053
// be returned which should be broadcasted to the rest of the network. The
2054
// boolean returned indicates whether any dependents of the announcement should
2055
// attempt to be processed as well.
2056
func (d *AuthenticatedGossiper) processNetworkAnnouncement(
2057
        nMsg *networkMsg) ([]networkMsg, bool) {
332✔
2058

332✔
2059
        // If this is a remote update, we set the scheduler option to lazily
332✔
2060
        // add it to the graph.
332✔
2061
        var schedulerOp []batch.SchedulerOption
332✔
2062
        if nMsg.isRemote {
617✔
2063
                schedulerOp = append(schedulerOp, batch.LazyAdd())
285✔
2064
        }
285✔
2065

2066
        switch msg := nMsg.msg.(type) {
332✔
2067
        // A new node announcement has arrived which either presents new
2068
        // information about a node in one of the channels we know about, or a
2069
        // updating previously advertised information.
2070
        case *lnwire.NodeAnnouncement:
26✔
2071
                return d.handleNodeAnnouncement(nMsg, msg, schedulerOp)
26✔
2072

2073
        // A new channel announcement has arrived, this indicates the
2074
        // *creation* of a new channel within the network. This only advertises
2075
        // the existence of a channel and not yet the routing policies in
2076
        // either direction of the channel.
2077
        case *lnwire.ChannelAnnouncement1:
232✔
2078
                return d.handleChanAnnouncement(nMsg, msg, schedulerOp)
232✔
2079

2080
        // A new authenticated channel edge update has arrived. This indicates
2081
        // that the directional information for an already known channel has
2082
        // been updated.
2083
        case *lnwire.ChannelUpdate1:
57✔
2084
                return d.handleChanUpdate(nMsg, msg, schedulerOp)
57✔
2085

2086
        // A new signature announcement has been received. This indicates
2087
        // willingness of nodes involved in the funding of a channel to
2088
        // announce this new channel to the rest of the world.
2089
        case *lnwire.AnnounceSignatures1:
23✔
2090
                return d.handleAnnSig(nMsg, msg)
23✔
2091

2092
        default:
×
2093
                err := errors.New("wrong type of the announcement")
×
2094
                nMsg.err <- err
×
2095
                return nil, false
×
2096
        }
2097
}
2098

2099
// processZombieUpdate determines whether the provided channel update should
2100
// resurrect a given zombie edge.
2101
//
2102
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2103
// should be inspected.
2104
func (d *AuthenticatedGossiper) processZombieUpdate(
2105
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2106
        msg *lnwire.ChannelUpdate1) error {
3✔
2107

3✔
2108
        // The least-significant bit in the flag on the channel update tells us
3✔
2109
        // which edge is being updated.
3✔
2110
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2111

3✔
2112
        // Since we've deemed the update as not stale above, before marking it
3✔
2113
        // live, we'll make sure it has been signed by the correct party. If we
3✔
2114
        // have both pubkeys, either party can resurrect the channel. If we've
3✔
2115
        // already marked this with the stricter, single-sided resurrection we
3✔
2116
        // will only have the pubkey of the node with the oldest timestamp.
3✔
2117
        var pubKey *btcec.PublicKey
3✔
2118
        switch {
3✔
2119
        case isNode1 && chanInfo.NodeKey1Bytes != emptyPubkey:
×
2120
                pubKey, _ = chanInfo.NodeKey1()
×
2121
        case !isNode1 && chanInfo.NodeKey2Bytes != emptyPubkey:
2✔
2122
                pubKey, _ = chanInfo.NodeKey2()
2✔
2123
        }
2124
        if pubKey == nil {
4✔
2125
                return fmt.Errorf("incorrect pubkey to resurrect zombie "+
1✔
2126
                        "with chan_id=%v", msg.ShortChannelID)
1✔
2127
        }
1✔
2128

2129
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2130
        if err != nil {
3✔
2131
                return fmt.Errorf("unable to verify channel "+
1✔
2132
                        "update signature: %v", err)
1✔
2133
        }
1✔
2134

2135
        // With the signature valid, we'll proceed to mark the
2136
        // edge as live and wait for the channel announcement to
2137
        // come through again.
2138
        err = d.cfg.Graph.MarkEdgeLive(scid)
1✔
2139
        switch {
1✔
2140
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2141
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2142
                        "zombie index: %v", err)
×
2143

×
2144
                return nil
×
2145

2146
        case err != nil:
×
2147
                return fmt.Errorf("unable to remove edge with "+
×
2148
                        "chan_id=%v from zombie index: %v",
×
2149
                        msg.ShortChannelID, err)
×
2150

2151
        default:
1✔
2152
        }
2153

2154
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2155
                "index", msg.ShortChannelID)
1✔
2156

1✔
2157
        return nil
1✔
2158
}
2159

2160
// fetchNodeAnn fetches the latest signed node announcement from our point of
2161
// view for the node with the given public key.
2162
func (d *AuthenticatedGossiper) fetchNodeAnn(
2163
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
22✔
2164

22✔
2165
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
22✔
2166
        if err != nil {
28✔
2167
                return nil, err
6✔
2168
        }
6✔
2169

2170
        return node.NodeAnnouncement(true)
16✔
2171
}
2172

2173
// isMsgStale determines whether a message retrieved from the backing
2174
// MessageStore is seen as stale by the current graph.
2175
func (d *AuthenticatedGossiper) isMsgStale(msg lnwire.Message) bool {
14✔
2176
        switch msg := msg.(type) {
14✔
2177
        case *lnwire.AnnounceSignatures1:
4✔
2178
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
4✔
2179
                        msg.ShortChannelID,
4✔
2180
                )
4✔
2181

4✔
2182
                // If the channel cannot be found, it is most likely a leftover
4✔
2183
                // message for a channel that was closed, so we can consider it
4✔
2184
                // stale.
4✔
2185
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
6✔
2186
                        return true
2✔
2187
                }
2✔
2188
                if err != nil {
4✔
2189
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2190
                                "%v", chanInfo.ChannelID, err)
×
2191
                        return false
×
2192
                }
×
2193

2194
                // If the proof exists in the graph, then we have successfully
2195
                // received the remote proof and assembled the full proof, so we
2196
                // can safely delete the local proof from the database.
2197
                return chanInfo.AuthProof != nil
4✔
2198

2199
        case *lnwire.ChannelUpdate1:
12✔
2200
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
12✔
2201

12✔
2202
                // If the channel cannot be found, it is most likely a leftover
12✔
2203
                // message for a channel that was closed, so we can consider it
12✔
2204
                // stale.
12✔
2205
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
14✔
2206
                        return true
2✔
2207
                }
2✔
2208
                if err != nil {
12✔
2209
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2210
                                "%v", msg.ShortChannelID, err)
×
2211
                        return false
×
2212
                }
×
2213

2214
                // Otherwise, we'll retrieve the correct policy that we
2215
                // currently have stored within our graph to check if this
2216
                // message is stale by comparing its timestamp.
2217
                var p *models.ChannelEdgePolicy
12✔
2218
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
24✔
2219
                        p = p1
12✔
2220
                } else {
14✔
2221
                        p = p2
2✔
2222
                }
2✔
2223

2224
                // If the policy is still unknown, then we can consider this
2225
                // policy fresh.
2226
                if p == nil {
12✔
2227
                        return false
×
2228
                }
×
2229

2230
                timestamp := time.Unix(int64(msg.Timestamp), 0)
12✔
2231
                return p.LastUpdate.After(timestamp)
12✔
2232

2233
        default:
×
2234
                // We'll make sure to not mark any unsupported messages as stale
×
2235
                // to ensure they are not removed.
×
2236
                return false
×
2237
        }
2238
}
2239

2240
// updateChannel creates a new fully signed update for the channel, and updates
2241
// the underlying graph with the new state.
2242
func (d *AuthenticatedGossiper) updateChannel(info *models.ChannelEdgeInfo,
2243
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2244
        *lnwire.ChannelUpdate1, error) {
6✔
2245

6✔
2246
        // Parse the unsigned edge into a channel update.
6✔
2247
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
6✔
2248

6✔
2249
        // We'll generate a new signature over a digest of the channel
6✔
2250
        // announcement itself and update the timestamp to ensure it propagate.
6✔
2251
        err := netann.SignChannelUpdate(
6✔
2252
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
6✔
2253
                netann.ChanUpdSetTimestamp,
6✔
2254
        )
6✔
2255
        if err != nil {
6✔
2256
                return nil, nil, err
×
2257
        }
×
2258

2259
        // Next, we'll set the new signature in place, and update the reference
2260
        // in the backing slice.
2261
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
6✔
2262
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
6✔
2263

6✔
2264
        // To ensure that our signature is valid, we'll verify it ourself
6✔
2265
        // before committing it to the slice returned.
6✔
2266
        err = netann.ValidateChannelUpdateAnn(
6✔
2267
                d.selfKey, info.Capacity, chanUpdate,
6✔
2268
        )
6✔
2269
        if err != nil {
6✔
2270
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2271
                        "update sig: %v", err)
×
2272
        }
×
2273

2274
        // Finally, we'll write the new edge policy to disk.
2275
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
6✔
2276
                return nil, nil, err
×
2277
        }
×
2278

2279
        // We'll also create the original channel announcement so the two can
2280
        // be broadcast along side each other (if necessary), but only if we
2281
        // have a full channel announcement for this channel.
2282
        var chanAnn *lnwire.ChannelAnnouncement1
6✔
2283
        if info.AuthProof != nil {
11✔
2284
                chanID := lnwire.NewShortChanIDFromInt(info.ChannelID)
5✔
2285
                chanAnn = &lnwire.ChannelAnnouncement1{
5✔
2286
                        ShortChannelID:  chanID,
5✔
2287
                        NodeID1:         info.NodeKey1Bytes,
5✔
2288
                        NodeID2:         info.NodeKey2Bytes,
5✔
2289
                        ChainHash:       info.ChainHash,
5✔
2290
                        BitcoinKey1:     info.BitcoinKey1Bytes,
5✔
2291
                        Features:        lnwire.NewRawFeatureVector(),
5✔
2292
                        BitcoinKey2:     info.BitcoinKey2Bytes,
5✔
2293
                        ExtraOpaqueData: info.ExtraOpaqueData,
5✔
2294
                }
5✔
2295
                chanAnn.NodeSig1, err = lnwire.NewSigFromECDSARawSignature(
5✔
2296
                        info.AuthProof.NodeSig1Bytes,
5✔
2297
                )
5✔
2298
                if err != nil {
5✔
2299
                        return nil, nil, err
×
2300
                }
×
2301
                chanAnn.NodeSig2, err = lnwire.NewSigFromECDSARawSignature(
5✔
2302
                        info.AuthProof.NodeSig2Bytes,
5✔
2303
                )
5✔
2304
                if err != nil {
5✔
2305
                        return nil, nil, err
×
2306
                }
×
2307
                chanAnn.BitcoinSig1, err = lnwire.NewSigFromECDSARawSignature(
5✔
2308
                        info.AuthProof.BitcoinSig1Bytes,
5✔
2309
                )
5✔
2310
                if err != nil {
5✔
2311
                        return nil, nil, err
×
2312
                }
×
2313
                chanAnn.BitcoinSig2, err = lnwire.NewSigFromECDSARawSignature(
5✔
2314
                        info.AuthProof.BitcoinSig2Bytes,
5✔
2315
                )
5✔
2316
                if err != nil {
5✔
2317
                        return nil, nil, err
×
2318
                }
×
2319
        }
2320

2321
        return chanAnn, chanUpdate, err
6✔
2322
}
2323

2324
// SyncManager returns the gossiper's SyncManager instance.
2325
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
2✔
2326
        return d.syncMgr
2✔
2327
}
2✔
2328

2329
// IsKeepAliveUpdate determines whether this channel update is considered a
2330
// keep-alive update based on the previous channel update processed for the same
2331
// direction.
2332
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2333
        prev *models.ChannelEdgePolicy) bool {
16✔
2334

16✔
2335
        // Both updates should be from the same direction.
16✔
2336
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
16✔
2337
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
16✔
2338

×
2339
                return false
×
2340
        }
×
2341

2342
        // The timestamp should always increase for a keep-alive update.
2343
        timestamp := time.Unix(int64(update.Timestamp), 0)
16✔
2344
        if !timestamp.After(prev.LastUpdate) {
18✔
2345
                return false
2✔
2346
        }
2✔
2347

2348
        // None of the remaining fields should change for a keep-alive update.
2349
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
18✔
2350
                return false
2✔
2351
        }
2✔
2352
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
30✔
2353
                return false
14✔
2354
        }
14✔
2355
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
6✔
2356
                return false
2✔
2357
        }
2✔
2358
        if update.TimeLockDelta != prev.TimeLockDelta {
4✔
2359
                return false
×
2360
        }
×
2361
        if update.HtlcMinimumMsat != prev.MinHTLC {
4✔
2362
                return false
×
2363
        }
×
2364
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
4✔
2365
                return false
×
2366
        }
×
2367
        if update.HtlcMaximumMsat != prev.MaxHTLC {
4✔
2368
                return false
×
2369
        }
×
2370
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
6✔
2371
                return false
2✔
2372
        }
2✔
2373
        return true
4✔
2374
}
2375

2376
// latestHeight returns the gossiper's latest height known of the chain.
2377
func (d *AuthenticatedGossiper) latestHeight() uint32 {
2✔
2378
        d.Lock()
2✔
2379
        defer d.Unlock()
2✔
2380
        return d.bestHeight
2✔
2381
}
2✔
2382

2383
// handleNodeAnnouncement processes a new node announcement.
2384
func (d *AuthenticatedGossiper) handleNodeAnnouncement(nMsg *networkMsg,
2385
        nodeAnn *lnwire.NodeAnnouncement,
2386
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
26✔
2387

26✔
2388
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
26✔
2389

26✔
2390
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
26✔
2391
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
26✔
2392
                nMsg.source.SerializeCompressed())
26✔
2393

26✔
2394
        // We'll quickly ask the router if it already has a newer update for
26✔
2395
        // this node so we can skip validating signatures if not required.
26✔
2396
        if d.cfg.Graph.IsStaleNode(nodeAnn.NodeID, timestamp) {
36✔
2397
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
10✔
2398
                nMsg.err <- nil
10✔
2399
                return nil, true
10✔
2400
        }
10✔
2401

2402
        if err := d.addNode(nodeAnn, ops...); err != nil {
20✔
2403
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
2✔
2404
                        err)
2✔
2405

2✔
2406
                if !graph.IsError(
2✔
2407
                        err,
2✔
2408
                        graph.ErrOutdated,
2✔
2409
                        graph.ErrIgnored,
2✔
2410
                        graph.ErrVBarrierShuttingDown,
2✔
2411
                ) {
2✔
2412

×
2413
                        log.Error(err)
×
2414
                }
×
2415

2416
                nMsg.err <- err
2✔
2417
                return nil, false
2✔
2418
        }
2419

2420
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2421
        // quick check to ensure this node intends to publicly advertise itself
2422
        // to the network.
2423
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
18✔
2424
        if err != nil {
18✔
2425
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2426
                        nodeAnn.NodeID, err)
×
2427
                nMsg.err <- err
×
2428
                return nil, false
×
2429
        }
×
2430

2431
        var announcements []networkMsg
18✔
2432

18✔
2433
        // If it does, we'll add their announcement to our batch so that it can
18✔
2434
        // be broadcast to the rest of our peers.
18✔
2435
        if isPublic {
23✔
2436
                announcements = append(announcements, networkMsg{
5✔
2437
                        peer:     nMsg.peer,
5✔
2438
                        isRemote: nMsg.isRemote,
5✔
2439
                        source:   nMsg.source,
5✔
2440
                        msg:      nodeAnn,
5✔
2441
                })
5✔
2442
        } else {
20✔
2443
                log.Tracef("Skipping broadcasting node announcement for %x "+
15✔
2444
                        "due to being unadvertised", nodeAnn.NodeID)
15✔
2445
        }
15✔
2446

2447
        nMsg.err <- nil
18✔
2448
        // TODO(roasbeef): get rid of the above
18✔
2449

18✔
2450
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
18✔
2451
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
18✔
2452
                nMsg.source.SerializeCompressed())
18✔
2453

18✔
2454
        return announcements, true
18✔
2455
}
2456

2457
// handleChanAnnouncement processes a new channel announcement.
2458
func (d *AuthenticatedGossiper) handleChanAnnouncement(nMsg *networkMsg,
2459
        ann *lnwire.ChannelAnnouncement1,
2460
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
232✔
2461

232✔
2462
        scid := ann.ShortChannelID
232✔
2463

232✔
2464
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
232✔
2465
                nMsg.peer, scid.ToUint64())
232✔
2466

232✔
2467
        // We'll ignore any channel announcements that target any chain other
232✔
2468
        // than the set of chains we know of.
232✔
2469
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
232✔
2470
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2471
                        ", gossiper on chain=%v", ann.ChainHash,
×
2472
                        d.cfg.ChainHash)
×
2473
                log.Errorf(err.Error())
×
2474

×
2475
                key := newRejectCacheKey(
×
2476
                        scid.ToUint64(),
×
2477
                        sourceToPub(nMsg.source),
×
2478
                )
×
2479
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2480

×
2481
                nMsg.err <- err
×
2482
                return nil, false
×
2483
        }
×
2484

2485
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2486
        // reject the announcement. Since the router accepts alias SCIDs,
2487
        // not erroring out would be a DoS vector.
2488
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
232✔
2489
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2490
                log.Errorf(err.Error())
×
2491

×
2492
                key := newRejectCacheKey(
×
2493
                        scid.ToUint64(),
×
2494
                        sourceToPub(nMsg.source),
×
2495
                )
×
2496
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2497

×
2498
                nMsg.err <- err
×
2499
                return nil, false
×
2500
        }
×
2501

2502
        // If the advertised inclusionary block is beyond our knowledge of the
2503
        // chain tip, then we'll ignore it for now.
2504
        d.Lock()
232✔
2505
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
233✔
2506
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2507
                        "advertises height %v, only height %v is known",
1✔
2508
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2509
                d.Unlock()
1✔
2510
                nMsg.err <- nil
1✔
2511
                return nil, false
1✔
2512
        }
1✔
2513
        d.Unlock()
231✔
2514

231✔
2515
        // At this point, we'll now ask the router if this is a zombie/known
231✔
2516
        // edge. If so we can skip all the processing below.
231✔
2517
        if d.cfg.Graph.IsKnownEdge(scid) {
234✔
2518
                nMsg.err <- nil
3✔
2519
                return nil, true
3✔
2520
        }
3✔
2521

2522
        // Check if the channel is already closed in which case we can ignore
2523
        // it.
2524
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
230✔
2525
        if err != nil {
230✔
2526
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2527
                        err)
×
2528
                nMsg.err <- err
×
2529

×
2530
                return nil, false
×
2531
        }
×
2532

2533
        if closed {
231✔
2534
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2535
                log.Error(err)
1✔
2536

1✔
2537
                // If this is an announcement from us, we'll just ignore it.
1✔
2538
                if !nMsg.isRemote {
1✔
2539
                        nMsg.err <- err
×
2540
                        return nil, false
×
2541
                }
×
2542

2543
                // Increment the peer's ban score if they are sending closed
2544
                // channel announcements.
2545
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2546

1✔
2547
                // If the peer is banned and not a channel peer, we'll
1✔
2548
                // disconnect them.
1✔
2549
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2550
                if dcErr != nil {
1✔
2551
                        log.Errorf("failed to check if we should disconnect "+
×
2552
                                "peer: %v", dcErr)
×
2553
                        nMsg.err <- dcErr
×
2554

×
2555
                        return nil, false
×
2556
                }
×
2557

2558
                if shouldDc {
1✔
2559
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2560
                }
×
2561

2562
                nMsg.err <- err
1✔
2563

1✔
2564
                return nil, false
1✔
2565
        }
2566

2567
        // If this is a remote channel announcement, then we'll validate all
2568
        // the signatures within the proof as it should be well formed.
2569
        var proof *models.ChannelAuthProof
229✔
2570
        if nMsg.isRemote {
444✔
2571
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
215✔
2572
                if err != nil {
215✔
2573
                        err := fmt.Errorf("unable to validate announcement: "+
×
2574
                                "%v", err)
×
2575

×
2576
                        key := newRejectCacheKey(
×
2577
                                scid.ToUint64(),
×
2578
                                sourceToPub(nMsg.source),
×
2579
                        )
×
2580
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2581

×
2582
                        log.Error(err)
×
2583
                        nMsg.err <- err
×
2584
                        return nil, false
×
2585
                }
×
2586

2587
                // If the proof checks out, then we'll save the proof itself to
2588
                // the database so we can fetch it later when gossiping with
2589
                // other nodes.
2590
                proof = &models.ChannelAuthProof{
215✔
2591
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
215✔
2592
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
215✔
2593
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
215✔
2594
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
215✔
2595
                }
215✔
2596
        }
2597

2598
        // With the proof validated (if necessary), we can now store it within
2599
        // the database for our path finding and syncing needs.
2600
        var featureBuf bytes.Buffer
229✔
2601
        if err := ann.Features.Encode(&featureBuf); err != nil {
229✔
2602
                log.Errorf("unable to encode features: %v", err)
×
2603
                nMsg.err <- err
×
2604
                return nil, false
×
2605
        }
×
2606

2607
        edge := &models.ChannelEdgeInfo{
229✔
2608
                ChannelID:        scid.ToUint64(),
229✔
2609
                ChainHash:        ann.ChainHash,
229✔
2610
                NodeKey1Bytes:    ann.NodeID1,
229✔
2611
                NodeKey2Bytes:    ann.NodeID2,
229✔
2612
                BitcoinKey1Bytes: ann.BitcoinKey1,
229✔
2613
                BitcoinKey2Bytes: ann.BitcoinKey2,
229✔
2614
                AuthProof:        proof,
229✔
2615
                Features:         featureBuf.Bytes(),
229✔
2616
                ExtraOpaqueData:  ann.ExtraOpaqueData,
229✔
2617
        }
229✔
2618

229✔
2619
        // If there were any optional message fields provided, we'll include
229✔
2620
        // them in its serialized disk representation now.
229✔
2621
        if nMsg.optionalMsgFields != nil {
245✔
2622
                if nMsg.optionalMsgFields.capacity != nil {
19✔
2623
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
3✔
2624
                }
3✔
2625
                if nMsg.optionalMsgFields.channelPoint != nil {
22✔
2626
                        cp := *nMsg.optionalMsgFields.channelPoint
6✔
2627
                        edge.ChannelPoint = cp
6✔
2628
                }
6✔
2629

2630
                // Optional tapscript root for custom channels.
2631
                edge.TapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
16✔
2632
        }
2633

2634
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
229✔
2635

229✔
2636
        // We will add the edge to the channel router. If the nodes present in
229✔
2637
        // this channel are not present in the database, a partial node will be
229✔
2638
        // added to represent each node while we wait for a node announcement.
229✔
2639
        //
229✔
2640
        // Before we add the edge to the database, we obtain the mutex for this
229✔
2641
        // channel ID. We do this to ensure no other goroutine has read the
229✔
2642
        // database and is now making decisions based on this DB state, before
229✔
2643
        // it writes to the DB.
229✔
2644
        d.channelMtx.Lock(scid.ToUint64())
229✔
2645
        err = d.cfg.Graph.AddEdge(edge, ops...)
229✔
2646
        if err != nil {
433✔
2647
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
204✔
2648
                        scid.ToUint64(), err)
204✔
2649

204✔
2650
                defer d.channelMtx.Unlock(scid.ToUint64())
204✔
2651

204✔
2652
                // If the edge was rejected due to already being known, then it
204✔
2653
                // may be the case that this new message has a fresh channel
204✔
2654
                // proof, so we'll check.
204✔
2655
                switch {
204✔
2656
                case graph.IsError(err, graph.ErrIgnored):
2✔
2657
                        // Attempt to process the rejected message to see if we
2✔
2658
                        // get any new announcements.
2✔
2659
                        anns, rErr := d.processRejectedEdge(ann, proof)
2✔
2660
                        if rErr != nil {
2✔
2661
                                key := newRejectCacheKey(
×
2662
                                        scid.ToUint64(),
×
2663
                                        sourceToPub(nMsg.source),
×
2664
                                )
×
2665
                                cr := &cachedReject{}
×
2666
                                _, _ = d.recentRejects.Put(key, cr)
×
2667

×
2668
                                nMsg.err <- rErr
×
2669
                                return nil, false
×
2670
                        }
×
2671

2672
                        log.Debugf("Extracted %v announcements from rejected "+
2✔
2673
                                "msgs", len(anns))
2✔
2674

2✔
2675
                        // If while processing this rejected edge, we realized
2✔
2676
                        // there's a set of announcements we could extract,
2✔
2677
                        // then we'll return those directly.
2✔
2678
                        //
2✔
2679
                        // NOTE: since this is an ErrIgnored, we can return
2✔
2680
                        // true here to signal "allow" to its dependants.
2✔
2681
                        nMsg.err <- nil
2✔
2682

2✔
2683
                        return anns, true
2✔
2684

2685
                case graph.IsError(
2686
                        err, graph.ErrNoFundingTransaction,
2687
                        graph.ErrInvalidFundingOutput,
2688
                ):
200✔
2689
                        key := newRejectCacheKey(
200✔
2690
                                scid.ToUint64(),
200✔
2691
                                sourceToPub(nMsg.source),
200✔
2692
                        )
200✔
2693
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
200✔
2694

200✔
2695
                        // Increment the peer's ban score. We check isRemote
200✔
2696
                        // so we don't actually ban the peer in case of a local
200✔
2697
                        // bug.
200✔
2698
                        if nMsg.isRemote {
400✔
2699
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
200✔
2700
                        }
200✔
2701

2702
                case graph.IsError(err, graph.ErrChannelSpent):
1✔
2703
                        key := newRejectCacheKey(
1✔
2704
                                scid.ToUint64(),
1✔
2705
                                sourceToPub(nMsg.source),
1✔
2706
                        )
1✔
2707
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2708

1✔
2709
                        // Since this channel has already been closed, we'll
1✔
2710
                        // add it to the graph's closed channel index such that
1✔
2711
                        // we won't attempt to do expensive validation checks
1✔
2712
                        // on it again.
1✔
2713
                        // TODO: Populate the ScidCloser by using closed
1✔
2714
                        // channel notifications.
1✔
2715
                        dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
1✔
2716
                        if dbErr != nil {
1✔
2717
                                log.Errorf("failed to mark scid(%v) as "+
×
2718
                                        "closed: %v", scid, dbErr)
×
2719

×
2720
                                nMsg.err <- dbErr
×
2721

×
2722
                                return nil, false
×
2723
                        }
×
2724

2725
                        // Increment the peer's ban score. We check isRemote
2726
                        // so we don't accidentally ban ourselves in case of a
2727
                        // bug.
2728
                        if nMsg.isRemote {
2✔
2729
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2730
                        }
1✔
2731

2732
                default:
1✔
2733
                        // Otherwise, this is just a regular rejected edge.
1✔
2734
                        key := newRejectCacheKey(
1✔
2735
                                scid.ToUint64(),
1✔
2736
                                sourceToPub(nMsg.source),
1✔
2737
                        )
1✔
2738
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2739
                }
2740

2741
                if !nMsg.isRemote {
202✔
2742
                        log.Errorf("failed to add edge for local channel: %v",
×
2743
                                err)
×
2744
                        nMsg.err <- err
×
2745

×
2746
                        return nil, false
×
2747
                }
×
2748

2749
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
202✔
2750
                if dcErr != nil {
202✔
2751
                        log.Errorf("failed to check if we should disconnect "+
×
2752
                                "peer: %v", dcErr)
×
2753
                        nMsg.err <- dcErr
×
2754

×
2755
                        return nil, false
×
2756
                }
×
2757

2758
                if shouldDc {
203✔
2759
                        nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2760
                }
1✔
2761

2762
                nMsg.err <- err
202✔
2763

202✔
2764
                return nil, false
202✔
2765
        }
2766

2767
        // If err is nil, release the lock immediately.
2768
        d.channelMtx.Unlock(scid.ToUint64())
27✔
2769

27✔
2770
        log.Debugf("Finish adding edge for short_chan_id: %v", scid.ToUint64())
27✔
2771

27✔
2772
        // If we earlier received any ChannelUpdates for this channel, we can
27✔
2773
        // now process them, as the channel is added to the graph.
27✔
2774
        var channelUpdates []*processedNetworkMsg
27✔
2775

27✔
2776
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
27✔
2777
        if err == nil {
31✔
2778
                // There was actually an entry in the map, so we'll accumulate
4✔
2779
                // it. We don't worry about deletion, since it'll eventually
4✔
2780
                // fall out anyway.
4✔
2781
                chanMsgs := earlyChanUpdates
4✔
2782
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
4✔
2783
        }
4✔
2784

2785
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2786
        // ensure we don't block here, as we can handle only one announcement
2787
        // at a time.
2788
        for _, cu := range channelUpdates {
31✔
2789
                // Skip if already processed.
4✔
2790
                if cu.processed {
5✔
2791
                        continue
1✔
2792
                }
2793

2794
                // Mark the ChannelUpdate as processed. This ensures that a
2795
                // subsequent announcement in the option-scid-alias case does
2796
                // not re-use an old ChannelUpdate.
2797
                cu.processed = true
4✔
2798

4✔
2799
                d.wg.Add(1)
4✔
2800
                go func(updMsg *networkMsg) {
8✔
2801
                        defer d.wg.Done()
4✔
2802

4✔
2803
                        switch msg := updMsg.msg.(type) {
4✔
2804
                        // Reprocess the message, making sure we return an
2805
                        // error to the original caller in case the gossiper
2806
                        // shuts down.
2807
                        case *lnwire.ChannelUpdate1:
4✔
2808
                                log.Debugf("Reprocessing ChannelUpdate for "+
4✔
2809
                                        "shortChanID=%v", scid.ToUint64())
4✔
2810

4✔
2811
                                select {
4✔
2812
                                case d.networkMsgs <- updMsg:
4✔
2813
                                case <-d.quit:
×
2814
                                        updMsg.err <- ErrGossiperShuttingDown
×
2815
                                }
2816

2817
                        // We don't expect any other message type than
2818
                        // ChannelUpdate to be in this cache.
2819
                        default:
×
2820
                                log.Errorf("Unsupported message type found "+
×
2821
                                        "among ChannelUpdates: %T", msg)
×
2822
                        }
2823
                }(cu.msg)
2824
        }
2825

2826
        // Channel announcement was successfully processed and now it might be
2827
        // broadcast to other connected nodes if it was an announcement with
2828
        // proof (remote).
2829
        var announcements []networkMsg
27✔
2830

27✔
2831
        if proof != nil {
40✔
2832
                announcements = append(announcements, networkMsg{
13✔
2833
                        peer:     nMsg.peer,
13✔
2834
                        isRemote: nMsg.isRemote,
13✔
2835
                        source:   nMsg.source,
13✔
2836
                        msg:      ann,
13✔
2837
                })
13✔
2838
        }
13✔
2839

2840
        nMsg.err <- nil
27✔
2841

27✔
2842
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
27✔
2843
                nMsg.peer, scid.ToUint64())
27✔
2844

27✔
2845
        return announcements, true
27✔
2846
}
2847

2848
// handleChanUpdate processes a new channel update.
2849
func (d *AuthenticatedGossiper) handleChanUpdate(nMsg *networkMsg,
2850
        upd *lnwire.ChannelUpdate1,
2851
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
57✔
2852

57✔
2853
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
57✔
2854
                nMsg.peer, upd.ShortChannelID.ToUint64())
57✔
2855

57✔
2856
        // We'll ignore any channel updates that target any chain other than
57✔
2857
        // the set of chains we know of.
57✔
2858
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
57✔
2859
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2860
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2861
                log.Errorf(err.Error())
×
2862

×
2863
                key := newRejectCacheKey(
×
2864
                        upd.ShortChannelID.ToUint64(),
×
2865
                        sourceToPub(nMsg.source),
×
2866
                )
×
2867
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2868

×
2869
                nMsg.err <- err
×
2870
                return nil, false
×
2871
        }
×
2872

2873
        blockHeight := upd.ShortChannelID.BlockHeight
57✔
2874
        shortChanID := upd.ShortChannelID.ToUint64()
57✔
2875

57✔
2876
        // If the advertised inclusionary block is beyond our knowledge of the
57✔
2877
        // chain tip, then we'll put the announcement in limbo to be fully
57✔
2878
        // verified once we advance forward in the chain. If the update has an
57✔
2879
        // alias SCID, we'll skip the isPremature check. This is necessary
57✔
2880
        // since aliases start at block height 16_000_000.
57✔
2881
        d.Lock()
57✔
2882
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
57✔
2883
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
57✔
UNCOV
2884

×
UNCOV
2885
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
UNCOV
2886
                        "premature: advertises height %v, only height %v is "+
×
UNCOV
2887
                        "known", shortChanID, blockHeight, d.bestHeight)
×
UNCOV
2888
                d.Unlock()
×
UNCOV
2889
                nMsg.err <- nil
×
UNCOV
2890
                return nil, false
×
UNCOV
2891
        }
×
2892
        d.Unlock()
57✔
2893

57✔
2894
        // Before we perform any of the expensive checks below, we'll check
57✔
2895
        // whether this update is stale or is for a zombie channel in order to
57✔
2896
        // quickly reject it.
57✔
2897
        timestamp := time.Unix(int64(upd.Timestamp), 0)
57✔
2898

57✔
2899
        // Fetch the SCID we should be using to lock the channelMtx and make
57✔
2900
        // graph queries with.
57✔
2901
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
57✔
2902
        if err != nil {
114✔
2903
                // Fallback and set the graphScid to the peer-provided SCID.
57✔
2904
                // This will occur for non-option-scid-alias channels and for
57✔
2905
                // public option-scid-alias channels after 6 confirmations.
57✔
2906
                // Once public option-scid-alias channels have 6 confs, we'll
57✔
2907
                // ignore ChannelUpdates with one of their aliases.
57✔
2908
                graphScid = upd.ShortChannelID
57✔
2909
        }
57✔
2910

2911
        if d.cfg.Graph.IsStaleEdgePolicy(
57✔
2912
                graphScid, timestamp, upd.ChannelFlags,
57✔
2913
        ) {
61✔
2914

4✔
2915
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
4✔
2916
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
4✔
2917
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
4✔
2918
                )
4✔
2919

4✔
2920
                nMsg.err <- nil
4✔
2921
                return nil, true
4✔
2922
        }
4✔
2923

2924
        // Check that the ChanUpdate is not too far into the future, this could
2925
        // reveal some faulty implementation therefore we log an error.
2926
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
55✔
2927
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
2928
                        "short_chan_id(%v), timestamp too far in the future: "+
×
2929
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
2930
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
2931
                        nMsg.isRemote,
×
2932
                )
×
2933

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

×
2937
                return nil, false
×
2938
        }
×
2939

2940
        // Get the node pub key as far since we don't have it in the channel
2941
        // update announcement message. We'll need this to properly verify the
2942
        // message's signature.
2943
        //
2944
        // We make sure to obtain the mutex for this channel ID before we
2945
        // access the database. This ensures the state we read from the
2946
        // database has not changed between this point and when we call
2947
        // UpdateEdge() later.
2948
        d.channelMtx.Lock(graphScid.ToUint64())
55✔
2949
        defer d.channelMtx.Unlock(graphScid.ToUint64())
55✔
2950

55✔
2951
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
55✔
2952
        switch {
55✔
2953
        // No error, break.
2954
        case err == nil:
51✔
2955
                break
51✔
2956

2957
        case errors.Is(err, graphdb.ErrZombieEdge):
3✔
2958
                err = d.processZombieUpdate(chanInfo, graphScid, upd)
3✔
2959
                if err != nil {
5✔
2960
                        log.Debug(err)
2✔
2961
                        nMsg.err <- err
2✔
2962
                        return nil, false
2✔
2963
                }
2✔
2964

2965
                // We'll fallthrough to ensure we stash the update until we
2966
                // receive its corresponding ChannelAnnouncement. This is
2967
                // needed to ensure the edge exists in the graph before
2968
                // applying the update.
2969
                fallthrough
1✔
2970
        case errors.Is(err, graphdb.ErrGraphNotFound):
1✔
2971
                fallthrough
1✔
2972
        case errors.Is(err, graphdb.ErrGraphNoEdgesFound):
1✔
2973
                fallthrough
1✔
2974
        case errors.Is(err, graphdb.ErrEdgeNotFound):
4✔
2975
                // If the edge corresponding to this ChannelUpdate was not
4✔
2976
                // found in the graph, this might be a channel in the process
4✔
2977
                // of being opened, and we haven't processed our own
4✔
2978
                // ChannelAnnouncement yet, hence it is not not found in the
4✔
2979
                // graph. This usually gets resolved after the channel proofs
4✔
2980
                // are exchanged and the channel is broadcasted to the rest of
4✔
2981
                // the network, but in case this is a private channel this
4✔
2982
                // won't ever happen. This can also happen in the case of a
4✔
2983
                // zombie channel with a fresh update for which we don't have a
4✔
2984
                // ChannelAnnouncement for since we reject them. Because of
4✔
2985
                // this, we temporarily add it to a map, and reprocess it after
4✔
2986
                // our own ChannelAnnouncement has been processed.
4✔
2987
                //
4✔
2988
                // The shortChanID may be an alias, but it is fine to use here
4✔
2989
                // since we don't have an edge in the graph and if the peer is
4✔
2990
                // not buggy, we should be able to use it once the gossiper
4✔
2991
                // receives the local announcement.
4✔
2992
                pMsg := &processedNetworkMsg{msg: nMsg}
4✔
2993

4✔
2994
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
4✔
2995
                switch {
4✔
2996
                // Nothing in the cache yet, we can just directly insert this
2997
                // element.
2998
                case err == cache.ErrElementNotFound:
4✔
2999
                        _, _ = d.prematureChannelUpdates.Put(
4✔
3000
                                shortChanID, &cachedNetworkMsg{
4✔
3001
                                        msgs: []*processedNetworkMsg{pMsg},
4✔
3002
                                })
4✔
3003

3004
                // There's already something in the cache, so we'll combine the
3005
                // set of messages into a single value.
3006
                default:
2✔
3007
                        msgs := earlyMsgs.msgs
2✔
3008
                        msgs = append(msgs, pMsg)
2✔
3009
                        _, _ = d.prematureChannelUpdates.Put(
2✔
3010
                                shortChanID, &cachedNetworkMsg{
2✔
3011
                                        msgs: msgs,
2✔
3012
                                })
2✔
3013
                }
3014

3015
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
4✔
3016
                        "(shortChanID=%v), saving for reprocessing later",
4✔
3017
                        shortChanID)
4✔
3018

4✔
3019
                // NOTE: We don't return anything on the error channel for this
4✔
3020
                // message, as we expect that will be done when this
4✔
3021
                // ChannelUpdate is later reprocessed.
4✔
3022
                return nil, false
4✔
3023

3024
        default:
×
3025
                err := fmt.Errorf("unable to validate channel update "+
×
3026
                        "short_chan_id=%v: %v", shortChanID, err)
×
3027
                log.Error(err)
×
3028
                nMsg.err <- err
×
3029

×
3030
                key := newRejectCacheKey(
×
3031
                        upd.ShortChannelID.ToUint64(),
×
3032
                        sourceToPub(nMsg.source),
×
3033
                )
×
3034
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3035

×
3036
                return nil, false
×
3037
        }
3038

3039
        // The least-significant bit in the flag on the channel update
3040
        // announcement tells us "which" side of the channels directed edge is
3041
        // being updated.
3042
        var (
51✔
3043
                pubKey       *btcec.PublicKey
51✔
3044
                edgeToUpdate *models.ChannelEdgePolicy
51✔
3045
        )
51✔
3046
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
51✔
3047
        switch direction {
51✔
3048
        case 0:
36✔
3049
                pubKey, _ = chanInfo.NodeKey1()
36✔
3050
                edgeToUpdate = e1
36✔
3051
        case 1:
17✔
3052
                pubKey, _ = chanInfo.NodeKey2()
17✔
3053
                edgeToUpdate = e2
17✔
3054
        }
3055

3056
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
51✔
3057
                "edge policy=%v", chanInfo.ChannelID,
51✔
3058
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
51✔
3059

51✔
3060
        // Validate the channel announcement with the expected public key and
51✔
3061
        // channel capacity. In the case of an invalid channel update, we'll
51✔
3062
        // return an error to the caller and exit early.
51✔
3063
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
51✔
3064
        if err != nil {
55✔
3065
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3066
                        "announcement for short_chan_id=%v: %v",
4✔
3067
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3068

4✔
3069
                log.Error(rErr)
4✔
3070
                nMsg.err <- rErr
4✔
3071
                return nil, false
4✔
3072
        }
4✔
3073

3074
        // If we have a previous version of the edge being updated, we'll want
3075
        // to rate limit its updates to prevent spam throughout the network.
3076
        if nMsg.isRemote && edgeToUpdate != nil {
63✔
3077
                // If it's a keep-alive update, we'll only propagate one if
16✔
3078
                // it's been a day since the previous. This follows our own
16✔
3079
                // heuristic of sending keep-alive updates after the same
16✔
3080
                // duration (see retransmitStaleAnns).
16✔
3081
                timeSinceLastUpdate := timestamp.Sub(edgeToUpdate.LastUpdate)
16✔
3082
                if IsKeepAliveUpdate(upd, edgeToUpdate) {
20✔
3083
                        if timeSinceLastUpdate < d.cfg.RebroadcastInterval {
7✔
3084
                                log.Debugf("Ignoring keep alive update not "+
3✔
3085
                                        "within %v period for channel %v",
3✔
3086
                                        d.cfg.RebroadcastInterval, shortChanID)
3✔
3087
                                nMsg.err <- nil
3✔
3088
                                return nil, false
3✔
3089
                        }
3✔
3090
                } else {
14✔
3091
                        // If it's not, we'll allow an update per minute with a
14✔
3092
                        // maximum burst of 10. If we haven't seen an update
14✔
3093
                        // for this channel before, we'll need to initialize a
14✔
3094
                        // rate limiter for each direction.
14✔
3095
                        //
14✔
3096
                        // Since the edge exists in the graph, we'll create a
14✔
3097
                        // rate limiter for chanInfo.ChannelID rather then the
14✔
3098
                        // SCID the peer sent. This is because there may be
14✔
3099
                        // multiple aliases for a channel and we may otherwise
14✔
3100
                        // rate-limit only a single alias of the channel,
14✔
3101
                        // instead of the whole channel.
14✔
3102
                        baseScid := chanInfo.ChannelID
14✔
3103
                        d.Lock()
14✔
3104
                        rls, ok := d.chanUpdateRateLimiter[baseScid]
14✔
3105
                        if !ok {
17✔
3106
                                r := rate.Every(d.cfg.ChannelUpdateInterval)
3✔
3107
                                b := d.cfg.MaxChannelUpdateBurst
3✔
3108
                                rls = [2]*rate.Limiter{
3✔
3109
                                        rate.NewLimiter(r, b),
3✔
3110
                                        rate.NewLimiter(r, b),
3✔
3111
                                }
3✔
3112
                                d.chanUpdateRateLimiter[baseScid] = rls
3✔
3113
                        }
3✔
3114
                        d.Unlock()
14✔
3115

14✔
3116
                        if !rls[direction].Allow() {
21✔
3117
                                log.Debugf("Rate limiting update for channel "+
7✔
3118
                                        "%v from direction %x", shortChanID,
7✔
3119
                                        pubKey.SerializeCompressed())
7✔
3120
                                nMsg.err <- nil
7✔
3121
                                return nil, false
7✔
3122
                        }
7✔
3123
                }
3124
        }
3125

3126
        // We'll use chanInfo.ChannelID rather than the peer-supplied
3127
        // ShortChannelID in the ChannelUpdate to avoid the router having to
3128
        // lookup the stored SCID. If we're sending the update, we'll always
3129
        // use the SCID stored in the database rather than a potentially
3130
        // different alias. This might mean that SigBytes is incorrect as it
3131
        // signs a different SCID than the database SCID, but since there will
3132
        // only be a difference if AuthProof == nil, this is fine.
3133
        update := &models.ChannelEdgePolicy{
41✔
3134
                SigBytes:                  upd.Signature.ToSignatureBytes(),
41✔
3135
                ChannelID:                 chanInfo.ChannelID,
41✔
3136
                LastUpdate:                timestamp,
41✔
3137
                MessageFlags:              upd.MessageFlags,
41✔
3138
                ChannelFlags:              upd.ChannelFlags,
41✔
3139
                TimeLockDelta:             upd.TimeLockDelta,
41✔
3140
                MinHTLC:                   upd.HtlcMinimumMsat,
41✔
3141
                MaxHTLC:                   upd.HtlcMaximumMsat,
41✔
3142
                FeeBaseMSat:               lnwire.MilliSatoshi(upd.BaseFee),
41✔
3143
                FeeProportionalMillionths: lnwire.MilliSatoshi(upd.FeeRate),
41✔
3144
                ExtraOpaqueData:           upd.ExtraOpaqueData,
41✔
3145
        }
41✔
3146

41✔
3147
        if err := d.cfg.Graph.UpdateEdge(update, ops...); err != nil {
43✔
3148
                if graph.IsError(
2✔
3149
                        err, graph.ErrOutdated,
2✔
3150
                        graph.ErrIgnored,
2✔
3151
                        graph.ErrVBarrierShuttingDown,
2✔
3152
                ) {
4✔
3153

2✔
3154
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
2✔
3155
                                shortChanID, err)
2✔
3156
                } else {
2✔
3157
                        // Since we know the stored SCID in the graph, we'll
×
3158
                        // cache that SCID.
×
3159
                        key := newRejectCacheKey(
×
3160
                                chanInfo.ChannelID,
×
3161
                                sourceToPub(nMsg.source),
×
3162
                        )
×
3163
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3164

×
3165
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3166
                                shortChanID, err)
×
3167
                }
×
3168

3169
                nMsg.err <- err
2✔
3170
                return nil, false
2✔
3171
        }
3172

3173
        // If this is a local ChannelUpdate without an AuthProof, it means it
3174
        // is an update to a channel that is not (yet) supposed to be announced
3175
        // to the greater network. However, our channel counter party will need
3176
        // to be given the update, so we'll try sending the update directly to
3177
        // the remote peer.
3178
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
54✔
3179
                if nMsg.optionalMsgFields != nil {
26✔
3180
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
13✔
3181
                        if remoteAlias != nil {
15✔
3182
                                // The remoteAlias field was specified, meaning
2✔
3183
                                // that we should replace the SCID in the
2✔
3184
                                // update with the remote's alias. We'll also
2✔
3185
                                // need to re-sign the channel update. This is
2✔
3186
                                // required for option-scid-alias feature-bit
2✔
3187
                                // negotiated channels.
2✔
3188
                                upd.ShortChannelID = *remoteAlias
2✔
3189

2✔
3190
                                sig, err := d.cfg.SignAliasUpdate(upd)
2✔
3191
                                if err != nil {
2✔
3192
                                        log.Error(err)
×
3193
                                        nMsg.err <- err
×
3194
                                        return nil, false
×
3195
                                }
×
3196

3197
                                lnSig, err := lnwire.NewSigFromSignature(sig)
2✔
3198
                                if err != nil {
2✔
3199
                                        log.Error(err)
×
3200
                                        nMsg.err <- err
×
3201
                                        return nil, false
×
3202
                                }
×
3203

3204
                                upd.Signature = lnSig
2✔
3205
                        }
3206
                }
3207

3208
                // Get our peer's public key.
3209
                remotePubKey := remotePubFromChanInfo(
13✔
3210
                        chanInfo, upd.ChannelFlags,
13✔
3211
                )
13✔
3212

13✔
3213
                log.Debugf("The message %v has no AuthProof, sending the "+
13✔
3214
                        "update to remote peer %x", upd.MsgType(), remotePubKey)
13✔
3215

13✔
3216
                // Now we'll attempt to send the channel update message
13✔
3217
                // reliably to the remote peer in the background, so that we
13✔
3218
                // don't block if the peer happens to be offline at the moment.
13✔
3219
                err := d.reliableSender.sendMessage(upd, remotePubKey)
13✔
3220
                if err != nil {
13✔
3221
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3222
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3223
                                upd.ShortChannelID, remotePubKey, err)
×
3224
                        nMsg.err <- err
×
3225
                        return nil, false
×
3226
                }
×
3227
        }
3228

3229
        // Channel update announcement was successfully processed and now it
3230
        // can be broadcast to the rest of the network. However, we'll only
3231
        // broadcast the channel update announcement if it has an attached
3232
        // authentication proof. We also won't broadcast the update if it
3233
        // contains an alias because the network would reject this.
3234
        var announcements []networkMsg
41✔
3235
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
62✔
3236
                announcements = append(announcements, networkMsg{
21✔
3237
                        peer:     nMsg.peer,
21✔
3238
                        source:   nMsg.source,
21✔
3239
                        isRemote: nMsg.isRemote,
21✔
3240
                        msg:      upd,
21✔
3241
                })
21✔
3242
        }
21✔
3243

3244
        nMsg.err <- nil
41✔
3245

41✔
3246
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
41✔
3247
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
41✔
3248
                timestamp)
41✔
3249
        return announcements, true
41✔
3250
}
3251

3252
// handleAnnSig processes a new announcement signatures message.
3253
func (d *AuthenticatedGossiper) handleAnnSig(nMsg *networkMsg,
3254
        ann *lnwire.AnnounceSignatures1) ([]networkMsg, bool) {
23✔
3255

23✔
3256
        needBlockHeight := ann.ShortChannelID.BlockHeight +
23✔
3257
                d.cfg.ProofMatureDelta
23✔
3258
        shortChanID := ann.ShortChannelID.ToUint64()
23✔
3259

23✔
3260
        prefix := "local"
23✔
3261
        if nMsg.isRemote {
36✔
3262
                prefix = "remote"
13✔
3263
        }
13✔
3264

3265
        log.Infof("Received new %v announcement signature for %v", prefix,
23✔
3266
                ann.ShortChannelID)
23✔
3267

23✔
3268
        // By the specification, channel announcement proofs should be sent
23✔
3269
        // after some number of confirmations after channel was registered in
23✔
3270
        // bitcoin blockchain. Therefore, we check if the proof is mature.
23✔
3271
        d.Lock()
23✔
3272
        premature := d.isPremature(
23✔
3273
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
23✔
3274
        )
23✔
3275
        if premature {
25✔
3276
                log.Warnf("Premature proof announcement, current block height"+
2✔
3277
                        "lower than needed: %v < %v", d.bestHeight,
2✔
3278
                        needBlockHeight)
2✔
3279
                d.Unlock()
2✔
3280
                nMsg.err <- nil
2✔
3281
                return nil, false
2✔
3282
        }
2✔
3283
        d.Unlock()
23✔
3284

23✔
3285
        // Ensure that we know of a channel with the target channel ID before
23✔
3286
        // proceeding further.
23✔
3287
        //
23✔
3288
        // We must acquire the mutex for this channel ID before getting the
23✔
3289
        // channel from the database, to ensure what we read does not change
23✔
3290
        // before we call AddProof() later.
23✔
3291
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
23✔
3292
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
23✔
3293

23✔
3294
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
23✔
3295
                ann.ShortChannelID,
23✔
3296
        )
23✔
3297
        if err != nil {
26✔
3298
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
3✔
3299
                if err != nil {
5✔
3300
                        err := fmt.Errorf("unable to store the proof for "+
2✔
3301
                                "short_chan_id=%v: %v", shortChanID, err)
2✔
3302
                        log.Error(err)
2✔
3303
                        nMsg.err <- err
2✔
3304

2✔
3305
                        return nil, false
2✔
3306
                }
2✔
3307

3308
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
3✔
3309
                err := d.cfg.WaitingProofStore.Add(proof)
3✔
3310
                if err != nil {
3✔
3311
                        err := fmt.Errorf("unable to store the proof for "+
×
3312
                                "short_chan_id=%v: %v", shortChanID, err)
×
3313
                        log.Error(err)
×
3314
                        nMsg.err <- err
×
3315
                        return nil, false
×
3316
                }
×
3317

3318
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
3✔
3319
                        ", adding to waiting batch", prefix, shortChanID)
3✔
3320
                nMsg.err <- nil
3✔
3321
                return nil, false
3✔
3322
        }
3323

3324
        nodeID := nMsg.source.SerializeCompressed()
22✔
3325
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
22✔
3326
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
22✔
3327

22✔
3328
        // Ensure that channel that was retrieved belongs to the peer which
22✔
3329
        // sent the proof announcement.
22✔
3330
        if !(isFirstNode || isSecondNode) {
22✔
3331
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3332
                        "to the peer which sent the proof, short_chan_id=%v",
×
3333
                        shortChanID)
×
3334
                log.Error(err)
×
3335
                nMsg.err <- err
×
3336
                return nil, false
×
3337
        }
×
3338

3339
        // If proof was sent by a local sub-system, then we'll send the
3340
        // announcement signature to the remote node so they can also
3341
        // reconstruct the full channel announcement.
3342
        if !nMsg.isRemote {
34✔
3343
                var remotePubKey [33]byte
12✔
3344
                if isFirstNode {
24✔
3345
                        remotePubKey = chanInfo.NodeKey2Bytes
12✔
3346
                } else {
14✔
3347
                        remotePubKey = chanInfo.NodeKey1Bytes
2✔
3348
                }
2✔
3349

3350
                // Since the remote peer might not be online we'll call a
3351
                // method that will attempt to deliver the proof when it comes
3352
                // online.
3353
                err := d.reliableSender.sendMessage(ann, remotePubKey)
12✔
3354
                if err != nil {
12✔
3355
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3356
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3357
                                ann.ShortChannelID, remotePubKey, err)
×
3358
                        nMsg.err <- err
×
3359
                        return nil, false
×
3360
                }
×
3361
        }
3362

3363
        // Check if we already have the full proof for this channel.
3364
        if chanInfo.AuthProof != nil {
25✔
3365
                // If we already have the fully assembled proof, then the peer
3✔
3366
                // sending us their proof has probably not received our local
3✔
3367
                // proof yet. So be kind and send them the full proof.
3✔
3368
                if nMsg.isRemote {
6✔
3369
                        peerID := nMsg.source.SerializeCompressed()
3✔
3370
                        log.Debugf("Got AnnounceSignatures for channel with " +
3✔
3371
                                "full proof.")
3✔
3372

3✔
3373
                        d.wg.Add(1)
3✔
3374
                        go func() {
6✔
3375
                                defer d.wg.Done()
3✔
3376

3✔
3377
                                log.Debugf("Received half proof for channel "+
3✔
3378
                                        "%v with existing full proof. Sending"+
3✔
3379
                                        " full proof to peer=%x",
3✔
3380
                                        ann.ChannelID, peerID)
3✔
3381

3✔
3382
                                ca, _, _, err := netann.CreateChanAnnouncement(
3✔
3383
                                        chanInfo.AuthProof, chanInfo, e1, e2,
3✔
3384
                                )
3✔
3385
                                if err != nil {
3✔
3386
                                        log.Errorf("unable to gen ann: %v",
×
3387
                                                err)
×
3388
                                        return
×
3389
                                }
×
3390

3391
                                err = nMsg.peer.SendMessage(false, ca)
3✔
3392
                                if err != nil {
3✔
3393
                                        log.Errorf("Failed sending full proof"+
×
3394
                                                " to peer=%x: %v", peerID, err)
×
3395
                                        return
×
3396
                                }
×
3397

3398
                                log.Debugf("Full proof sent to peer=%x for "+
3✔
3399
                                        "chanID=%v", peerID, ann.ChannelID)
3✔
3400
                        }()
3401
                }
3402

3403
                log.Debugf("Already have proof for channel with chanID=%v",
3✔
3404
                        ann.ChannelID)
3✔
3405
                nMsg.err <- nil
3✔
3406
                return nil, true
3✔
3407
        }
3408

3409
        // Check that we received the opposite proof. If so, then we're now
3410
        // able to construct the full proof, and create the channel
3411
        // announcement. If we didn't receive the opposite half of the proof
3412
        // then we should store this one, and wait for the opposite to be
3413
        // received.
3414
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
21✔
3415
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
21✔
3416
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
21✔
3417
                err := fmt.Errorf("unable to get the opposite proof for "+
×
3418
                        "short_chan_id=%v: %v", shortChanID, err)
×
3419
                log.Error(err)
×
3420
                nMsg.err <- err
×
3421
                return nil, false
×
3422
        }
×
3423

3424
        if err == channeldb.ErrWaitingProofNotFound {
32✔
3425
                err := d.cfg.WaitingProofStore.Add(proof)
11✔
3426
                if err != nil {
11✔
3427
                        err := fmt.Errorf("unable to store the proof for "+
×
3428
                                "short_chan_id=%v: %v", shortChanID, err)
×
3429
                        log.Error(err)
×
3430
                        nMsg.err <- err
×
3431
                        return nil, false
×
3432
                }
×
3433

3434
                log.Infof("1/2 of channel ann proof received for "+
11✔
3435
                        "short_chan_id=%v, waiting for other half",
11✔
3436
                        shortChanID)
11✔
3437

11✔
3438
                nMsg.err <- nil
11✔
3439
                return nil, false
11✔
3440
        }
3441

3442
        // We now have both halves of the channel announcement proof, then
3443
        // we'll reconstruct the initial announcement so we can validate it
3444
        // shortly below.
3445
        var dbProof models.ChannelAuthProof
12✔
3446
        if isFirstNode {
15✔
3447
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
3✔
3448
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
3✔
3449
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
3✔
3450
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
3✔
3451
        } else {
14✔
3452
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
11✔
3453
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
11✔
3454
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
11✔
3455
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
11✔
3456
        }
11✔
3457

3458
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
12✔
3459
                &dbProof, chanInfo, e1, e2,
12✔
3460
        )
12✔
3461
        if err != nil {
12✔
3462
                log.Error(err)
×
3463
                nMsg.err <- err
×
3464
                return nil, false
×
3465
        }
×
3466

3467
        // With all the necessary components assembled validate the full
3468
        // channel announcement proof.
3469
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
12✔
3470
        if err != nil {
12✔
3471
                err := fmt.Errorf("channel announcement proof for "+
×
3472
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3473

×
3474
                log.Error(err)
×
3475
                nMsg.err <- err
×
3476
                return nil, false
×
3477
        }
×
3478

3479
        // If the channel was returned by the router it means that existence of
3480
        // funding point and inclusion of nodes bitcoin keys in it already
3481
        // checked by the router. In this stage we should check that node keys
3482
        // attest to the bitcoin keys by validating the signatures of
3483
        // announcement. If proof is valid then we'll populate the channel edge
3484
        // with it, so we can announce it on peer connect.
3485
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
12✔
3486
        if err != nil {
12✔
3487
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
3488
                        " %v", ann.ChannelID, err)
×
3489
                log.Error(err)
×
3490
                nMsg.err <- err
×
3491
                return nil, false
×
3492
        }
×
3493

3494
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
12✔
3495
        if err != nil {
12✔
3496
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3497
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3498
                log.Error(err)
×
3499
                nMsg.err <- err
×
3500
                return nil, false
×
3501
        }
×
3502

3503
        // Proof was successfully created and now can announce the channel to
3504
        // the remain network.
3505
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
12✔
3506
                ", adding to next ann batch", shortChanID)
12✔
3507

12✔
3508
        // Assemble the necessary announcements to add to the next broadcasting
12✔
3509
        // batch.
12✔
3510
        var announcements []networkMsg
12✔
3511
        announcements = append(announcements, networkMsg{
12✔
3512
                peer:   nMsg.peer,
12✔
3513
                source: nMsg.source,
12✔
3514
                msg:    chanAnn,
12✔
3515
        })
12✔
3516
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
23✔
3517
                announcements = append(announcements, networkMsg{
11✔
3518
                        peer:   nMsg.peer,
11✔
3519
                        source: src,
11✔
3520
                        msg:    e1Ann,
11✔
3521
                })
11✔
3522
        }
11✔
3523
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
22✔
3524
                announcements = append(announcements, networkMsg{
10✔
3525
                        peer:   nMsg.peer,
10✔
3526
                        source: src,
10✔
3527
                        msg:    e2Ann,
10✔
3528
                })
10✔
3529
        }
10✔
3530

3531
        // We'll also send along the node announcements for each channel
3532
        // participant if we know of them. To ensure our node announcement
3533
        // propagates to our channel counterparty, we'll set the source for
3534
        // each announcement to the node it belongs to, otherwise we won't send
3535
        // it since the source gets skipped. This isn't necessary for channel
3536
        // updates and announcement signatures since we send those directly to
3537
        // our channel counterparty through the gossiper's reliable sender.
3538
        node1Ann, err := d.fetchNodeAnn(chanInfo.NodeKey1Bytes)
12✔
3539
        if err != nil {
16✔
3540
                log.Debugf("Unable to fetch node announcement for %x: %v",
4✔
3541
                        chanInfo.NodeKey1Bytes, err)
4✔
3542
        } else {
14✔
3543
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
20✔
3544
                        announcements = append(announcements, networkMsg{
10✔
3545
                                peer:   nMsg.peer,
10✔
3546
                                source: nodeKey1,
10✔
3547
                                msg:    node1Ann,
10✔
3548
                        })
10✔
3549
                }
10✔
3550
        }
3551

3552
        node2Ann, err := d.fetchNodeAnn(chanInfo.NodeKey2Bytes)
12✔
3553
        if err != nil {
18✔
3554
                log.Debugf("Unable to fetch node announcement for %x: %v",
6✔
3555
                        chanInfo.NodeKey2Bytes, err)
6✔
3556
        } else {
14✔
3557
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
16✔
3558
                        announcements = append(announcements, networkMsg{
8✔
3559
                                peer:   nMsg.peer,
8✔
3560
                                source: nodeKey2,
8✔
3561
                                msg:    node2Ann,
8✔
3562
                        })
8✔
3563
                }
8✔
3564
        }
3565

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

3570
// isBanned returns true if the peer identified by pubkey is banned for sending
3571
// invalid channel announcements.
3572
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
207✔
3573
        return d.banman.isBanned(pubkey)
207✔
3574
}
207✔
3575

3576
// ShouldDisconnect returns true if we should disconnect the peer identified by
3577
// pubkey.
3578
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3579
        bool, error) {
205✔
3580

205✔
3581
        pubkeySer := pubkey.SerializeCompressed()
205✔
3582

205✔
3583
        var pubkeyBytes [33]byte
205✔
3584
        copy(pubkeyBytes[:], pubkeySer)
205✔
3585

205✔
3586
        // If the public key is banned, check whether or not this is a channel
205✔
3587
        // peer.
205✔
3588
        if d.isBanned(pubkeyBytes) {
207✔
3589
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3590
                if err != nil {
2✔
3591
                        return false, err
×
3592
                }
×
3593

3594
                // We should only disconnect non-channel peers.
3595
                if !isChanPeer {
3✔
3596
                        return true, nil
1✔
3597
                }
1✔
3598
        }
3599

3600
        return false, nil
204✔
3601
}
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