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

lightningnetwork / lnd / 12885323020

21 Jan 2025 10:47AM UTC coverage: 58.729% (+0.009%) from 58.72%
12885323020

Pull #9432

github

NishantBansal2003
docs: add release notes.

Signed-off-by: Nishant Bansal <nishant.bansal.282003@gmail.com>
Pull Request #9432: multi: add upfront-shutdown-address to lnd.conf.

30 of 38 new or added lines in 4 files covered. (78.95%)

64 existing lines in 16 files now uncovered.

135482 of 230690 relevant lines covered (58.73%)

19132.94 hits per line

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

80.15
/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) {
50✔
99
        for _, optionalMsgField := range optionalMsgFields {
58✔
100
                optionalMsgField(f)
8✔
101
        }
8✔
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 {
30✔
112
        return func(f *optionalMsgFields) {
34✔
113
                f.capacity = &capacity
4✔
114
        }
4✔
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 {
33✔
120
        return func(f *optionalMsgFields) {
40✔
121
                f.channelPoint = &op
7✔
122
        }
7✔
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 {
29✔
128
        return func(f *optionalMsgFields) {
32✔
129
                f.tapscriptRoot = root
3✔
130
        }
3✔
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 {
29✔
140
        return func(f *optionalMsgFields) {
32✔
141
                f.remoteAlias = alias
3✔
142
        }
3✔
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) {
5✔
387
        return uint64(len(c.msgs)), nil
5✔
388
}
5✔
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 {
465✔
399
        k := rejectCacheKey{
465✔
400
                chanID: cid,
465✔
401
                pubkey: pub,
465✔
402
        }
465✔
403

465✔
404
        return k
465✔
405
}
465✔
406

407
// sourceToPub returns a serialized-compressed public key for use in the reject
408
// cache.
409
func sourceToPub(pk *btcec.PublicKey) [33]byte {
479✔
410
        var pub [33]byte
479✔
411
        copy(pub[:], pk.SerializeCompressed())
479✔
412
        return pub
479✔
413
}
479✔
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 {
30✔
526
        gossiper := &AuthenticatedGossiper{
30✔
527
                selfKey:           selfKeyDesc.PubKey,
30✔
528
                selfKeyLoc:        selfKeyDesc.KeyLocator,
30✔
529
                cfg:               &cfg,
30✔
530
                networkMsgs:       make(chan *networkMsg),
30✔
531
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
30✔
532
                quit:              make(chan struct{}),
30✔
533
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
30✔
534
                prematureChannelUpdates: lru.NewCache[uint64, *cachedNetworkMsg]( //nolint: ll
30✔
535
                        maxPrematureUpdates,
30✔
536
                ),
30✔
537
                channelMtx: multimutex.NewMutex[uint64](),
30✔
538
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
30✔
539
                        maxRejectedUpdates,
30✔
540
                ),
30✔
541
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
30✔
542
                banman:                newBanman(),
30✔
543
        }
30✔
544

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

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

30✔
565
        return gossiper
30✔
566
}
30✔
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 {
4✔
585

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

4✔
592
        select {
4✔
593
        case d.chanPolicyUpdates <- policyUpdate:
4✔
594
                err := <-errChan
4✔
595
                return err
4✔
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 {
30✔
604
        var err error
30✔
605
        d.started.Do(func() {
60✔
606
                log.Info("Authenticated Gossiper starting")
30✔
607
                err = d.start()
30✔
608
        })
30✔
609
        return err
30✔
610
}
611

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

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

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

635
        d.syncMgr.Start()
30✔
636

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

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

30✔
644
        return nil
30✔
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() {
30✔
652
        defer d.wg.Done()
30✔
653

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

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

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

3✔
675
                        // Resend future messages, if any.
3✔
676
                        d.resendFutureMessages(blockHeight)
3✔
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 {
6✔
695
        return f.msgID.Add(1)
6✔
696
}
6✔
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 {
31✔
701
        // Create a new cache.
31✔
702
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
31✔
703

31✔
704
        return &futureMsgCache{
31✔
705
                Cache: cache,
31✔
706
        }
31✔
707
}
31✔
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) {
7✔
720
        // Return a constant 1.
7✔
721
        return 1, nil
7✔
722
}
7✔
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) {
3✔
728
        var (
3✔
729
                // msgs are the target messages.
3✔
730
                msgs []*networkMsg
3✔
731

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

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

743
                return true
3✔
744
        }
745

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

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

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

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

3✔
762
        for _, msg := range msgs {
6✔
763
                select {
3✔
764
                case d.networkMsgs <- msg:
3✔
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 {
31✔
773
        d.stopped.Do(func() {
61✔
774
                log.Info("Authenticated gossiper shutting down...")
30✔
775
                defer log.Debug("Authenticated gossiper shutdown complete")
30✔
776

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

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

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

793
        d.syncMgr.Stop()
30✔
794

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

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

30✔
800
        // We'll stop our reliable sender after all of the gossiper's goroutines
30✔
801
        // have exited to ensure nothing can cause it to continue executing.
30✔
802
        d.reliableSender.Stop()
30✔
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 {
287✔
815

287✔
816
        errChan := make(chan error, 1)
287✔
817

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

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

×
832
                        errChan <- ErrGossipSyncerNotFound
×
833
                        return errChan
×
834
                }
×
835

836
                // If we've found the message target, then we'll dispatch the
837
                // message directly to it.
838
                syncer.ProcessQueryMsg(m, peer.QuitSignal())
3✔
839

3✔
840
                errChan <- nil
3✔
841
                return errChan
3✔
842

843
        // If a peer is updating its current update horizon, then we'll dispatch
844
        // that directly to the proper GossipSyncer.
845
        case *lnwire.GossipTimestampRange:
3✔
846
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
847
                if !ok {
3✔
848
                        log.Warnf("Gossip syncer for peer=%x not found",
×
849
                                peer.PubKey())
×
850

×
851
                        errChan <- ErrGossipSyncerNotFound
×
852
                        return errChan
×
853
                }
×
854

855
                // If we've found the message target, then we'll dispatch the
856
                // message directly to it.
857
                if err := syncer.ApplyGossipFilter(m); err != nil {
3✔
858
                        log.Warnf("Unable to apply gossip filter for peer=%x: "+
×
859
                                "%v", peer.PubKey(), err)
×
860

×
861
                        errChan <- err
×
862
                        return errChan
×
863
                }
×
864

865
                errChan <- nil
3✔
866
                return errChan
3✔
867

868
        // To avoid inserting edges in the graph for our own channels that we
869
        // have already closed, we ignore such channel announcements coming
870
        // from the remote.
871
        case *lnwire.ChannelAnnouncement1:
222✔
872
                ownKey := d.selfKey.SerializeCompressed()
222✔
873
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
222✔
874
                        "for own channel")
222✔
875

222✔
876
                if bytes.Equal(m.NodeID1[:], ownKey) ||
222✔
877
                        bytes.Equal(m.NodeID2[:], ownKey) {
227✔
878

5✔
879
                        log.Warn(ownErr)
5✔
880
                        errChan <- ownErr
5✔
881
                        return errChan
5✔
882
                }
5✔
883
        }
884

885
        nMsg := &networkMsg{
285✔
886
                msg:      msg,
285✔
887
                isRemote: true,
285✔
888
                peer:     peer,
285✔
889
                source:   peer.IdentityKey(),
285✔
890
                err:      errChan,
285✔
891
        }
285✔
892

285✔
893
        select {
285✔
894
        case d.networkMsgs <- nMsg:
285✔
895

896
        // If the peer that sent us this error is quitting, then we don't need
897
        // to send back an error and can return immediately.
898
        case <-peer.QuitSignal():
×
899
                return nil
×
900
        case <-d.quit:
×
901
                nMsg.err <- ErrGossiperShuttingDown
×
902
        }
903

904
        return nMsg.err
285✔
905
}
906

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

50✔
917
        optionalMsgFields := &optionalMsgFields{}
50✔
918
        optionalMsgFields.apply(optionalFields...)
50✔
919

50✔
920
        nMsg := &networkMsg{
50✔
921
                msg:               msg,
50✔
922
                optionalMsgFields: optionalMsgFields,
50✔
923
                isRemote:          false,
50✔
924
                source:            d.selfKey,
50✔
925
                err:               make(chan error, 1),
50✔
926
        }
50✔
927

50✔
928
        select {
50✔
929
        case d.networkMsgs <- nMsg:
50✔
930
        case <-d.quit:
×
931
                nMsg.err <- ErrGossiperShuttingDown
×
932
        }
933

934
        return nMsg.err
50✔
935
}
936

937
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
938
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
939
// tuple.
940
type channelUpdateID struct {
941
        // channelID represents the set of data which is needed to
942
        // retrieve all necessary data to validate the channel existence.
943
        channelID lnwire.ShortChannelID
944

945
        // Flags least-significant bit must be set to 0 if the creating node
946
        // corresponds to the first node in the previously sent channel
947
        // announcement and 1 otherwise.
948
        flags lnwire.ChanUpdateChanFlags
949
}
950

951
// msgWithSenders is a wrapper struct around a message, and the set of peers
952
// that originally sent us this message. Using this struct, we can ensure that
953
// we don't re-send a message to the peer that sent it to us in the first
954
// place.
955
type msgWithSenders struct {
956
        // msg is the wire message itself.
957
        msg lnwire.Message
958

959
        // isLocal is true if this was a message that originated locally. We'll
960
        // use this to bypass our normal checks to ensure we prioritize sending
961
        // out our own updates.
962
        isLocal bool
963

964
        // sender is the set of peers that sent us this message.
965
        senders map[route.Vertex]struct{}
966
}
967

968
// mergeSyncerMap is used to merge the set of senders of a particular message
969
// with peers that we have an active GossipSyncer with. We do this to ensure
970
// that we don't broadcast messages to any peers that we have active gossip
971
// syncers for.
972
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
27✔
973
        for peerPub := range syncers {
30✔
974
                m.senders[peerPub] = struct{}{}
3✔
975
        }
3✔
976
}
977

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

989
        // channelUpdates are identified by the channel update id field.
990
        channelUpdates map[channelUpdateID]msgWithSenders
991

992
        // nodeAnnouncements are identified by the Vertex field.
993
        nodeAnnouncements map[route.Vertex]msgWithSenders
994

995
        sync.Mutex
996
}
997

998
// Reset operates on deDupedAnnouncements to reset the storage of
999
// announcements.
1000
func (d *deDupedAnnouncements) Reset() {
32✔
1001
        d.Lock()
32✔
1002
        defer d.Unlock()
32✔
1003

32✔
1004
        d.reset()
32✔
1005
}
32✔
1006

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

1018
// addMsg adds a new message to the current batch. If the message is already
1019
// present in the current batch, then this new instance replaces the latter,
1020
// and the set of senders is updated to reflect which node sent us this
1021
// message.
1022
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
89✔
1023
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
89✔
1024

89✔
1025
        // Depending on the message type (channel announcement, channel update,
89✔
1026
        // or node announcement), the message is added to the corresponding map
89✔
1027
        // in deDupedAnnouncements. Because each identifying key can have at
89✔
1028
        // most one value, the announcements are de-duplicated, with newer ones
89✔
1029
        // replacing older ones.
89✔
1030
        switch msg := message.msg.(type) {
89✔
1031

1032
        // Channel announcements are identified by the short channel id field.
1033
        case *lnwire.ChannelAnnouncement1:
25✔
1034
                deDupKey := msg.ShortChannelID
25✔
1035
                sender := route.NewVertex(message.source)
25✔
1036

25✔
1037
                mws, ok := d.channelAnnouncements[deDupKey]
25✔
1038
                if !ok {
49✔
1039
                        mws = msgWithSenders{
24✔
1040
                                msg:     msg,
24✔
1041
                                isLocal: !message.isRemote,
24✔
1042
                                senders: make(map[route.Vertex]struct{}),
24✔
1043
                        }
24✔
1044
                        mws.senders[sender] = struct{}{}
24✔
1045

24✔
1046
                        d.channelAnnouncements[deDupKey] = mws
24✔
1047

24✔
1048
                        return
24✔
1049
                }
24✔
1050

1051
                mws.msg = msg
1✔
1052
                mws.senders[sender] = struct{}{}
1✔
1053
                d.channelAnnouncements[deDupKey] = mws
1✔
1054

1055
        // Channel updates are identified by the (short channel id,
1056
        // channelflags) tuple.
1057
        case *lnwire.ChannelUpdate1:
45✔
1058
                sender := route.NewVertex(message.source)
45✔
1059
                deDupKey := channelUpdateID{
45✔
1060
                        msg.ShortChannelID,
45✔
1061
                        msg.ChannelFlags,
45✔
1062
                }
45✔
1063

45✔
1064
                oldTimestamp := uint32(0)
45✔
1065
                mws, ok := d.channelUpdates[deDupKey]
45✔
1066
                if ok {
48✔
1067
                        // If we already have seen this message, record its
3✔
1068
                        // timestamp.
3✔
1069
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1070
                        if !ok {
3✔
1071
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1072
                                        "got: %T", mws.msg)
×
1073

×
1074
                                return
×
1075
                        }
×
1076

1077
                        oldTimestamp = update.Timestamp
3✔
1078
                }
1079

1080
                // If we already had this message with a strictly newer
1081
                // timestamp, then we'll just discard the message we got.
1082
                if oldTimestamp > msg.Timestamp {
46✔
1083
                        log.Debugf("Ignored outdated network message: "+
1✔
1084
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1085
                        return
1✔
1086
                }
1✔
1087

1088
                // If the message we just got is newer than what we previously
1089
                // have seen, or this is the first time we see it, then we'll
1090
                // add it to our map of announcements.
1091
                if oldTimestamp < msg.Timestamp {
87✔
1092
                        mws = msgWithSenders{
43✔
1093
                                msg:     msg,
43✔
1094
                                isLocal: !message.isRemote,
43✔
1095
                                senders: make(map[route.Vertex]struct{}),
43✔
1096
                        }
43✔
1097

43✔
1098
                        // We'll mark the sender of the message in the
43✔
1099
                        // senders map.
43✔
1100
                        mws.senders[sender] = struct{}{}
43✔
1101

43✔
1102
                        d.channelUpdates[deDupKey] = mws
43✔
1103

43✔
1104
                        return
43✔
1105
                }
43✔
1106

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

1115
        // Node announcements are identified by the Vertex field.  Use the
1116
        // NodeID to create the corresponding Vertex.
1117
        case *lnwire.NodeAnnouncement:
25✔
1118
                sender := route.NewVertex(message.source)
25✔
1119
                deDupKey := route.Vertex(msg.NodeID)
25✔
1120

25✔
1121
                // We do the same for node announcements as we did for channel
25✔
1122
                // updates, as they also carry a timestamp.
25✔
1123
                oldTimestamp := uint32(0)
25✔
1124
                mws, ok := d.nodeAnnouncements[deDupKey]
25✔
1125
                if ok {
33✔
1126
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
8✔
1127
                }
8✔
1128

1129
                // Discard the message if it's old.
1130
                if oldTimestamp > msg.Timestamp {
28✔
1131
                        return
3✔
1132
                }
3✔
1133

1134
                // Replace if it's newer.
1135
                if oldTimestamp < msg.Timestamp {
46✔
1136
                        mws = msgWithSenders{
21✔
1137
                                msg:     msg,
21✔
1138
                                isLocal: !message.isRemote,
21✔
1139
                                senders: make(map[route.Vertex]struct{}),
21✔
1140
                        }
21✔
1141

21✔
1142
                        mws.senders[sender] = struct{}{}
21✔
1143

21✔
1144
                        d.nodeAnnouncements[deDupKey] = mws
21✔
1145

21✔
1146
                        return
21✔
1147
                }
21✔
1148

1149
                // Add to senders map if it's the same as we had.
1150
                mws.msg = msg
7✔
1151
                mws.senders[sender] = struct{}{}
7✔
1152
                d.nodeAnnouncements[deDupKey] = mws
7✔
1153
        }
1154
}
1155

1156
// AddMsgs is a helper method to add multiple messages to the announcement
1157
// batch.
1158
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
57✔
1159
        d.Lock()
57✔
1160
        defer d.Unlock()
57✔
1161

57✔
1162
        for _, msg := range msgs {
146✔
1163
                d.addMsg(msg)
89✔
1164
        }
89✔
1165
}
1166

1167
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1168
// to broadcast next into messages that are locally sourced and those that are
1169
// sourced remotely.
1170
type msgsToBroadcast struct {
1171
        // localMsgs is the set of messages we created locally.
1172
        localMsgs []msgWithSenders
1173

1174
        // remoteMsgs is the set of messages that we received from a remote
1175
        // party.
1176
        remoteMsgs []msgWithSenders
1177
}
1178

1179
// addMsg adds a new message to the appropriate sub-slice.
1180
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
74✔
1181
        if msg.isLocal {
124✔
1182
                m.localMsgs = append(m.localMsgs, msg)
50✔
1183
        } else {
77✔
1184
                m.remoteMsgs = append(m.remoteMsgs, msg)
27✔
1185
        }
27✔
1186
}
1187

1188
// isEmpty returns true if the batch is empty.
1189
func (m *msgsToBroadcast) isEmpty() bool {
289✔
1190
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
289✔
1191
}
289✔
1192

1193
// length returns the length of the combined message set.
1194
func (m *msgsToBroadcast) length() int {
1✔
1195
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1196
}
1✔
1197

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

290✔
1208
        // Get the total number of announcements.
290✔
1209
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
290✔
1210
                len(d.nodeAnnouncements)
290✔
1211

290✔
1212
        // Create an empty array of lnwire.Messages with a length equal to
290✔
1213
        // the total number of announcements.
290✔
1214
        msgs := msgsToBroadcast{
290✔
1215
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
290✔
1216
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
290✔
1217
        }
290✔
1218

290✔
1219
        // Add the channel announcements to the array first.
290✔
1220
        for _, message := range d.channelAnnouncements {
311✔
1221
                msgs.addMsg(message)
21✔
1222
        }
21✔
1223

1224
        // Then add the channel updates.
1225
        for _, message := range d.channelUpdates {
329✔
1226
                msgs.addMsg(message)
39✔
1227
        }
39✔
1228

1229
        // Finally add the node announcements.
1230
        for _, message := range d.nodeAnnouncements {
310✔
1231
                msgs.addMsg(message)
20✔
1232
        }
20✔
1233

1234
        d.reset()
290✔
1235

290✔
1236
        // Return the array of lnwire.messages.
290✔
1237
        return msgs
290✔
1238
}
1239

