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

lightningnetwork / lnd / 12775863480

14 Jan 2025 08:26PM UTC coverage: 58.569% (-0.1%) from 58.718%
12775863480

Pull #9241

github

Crypt-iQ
release-notes: update for 0.19.0
Pull Request #9241: discovery+graph: track job set dependencies in vb

205 of 244 new or added lines in 3 files covered. (84.02%)

422 existing lines in 31 files now uncovered.

135070 of 230618 relevant lines covered (58.57%)

19130.29 hits per line

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

80.05
/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

67
var (
68
        // ErrGossiperShuttingDown is an error that is returned if the gossiper
69
        // is in the process of being shut down.
70
        ErrGossiperShuttingDown = errors.New("gossiper is shutting down")
71

72
        // ErrGossipSyncerNotFound signals that we were unable to find an active
73
        // gossip syncer corresponding to a gossip query message received from
74
        // the remote peer.
75
        ErrGossipSyncerNotFound = errors.New("gossip syncer not found")
76

77
        // emptyPubkey is used to compare compressed pubkeys against an empty
78
        // byte array.
79
        emptyPubkey [33]byte
80
)
81

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

92
// apply applies the optional fields within the functional options.
93
func (f *optionalMsgFields) apply(optionalMsgFields ...OptionalMsgField) {
49✔
94
        for _, optionalMsgField := range optionalMsgFields {
56✔
95
                optionalMsgField(f)
7✔
96
        }
7✔
97
}
98

99
// OptionalMsgField is a functional option parameter that can be used to provide
100
// external information that is not included within a network message but serves
101
// useful when processing it.
102
type OptionalMsgField func(*optionalMsgFields)
103

104
// ChannelCapacity is an optional field that lets the gossiper know of the
105
// capacity of a channel.
106
func ChannelCapacity(capacity btcutil.Amount) OptionalMsgField {
29✔
107
        return func(f *optionalMsgFields) {
32✔
108
                f.capacity = &capacity
3✔
109
        }
3✔
110
}
111

112
// ChannelPoint is an optional field that lets the gossiper know of the outpoint
113
// of a channel.
114
func ChannelPoint(op wire.OutPoint) OptionalMsgField {
32✔
115
        return func(f *optionalMsgFields) {
38✔
116
                f.channelPoint = &op
6✔
117
        }
6✔
118
}
119

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

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

140
// networkMsg couples a routing related wire message with the peer that
141
// originally sent it.
142
type networkMsg struct {
143
        peer              lnpeer.Peer
144
        source            *btcec.PublicKey
145
        msg               lnwire.Message
146
        optionalMsgFields *optionalMsgFields
147

148
        isRemote bool
149

150
        err chan error
151
}
152

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

162
// PinnedSyncers is a set of node pubkeys for which we will maintain an active
163
// syncer at all times.
164
type PinnedSyncers map[route.Vertex]struct{}
165

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

178
        // Graph is the subsystem which is responsible for managing the
179
        // topology of lightning network. After incoming channel, node, channel
180
        // updates announcements are validated they are sent to the router in
181
        // order to be included in the LN graph.
182
        Graph graph.ChannelGraphSource
183

184
        // ChainIO represents an abstraction over a source that can query the
185
        // blockchain.
186
        ChainIO lnwallet.BlockChainIO
187

188
        // ChanSeries is an interfaces that provides access to a time series
189
        // view of the current known channel graph. Each GossipSyncer enabled
190
        // peer will utilize this in order to create and respond to channel
191
        // graph time series queries.
192
        ChanSeries ChannelGraphTimeSeries
193

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

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

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

216
        // NotifyWhenOffline is a function that allows the gossiper to be
217
        // notified when a certain peer disconnects, allowing it to request a
218
        // notification for when it reconnects.
219
        NotifyWhenOffline func(peerPubKey [33]byte) <-chan struct{}
220

221
        // FetchSelfAnnouncement retrieves our current node announcement, for
222
        // use when determining whether we should update our peers about our
223
        // presence in the network.
224
        FetchSelfAnnouncement func() lnwire.NodeAnnouncement
225

226
        // UpdateSelfAnnouncement produces a new announcement for our node with
227
        // an updated timestamp which can be broadcast to our peers.
228
        UpdateSelfAnnouncement func() (lnwire.NodeAnnouncement, error)