1240
// calculateSubBatchSize is a helper function that calculates the size to break
1241
// down the batchSize into.
1242
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1243
        minimumBatchSize, batchSize int) int {
16✔
1244
        if subBatchDelay > totalDelay {
18✔
1245
                return batchSize
2✔
1246
        }
2✔
1247

1248
        subBatchSize := (batchSize*int(subBatchDelay) +
14✔
1249
                int(totalDelay) - 1) / int(totalDelay)
14✔
1250

14✔
1251
        if subBatchSize < minimumBatchSize {
18✔
1252
                return minimumBatchSize
4✔
1253
        }
4✔
1254

1255
        return subBatchSize
10✔
1256
}
1257

1258
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1259
// this variable so the function can be mocked in our test.
1260
var batchSizeCalculator = calculateSubBatchSize
1261

1262
// splitAnnouncementBatches takes an exiting list of announcements and
1263
// decomposes it into sub batches controlled by the `subBatchSize`.
1264
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1265
        announcementBatch []msgWithSenders) [][]msgWithSenders {
72✔
1266

72✔
1267
        subBatchSize := batchSizeCalculator(
72✔
1268
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
72✔
1269
                d.cfg.MinimumBatchSize, len(announcementBatch),
72✔
1270
        )
72✔
1271

72✔
1272
        var splitAnnouncementBatch [][]msgWithSenders
72✔
1273

72✔
1274
        for subBatchSize < len(announcementBatch) {
196✔
1275
                // For slicing with minimal allocation
124✔
1276
                // https://github.com/golang/go/wiki/SliceTricks
124✔
1277
                announcementBatch, splitAnnouncementBatch =
124✔
1278
                        announcementBatch[subBatchSize:],
124✔
1279
                        append(splitAnnouncementBatch,
124✔
1280
                                announcementBatch[0:subBatchSize:subBatchSize])
124✔
1281
        }
124✔
1282
        splitAnnouncementBatch = append(
72✔
1283
                splitAnnouncementBatch, announcementBatch,
72✔
1284
        )
72✔
1285

72✔
1286
        return splitAnnouncementBatch
72✔
1287
}
1288

1289
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1290
// split size, and then sends out all items to the set of target peers. Locally
1291
// generated announcements are always sent before remotely generated
1292
// announcements.
1293
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(
1294
        annBatch msgsToBroadcast) {
34✔
1295

34✔
1296
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
34✔
1297
        // duration to delay the sending of next announcement batch.
34✔
1298
        delayNextBatch := func() {
99✔
1299
                select {
65✔
1300
                case <-time.After(d.cfg.SubBatchDelay):
48✔
1301
                case <-d.quit:
17✔
1302
                        return
17✔
1303
                }
1304
        }
1305

1306
        // Fetch the local and remote announcements.
1307
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
34✔
1308
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
34✔
1309

34✔
1310
        d.wg.Add(1)
34✔
1311
        go func() {
68✔
1312
                defer d.wg.Done()
34✔
1313

34✔
1314
                log.Debugf("Broadcasting %v new local announcements in %d "+
34✔
1315
                        "sub batches", len(annBatch.localMsgs),
34✔
1316
                        len(localBatches))
34✔
1317

34✔
1318
                // Send out the local announcements first.
34✔
1319
                for _, annBatch := range localBatches {
68✔
1320
                        d.sendLocalBatch(annBatch)
34✔
1321
                        delayNextBatch()
34✔
1322
                }
34✔
1323

1324
                log.Debugf("Broadcasting %v new remote announcements in %d "+
34✔
1325
                        "sub batches", len(annBatch.remoteMsgs),
34✔
1326
                        len(remoteBatches))
34✔
1327

34✔
1328
                // Now send the remote announcements.
34✔
1329
                for _, annBatch := range remoteBatches {
68✔
1330
                        d.sendRemoteBatch(annBatch)
34✔
1331
                        delayNextBatch()
34✔
1332
                }
34✔
1333
        }()
1334
}
1335

1336
// sendLocalBatch broadcasts a list of locally generated announcements to our
1337
// peers. For local announcements, we skip the filter and dedup logic and just
1338
// send the announcements out to all our coonnected peers.
1339
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
34✔
1340
        msgsToSend := lnutils.Map(
34✔
1341
                annBatch, func(m msgWithSenders) lnwire.Message {
80✔
1342
                        return m.msg
46✔
1343
                },
46✔
1344
        )
1345

1346
        err := d.cfg.Broadcast(nil, msgsToSend...)
34✔
1347
        if err != nil {
34✔
1348
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1349
        }
×
1350
}
1351

1352
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1353
// peers.
1354
func (d *AuthenticatedGossiper) sendRemoteBatch(annBatch []msgWithSenders) {
34✔
1355
        syncerPeers := d.syncMgr.GossipSyncers()
34✔
1356

34✔
1357
        // We'll first attempt to filter out this new message for all peers
34✔
1358
        // that have active gossip syncers active.
34✔
1359
        for pub, syncer := range syncerPeers {
37✔
1360
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
3✔
1361
                syncer.FilterGossipMsgs(annBatch...)
3✔
1362
        }
3✔
1363

1364
        for _, msgChunk := range annBatch {
61✔
1365
                msgChunk := msgChunk
27✔
1366

27✔
1367
                // With the syncers taken care of, we'll merge the sender map
27✔
1368
                // with the set of syncers, so we don't send out duplicate
27✔
1369
                // messages.
27✔
1370
                msgChunk.mergeSyncerMap(syncerPeers)
27✔
1371

27✔
1372
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
27✔
1373
                if err != nil {
27✔
1374
                        log.Errorf("Unable to send batch "+
×
1375
                                "announcements: %v", err)
×
1376
                        continue
×
1377
                }
1378
        }
1379
}
1380

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

30✔
1390
        // Initialize empty deDupedAnnouncements to store announcement batch.
30✔
1391
        announcements := deDupedAnnouncements{}
30✔
1392
        announcements.Reset()
30✔
1393

30✔
1394
        d.cfg.RetransmitTicker.Resume()
30✔
1395
        defer d.cfg.RetransmitTicker.Stop()
30✔
1396

30✔
1397
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
30✔
1398
        defer trickleTimer.Stop()
30✔
1399

30✔
1400
        // To start, we'll first check to see if there are any stale channel or
30✔
1401
        // node announcements that we need to re-transmit.
30✔
1402
        if err := d.retransmitStaleAnns(time.Now()); err != nil {
30✔
1403
                log.Errorf("Unable to rebroadcast stale announcements: %v", err)
×
1404
        }
×
1405

1406
        // We'll use this validation to ensure that we process jobs in their
1407
        // dependency order during parallel validation.
1408
        validationBarrier := graph.NewValidationBarrier(1000, d.quit)
30✔
1409

30✔
1410
        for {
679✔
1411
                select {
649✔
1412
                // A new policy update has arrived. We'll commit it to the
1413
                // sub-systems below us, then craft, sign, and broadcast a new
1414
                // ChannelUpdate for the set of affected clients.
1415
                case policyUpdate := <-d.chanPolicyUpdates:
4✔
1416
                        log.Tracef("Received channel %d policy update requests",
4✔
1417
                                len(policyUpdate.edgesToUpdate))
4✔
1418

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

1432
                        // Finally, with the updates committed, we'll now add
1433
                        // them to the announcement batch to be flushed at the
1434
                        // start of the next epoch.
1435
                        announcements.AddMsgs(newChanUpdates...)
4✔
1436

1437
                case announcement := <-d.networkMsgs:
334✔
1438
                        log.Tracef("Received network message: "+
334✔
1439
                                "peer=%v, msg=%s, is_remote=%v",
334✔
1440
                                announcement.peer, announcement.msg.MsgType(),
334✔
1441
                                announcement.isRemote)
334✔
1442

334✔
1443
                        switch announcement.msg.(type) {
334✔
1444
                        // Channel announcement signatures are amongst the only
1445
                        // messages that we'll process serially.
1446
                        case *lnwire.AnnounceSignatures1:
24✔
1447
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
24✔
1448
                                        announcement,
24✔
1449
                                )
24✔
1450
                                log.Debugf("Processed network message %s, "+
24✔
1451
                                        "returned len(announcements)=%v",
24✔
1452
                                        announcement.msg.MsgType(),
24✔
1453
                                        len(emittedAnnouncements))
24✔
1454

24✔
1455
                                if emittedAnnouncements != nil {
37✔
1456
                                        announcements.AddMsgs(
13✔
1457
                                                emittedAnnouncements...,
13✔
1458
                                        )
13✔
1459
                                }
13✔
1460
                                continue
24✔
1461
                        }
1462

1463
                        // If this message was recently rejected, then we won't
1464
                        // attempt to re-process it.
1465
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
313✔
1466
                                announcement.msg,
313✔
1467
                                sourceToPub(announcement.source),
313✔
1468
                        ) {
314✔
1469

1✔
1470
                                announcement.err <- fmt.Errorf("recently " +
1✔
1471
                                        "rejected")
1✔
1472
                                continue
1✔
1473
                        }
1474

1475
                        // We'll set up any dependent, and wait until a free
1476
                        // slot for this job opens up, this allow us to not
1477
                        // have thousands of goroutines active.
1478
                        validationBarrier.InitJobDependencies(announcement.msg)
312✔
1479

312✔
1480
                        d.wg.Add(1)
312✔
1481
                        go d.handleNetworkMessages(
312✔
1482
                                announcement, &announcements, validationBarrier,
312✔
1483
                        )
312✔
1484

1485
                // The trickle timer has ticked, which indicates we should
1486
                // flush to the network the pending batch of new announcements
1487
                // we've received since the last trickle tick.
1488
                case <-trickleTimer.C:
289✔
1489
                        // Emit the current batch of announcements from
289✔
1490
                        // deDupedAnnouncements.
289✔
1491
                        announcementBatch := announcements.Emit()
289✔
1492

289✔
1493
                        // If the current announcements batch is nil, then we
289✔
1494
                        // have no further work here.
289✔
1495
                        if announcementBatch.isEmpty() {
547✔
1496
                                continue
258✔
1497
                        }
1498

1499
                        // At this point, we have the set of local and remote
1500
                        // announcements we want to send out. We'll do the
1501
                        // batching as normal for both, but for local
1502
                        // announcements, we'll blast them out w/o regard for
1503
                        // our peer's policies so we ensure they propagate
1504
                        // properly.
1505
                        d.splitAndSendAnnBatch(announcementBatch)
34✔
1506

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

1519
                // The gossiper has been signalled to exit, to we exit our
1520
                // main loop so the wait group can be decremented.
1521
                case <-d.quit:
30✔
1522
                        return
30✔
1523
                }
1524
        }
1525
}
1526

1527
// handleNetworkMessages is responsible for waiting for dependencies for a
1528
// given network message and processing the message. Once processed, it will
1529
// signal its dependants and add the new announcements to the announce batch.
1530
//
1531
// NOTE: must be run as a goroutine.
1532
func (d *AuthenticatedGossiper) handleNetworkMessages(nMsg *networkMsg,
1533
        deDuped *deDupedAnnouncements, vb *graph.ValidationBarrier) {
312✔
1534

312✔
1535
        defer d.wg.Done()
312✔
1536
        defer vb.CompleteJob()
312✔
1537

312✔
1538
        // We should only broadcast this message forward if it originated from
312✔
1539
        // us or it wasn't received as part of our initial historical sync.
312✔
1540
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
312✔
1541

312✔
1542
        // If this message has an existing dependency, then we'll wait until
312✔
1543
        // that has been fully validated before we proceed.
312✔
1544
        err := vb.WaitForDependants(nMsg.msg)
312✔
1545
        if err != nil {
312✔
1546
                log.Debugf("Validating network message %s got err: %v",
×
1547
                        nMsg.msg.MsgType(), err)
×
1548

×
1549
                if !graph.IsError(
×
1550
                        err,
×
1551
                        graph.ErrVBarrierShuttingDown,
×
1552
                        graph.ErrParentValidationFailed,
×
1553
                ) {
×
1554

×
1555
                        log.Warnf("unexpected error during validation "+
×
1556
                                "barrier shutdown: %v", err)
×
1557
                }
×
1558
                nMsg.err <- err
×
1559

×
1560
                return
×
1561
        }
1562

1563
        // Process the network announcement to determine if this is either a
1564
        // new announcement from our PoV or an edges to a prior vertex/edge we
1565
        // previously proceeded.
1566
        newAnns, allow := d.processNetworkAnnouncement(nMsg)
312✔
1567

312✔
1568
        log.Tracef("Processed network message %s, returned "+
312✔
1569
                "len(announcements)=%v, allowDependents=%v",
312✔
1570
                nMsg.msg.MsgType(), len(newAnns), allow)
312✔
1571

312✔
1572
        // If this message had any dependencies, then we can now signal them to
312✔
1573
        // continue.
312✔
1574
        vb.SignalDependants(nMsg.msg, allow)
312✔
1575

312✔
1576
        // If the announcement was accepted, then add the emitted announcements
312✔
1577
        // to our announce batch to be broadcast once the trickle timer ticks
312✔
1578
        // gain.
312✔
1579
        if newAnns != nil && shouldBroadcast {
347✔
1580
                // TODO(roasbeef): exclude peer that sent.
35✔
1581
                deDuped.AddMsgs(newAnns...)
35✔
1582
        } else if newAnns != nil {
319✔
1583
                log.Trace("Skipping broadcast of announcements received " +
4✔
1584
                        "during initial graph sync")
4✔
1585
        }
4✔
1586
}
1587

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

1590
// InitSyncState is called by outside sub-systems when a connection is
1591
// established to a new peer that understands how to perform channel range
1592
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1593
// needed to handle new queries.
1594
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
3✔
1595
        d.syncMgr.InitSyncState(syncPeer)
3✔
1596
}
3✔
1597

1598
// PruneSyncState is called by outside sub-systems once a peer that we were
1599
// previously connected to has been disconnected. In this case we can stop the
1600
// existing GossipSyncer assigned to the peer and free up resources.
1601
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
3✔
1602
        d.syncMgr.PruneSyncState(peer)
3✔
1603
}
3✔
1604

1605
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1606
// false otherwise, This avoids expensive reprocessing of the message.
1607
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1608
        peerPub [33]byte) bool {
276✔
1609

276✔
1610
        var scid uint64
276✔
1611
        switch m := msg.(type) {
276✔
1612
        case *lnwire.ChannelUpdate1:
45✔
1613
                scid = m.ShortChannelID.ToUint64()
45✔
1614

1615
        case *lnwire.ChannelAnnouncement1:
220✔
1616
                scid = m.ShortChannelID.ToUint64()
220✔
1617

1618
        default:
17✔
1619
                return false
17✔
1620
        }
1621

1622
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
262✔
1623
        return err != cache.ErrElementNotFound
262✔
1624
}
1625

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

31✔
1639
        var (
31✔
1640
                havePublicChannels bool
31✔
1641
                edgesToUpdate      []updateTuple
31✔
1642
        )
31✔
1643
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
31✔
1644
                info *models.ChannelEdgeInfo,
31✔
1645
                edge *models.ChannelEdgePolicy) error {
36✔
1646

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

1658
                // We make a note that we have at least one public channel. We
1659
                // use this to determine whether we should send a node
1660
                // announcement below.
1661
                havePublicChannels = true
4✔
1662

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

×
1672
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1673
                                info: info,
×
1674
                                edge: edge,
×
1675
                        })
×
1676
                        return nil
×
1677
                }
×
1678

1679
                timeElapsed := now.Sub(edge.LastUpdate)
4✔
1680

4✔
1681
                // If it's been longer than RebroadcastInterval since we've
4✔
1682
                // re-broadcasted the channel, add the channel to the set of
4✔
1683
                // edges we need to update.
4✔
1684
                if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1685
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1686
                                info: info,
1✔
1687
                                edge: edge,
1✔
1688
                        })
1✔
1689
                }
1✔
1690

1691
                return nil
4✔
1692
        })
1693
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
31✔
1694
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1695
                        err)
×
1696
        }
×
1697

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

1709
                // If we have a valid announcement to transmit, then we'll send
1710
                // that along with the update.
1711
                if chanAnn != nil {
2✔
1712
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1713
                }
1✔
1714

1715
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1716
        }
1717

1718
        // If we don't have any public channels, we return as we don't want to
1719
        // broadcast anything that would reveal our existence.
1720
        if !havePublicChannels {
61✔
1721
                return nil
30✔
1722
        }
30✔
1723

1724
        // We'll also check that our NodeAnnouncement is not too old.
1725
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
4✔
1726
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
4✔
1727
        timeElapsed := now.Sub(timestamp)
4✔
1728

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

1739
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1740
                nodeAnnStr = " and our refreshed node announcement"
1✔
1741

1✔
1742
                // Before broadcasting the refreshed node announcement, add it
1✔
1743
                // to our own graph.