229

230
        // ProofMatureDelta the number of confirmations which is needed before
231
        // exchange the channel announcement proofs.
232
        ProofMatureDelta uint32
233

234
        // TrickleDelay the period of trickle timer which flushes to the
235
        // network the pending batch of new announcements we've received since
236
        // the last trickle tick.
237
        TrickleDelay time.Duration
238

239
        // RetransmitTicker is a ticker that ticks with a period which
240
        // indicates that we should check if we need re-broadcast any of our
241
        // personal channels.
242
        RetransmitTicker ticker.Ticker
243

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

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

260
        // MessageStore is a persistent storage of gossip messages which we will
261
        // use to determine which messages need to be resent for a given peer.
262
        MessageStore GossipMessageStore
263

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

273
        // ScidCloser is an instance of ClosedChannelTracker that helps the
274
        // gossiper cut down on spam channel announcements for already closed
275
        // channels.
276
        ScidCloser ClosedChannelTracker
277

278
        // NumActiveSyncers is the number of peers for which we should have
279
        // active syncers with. After reaching NumActiveSyncers, any future
280
        // gossip syncers will be passive.
281
        NumActiveSyncers int
282

283
        // NoTimestampQueries will prevent the GossipSyncer from querying
284
        // timestamps of announcement messages from the peer and from replying
285
        // to timestamp queries.
286
        NoTimestampQueries bool
287

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

294
        // HistoricalSyncTicker is a ticker responsible for notifying the
295
        // syncManager when it should attempt a historical sync with a gossip
296
        // sync peer.
297
        HistoricalSyncTicker ticker.Ticker
298

299
        // ActiveSyncerTimeoutTicker is a ticker responsible for notifying the
300
        // syncManager when it should attempt to start the next pending
301
        // activeSyncer due to the current one not completing its state machine
302
        // within the timeout.
303
        ActiveSyncerTimeoutTicker ticker.Ticker
304

305
        // MinimumBatchSize is minimum size of a sub batch of announcement
306
        // messages.
307
        MinimumBatchSize int
308

309
        // SubBatchDelay is the delay between sending sub batches of
310
        // gossip messages.
311
        SubBatchDelay time.Duration
312

313
        // IgnoreHistoricalFilters will prevent syncers from replying with
314
        // historical data when the remote peer sets a gossip_timestamp_range.
315
        // This prevents ranges with old start times from causing us to dump the
316
        // graph on connect.
317
        IgnoreHistoricalFilters bool
318

319
        // PinnedSyncers is a set of peers that will always transition to
320
        // ActiveSync upon connection. These peers will never transition to
321
        // PassiveSync.
322
        PinnedSyncers PinnedSyncers
323

324
        // MaxChannelUpdateBurst specifies the maximum number of updates for a
325
        // specific channel and direction that we'll accept over an interval.
326
        MaxChannelUpdateBurst int
327

328
        // ChannelUpdateInterval specifies the interval we'll use to determine
329
        // how often we should allow a new update for a specific channel and
330
        // direction.
331
        ChannelUpdateInterval time.Duration
332

333
        // IsAlias returns true if a given ShortChannelID is an alias for
334
        // option_scid_alias channels.
335
        IsAlias func(scid lnwire.ShortChannelID) bool
336

337
        // SignAliasUpdate is used to re-sign a channel update using the
338
        // remote's alias if the option-scid-alias feature bit was negotiated.
339
        SignAliasUpdate func(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
340
                error)
341

342
        // FindBaseByAlias finds the SCID stored in the graph by an alias SCID.
343
        // This is used for channels that have negotiated the option-scid-alias
344
        // feature bit.
345
        FindBaseByAlias func(alias lnwire.ShortChannelID) (
346
                lnwire.ShortChannelID, error)
347

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

353
        // FindChannel allows the gossiper to find a channel that we're party
354
        // to without iterating over the entire set of open channels.
355
        FindChannel func(node *btcec.PublicKey, chanID lnwire.ChannelID) (
356
                *channeldb.OpenChannel, error)
357

358
        // IsStillZombieChannel takes the timestamps of the latest channel
359
        // updates for a channel and returns true if the channel should be
360
        // considered a zombie based on these timestamps.
361
        IsStillZombieChannel func(time.Time, time.Time) bool
362
}
363