1✔
1744
                if err := d.addNode(&newNodeAnn); err != nil {
2✔
1745
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1746
                                "to graph: %v", err)
1✔
1747
                }
1✔
1748
        }
1749

1750
        // If we don't have any updates to re-broadcast, then we'll exit
1751
        // early.
1752
        if len(signedUpdates) == 0 {
7✔
1753
                return nil
3✔
1754
        }
3✔
1755

1756
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1757
                len(edgesToUpdate), nodeAnnStr)
1✔
1758

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

1765
        return nil
1✔
1766
}
1767

1768
// processChanPolicyUpdate generates a new set of channel updates for the
1769
// provided list of edges and updates the backing ChannelGraphSource.
1770
func (d *AuthenticatedGossiper) processChanPolicyUpdate(
1771
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
4✔
1772

4✔
1773
        var chanUpdates []networkMsg
4✔
1774
        for _, edgeInfo := range edgesToUpdate {
10✔
1775
                // Now that we've collected all the channels we need to update,
6✔
1776
                // we'll re-sign and update the backing ChannelGraphSource, and
6✔
1777
                // retrieve our ChannelUpdate to broadcast.
6✔
1778
                _, chanUpdate, err := d.updateChannel(
6✔
1779
                        edgeInfo.Info, edgeInfo.Edge,
6✔
1780
                )
6✔
1781
                if err != nil {
6✔
1782
                        return nil, err
×
1783
                }
×
1784

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

4✔
1799
                        var defaultAlias lnwire.ShortChannelID
4✔
1800
                        foundAlias, _ := d.cfg.GetAlias(chanID)
4✔
1801
                        if foundAlias != defaultAlias {
7✔
1802
                                chanUpdate.ShortChannelID = foundAlias
3✔
1803

3✔
1804
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
3✔
1805
                                if err != nil {
3✔
1806
                                        log.Errorf("Unable to sign alias "+
×
1807
                                                "update: %v", err)
×
1808
                                        continue
×
1809
                                }
1810

1811
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1812
                                if err != nil {
3✔
1813
                                        log.Errorf("Unable to create sig: %v",
×
1814
                                                err)
×
1815
                                        continue
×
1816
                                }
1817

1818
                                chanUpdate.Signature = lnSig
3✔
1819
                        }
1820

1821
                        remotePubKey := remotePubFromChanInfo(
4✔
1822
                                edgeInfo.Info, chanUpdate.ChannelFlags,
4✔
1823
                        )
4✔
1824
                        err := d.reliableSender.sendMessage(
4✔
1825
                                chanUpdate, remotePubKey,
4✔
1826
                        )
4✔
1827
                        if err != nil {
4✔
1828
                                log.Errorf("Unable to reliably send %v for "+
×
1829
                                        "channel=%v to peer=%x: %v",
×
1830
                                        chanUpdate.MsgType(),
×
1831
                                        chanUpdate.ShortChannelID,
×
1832
                                        remotePubKey, err)
×
1833
                        }
×
1834
                        continue
4✔
1835
                }
1836

1837
                // We set ourselves as the source of this message to indicate
1838
                // that we shouldn't skip any peers when sending this message.
1839
                chanUpdates = append(chanUpdates, networkMsg{
5✔
1840
                        source:   d.selfKey,
5✔
1841
                        isRemote: false,
5✔
1842
                        msg:      chanUpdate,
5✔
1843
                })
5✔
1844
        }
1845

1846
        return chanUpdates, nil
4✔
1847
}
1848

1849
// remotePubFromChanInfo returns the public key of the remote peer given a
1850
// ChannelEdgeInfo that describe a channel we have with them.
1851
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1852
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
15✔
1853

15✔
1854
        var remotePubKey [33]byte
15✔
1855
        switch {
15✔
1856
        case chanFlags&lnwire.ChanUpdateDirection == 0:
15✔
1857
                remotePubKey = chanInfo.NodeKey2Bytes
15✔
1858
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1859
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1860
        }
1861

1862
        return remotePubKey
15✔
1863
}
1864

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

3✔
1876
        // First, we'll fetch the state of the channel as we know if from the
3✔
1877
        // database.
3✔
1878
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
1879
                chanAnnMsg.ShortChannelID,
3✔
1880
        )
3✔
1881
        if err != nil {
3✔
1882
                return nil, err
×
1883
        }
×
1884

1885
        // The edge is in the graph, and has a proof attached, then we'll just
1886
        // reject it as normal.
1887
        if chanInfo.AuthProof != nil {
6✔
1888
                return nil, nil
3✔
1889
        }
3✔
1890

1891
        // Otherwise, this means that the edge is within the graph, but it
1892
        // doesn't yet have a proper proof attached. If we did not receive
1893
        // the proof such that we now can add it, there's nothing more we
1894
        // can do.
1895
        if proof == nil {
×
1896
                return nil, nil
×
1897
        }
×
1898

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

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

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

×
1946
        }
×
1947

1948
        return announcements, nil
×
1949
}
1950

1951
// fetchPKScript fetches the output script for the given SCID.
1952
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
1953
        []byte, error) {
×
1954

×
1955
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
1956
}
×
1957

1958
// addNode processes the given node announcement, and adds it to our channel
1959
// graph.
1960
func (d *AuthenticatedGossiper) addNode(msg *lnwire.NodeAnnouncement,
1961
        op ...batch.SchedulerOption) error {
20✔
1962

20✔
1963
        if err := graph.ValidateNodeAnn(msg); err != nil {
21✔
1964
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
1965
                        err)
1✔
1966
        }
1✔
1967

1968
        timestamp := time.Unix(int64(msg.Timestamp), 0)
19✔
1969
        features := lnwire.NewFeatureVector(msg.Features, lnwire.Features)
19✔
1970
        node := &models.LightningNode{
19✔
1971
                HaveNodeAnnouncement: true,
19✔
1972
                LastUpdate:           timestamp,
19✔
1973
                Addresses:            msg.Addresses,
19✔
1974
                PubKeyBytes:          msg.NodeID,
19✔
1975
                Alias:                msg.Alias.String(),
19✔
1976
                AuthSigBytes:         msg.Signature.ToSignatureBytes(),
19✔
1977
                Features:             features,
19✔
1978
                Color:                msg.RGBColor,
19✔
1979
                ExtraOpaqueData:      msg.ExtraOpaqueData,
19✔
1980
        }
19✔
1981

19✔
1982
        return d.cfg.Graph.AddNode(node, op...)
19✔
1983
}
1984

1985
// isPremature decides whether a given network message has a block height+delta
1986
// value specified in the future. If so, the message will be added to the
1987
// future message map and be processed when the block height as reached.
1988
//
1989
// NOTE: must be used inside a lock.
1990
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
1991
        delta uint32, msg *networkMsg) bool {
282✔
1992

282✔
1993
        // The channel is already confirmed at chanID.BlockHeight so we minus
282✔
1994
        // one block. For instance, if the required confirmation for this
282✔
1995
        // channel announcement is 6, we then only need to wait for 5 more
282✔
1996
        // blocks once the funding tx is confirmed.
282✔
1997
        if delta > 0 {
285✔
1998
                delta--
3✔
1999
        }
3✔
2000

2001
        msgHeight := chanID.BlockHeight + delta
282✔
2002

282✔
2003
        // The message height is smaller or equal to our best known height,
282✔
2004
        // thus the message is mature.
282✔
2005
        if msgHeight <= d.bestHeight {
563✔
2006
                return false
281✔
2007
        }
281✔
2008

2009
        // Add the premature message to our future messages which will be
2010
        // resent once the block height has reached.
2011
        //
2012
        // Copy the networkMsgs since the old message's err chan will be
2013
        // consumed.
2014
        copied := &networkMsg{
4✔
2015
                peer:              msg.peer,
4✔
2016
                source:            msg.source,
4✔
2017
                msg:               msg.msg,
4✔
2018
                optionalMsgFields: msg.optionalMsgFields,
4✔
2019
                isRemote:          msg.isRemote,
4✔
2020
                err:               make(chan error, 1),
4✔
2021
        }
4✔
2022

4✔
2023
        // Create the cached message.
4✔
2024
        cachedMsg := &cachedFutureMsg{
4✔
2025
                msg:    copied,
4✔
2026
                height: msgHeight,
4✔
2027
        }
4✔
2028

4✔
2029
        // Increment the msg ID and add it to the cache.
4✔
2030
        nextMsgID := d.futureMsgs.nextMsgID()
4✔
2031
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
4✔
2032
        if err != nil {
4✔
2033
                log.Errorf("Adding future message got error: %v", err)
×
2034
        }
×
2035

2036
        log.Debugf("Network message: %v added to future messages for "+
4✔
2037
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
4✔
2038
                msgHeight, d.bestHeight)
4✔
2039

4✔
2040
        return true
4✔
2041
}
2042

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

333✔
2053
        // If this is a remote update, we set the scheduler option to lazily
333✔
2054
        // add it to the graph.
333✔
2055
        var schedulerOp []batch.SchedulerOption
333✔
2056
        if nMsg.isRemote {
619✔
2057
                schedulerOp = append(schedulerOp, batch.LazyAdd())
286✔
2058
        }
286✔
2059

2060
        switch msg := nMsg.msg.(type) {
333✔
2061
        // A new node announcement has arrived which either presents new
2062
        // information about a node in one of the channels we know about, or a
2063
        // updating previously advertised information.
2064
        case *lnwire.NodeAnnouncement:
27✔
2065
                return d.handleNodeAnnouncement(nMsg, msg, schedulerOp)
27✔
2066

2067
        // A new channel announcement has arrived, this indicates the
2068
        // *creation* of a new channel within the network. This only advertises
2069
        // the existence of a channel and not yet the routing policies in
2070
        // either direction of the channel.
2071
        case *lnwire.ChannelAnnouncement1:
233✔
2072
                return d.handleChanAnnouncement(nMsg, msg, schedulerOp)
233✔
2073

2074
        // A new authenticated channel edge update has arrived. This indicates
2075
        // that the directional information for an already known channel has
2076
        // been updated.
2077
        case *lnwire.ChannelUpdate1:
58✔
2078
                return d.handleChanUpdate(nMsg, msg, schedulerOp)
58✔
2079

2080
        // A new signature announcement has been received. This indicates
2081
        // willingness of nodes involved in the funding of a channel to
2082
        // announce this new channel to the rest of the world.
2083
        case *lnwire.AnnounceSignatures1:
24✔
2084
                return d.handleAnnSig(nMsg, msg)
24✔
2085

2086
        default:
×
2087
                err := errors.New("wrong type of the announcement")
×
2088
                nMsg.err <- err
×
2089
                return nil, false
×
2090
        }
2091
}
2092

2093
// processZombieUpdate determines whether the provided channel update should
2094
// resurrect a given zombie edge.
2095
//
2096
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2097
// should be inspected.
2098
func (d *AuthenticatedGossiper) processZombieUpdate(
2099
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2100
        msg *lnwire.ChannelUpdate1) error {
3✔
2101

3✔
2102
        // The least-significant bit in the flag on the channel update tells us
3✔
2103
        // which edge is being updated.
3✔
2104
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2105

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

2123
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2124
        if err != nil {
3✔
2125
                return fmt.Errorf("unable to verify channel "+
1✔
2126
                        "update signature: %v", err)
1✔
2127
        }
1✔
2128

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

×
2138
                return nil
×
2139

2140
        case err != nil:
×
2141
                return fmt.Errorf("unable to remove edge with "+
×
2142
                        "chan_id=%v from zombie index: %v",
×
2143
                        msg.ShortChannelID, err)
×
2144

2145
        default:
1✔
2146
        }
2147

2148
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2149
                "index", msg.ShortChannelID)
1✔
2150

1✔
2151
        return nil
1✔
2152
}
2153

2154
// fetchNodeAnn fetches the latest signed node announcement from our point of
2155
// view for the node with the given public key.
2156
func (d *AuthenticatedGossiper) fetchNodeAnn(
2157
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
23✔
2158

23✔
2159
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
23✔
2160
        if err != nil {
29✔
2161
                return nil, err
6✔
2162
        }
6✔
2163

2164
        return node.NodeAnnouncement(true)
17✔
2165
}
2166

2167
// isMsgStale determines whether a message retrieved from the backing
2168
// MessageStore is seen as stale by the current graph.
2169
func (d *AuthenticatedGossiper) isMsgStale(msg lnwire.Message) bool {
15✔
2170
        switch msg := msg.(type) {
15✔
2171
        case *lnwire.AnnounceSignatures1:
5✔
2172
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
5✔
2173
                        msg.ShortChannelID,
5✔
2174
                )
5✔
2175

5✔
2176
                // If the channel cannot be found, it is most likely a leftover
5✔
2177
                // message for a channel that was closed, so we can consider it
5✔
2178
                // stale.
5✔
2179
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
8✔
2180
                        return true
3✔
2181
                }
3✔
2182
                if err != nil {
5✔
2183
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2184
                                "%v", chanInfo.ChannelID, err)
×
2185
                        return false
×
2186
                }
×
2187

2188
                // If the proof exists in the graph, then we have successfully
2189
                // received the remote proof and assembled the full proof, so we
2190
                // can safely delete the local proof from the database.
2191
                return chanInfo.AuthProof != nil
5✔
2192

2193
        case *lnwire.ChannelUpdate1:
13✔
2194
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
13✔
2195

13✔
2196
                // If the channel cannot be found, it is most likely a leftover
13✔
2197
                // message for a channel that was closed, so we can consider it
13✔
2198
                // stale.
13✔
2199
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
16✔
2200
                        return true
3✔
2201
                }
3✔
2202
                if err != nil {
13✔
2203
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2204
                                "%v", msg.ShortChannelID, err)
×
2205
                        return false
×
2206
                }
×
2207

2208
                // Otherwise, we'll retrieve the correct policy that we
2209
                // currently have stored within our graph to check if this
2210
                // message is stale by comparing its timestamp.
2211
                var p *models.ChannelEdgePolicy
13✔
2212
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
26✔
2213
                        p = p1
13✔
2214
                } else {
16✔
2215
                        p = p2
3✔
2216
                }
3✔
2217

2218
                // If the policy is still unknown, then we can consider this
2219
                // policy fresh.
2220
                if p == nil {
13✔
2221
                        return false
×
2222
                }
×
2223

2224
                timestamp := time.Unix(int64(msg.Timestamp), 0)
13✔
2225
                return p.LastUpdate.After(timestamp)
13✔
2226

2227
        default:
×
2228
                // We'll make sure to not mark any unsupported messages as stale
×
2229
                // to ensure they are not removed.
×
2230
                return false
×
2231
        }
2232
}
2233

2234
// updateChannel creates a new fully signed update for the channel, and updates
2235
// the underlying graph with the new state.
2236
func (d *AuthenticatedGossiper) updateChannel(info *models.ChannelEdgeInfo,
2237
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2238
        *lnwire.ChannelUpdate1, error) {
7✔
2239

7✔
2240
        // Parse the unsigned edge into a channel update.
7✔
2241
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
7✔
2242

7✔
2243
        // We'll generate a new signature over a digest of the channel
7✔
2244
        // announcement itself and update the timestamp to ensure it propagate.
7✔
2245
        err := netann.SignChannelUpdate(
7✔
2246
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
7✔
2247
                netann.ChanUpdSetTimestamp,
7✔
2248
        )
7✔
2249
        if err != nil {
7✔
2250
                return nil, nil, err
×
2251
        }
×
2252

2253
        // Next, we'll set the new signature in place, and update the reference
2254
        // in the backing slice.
2255
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
7✔
2256
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
7✔
2257

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

2268
        // Finally, we'll write the new edge policy to disk.
2269
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
7✔
2270
                return nil, nil, err
×
2271
        }
×
2272

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

2315
        return chanAnn, chanUpdate, err
7✔
2316
}
2317

2318
// SyncManager returns the gossiper's SyncManager instance.
2319
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2320
        return d.syncMgr
3✔
2321
}
3✔
2322

2323
// IsKeepAliveUpdate determines whether this channel update is considered a
2324
// keep-alive update based on the previous channel update processed for the same
2325
// direction.
2326
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2327
        prev *models.ChannelEdgePolicy) bool {
17✔
2328

17✔
2329
        // Both updates should be from the same direction.
17✔
2330
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
17✔
2331
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
17✔
2332

×
2333
                return false
×
2334
        }
×
2335

2336
        // The timestamp should always increase for a keep-alive update.
2337
        timestamp := time.Unix(int64(update.Timestamp), 0)
17✔
2338
        if !timestamp.After(prev.LastUpdate) {
20✔
2339
                return false
3✔
2340
        }
3✔
2341

2342
        // None of the remaining fields should change for a keep-alive update.
2343
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
20✔
2344
                return false
3✔
2345
        }
3✔
2346
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
32✔
2347
                return false
15✔
2348
        }
15✔
2349
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
8✔
2350
                return false
3✔
2351
        }
3✔
2352
        if update.TimeLockDelta != prev.TimeLockDelta {
5✔
2353
                return false
×
2354
        }
×
2355
        if update.HtlcMinimumMsat != prev.MinHTLC {
5✔
2356
                return false
×
2357
        }
×
2358
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
5✔
2359
                return false
×
2360
        }
×
2361
        if update.HtlcMaximumMsat != prev.MaxHTLC {
5✔
2362
                return false
×
2363
        }
×
2364
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
8✔
2365
                return false
3✔
2366
        }
3✔
2367
        return true
5✔
2368
}
2369

2370
// latestHeight returns the gossiper's latest height known of the chain.
2371
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2372
        d.Lock()
3✔
2373
        defer d.Unlock()
3✔
2374
        return d.bestHeight
3✔
2375
}
3✔
2376

2377
// handleNodeAnnouncement processes a new node announcement.
2378
func (d *AuthenticatedGossiper) handleNodeAnnouncement(nMsg *networkMsg,
2379
        nodeAnn *lnwire.NodeAnnouncement,
2380
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
27✔
2381

27✔
2382
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
27✔
2383

27✔
2384
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
27✔
2385
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
27✔
2386

27✔
2387
        // We'll quickly ask the router if it already has a newer update for
27✔
2388
        // this node so we can skip validating signatures if not required.
27✔
2389
        if d.cfg.Graph.IsStaleNode(nodeAnn.NodeID, timestamp) {
38✔
2390
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
11✔
2391
                nMsg.err <- nil
11✔
2392
                return nil, true
11✔
2393
        }
11✔
2394

2395
        if err := d.addNode(nodeAnn, ops...); err != nil {
22✔
2396
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2397
                        err)
3✔
2398

3✔
2399
                if !graph.IsError(
3✔
2400
                        err,
3✔
2401
                        graph.ErrOutdated,
3✔
2402
                        graph.ErrIgnored,
3✔
2403
                        graph.ErrVBarrierShuttingDown,
3✔
2404
                ) {
3✔
2405

×
2406
                        log.Error(err)
×
2407
                }
×
2408

2409
                nMsg.err <- err
3✔
2410
                return nil, false
3✔
2411
        }
2412

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

2424
        var announcements []networkMsg
19✔
2425

19✔
2426
        // If it does, we'll add their announcement to our batch so that it can
19✔
2427
        // be broadcast to the rest of our peers.
19✔
2428
        if isPublic {
25✔
2429
                announcements = append(announcements, networkMsg{
6✔
2430
                        peer:     nMsg.peer,
6✔
2431
                        isRemote: nMsg.isRemote,
6✔
2432
                        source:   nMsg.source,
6✔
2433
                        msg:      nodeAnn,
6✔
2434
                })
6✔
2435
        } else {
22✔
2436
                log.Tracef("Skipping broadcasting node announcement for %x "+
16✔
2437
                        "due to being unadvertised", nodeAnn.NodeID)
16✔
2438
        }
16✔
2439

2440
        nMsg.err <- nil
19✔
2441
        // TODO(roasbeef): get rid of the above
19✔
2442

19✔
2443
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
19✔
2444
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
19✔
2445

19✔
2446
        return announcements, true
19✔
2447
}
2448

2449
// handleChanAnnouncement processes a new channel announcement.
2450
func (d *AuthenticatedGossiper) handleChanAnnouncement(nMsg *networkMsg,
2451
        ann *lnwire.ChannelAnnouncement1,
2452
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
233✔
2453

233✔
2454
        scid := ann.ShortChannelID
233✔
2455

233✔
2456
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
233✔
2457
                nMsg.peer, scid.ToUint64())
233✔
2458

233✔
2459
        // We'll ignore any channel announcements that target any chain other
233✔
2460
        // than the set of chains we know of.
233✔
2461
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
233✔
2462
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2463
                        ", gossiper on chain=%v", ann.ChainHash,
×
2464
                        d.cfg.ChainHash)
×
2465
                log.Errorf(err.Error())
×
2466

×
2467
                key := newRejectCacheKey(
×
2468
                        scid.ToUint64(),
×
2469
                        sourceToPub(nMsg.source),
×
2470
                )
×
2471
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2472

×
2473
                nMsg.err <- err
×
2474
                return nil, false
×
2475
        }
×
2476

2477
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2478
        // reject the announcement. Since the router accepts alias SCIDs,
2479
        // not erroring out would be a DoS vector.
2480
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
233✔
2481
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2482
                log.Errorf(err.Error())
×
2483

×
2484
                key := newRejectCacheKey(
×
2485
                        scid.ToUint64(),
×
2486
                        sourceToPub(nMsg.source),
×
2487
                )
×
2488
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2489

×
2490
                nMsg.err <- err
×
2491
                return nil, false
×
2492
        }
×
2493

2494
        // If the advertised inclusionary block is beyond our knowledge of the
2495
        // chain tip, then we'll ignore it for now.
2496
        d.Lock()
233✔
2497
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
234✔
2498
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2499
                        "advertises height %v, only height %v is known",
1✔
2500
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2501
                d.Unlock()
1✔
2502
                nMsg.err <- nil
1✔
2503
                return nil, false
1✔
2504
        }
1✔
2505
        d.Unlock()
232✔
2506

232✔
2507
        // At this point, we'll now ask the router if this is a zombie/known
232✔
2508
        // edge. If so we can skip all the processing below.
232✔
2509
        if d.cfg.Graph.IsKnownEdge(scid) {
236✔
2510
                nMsg.err <- nil
4✔
2511
                return nil, true
4✔
2512
        }
4✔
2513

2514
        // Check if the channel is already closed in which case we can ignore
2515
        // it.
2516
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
231✔
2517
        if err != nil {
231✔
2518
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2519
                        err)
×
2520
                nMsg.err <- err
×
2521

×
2522
                return nil, false
×
2523
        }
×
2524

2525
        if closed {
232✔
2526
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2527
                log.Error(err)
1✔
2528

1✔
2529
                // If this is an announcement from us, we'll just ignore it.
1✔
2530
                if !nMsg.isRemote {
1✔
2531
                        nMsg.err <- err
×
2532
                        return nil, false
×
2533
                }
×
2534

2535
                // Increment the peer's ban score if they are sending closed
2536
                // channel announcements.
2537
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2538

1✔
2539
                // If the peer is banned and not a channel peer, we'll
1✔
2540
                // disconnect them.
1✔
2541
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2542
                if dcErr != nil {
1✔
2543
                        log.Errorf("failed to check if we should disconnect "+
×
2544
                                "peer: %v", dcErr)
×
2545
                        nMsg.err <- dcErr
×
2546

×
2547
                        return nil, false
×
2548
                }
×
2549

2550
                if shouldDc {
1✔
2551
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2552
                }
×
2553

2554
                nMsg.err <- err
1✔
2555

1✔
2556
                return nil, false
1✔
2557
        }