364
// processedNetworkMsg is a wrapper around networkMsg and a boolean. It is
365
// used to let the caller of the lru.Cache know if a message has already been
366
// processed or not.
367
type processedNetworkMsg struct {
368
        processed bool
369
        msg       *networkMsg
370
}
371

372
// cachedNetworkMsg is a wrapper around a network message that can be used with
373
// *lru.Cache.
374
type cachedNetworkMsg struct {
375
        msgs []*processedNetworkMsg
376
}
377

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

385
// rejectCacheKey is the cache key that we'll use to track announcements we've
386
// recently rejected.
387
type rejectCacheKey struct {
388
        pubkey [33]byte
389
        chanID uint64
390
}
391

392
// newRejectCacheKey returns a new cache key for the reject cache.
393
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
464✔
394
        k := rejectCacheKey{
464✔
395
                chanID: cid,
464✔
396
                pubkey: pub,
464✔
397
        }
464✔
398

464✔
399
        return k
464✔
400
}
464✔
401

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

410
// cachedReject is the empty value used to track the value for rejects.
411
type cachedReject struct {
412
}
413

414
// Size returns the "size" of an entry. We return 1 as we just want to limit
415
// the total size.
416
func (c *cachedReject) Size() (uint64, error) {
203✔
417
        return 1, nil
203✔
418
}
203✔
419

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

434
        // bestHeight is the height of the block at the tip of the main chain
435
        // as we know it. Accesses *MUST* be done with the gossiper's lock
436
        // held.
437
        bestHeight uint32
438

439
        quit chan struct{}
440
        wg   sync.WaitGroup
441

442
        // cfg is a copy of the configuration struct that the gossiper service
443
        // was initialized with.
444
        cfg *Config
445

446
        // blockEpochs encapsulates a stream of block epochs that are sent at
447
        // every new block height.
448
        blockEpochs *chainntnfs.BlockEpochEvent
449

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

456
        // banman tracks our peer's ban status.
457
        banman *banman
458

459
        // networkMsgs is a channel that carries new network broadcasted
460
        // message from outside the gossiper service to be processed by the
461
        // networkHandler.
462
        networkMsgs chan *networkMsg
463

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

471
        // chanPolicyUpdates is a channel that requests to update the
472
        // forwarding policy of a set of channels is sent over.
473
        chanPolicyUpdates chan *chanPolicyUpdateRequest
474

475
        // selfKey is the identity public key of the backing Lightning node.
476
        selfKey *btcec.PublicKey
477

478
        // selfKeyLoc is the locator for the identity public key of the backing
479
        // Lightning node.
480
        selfKeyLoc keychain.KeyLocator
481

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

488
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
489

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

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

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

515
        // vb is used to enforce job dependency ordering of gossip messages.
516
        vb *graph.ValidationBarrier
517

518
        sync.Mutex
519
}
520

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

29✔
543
        gossiper.vb = graph.NewValidationBarrier(1000, gossiper.quit)
29✔
544

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

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

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

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

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

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

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

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

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

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

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

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

635
        d.syncMgr.Start()
29✔
636

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

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

29✔
644
        return nil
29✔
645
}
646

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

743
                return true
1✔
744
        }
745

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

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

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

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

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

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

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

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

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

793
        d.syncMgr.Stop()
29✔
794

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

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

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

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

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

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

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

2✔
827
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
2✔
828
                if !ok {
2✔
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())
2✔
839

2✔
840
                errChan <- nil
2✔
841
                return errChan