2558

2559
        // If this is a remote channel announcement, then we'll validate all
2560
        // the signatures within the proof as it should be well formed.
2561
        var proof *models.ChannelAuthProof
230✔
2562
        if nMsg.isRemote {
446✔
2563
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
216✔
2564
                if err != nil {
216✔
2565
                        err := fmt.Errorf("unable to validate announcement: "+
×
2566
                                "%v", err)
×
2567

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

×
2574
                        log.Error(err)
×
2575
                        nMsg.err <- err
×
2576
                        return nil, false
×
2577
                }
×
2578

2579
                // If the proof checks out, then we'll save the proof itself to
2580
                // the database so we can fetch it later when gossiping with
2581
                // other nodes.
2582
                proof = &models.ChannelAuthProof{
216✔
2583
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
216✔
2584
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
216✔
2585
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
216✔
2586
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
216✔
2587
                }
216✔
2588
        }
2589

2590
        // With the proof validated (if necessary), we can now store it within
2591
        // the database for our path finding and syncing needs.
2592
        var featureBuf bytes.Buffer
230✔
2593
        if err := ann.Features.Encode(&featureBuf); err != nil {
230✔
2594
                log.Errorf("unable to encode features: %v", err)
×
2595
                nMsg.err <- err
×
2596
                return nil, false
×
2597
        }
×
2598

2599
        edge := &models.ChannelEdgeInfo{
230✔
2600
                ChannelID:        scid.ToUint64(),
230✔
2601
                ChainHash:        ann.ChainHash,
230✔
2602
                NodeKey1Bytes:    ann.NodeID1,
230✔
2603
                NodeKey2Bytes:    ann.NodeID2,
230✔
2604
                BitcoinKey1Bytes: ann.BitcoinKey1,
230✔
2605
                BitcoinKey2Bytes: ann.BitcoinKey2,
230✔
2606
                AuthProof:        proof,
230✔
2607
                Features:         featureBuf.Bytes(),
230✔
2608
                ExtraOpaqueData:  ann.ExtraOpaqueData,
230✔
2609
        }
230✔
2610

230✔
2611
        // If there were any optional message fields provided, we'll include
230✔
2612
        // them in its serialized disk representation now.
230✔
2613
        if nMsg.optionalMsgFields != nil {
247✔
2614
                if nMsg.optionalMsgFields.capacity != nil {
21✔
2615
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
4✔
2616
                }
4✔
2617
                if nMsg.optionalMsgFields.channelPoint != nil {
24✔
2618
                        cp := *nMsg.optionalMsgFields.channelPoint
7✔
2619
                        edge.ChannelPoint = cp
7✔
2620
                }
7✔
2621

2622
                // Optional tapscript root for custom channels.
2623
                edge.TapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
17✔
2624
        }
2625

2626
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
230✔
2627

230✔
2628
        // We will add the edge to the channel router. If the nodes present in
230✔
2629
        // this channel are not present in the database, a partial node will be
230✔
2630
        // added to represent each node while we wait for a node announcement.
230✔
2631
        //
230✔
2632
        // Before we add the edge to the database, we obtain the mutex for this
230✔
2633
        // channel ID. We do this to ensure no other goroutine has read the
230✔
2634
        // database and is now making decisions based on this DB state, before
230✔
2635
        // it writes to the DB.
230✔
2636
        d.channelMtx.Lock(scid.ToUint64())
230✔
2637
        err = d.cfg.Graph.AddEdge(edge, ops...)
230✔
2638
        if err != nil {
435✔
2639
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
205✔
2640
                        scid.ToUint64(), err)
205✔
2641

205✔
2642
                defer d.channelMtx.Unlock(scid.ToUint64())
205✔
2643

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

×
2660
                                nMsg.err <- rErr
×
2661
                                return nil, false
×
2662
                        }
×
2663

2664
                        log.Debugf("Extracted %v announcements from rejected "+
3✔
2665
                                "msgs", len(anns))
3✔
2666

3✔
2667
                        // If while processing this rejected edge, we realized
3✔
2668
                        // there's a set of announcements we could extract,
3✔
2669
                        // then we'll return those directly.
3✔
2670
                        //
3✔
2671
                        // NOTE: since this is an ErrIgnored, we can return
3✔
2672
                        // true here to signal "allow" to its dependants.
3✔
2673
                        nMsg.err <- nil
3✔
2674

3✔
2675
                        return anns, true
3✔
2676

2677
                case graph.IsError(
2678
                        err, graph.ErrNoFundingTransaction,
2679
                        graph.ErrInvalidFundingOutput,
2680
                ):
200✔
2681
                        key := newRejectCacheKey(
200✔
2682
                                scid.ToUint64(),
200✔
2683
                                sourceToPub(nMsg.source),
200✔
2684
                        )
200✔
2685
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
200✔
2686

200✔
2687
                        // Increment the peer's ban score. We check isRemote
200✔
2688
                        // so we don't actually ban the peer in case of a local
200✔
2689
                        // bug.
200✔
2690
                        if nMsg.isRemote {
400✔
2691
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
200✔
2692
                        }
200✔
2693

2694
                case graph.IsError(err, graph.ErrChannelSpent):
1✔
2695
                        key := newRejectCacheKey(
1✔
2696
                                scid.ToUint64(),
1✔
2697
                                sourceToPub(nMsg.source),
1✔
2698
                        )
1✔
2699
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2700

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

×
2712
                                nMsg.err <- dbErr
×
2713

×
2714
                                return nil, false
×
2715
                        }
×
2716

2717
                        // Increment the peer's ban score. We check isRemote
2718
                        // so we don't accidentally ban ourselves in case of a
2719
                        // bug.
2720
                        if nMsg.isRemote {
2✔
2721
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2722
                        }
1✔
2723

2724
                default:
1✔
2725
                        // Otherwise, this is just a regular rejected edge.
1✔
2726
                        key := newRejectCacheKey(
1✔
2727
                                scid.ToUint64(),
1✔
2728
                                sourceToPub(nMsg.source),
1✔
2729
                        )
1✔
2730
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2731
                }
2732

2733
                if !nMsg.isRemote {
202✔
2734
                        log.Errorf("failed to add edge for local channel: %v",
×
2735
                                err)
×
2736
                        nMsg.err <- err
×
2737

×
2738
                        return nil, false
×
2739
                }
×
2740

2741
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
202✔
2742
                if dcErr != nil {
202✔
2743
                        log.Errorf("failed to check if we should disconnect "+
×
2744
                                "peer: %v", dcErr)
×
2745
                        nMsg.err <- dcErr
×
2746

×
2747
                        return nil, false
×
2748
                }
×
2749

2750
                if shouldDc {
203✔
2751
                        nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2752
                }
1✔
2753

2754
                nMsg.err <- err
202✔
2755

202✔
2756
                return nil, false
202✔
2757
        }
2758

2759
        // If err is nil, release the lock immediately.
2760
        d.channelMtx.Unlock(scid.ToUint64())
28✔
2761

28✔
2762
        log.Debugf("Finish adding edge for short_chan_id: %v", scid.ToUint64())
28✔
2763

28✔
2764
        // If we earlier received any ChannelUpdates for this channel, we can
28✔
2765
        // now process them, as the channel is added to the graph.
28✔
2766
        var channelUpdates []*processedNetworkMsg
28✔
2767

28✔
2768
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
28✔
2769
        if err == nil {
33✔
2770
                // There was actually an entry in the map, so we'll accumulate
5✔
2771
                // it. We don't worry about deletion, since it'll eventually
5✔
2772
                // fall out anyway.
5✔
2773
                chanMsgs := earlyChanUpdates
5✔
2774
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
5✔
2775
        }
5✔
2776

2777
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2778
        // ensure we don't block here, as we can handle only one announcement
2779
        // at a time.
2780
        for _, cu := range channelUpdates {
33✔
2781
                // Skip if already processed.
5✔
2782
                if cu.processed {
6✔
2783
                        continue
1✔
2784
                }
2785

2786
                // Mark the ChannelUpdate as processed. This ensures that a
2787
                // subsequent announcement in the option-scid-alias case does
2788
                // not re-use an old ChannelUpdate.
2789
                cu.processed = true
5✔
2790

5✔
2791
                d.wg.Add(1)
5✔
2792
                go func(updMsg *networkMsg) {
10✔
2793
                        defer d.wg.Done()
5✔
2794

5✔
2795
                        switch msg := updMsg.msg.(type) {
5✔
2796
                        // Reprocess the message, making sure we return an
2797
                        // error to the original caller in case the gossiper
2798
                        // shuts down.
2799
                        case *lnwire.ChannelUpdate1:
5✔
2800
                                log.Debugf("Reprocessing ChannelUpdate for "+
5✔
2801
                                        "shortChanID=%v", scid.ToUint64())
5✔
2802

5✔
2803
                                select {
5✔
2804
                                case d.networkMsgs <- updMsg:
5✔
2805
                                case <-d.quit:
×
2806
                                        updMsg.err <- ErrGossiperShuttingDown
×
2807
                                }
2808

2809
                        // We don't expect any other message type than
2810
                        // ChannelUpdate to be in this cache.
2811
                        default:
×
2812
                                log.Errorf("Unsupported message type found "+
×
2813
                                        "among ChannelUpdates: %T", msg)
×
2814
                        }
2815
                }(cu.msg)
2816
        }
2817

2818
        // Channel announcement was successfully processed and now it might be
2819
        // broadcast to other connected nodes if it was an announcement with
2820
        // proof (remote).
2821
        var announcements []networkMsg
28✔
2822

28✔
2823
        if proof != nil {
42✔
2824
                announcements = append(announcements, networkMsg{
14✔
2825
                        peer:     nMsg.peer,
14✔
2826
                        isRemote: nMsg.isRemote,
14✔
2827
                        source:   nMsg.source,
14✔
2828
                        msg:      ann,
14✔
2829
                })
14✔
2830
        }
14✔
2831

2832
        nMsg.err <- nil
28✔
2833

28✔
2834
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
28✔
2835
                nMsg.peer, scid.ToUint64())
28✔
2836

28✔
2837
        return announcements, true
28✔
2838
}
2839

2840
// handleChanUpdate processes a new channel update.
2841
func (d *AuthenticatedGossiper) handleChanUpdate(nMsg *networkMsg,
2842
        upd *lnwire.ChannelUpdate1,
2843
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
58✔
2844

58✔
2845
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
58✔
2846
                nMsg.peer, upd.ShortChannelID.ToUint64())
58✔
2847

58✔
2848
        // We'll ignore any channel updates that target any chain other than
58✔
2849
        // the set of chains we know of.
58✔
2850
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
58✔
2851
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2852
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2853
                log.Errorf(err.Error())
×
2854

×
2855
                key := newRejectCacheKey(
×
2856
                        upd.ShortChannelID.ToUint64(),
×
2857
                        sourceToPub(nMsg.source),
×
2858
                )
×
2859
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2860

×
2861
                nMsg.err <- err
×
2862
                return nil, false
×
2863
        }
×
2864

2865
        blockHeight := upd.ShortChannelID.BlockHeight
58✔
2866
        shortChanID := upd.ShortChannelID.ToUint64()
58✔
2867

58✔
2868
        // If the advertised inclusionary block is beyond our knowledge of the
58✔
2869
        // chain tip, then we'll put the announcement in limbo to be fully
58✔
2870
        // verified once we advance forward in the chain. If the update has an
58✔
2871
        // alias SCID, we'll skip the isPremature check. This is necessary
58✔
2872
        // since aliases start at block height 16_000_000.
58✔
2873
        d.Lock()
58✔
2874
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
58✔
2875
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
58✔
UNCOV
2876

×
UNCOV
2877
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
UNCOV
2878
                        "premature: advertises height %v, only height %v is "+
×
UNCOV
2879
                        "known", shortChanID, blockHeight, d.bestHeight)
×
UNCOV
2880
                d.Unlock()
×
UNCOV
2881
                nMsg.err <- nil
×
UNCOV
2882
                return nil, false
×
UNCOV
2883
        }
×
2884
        d.Unlock()
58✔
2885

58✔
2886
        // Before we perform any of the expensive checks below, we'll check
58✔
2887
        // whether this update is stale or is for a zombie channel in order to
58✔
2888
        // quickly reject it.
58✔
2889
        timestamp := time.Unix(int64(upd.Timestamp), 0)
58✔
2890

58✔
2891
        // Fetch the SCID we should be using to lock the channelMtx and make
58✔
2892
        // graph queries with.
58✔
2893
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
58✔
2894
        if err != nil {
116✔
2895
                // Fallback and set the graphScid to the peer-provided SCID.
58✔
2896
                // This will occur for non-option-scid-alias channels and for
58✔
2897
                // public option-scid-alias channels after 6 confirmations.
58✔
2898
                // Once public option-scid-alias channels have 6 confs, we'll
58✔
2899
                // ignore ChannelUpdates with one of their aliases.
58✔
2900
                graphScid = upd.ShortChannelID
58✔
2901
        }
58✔
2902

2903
        if d.cfg.Graph.IsStaleEdgePolicy(
58✔
2904
                graphScid, timestamp, upd.ChannelFlags,
58✔
2905
        ) {
63✔
2906

5✔
2907
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
5✔
2908
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
5✔
2909
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
5✔
2910
                )
5✔
2911

5✔
2912
                nMsg.err <- nil
5✔
2913
                return nil, true
5✔
2914
        }
5✔
2915

2916
        // Check that the ChanUpdate is not too far into the future, this could
2917
        // reveal some faulty implementation therefore we log an error.
2918
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
56✔
2919
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
2920
                        "short_chan_id(%v), timestamp too far in the future: "+
×
2921
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
2922
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
2923
                        nMsg.isRemote,
×
2924
                )
×
2925

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

×
2929
                return nil, false
×
2930
        }
×
2931

2932
        // Get the node pub key as far since we don't have it in the channel
2933
        // update announcement message. We'll need this to properly verify the
2934
        // message's signature.
2935
        //
2936
        // We make sure to obtain the mutex for this channel ID before we
2937
        // access the database. This ensures the state we read from the
2938
        // database has not changed between this point and when we call
2939
        // UpdateEdge() later.
2940
        d.channelMtx.Lock(graphScid.ToUint64())
56✔
2941
        defer d.channelMtx.Unlock(graphScid.ToUint64())
56✔
2942

56✔
2943
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
56✔
2944
        switch {
56✔
2945
        // No error, break.
2946
        case err == nil:
52✔
2947
                break
52✔
2948

2949
        case errors.Is(err, graphdb.ErrZombieEdge):
3✔
2950
                err = d.processZombieUpdate(chanInfo, graphScid, upd)
3✔
2951
                if err != nil {
5✔
2952
                        log.Debug(err)
2✔
2953
                        nMsg.err <- err
2✔
2954
                        return nil, false
2✔
2955
                }
2✔
2956

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

5✔
2986
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
5✔
2987
                switch {
5✔
2988
                // Nothing in the cache yet, we can just directly insert this
2989
                // element.
2990
                case err == cache.ErrElementNotFound:
5✔
2991
                        _, _ = d.prematureChannelUpdates.Put(
5✔
2992
                                shortChanID, &cachedNetworkMsg{
5✔
2993
                                        msgs: []*processedNetworkMsg{pMsg},
5✔
2994
                                })
5✔
2995

2996
                // There's already something in the cache, so we'll combine the
2997
                // set of messages into a single value.
2998
                default:
3✔
2999
                        msgs := earlyMsgs.msgs
3✔
3000
                        msgs = append(msgs, pMsg)
3✔
3001
                        _, _ = d.prematureChannelUpdates.Put(
3✔
3002
                                shortChanID, &cachedNetworkMsg{
3✔
3003
                                        msgs: msgs,
3✔
3004
                                })
3✔
3005
                }
3006

3007
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
5✔
3008
                        "(shortChanID=%v), saving for reprocessing later",
5✔
3009
                        shortChanID)
5✔
3010

5✔
3011
                // NOTE: We don't return anything on the error channel for this
5✔
3012
                // message, as we expect that will be done when this
5✔
3013
                // ChannelUpdate is later reprocessed.
5✔
3014
                return nil, false
5✔
3015

3016
        default:
×
3017
                err := fmt.Errorf("unable to validate channel update "+
×
3018
                        "short_chan_id=%v: %v", shortChanID, err)
×
3019
                log.Error(err)
×
3020
                nMsg.err <- err
×
3021

×
3022
                key := newRejectCacheKey(
×
3023
                        upd.ShortChannelID.ToUint64(),
×
3024
                        sourceToPub(nMsg.source),
×
3025
                )
×
3026
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3027

×
3028
                return nil, false
×
3029
        }
3030

3031
        // The least-significant bit in the flag on the channel update
3032
        // announcement tells us "which" side of the channels directed edge is
3033
        // being updated.
3034
        var (
52✔
3035
                pubKey       *btcec.PublicKey
52✔
3036
                edgeToUpdate *models.ChannelEdgePolicy
52✔
3037
        )
52✔
3038
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
52✔
3039
        switch direction {
52✔
3040
        case 0:
37✔
3041
                pubKey, _ = chanInfo.NodeKey1()
37✔
3042
                edgeToUpdate = e1
37✔
3043
        case 1:
18✔
3044
                pubKey, _ = chanInfo.NodeKey2()
18✔
3045
                edgeToUpdate = e2
18✔
3046
        }
3047

3048
        log.Debugf("Validating ChannelUpdate: channel=%v, from node=%x, has "+
52✔
3049
                "edge=%v", chanInfo.ChannelID, pubKey.SerializeCompressed(),
52✔
3050
                edgeToUpdate != nil)
52✔
3051

52✔
3052
        // Validate the channel announcement with the expected public key and
52✔
3053
        // channel capacity. In the case of an invalid channel update, we'll
52✔
3054
        // return an error to the caller and exit early.
52✔
3055
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
52✔
3056
        if err != nil {
56✔
3057
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3058
                        "announcement for short_chan_id=%v: %v",
4✔
3059
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3060

4✔
3061
                log.Error(rErr)
4✔
3062
                nMsg.err <- rErr
4✔
3063
                return nil, false
4✔
3064
        }
4✔
3065

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

15✔
3108
                        if !rls[direction].Allow() {
23✔
3109
                                log.Debugf("Rate limiting update for channel "+
8✔
3110
                                        "%v from direction %x", shortChanID,
8✔
3111
                                        pubKey.SerializeCompressed())
8✔
3112
                                nMsg.err <- nil
8✔
3113
                                return nil, false
8✔
3114
                        }
8✔
3115
                }
3116
        }
3117

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

42✔
3139
        if err := d.cfg.Graph.UpdateEdge(update, ops...); err != nil {
45✔
3140
                if graph.IsError(
3✔
3141
                        err, graph.ErrOutdated,
3✔
3142
                        graph.ErrIgnored,
3✔
3143
                        graph.ErrVBarrierShuttingDown,
3✔
3144
                ) {
6✔
3145

3✔
3146
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
3✔
3147
                                shortChanID, err)
3✔
3148
                } else {
3✔
3149
                        // Since we know the stored SCID in the graph, we'll
×
3150
                        // cache that SCID.
×
3151
                        key := newRejectCacheKey(
×
3152
                                chanInfo.ChannelID,
×
3153
                                sourceToPub(nMsg.source),
×
3154
                        )
×
3155
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3156

×
3157
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3158
                                shortChanID, err)
×
3159
                }
×
3160

3161
                nMsg.err <- err
3✔
3162
                return nil, false
3✔
3163
        }
3164

3165
        // If this is a local ChannelUpdate without an AuthProof, it means it
3166
        // is an update to a channel that is not (yet) supposed to be announced
3167
        // to the greater network. However, our channel counter party will need
3168
        // to be given the update, so we'll try sending the update directly to
3169
        // the remote peer.
3170
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
56✔
3171
                if nMsg.optionalMsgFields != nil {
28✔
3172
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
14✔
3173
                        if remoteAlias != nil {
17✔
3174
                                // The remoteAlias field was specified, meaning
3✔
3175
                                // that we should replace the SCID in the
3✔
3176
                                // update with the remote's alias. We'll also
3✔
3177
                                // need to re-sign the channel update. This is
3✔
3178
                                // required for option-scid-alias feature-bit
3✔
3179
                                // negotiated channels.
3✔
3180
                                upd.ShortChannelID = *remoteAlias
3✔
3181

3✔
3182
                                sig, err := d.cfg.SignAliasUpdate(upd)
3✔
3183
                                if err != nil {
3✔
3184
                                        log.Error(err)
×
3185
                                        nMsg.err <- err
×
3186
                                        return nil, false
×
3187
                                }
×
3188

3189
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
3190
                                if err != nil {
3✔
3191
                                        log.Error(err)
×
3192
                                        nMsg.err <- err
×
3193
                                        return nil, false
×
3194
                                }
×
3195

3196
                                upd.Signature = lnSig
3✔
3197
                        }
3198
                }
3199

3200
                // Get our peer's public key.
3201
                remotePubKey := remotePubFromChanInfo(
14✔
3202
                        chanInfo, upd.ChannelFlags,
14✔
3203
                )
14✔
3204

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

14✔
3208
                // Now we'll attempt to send the channel update message
14✔
3209
                // reliably to the remote peer in the background, so that we
14✔
3210
                // don't block if the peer happens to be offline at the moment.
14✔
3211
                err := d.reliableSender.sendMessage(upd, remotePubKey)
14✔
3212
                if err != nil {
14✔
3213
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3214
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3215
                                upd.ShortChannelID, remotePubKey, err)
×
3216
                        nMsg.err <- err
×
3217
                        return nil, false
×
3218
                }
×
3219
        }
3220

3221
        // Channel update announcement was successfully processed and now it
3222
        // can be broadcast to the rest of the network. However, we'll only
3223
        // broadcast the channel update announcement if it has an attached
3224
        // authentication proof. We also won't broadcast the update if it
3225
        // contains an alias because the network would reject this.
3226
        var announcements []networkMsg
42✔
3227
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
64✔
3228
                announcements = append(announcements, networkMsg{
22✔
3229
                        peer:     nMsg.peer,
22✔
3230
                        source:   nMsg.source,
22✔
3231
                        isRemote: nMsg.isRemote,
22✔
3232
                        msg:      upd,
22✔
3233
                })
22✔
3234
        }
22✔
3235

3236
        nMsg.err <- nil
42✔
3237

42✔
3238
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
42✔
3239
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
42✔
3240
                timestamp)
42✔
3241
        return announcements, true
42✔
3242
}
3243

3244
// handleAnnSig processes a new announcement signatures message.
3245
func (d *AuthenticatedGossiper) handleAnnSig(nMsg *networkMsg,
3246
        ann *lnwire.AnnounceSignatures1) ([]networkMsg, bool) {
24✔
3247

24✔
3248
        needBlockHeight := ann.ShortChannelID.BlockHeight +
24✔
3249
                d.cfg.ProofMatureDelta
24✔
3250
        shortChanID := ann.ShortChannelID.ToUint64()
24✔
3251

24✔
3252
        prefix := "local"
24✔
3253
        if nMsg.isRemote {
38✔
3254
                prefix = "remote"
14✔
3255
        }
14✔
3256

3257
        log.Infof("Received new %v announcement signature for %v", prefix,
24✔
3258
                ann.ShortChannelID)
24✔
3259

24✔
3260
        // By the specification, channel announcement proofs should be sent
24✔
3261
        // after some number of confirmations after channel was registered in
24✔
3262
        // bitcoin blockchain. Therefore, we check if the proof is mature.
24✔
3263
        d.Lock()
24✔
3264
        premature := d.isPremature(
24✔
3265
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
24✔
3266
        )
24✔
3267
        if premature {
27✔
3268
                log.Warnf("Premature proof announcement, current block height"+
3✔
3269
                        "lower than needed: %v < %v", d.bestHeight,
3✔
3270
                        needBlockHeight)
3✔
3271
                d.Unlock()
3✔
3272
                nMsg.err <- nil
3✔
3273
                return nil, false
3✔
3274
        }
3✔
3275
        d.Unlock()
24✔
3276

24✔
3277
        // Ensure that we know of a channel with the target channel ID before
24✔
3278
        // proceeding further.
24✔
3279
        //
24✔
3280
        // We must acquire the mutex for this channel ID before getting the
24✔
3281
        // channel from the database, to ensure what we read does not change
24✔
3282
        // before we call AddProof() later.
24✔
3283
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
24✔
3284
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
24✔
3285

24✔
3286
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
24✔
3287
                ann.ShortChannelID,
24✔
3288
        )