2✔
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:
2✔
846
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
2✔
847
                if !ok {
2✔
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 {
2✔
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
2✔
866
                return errChan
2✔
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:
221✔
872
                ownKey := d.selfKey.SerializeCompressed()
221✔
873
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
221✔
874
                        "for own channel")
221✔
875

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

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

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

284✔
893
        select {
284✔
894
        case d.networkMsgs <- nMsg:
284✔
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
284✔
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 {
49✔
916

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

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

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

934
        return nMsg.err
49✔
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) {
26✔
973
        for peerPub := range syncers {
28✔
974
                m.senders[peerPub] = struct{}{}
2✔
975
        }
2✔
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() {
31✔
1001
        d.Lock()
31✔
1002
        defer d.Unlock()
31✔
1003

31✔
1004
        d.reset()
31✔
1005
}
31✔
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() {
317✔
1010
        // Storage of each type of announcement (channel announcements, channel
317✔
1011
        // updates, node announcements) is set to an empty map where the
317✔
1012
        // appropriate key points to the corresponding lnwire.Message.
317✔
1013
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
317✔
1014
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
317✔
1015
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
317✔
1016
}
317✔
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) {
88✔
1023
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
88✔
1024

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

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

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

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

23✔
1048
                        return
23✔
1049
                }
23✔
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:
44✔
1058
                sender := route.NewVertex(message.source)
44✔
1059
                deDupKey := channelUpdateID{
44✔
1060
                        msg.ShortChannelID,
44✔
1061
                        msg.ChannelFlags,
44✔
1062
                }
44✔
1063

44✔
1064
                oldTimestamp := uint32(0)
44✔
1065
                mws, ok := d.channelUpdates[deDupKey]
44✔
1066
                if ok {
47✔
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 {
45✔
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 {
85✔
1092
                        mws = msgWithSenders{
42✔
1093
                                msg:     msg,
42✔
1094
                                isLocal: !message.isRemote,
42✔
1095
                                senders: make(map[route.Vertex]struct{}),
42✔
1096
                        }
42✔
1097

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

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

42✔
1104
                        return
42✔
1105
                }
42✔
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:
24✔
1118
                sender := route.NewVertex(message.source)
24✔
1119
                deDupKey := route.Vertex(msg.NodeID)
24✔
1120

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

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

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

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

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

20✔
1146
                        return
20✔
1147
                }
20✔
1148

1149
                // Add to senders map if it's the same as we had.
1150
                mws.msg = msg
6✔
1151
                mws.senders[sender] = struct{}{}
6✔
1152
                d.nodeAnnouncements[deDupKey] = mws
6✔
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) {
56✔
1159
        d.Lock()
56✔
1160
        defer d.Unlock()
56✔
1161

56✔
1162
        for _, msg := range msgs {
144✔
1163
                d.addMsg(msg)
88✔
1164
        }
88✔
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) {
73✔
1181
        if msg.isLocal {
122✔
1182
                m.localMsgs = append(m.localMsgs, msg)
49✔
1183
        } else {
75✔
1184
                m.remoteMsgs = append(m.remoteMsgs, msg)
26✔
1185
        }
26✔
1186
}
1187

1188
// isEmpty returns true if the batch is empty.
1189
func (m *msgsToBroadcast) isEmpty() bool {
287✔
1190
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
287✔
1191
}
287✔
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 {
288✔
1205
        d.Lock()
288✔
1206
        defer d.Unlock()
288✔
1207

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

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

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

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

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

1234
        d.reset()
288✔
1235

288✔
1236
        // Return the array of lnwire.messages.
288✔
1237
        return msgs
288✔
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 {
15✔
1244
        if subBatchDelay > totalDelay {
17✔
1245
                return batchSize
2✔
1246
        }
2✔
1247

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

13✔
1251
        if subBatchSize < minimumBatchSize {
16✔
1252
                return minimumBatchSize
3✔
1253
        }
3✔
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 {
71✔
1266

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

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

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

71✔
1286
        return splitAnnouncementBatch
71✔
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) {
33✔
1295

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

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

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

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

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

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

33✔
1328
                // Now send the remote announcements.
33✔
1329
                for _, annBatch := range remoteBatches {
66✔
1330
                        d.sendRemoteBatch(annBatch)
33✔
1331
                        delayNextBatch()
33✔
1332
                }
33✔
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) {
33✔
1340
        msgsToSend := lnutils.Map(
33✔
1341
                annBatch, func(m msgWithSenders) lnwire.Message {
78✔
1342
                        return m.msg
45✔
1343
                },
45✔
1344
        )
1345

1346
        err := d.cfg.Broadcast(nil, msgsToSend...)
33✔
1347
        if err != nil {
33✔
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) {
33✔
1355
        syncerPeers := d.syncMgr.GossipSyncers()
33✔
1356

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

1364
        for _, msgChunk := range annBatch {
59✔
1365
                msgChunk := msgChunk
26✔
1366

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

26✔
1372
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
26✔
1373
                if err != nil {
26✔
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() {
29✔
1388
        defer d.wg.Done()
29✔
1389

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

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

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

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

1406
        for {
676✔
1407
                select {
647✔
1408
                // A new policy update has arrived. We'll commit it to the
1409
                // sub-systems below us, then craft, sign, and broadcast a new
1410
                // ChannelUpdate for the set of affected clients.
1411
                case policyUpdate := <-d.chanPolicyUpdates:
3✔
1412
                        log.Tracef("Received channel %d policy update requests",
3✔
1413
                                len(policyUpdate.edgesToUpdate))
3✔
1414

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

1428
                        // Finally, with the updates committed, we'll now add
1429
                        // them to the announcement batch to be flushed at the
1430
                        // start of the next epoch.
1431
                        announcements.AddMsgs(newChanUpdates...)
3✔
1432

1433
                case announcement := <-d.networkMsgs:
333✔
1434
                        log.Tracef("Received network message: "+
333✔
1435
                                "peer=%v, msg=%s, is_remote=%v",
333✔
1436
                                announcement.peer, announcement.msg.MsgType(),
333✔
1437
                                announcement.isRemote)
333✔
1438

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

23✔
1451
                                if emittedAnnouncements != nil {
35✔
1452
                                        announcements.AddMsgs(
12✔
1453
                                                emittedAnnouncements...,
12✔
1454
                                        )
12✔
1455
                                }
12✔
1456
                                continue
23✔
1457
                        }
1458

1459
                        // If this message was recently rejected, then we won't
1460
                        // attempt to re-process it.
1461
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
312✔
1462
                                announcement.msg,
312✔
1463
                                sourceToPub(announcement.source),
312✔
1464
                        ) {
313✔
1465

1✔
1466
                                announcement.err <- fmt.Errorf("recently " +
1✔
1467
                                        "rejected")
1✔
1468
                                continue
1✔
1469
                        }
1470

1471
                        // We'll set up any dependent, and wait until a free
1472
                        // slot for this job opens up, this allow us to not
1473
                        // have thousands of goroutines active.
1474
                        annJobID, err := d.vb.InitJobDependencies(
311✔
1475
                                announcement.msg,
311✔
1476
                        )
311✔
1477
                        if err != nil {
311✔
NEW
1478
                                announcement.err <- err
×
NEW
1479
                                continue
×
1480
                        }
1481

1482
                        d.wg.Add(1)
311✔
1483
                        go d.handleNetworkMessages(
311✔
1484
                                announcement, &announcements, annJobID,
311✔
1485
                        )
311✔
1486

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

287✔
1495
                        // If the current announcements batch is nil, then we
287✔
1496
                        // have no further work here.
287✔
1497
                        if announcementBatch.isEmpty() {
543✔
1498
                                continue
256✔
1499
                        }
1500

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

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

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

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

311✔
1537
        defer d.wg.Done()
311✔
1538
        defer d.vb.CompleteJob()
311✔
1539

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

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

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

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

×
1562
                return
×
1563
        }
1564

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

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

311✔
1574
        // If this message had any dependencies, then we can now signal them to
311✔
1575
        // continue.
311✔
1576
        err = d.vb.SignalDependents(nMsg.msg, jobID)
311✔
1577
        if err != nil {
311✔
NEW
1578
                // Something is wrong if SignalDependents returns an error.
×
NEW
1579
                log.Errorf("SignalDependents returned error for msg=%v with "+
×
NEW
1580
                        "JobID=%v", spew.Sdump(nMsg.msg), jobID)
×
NEW
1581

×
NEW
1582
                nMsg.err <- err
×
NEW
1583

×
NEW
1584
                return
×
NEW
1585
        }
×
1586

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

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

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

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

1616
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1617
// false otherwise, This avoids expensive reprocessing of the message.
1618
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1619
        peerPub [33]byte) bool {
275✔
1620

275✔
1621
        var scid uint64
275✔
1622
        switch m := msg.(type) {
275✔
1623
        case *lnwire.ChannelUpdate1:
44✔
1624
                scid = m.ShortChannelID.ToUint64()
44✔
1625

1626
        case *lnwire.ChannelAnnouncement1:
219✔
1627
                scid = m.ShortChannelID.ToUint64()
219✔
1628

1629
        default:
16✔
1630
                return false
16✔
1631
        }
1632

1633
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
261✔
1634
        return err != cache.ErrElementNotFound
261✔
1635
}
1636

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

30✔
1650
        var (
30✔
1651
                havePublicChannels bool
30✔
1652
                edgesToUpdate      []updateTuple
30✔
1653
        )
30✔
1654
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
30✔
1655
                info *models.ChannelEdgeInfo,
30✔
1656
                edge *models.ChannelEdgePolicy) error {
34✔
1657

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

1669
                // We make a note that we have at least one public channel. We
1670
                // use this to determine whether we should send a node
1671
                // announcement below.
1672
                havePublicChannels = true
3✔
1673

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

×
1683
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1684
                                info: info,
×
1685
                                edge: edge,
×
1686
                        })
×
1687
                        return nil
×
1688
                }
×
1689

1690
                timeElapsed := now.Sub(edge.LastUpdate)
3✔
1691

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

1702
                return nil
3✔
1703
        })
1704
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
30✔
1705
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1706
                        err)
×
1707
        }