24✔
3289
        if err != nil {
28✔
3290
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
4✔
3291
                if err != nil {
7✔
3292
                        err := fmt.Errorf("unable to store the proof for "+
3✔
3293
                                "short_chan_id=%v: %v", shortChanID, err)
3✔
3294
                        log.Error(err)
3✔
3295
                        nMsg.err <- err
3✔
3296

3✔
3297
                        return nil, false
3✔
3298
                }
3✔
3299

3300
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
4✔
3301
                err := d.cfg.WaitingProofStore.Add(proof)
4✔
3302
                if err != nil {
4✔
3303
                        err := fmt.Errorf("unable to store the proof for "+
×
3304
                                "short_chan_id=%v: %v", shortChanID, err)
×
3305
                        log.Error(err)
×
3306
                        nMsg.err <- err
×
3307
                        return nil, false
×
3308
                }
×
3309

3310
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
4✔
3311
                        ", adding to waiting batch", prefix, shortChanID)
4✔
3312
                nMsg.err <- nil
4✔
3313
                return nil, false
4✔
3314
        }
3315

3316
        nodeID := nMsg.source.SerializeCompressed()
23✔
3317
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
23✔
3318
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
23✔
3319

23✔
3320
        // Ensure that channel that was retrieved belongs to the peer which
23✔
3321
        // sent the proof announcement.
23✔
3322
        if !(isFirstNode || isSecondNode) {
23✔
3323
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3324
                        "to the peer which sent the proof, short_chan_id=%v",
×
3325
                        shortChanID)
×
3326
                log.Error(err)
×
3327
                nMsg.err <- err
×
3328
                return nil, false
×
3329
        }
×
3330

3331
        // If proof was sent by a local sub-system, then we'll send the
3332
        // announcement signature to the remote node so they can also
3333
        // reconstruct the full channel announcement.
3334
        if !nMsg.isRemote {
36✔
3335
                var remotePubKey [33]byte
13✔
3336
                if isFirstNode {
26✔
3337
                        remotePubKey = chanInfo.NodeKey2Bytes
13✔
3338
                } else {
16✔
3339
                        remotePubKey = chanInfo.NodeKey1Bytes
3✔
3340
                }
3✔
3341

3342
                // Since the remote peer might not be online we'll call a
3343
                // method that will attempt to deliver the proof when it comes
3344
                // online.
3345
                err := d.reliableSender.sendMessage(ann, remotePubKey)
13✔
3346
                if err != nil {
13✔
3347
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3348
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3349
                                ann.ShortChannelID, remotePubKey, err)
×
3350
                        nMsg.err <- err
×
3351
                        return nil, false
×
3352
                }
×
3353
        }
3354

3355
        // Check if we already have the full proof for this channel.
3356
        if chanInfo.AuthProof != nil {
27✔
3357
                // If we already have the fully assembled proof, then the peer
4✔
3358
                // sending us their proof has probably not received our local
4✔
3359
                // proof yet. So be kind and send them the full proof.
4✔
3360
                if nMsg.isRemote {
8✔
3361
                        peerID := nMsg.source.SerializeCompressed()
4✔
3362
                        log.Debugf("Got AnnounceSignatures for channel with " +
4✔
3363
                                "full proof.")
4✔
3364

4✔
3365
                        d.wg.Add(1)
4✔
3366
                        go func() {
8✔
3367
                                defer d.wg.Done()
4✔
3368

4✔
3369
                                log.Debugf("Received half proof for channel "+
4✔
3370
                                        "%v with existing full proof. Sending"+
4✔
3371
                                        " full proof to peer=%x",
4✔
3372
                                        ann.ChannelID, peerID)
4✔
3373

4✔
3374
                                ca, _, _, err := netann.CreateChanAnnouncement(
4✔
3375
                                        chanInfo.AuthProof, chanInfo, e1, e2,
4✔
3376
                                )
4✔
3377
                                if err != nil {
4✔
3378
                                        log.Errorf("unable to gen ann: %v",
×
3379
                                                err)
×
3380
                                        return
×
3381
                                }
×
3382

3383
                                err = nMsg.peer.SendMessage(false, ca)
4✔
3384
                                if err != nil {
4✔
3385
                                        log.Errorf("Failed sending full proof"+
×
3386
                                                " to peer=%x: %v", peerID, err)
×
3387
                                        return
×
3388
                                }
×
3389

3390
                                log.Debugf("Full proof sent to peer=%x for "+
4✔
3391
                                        "chanID=%v", peerID, ann.ChannelID)
4✔
3392
                        }()
3393
                }
3394

3395
                log.Debugf("Already have proof for channel with chanID=%v",
4✔
3396
                        ann.ChannelID)
4✔
3397
                nMsg.err <- nil
4✔
3398
                return nil, true
4✔
3399
        }
3400

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

3416
        if err == channeldb.ErrWaitingProofNotFound {
34✔
3417
                err := d.cfg.WaitingProofStore.Add(proof)
12✔
3418
                if err != nil {
12✔
3419
                        err := fmt.Errorf("unable to store the proof for "+
×
3420
                                "short_chan_id=%v: %v", shortChanID, err)
×
3421
                        log.Error(err)
×
3422
                        nMsg.err <- err
×
3423
                        return nil, false
×
3424
                }
×
3425

3426
                log.Infof("1/2 of channel ann proof received for "+
12✔
3427
                        "short_chan_id=%v, waiting for other half",
12✔
3428
                        shortChanID)
12✔
3429

12✔
3430
                nMsg.err <- nil
12✔
3431
                return nil, false
12✔
3432
        }
3433

3434
        // We now have both halves of the channel announcement proof, then
3435
        // we'll reconstruct the initial announcement so we can validate it
3436
        // shortly below.
3437
        var dbProof models.ChannelAuthProof
13✔
3438
        if isFirstNode {
17✔
3439
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
4✔
3440
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
4✔
3441
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
4✔
3442
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
4✔
3443
        } else {
16✔
3444
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
12✔
3445
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
12✔
3446
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
12✔
3447
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
12✔
3448
        }
12✔
3449

3450
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
13✔
3451
                &dbProof, chanInfo, e1, e2,
13✔
3452
        )
13✔
3453
        if err != nil {
13✔
3454
                log.Error(err)
×
3455
                nMsg.err <- err
×
3456
                return nil, false
×
3457
        }
×
3458

3459
        // With all the necessary components assembled validate the full
3460
        // channel announcement proof.
3461
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
13✔
3462
        if err != nil {
13✔
3463
                err := fmt.Errorf("channel announcement proof for "+
×
3464
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3465

×
3466
                log.Error(err)
×
3467
                nMsg.err <- err
×
3468
                return nil, false
×
3469
        }
×
3470

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

3486
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
13✔
3487
        if err != nil {
13✔
3488
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3489
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3490
                log.Error(err)
×
3491
                nMsg.err <- err
×
3492
                return nil, false
×
3493
        }
×
3494

3495
        // Proof was successfully created and now can announce the channel to
3496
        // the remain network.
3497
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
13✔
3498
                ", adding to next ann batch", shortChanID)
13✔
3499

13✔
3500
        // Assemble the necessary announcements to add to the next broadcasting
13✔
3501
        // batch.
13✔
3502
        var announcements []networkMsg
13✔
3503
        announcements = append(announcements, networkMsg{
13✔
3504
                peer:   nMsg.peer,
13✔
3505
                source: nMsg.source,
13✔
3506
                msg:    chanAnn,
13✔
3507
        })
13✔
3508
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
25✔
3509
                announcements = append(announcements, networkMsg{
12✔
3510
                        peer:   nMsg.peer,
12✔
3511
                        source: src,
12✔
3512
                        msg:    e1Ann,
12✔
3513
                })
12✔
3514
        }
12✔
3515
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
24✔
3516
                announcements = append(announcements, networkMsg{
11✔
3517
                        peer:   nMsg.peer,
11✔
3518
                        source: src,
11✔
3519
                        msg:    e2Ann,
11✔
3520
                })
11✔
3521
        }
11✔
3522

3523
        // We'll also send along the node announcements for each channel
3524
        // participant if we know of them. To ensure our node announcement
3525
        // propagates to our channel counterparty, we'll set the source for
3526
        // each announcement to the node it belongs to, otherwise we won't send
3527
        // it since the source gets skipped. This isn't necessary for channel
3528
        // updates and announcement signatures since we send those directly to
3529
        // our channel counterparty through the gossiper's reliable sender.
3530
        node1Ann, err := d.fetchNodeAnn(chanInfo.NodeKey1Bytes)
13✔
3531
        if err != nil {
18✔
3532
                log.Debugf("Unable to fetch node announcement for %x: %v",
5✔
3533
                        chanInfo.NodeKey1Bytes, err)
5✔
3534
        } else {
16✔
3535
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
22✔
3536
                        announcements = append(announcements, networkMsg{
11✔
3537
                                peer:   nMsg.peer,
11✔
3538
                                source: nodeKey1,
11✔
3539
                                msg:    node1Ann,
11✔
3540
                        })
11✔
3541
                }
11✔
3542
        }
3543

3544
        node2Ann, err := d.fetchNodeAnn(chanInfo.NodeKey2Bytes)
13✔
3545
        if err != nil {
20✔
3546
                log.Debugf("Unable to fetch node announcement for %x: %v",
7✔
3547
                        chanInfo.NodeKey2Bytes, err)
7✔
3548
        } else {
16✔
3549
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
18✔
3550
                        announcements = append(announcements, networkMsg{
9✔
3551
                                peer:   nMsg.peer,
9✔
3552
                                source: nodeKey2,
9✔
3553
                                msg:    node2Ann,
9✔
3554
                        })
9✔
3555
                }
9✔
3556
        }
3557

3558
        nMsg.err <- nil
13✔
3559
        return announcements, true
13✔
3560
}
3561

3562
// isBanned returns true if the peer identified by pubkey is banned for sending
3563
// invalid channel announcements.
3564
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
208✔
3565
        return d.banman.isBanned(pubkey)
208✔
3566
}
208✔
3567

3568
// ShouldDisconnect returns true if we should disconnect the peer identified by
3569
// pubkey.
3570
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3571
        bool, error) {
206✔
3572

206✔
3573
        pubkeySer := pubkey.SerializeCompressed()
206✔
3574

206✔
3575
        var pubkeyBytes [33]byte
206✔
3576
        copy(pubkeyBytes[:], pubkeySer)
206✔
3577

206✔
3578
        // If the public key is banned, check whether or not this is a channel
206✔
3579
        // peer.
206✔
3580
        if d.isBanned(pubkeyBytes) {
208✔
3581
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3582
                if err != nil {
2✔
3583
                        return false, err
×
3584
                }
×
3585

3586
                // We should only disconnect non-channel peers.
3587
                if !isChanPeer {
3✔
3588
                        return true, nil
1✔
3589
                }
1✔
3590
        }
3591

3592
        return false, nil
205✔
3593
}
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