×
1708

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

1720
                // If we have a valid announcement to transmit, then we'll send
1721
                // that along with the update.
1722
                if chanAnn != nil {
2✔
1723
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1724
                }
1✔
1725

1726
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1727
        }
1728

1729
        // If we don't have any public channels, we return as we don't want to
1730
        // broadcast anything that would reveal our existence.
1731
        if !havePublicChannels {
59✔
1732
                return nil
29✔
1733
        }
29✔
1734

1735
        // We'll also check that our NodeAnnouncement is not too old.
1736
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
3✔
1737
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
3✔
1738
        timeElapsed := now.Sub(timestamp)
3✔
1739

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

1750
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1751
                nodeAnnStr = " and our refreshed node announcement"
1✔
1752

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

1761
        // If we don't have any updates to re-broadcast, then we'll exit
1762
        // early.
1763
        if len(signedUpdates) == 0 {
5✔
1764
                return nil
2✔
1765
        }
2✔
1766

1767
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1768
                len(edgesToUpdate), nodeAnnStr)
1✔
1769

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

1776
        return nil
1✔
1777
}
1778

1779
// processChanPolicyUpdate generates a new set of channel updates for the
1780
// provided list of edges and updates the backing ChannelGraphSource.
1781
func (d *AuthenticatedGossiper) processChanPolicyUpdate(
1782
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
3✔
1783

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

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

3✔
1810
                        var defaultAlias lnwire.ShortChannelID
3✔
1811
                        foundAlias, _ := d.cfg.GetAlias(chanID)
3✔
1812
                        if foundAlias != defaultAlias {
5✔
1813
                                chanUpdate.ShortChannelID = foundAlias
2✔
1814

2✔
1815
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
2✔
1816
                                if err != nil {
2✔
1817
                                        log.Errorf("Unable to sign alias "+
×
1818
                                                "update: %v", err)
×
1819
                                        continue
×
1820
                                }
1821

1822
                                lnSig, err := lnwire.NewSigFromSignature(sig)
2✔
1823
                                if err != nil {
2✔
1824
                                        log.Errorf("Unable to create sig: %v",
×
1825
                                                err)
×
1826
                                        continue
×
1827
                                }
1828

1829
                                chanUpdate.Signature = lnSig
2✔
1830
                        }
1831

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

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

1857
        return chanUpdates, nil
3✔
1858
}
1859

1860
// remotePubFromChanInfo returns the public key of the remote peer given a
1861
// ChannelEdgeInfo that describe a channel we have with them.
1862
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1863
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
14✔
1864

14✔
1865
        var remotePubKey [33]byte
14✔
1866
        switch {
14✔
1867
        case chanFlags&lnwire.ChanUpdateDirection == 0:
14✔
1868
                remotePubKey = chanInfo.NodeKey2Bytes
14✔
1869
        case chanFlags&lnwire.ChanUpdateDirection == 1:
2✔
1870
                remotePubKey = chanInfo.NodeKey1Bytes
2✔
1871
        }
1872

1873
        return remotePubKey
14✔
1874
}
1875

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

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

1896
        // The edge is in the graph, and has a proof attached, then we'll just
1897
        // reject it as normal.
1898
        if chanInfo.AuthProof != nil {
4✔
1899
                return nil, nil
2✔
1900
        }
2✔
1901

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

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

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

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

×
1957
        }
×
1958

1959
        return announcements, nil
×
1960
}
1961

1962
// fetchPKScript fetches the output script for the given SCID.
1963
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
1964
        []byte, error) {
×
1965

×
1966
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
1967
}
×
1968

1969
// addNode processes the given node announcement, and adds it to our channel
1970
// graph.
1971
func (d *AuthenticatedGossiper) addNode(msg *lnwire.NodeAnnouncement,
1972
        op ...batch.SchedulerOption) error {
19✔
1973

19✔
1974
        if err := graph.ValidateNodeAnn(msg); err != nil {
20✔
1975
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
1976
                        err)
1✔
1977
        }
1✔
1978

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

18✔
1993
        return d.cfg.Graph.AddNode(node, op...)
18✔
1994
}
1995

1996
// isPremature decides whether a given network message has a block height+delta
1997
// value specified in the future. If so, the message will be added to the
1998
// future message map and be processed when the block height as reached.
1999
//
2000
// NOTE: must be used inside a lock.
2001
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2002
        delta uint32, msg *networkMsg) bool {
281✔
2003
        // TODO(roasbeef) make height delta 6
281✔
2004
        //  * or configurable
281✔
2005

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

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

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

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

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

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

2✔
2045
        return true
2✔
2046
}
2047

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

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

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

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

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

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

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

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

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

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

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

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

×
2143
                return nil
×
2144

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

2150
        default:
1✔
2151
        }
2152

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

1✔
2156
        return nil
1✔
2157
}
2158

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2338
                return false
×
2339
        }
×
2340

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

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

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

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

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

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

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

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

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

×
UNCOV
2411
                        log.Error(err)
×
UNCOV
2412
                }
×
2413

2414
                nMsg.err <- err
2✔
2415
                return nil, false
2✔
2416
        }
2417

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

2429
        var announcements []networkMsg
18✔
2430

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

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

18✔
2448
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
18✔
2449
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
18✔
2450

18✔
2451
        return announcements, true
18✔
2452
}
2453

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

232✔
2459
        scid := ann.ShortChannelID
232✔
2460

232✔
2461
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
232✔
2462
                nMsg.peer, scid.ToUint64())
232✔
2463

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

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

×
2478
                nMsg.err <- err
×
2479
                return nil, false
×
2480
        }
×
2481

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

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

×
2495
                nMsg.err <- err
×
2496
                return nil, false
×
2497
        }
×
2498

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

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

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

×
2527
                return nil, false
×
2528
        }
×
2529

2530
        if closed {
231✔
2531
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2532
                log.Error(err)
1✔
2533

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

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

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

×
2552
                        return nil, false
×
2553
                }
×
2554

2555
                if shouldDc {
1✔
2556
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2557
                }
×
2558

2559
                nMsg.err <- err
1✔
2560

1✔
2561
                return nil, false
1✔
2562
        }
2563

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

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

×
2579
                        log.Error(err)
×
2580
                        nMsg.err <- err
×
2581
                        return nil, false
×
2582
                }
×
2583

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

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

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

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

2627
                // Optional tapscript root for custom channels.
2628
                edge.TapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
16✔
2629
        }
2630

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

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

204✔
2647
                defer d.channelMtx.Unlock(scid.ToUint64())
204✔
2648

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

×
2665
                                nMsg.err <- rErr
×
2666
                                return nil, false
×
2667
                        }
×
2668

2669
                        log.Debugf("Extracted %v announcements from rejected "+
2✔
2670
                                "msgs", len(anns))
2✔
2671

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

2✔
2680
                        return anns, true
2✔
2681

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

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

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

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

×
2717
                                nMsg.err <- dbErr
×
2718

×
2719
                                return nil, false
×
2720
                        }
×
2721

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

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

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

×
2743
                        return nil, false
×
2744
                }
×
2745

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

×
2752
                        return nil, false
×
2753
                }
×
2754

2755
                if shouldDc {
203✔
2756
                        nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2757
                }
1✔
2758

2759
                nMsg.err <- err
202✔
2760

202✔
2761
                return nil, false
202✔
2762
        }
2763

2764
        // If err is nil, release the lock immediately.
2765
        d.channelMtx.Unlock(scid.ToUint64())
27✔
2766

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

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

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

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

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

4✔
2796
                d.wg.Add(1)
4✔
2797
                go func(updMsg *networkMsg) {
8✔
2798
                        defer d.wg.Done()
4✔
2799

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

4✔
2808
                                select {
4✔
2809
                                case d.networkMsgs <- updMsg:
4✔
2810
                                case <-d.quit:
×
2811
                                        updMsg.err <- ErrGossiperShuttingDown
×
2812
                                }
2813

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

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

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

2837
        nMsg.err <- nil
27✔
2838

27✔
2839
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
27✔
2840
                nMsg.peer, scid.ToUint64())
27✔
2841

27✔
2842
        return announcements, true
27✔
2843
}
2844

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

57✔
2850
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
57✔
2851
                nMsg.peer, upd.ShortChannelID.ToUint64())
57✔
2852

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

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

×
2866
                nMsg.err <- err
×
2867
                return nil, false
×
2868
        }
×
2869

2870
        blockHeight := upd.ShortChannelID.BlockHeight
57✔
2871
        shortChanID := upd.ShortChannelID.ToUint64()
57✔
2872

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

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

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

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

2908
        if d.cfg.Graph.IsStaleEdgePolicy(
57✔
2909
                graphScid, timestamp, upd.ChannelFlags,
57✔
2910
        ) {
61✔
2911

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

4✔
2917
                nMsg.err <- nil
4✔
2918
                return nil, true
4✔
2919
        }
4✔
2920

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

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

×
2934
                return nil, false
×
2935
        }
×
2936

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

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

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

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

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

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

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

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

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

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

×
3033
                return nil, false
×
3034
        }
3035

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

3053
        log.Debugf("Validating ChannelUpdate: channel=%v, from node=%x, has "+
51✔
3054
                "edge=%v", chanInfo.ChannelID, pubKey.SerializeCompressed(),
51✔
3055
                edgeToUpdate != nil)
51✔
3056

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

4✔
3066
                log.Error(rErr)
4✔
3067
                nMsg.err <- rErr
4✔
3068
                return nil, false
4✔
3069
        }
4✔
3070

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

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

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

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

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

×
3162
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3163
                                shortChanID, err)
×
3164
                }
×
3165

3166
                nMsg.err <- err
2✔
3167
                return nil, false
2✔
3168
        }
3169

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

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

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

3201
                                upd.Signature = lnSig
2✔
3202
                        }
3203
                }
3204

3205
                // Get our peer's public key.
3206
                remotePubKey := remotePubFromChanInfo(
13✔
3207
                        chanInfo, upd.ChannelFlags,
13✔
3208
                )
13✔
3209

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

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

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

3241
        nMsg.err <- nil
41✔
3242

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

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

23✔
3253
        needBlockHeight := ann.ShortChannelID.BlockHeight +
23✔
3254
                d.cfg.ProofMatureDelta
23✔
3255
        shortChanID := ann.ShortChannelID.ToUint64()
23✔
3256

23✔
3257
        prefix := "local"
23✔
3258
        if nMsg.isRemote {
36✔
3259
                prefix = "remote"
13✔
3260
        }
13✔
3261

3262
        log.Infof("Received new %v announcement signature for %v", prefix,
23✔
3263
                ann.ShortChannelID)
23✔
3264

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

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

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

2✔
3302
                        return nil, false
2✔
3303
                }
2✔
3304

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

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

3321
        nodeID := nMsg.source.SerializeCompressed()
22✔
3322
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
22✔
3323
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
22✔
3324

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

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

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

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

3✔
3370
                        d.wg.Add(1)
3✔
3371
                        go func() {
6✔
3372
                                defer d.wg.Done()
3✔
3373

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

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

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

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

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

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

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

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

11✔
3435
                nMsg.err <- nil
11✔
3436
                return nil, false
11✔
3437
        }
3438

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

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

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

×
3471
                log.Error(err)
×
3472
                nMsg.err <- err
×
3473
                return nil, false
×
3474
        }
×
3475

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

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

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

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

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

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

3563
        nMsg.err <- nil
12✔
3564
        return announcements, true
12✔
3565
}
3566

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

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

205✔
3578
        pubkeySer := pubkey.SerializeCompressed()
205✔
3579

205✔
3580
        var pubkeyBytes [33]byte
205✔
3581
        copy(pubkeyBytes[:], pubkeySer)
205✔
3582

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

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

3597
        return false, nil
204✔
3598
}
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