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

lightningnetwork / lnd / 12430728843

20 Dec 2024 11:36AM UTC coverage: 61.336% (+2.6%) from 58.716%
12430728843

Pull #8777

github

ziggie1984
channeldb: fix typo.
Pull Request #8777: multi: make reassignment of alias channel edge atomic

161 of 213 new or added lines in 7 files covered. (75.59%)

70 existing lines in 17 files now uncovered.

23369 of 38100 relevant lines covered (61.34%)

115813.77 hits per line

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

80.6
/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) {
51✔
94
        for _, optionalMsgField := range optionalMsgFields {
60✔
95
                optionalMsgField(f)
9✔
96
        }
9✔
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) {
34✔
108
                f.capacity = &capacity
5✔
109
        }
5✔
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) {
40✔
116
                f.channelPoint = &op
8✔
117
        }
8✔
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) {
32✔
124
                f.tapscriptRoot = root
4✔
125
        }
4✔
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) {
32✔
136
                f.remoteAlias = alias
4✔
137
        }
4✔
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) {
6✔
382
        return uint64(len(c.msgs)), nil
6✔
383
}
6✔
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 {
466✔
394
        k := rejectCacheKey{
466✔
395
                chanID: cid,
466✔
396
                pubkey: pub,
466✔
397
        }
466✔
398

466✔
399
        return k
466✔
400
}
466✔
401

402
// sourceToPub returns a serialized-compressed public key for use in the reject
403
// cache.
404
func sourceToPub(pk *btcec.PublicKey) [33]byte {
480✔
405
        var pub [33]byte
480✔
406
        copy(pub[:], pk.SerializeCompressed())
480✔
407
        return pub
480✔
408
}
480✔
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
        sync.Mutex
516
}
517

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

31✔
540
        gossiper.syncMgr = newSyncManager(&SyncManagerCfg{
31✔
541
                ChainHash:               cfg.ChainHash,
31✔
542
                ChanSeries:              cfg.ChanSeries,
31✔
543
                RotateTicker:            cfg.RotateTicker,
31✔
544
                HistoricalSyncTicker:    cfg.HistoricalSyncTicker,
31✔
545
                NumActiveSyncers:        cfg.NumActiveSyncers,
31✔
546
                NoTimestampQueries:      cfg.NoTimestampQueries,
31✔
547
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalFilters,
31✔
548
                BestHeight:              gossiper.latestHeight,
31✔
549
                PinnedSyncers:           cfg.PinnedSyncers,
31✔
550
                IsStillZombieChannel:    cfg.IsStillZombieChannel,
31✔
551
        })
31✔
552

31✔
553
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
31✔
554
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
31✔
555
                NotifyWhenOffline: cfg.NotifyWhenOffline,
31✔
556
                MessageStore:      cfg.MessageStore,
31✔
557
                IsMsgStale:        gossiper.isMsgStale,
31✔
558
        })
31✔
559

31✔
560
        return gossiper
31✔
561
}
31✔
562

563
// EdgeWithInfo contains the information that is required to update an edge.
564
type EdgeWithInfo struct {
565
        // Info describes the channel.
566
        Info *models.ChannelEdgeInfo
567

568
        // Edge describes the policy in one direction of the channel.
569
        Edge *models.ChannelEdgePolicy
570
}
571

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

5✔
581
        errChan := make(chan error, 1)
5✔
582
        policyUpdate := &chanPolicyUpdateRequest{
5✔
583
                edgesToUpdate: edgesToUpdate,
5✔
584
                errChan:       errChan,
5✔
585
        }
5✔
586

5✔
587
        select {
5✔
588
        case d.chanPolicyUpdates <- policyUpdate:
5✔
589
                err := <-errChan
5✔
590
                return err
5✔
591
        case <-d.quit:
×
592
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
593
        }
594
}
595

596
// Start spawns network messages handler goroutine and registers on new block
597
// notifications in order to properly handle the premature announcements.
598
func (d *AuthenticatedGossiper) Start() error {
31✔
599
        var err error
31✔
600
        d.started.Do(func() {
62✔
601
                log.Info("Authenticated Gossiper starting")
31✔
602
                err = d.start()
31✔
603
        })
31✔
604
        return err
31✔
605
}
606

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

31✔
617
        height, err := d.cfg.Graph.CurrentBlockHeight()
31✔
618
        if err != nil {
31✔
619
                return err
×
620
        }
×
621
        d.bestHeight = height
31✔
622

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

630
        d.syncMgr.Start()
31✔
631

31✔
632
        d.banman.start()
31✔
633

31✔
634
        // Start receiving blocks in its dedicated goroutine.
31✔
635
        d.wg.Add(2)
31✔
636
        go d.syncBlockHeight()
31✔
637
        go d.networkHandler()
31✔
638

31✔
639
        return nil
31✔
640
}
641

642
// syncBlockHeight syncs the best block height for the gossiper by reading
643
// blockEpochs.
644
//
645
// NOTE: must be run as a goroutine.
646
func (d *AuthenticatedGossiper) syncBlockHeight() {
31✔
647
        defer d.wg.Done()
31✔
648

31✔
649
        for {
62✔
650
                select {
31✔
651
                // A new block has arrived, so we can re-process the previously
652
                // premature announcements.
653
                case newBlock, ok := <-d.blockEpochs.Epochs:
4✔
654
                        // If the channel has been closed, then this indicates
4✔
655
                        // the daemon is shutting down, so we exit ourselves.
4✔
656
                        if !ok {
8✔
657
                                return
4✔
658
                        }
4✔
659

660
                        // Once a new block arrives, we update our running
661
                        // track of the height of the chain tip.
662
                        d.Lock()
4✔
663
                        blockHeight := uint32(newBlock.Height)
4✔
664
                        d.bestHeight = blockHeight
4✔
665
                        d.Unlock()
4✔
666

4✔
667
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
4✔
668
                                newBlock.Hash)
4✔
669

4✔
670
                        // Resend future messages, if any.
4✔
671
                        d.resendFutureMessages(blockHeight)
4✔
672

673
                case <-d.quit:
27✔
674
                        return
27✔
675
                }
676
        }
677
}
678

679
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
680
// the unique ID when saving the message.
681
type futureMsgCache struct {
682
        *lru.Cache[uint64, *cachedFutureMsg]
683

684
        // msgID is a monotonically increased integer.
685
        msgID atomic.Uint64
686
}
687

688
// nextMsgID returns a unique message ID.
689
func (f *futureMsgCache) nextMsgID() uint64 {
4✔
690
        return f.msgID.Add(1)
4✔
691
}
4✔
692

693
// newFutureMsgCache creates a new future message cache with the underlying lru
694
// cache being initialized with the specified capacity.
695
func newFutureMsgCache(capacity uint64) *futureMsgCache {
32✔
696
        // Create a new cache.
32✔
697
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
32✔
698

32✔
699
        return &futureMsgCache{
32✔
700
                Cache: cache,
32✔
701
        }
32✔
702
}
32✔
703

704
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
705
type cachedFutureMsg struct {
706
        // msg is the network message.
707
        msg *networkMsg
708

709
        // height is the block height.
710
        height uint32
711
}
712

713
// Size returns the size of the message.
714
func (c *cachedFutureMsg) Size() (uint64, error) {
5✔
715
        // Return a constant 1.
5✔
716
        return 1, nil
5✔
717
}
5✔
718

719
// resendFutureMessages takes a block height, resends all the future messages
720
// found below and equal to that height and deletes those messages found in the
721
// gossiper's futureMsgs.
722
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
4✔
723
        var (
4✔
724
                // msgs are the target messages.
4✔
725
                msgs []*networkMsg
4✔
726

4✔
727
                // keys are the target messages' caching keys.
4✔
728
                keys []uint64
4✔
729
        )
4✔
730

4✔
731
        // filterMsgs is the visitor used when iterating the future cache.
4✔
732
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
5✔
733
                if cmsg.height <= height {
2✔
734
                        msgs = append(msgs, cmsg.msg)
1✔
735
                        keys = append(keys, k)
1✔
736
                }
1✔
737

738
                return true
1✔
739
        }
740

741
        // Filter out the target messages.
742
        d.futureMsgs.Range(filterMsgs)
4✔
743

4✔
744
        // Return early if no messages found.
4✔
745
        if len(msgs) == 0 {
8✔
746
                return
4✔
747
        }
4✔
748

749
        // Remove the filtered messages.
750
        for _, key := range keys {
2✔
751
                d.futureMsgs.Delete(key)
1✔
752
        }
1✔
753

754
        log.Debugf("Resending %d network messages at height %d",
1✔
755
                len(msgs), height)
1✔
756

1✔
757
        for _, msg := range msgs {
2✔
758
                select {
1✔
759
                case d.networkMsgs <- msg:
1✔
760
                case <-d.quit:
×
761
                        msg.err <- ErrGossiperShuttingDown
×
762
                }
763
        }
764
}
765

766
// Stop signals any active goroutines for a graceful closure.
767
func (d *AuthenticatedGossiper) Stop() error {
32✔
768
        d.stopped.Do(func() {
63✔
769
                log.Info("Authenticated gossiper shutting down...")
31✔
770
                defer log.Debug("Authenticated gossiper shutdown complete")
31✔
771

31✔
772
                d.stop()
31✔
773
        })
31✔
774
        return nil
32✔
775
}
776

777
func (d *AuthenticatedGossiper) stop() {
31✔
778
        log.Debug("Authenticated Gossiper is stopping")
31✔
779
        defer log.Debug("Authenticated Gossiper stopped")
31✔
780

31✔
781
        // `blockEpochs` is only initialized in the start routine so we make
31✔
782
        // sure we don't panic here in the case where the `Stop` method is
31✔
783
        // called when the `Start` method does not complete.
31✔
784
        if d.blockEpochs != nil {
62✔
785
                d.blockEpochs.Cancel()
31✔
786
        }
31✔
787

788
        d.syncMgr.Stop()
31✔
789

31✔
790
        d.banman.stop()
31✔
791

31✔
792
        close(d.quit)
31✔
793
        d.wg.Wait()
31✔
794

31✔
795
        // We'll stop our reliable sender after all of the gossiper's goroutines
31✔
796
        // have exited to ensure nothing can cause it to continue executing.
31✔
797
        d.reliableSender.Stop()
31✔
798
}
799

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

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

288✔
811
        errChan := make(chan error, 1)
288✔
812

288✔
813
        // For messages in the known set of channel series queries, we'll
288✔
814
        // dispatch the message directly to the GossipSyncer, and skip the main
288✔
815
        // processing loop.
288✔
816
        switch m := msg.(type) {
288✔
817
        case *lnwire.QueryShortChanIDs,
818
                *lnwire.QueryChannelRange,
819
                *lnwire.ReplyChannelRange,
820
                *lnwire.ReplyShortChanIDsEnd:
4✔
821

4✔
822
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
4✔
823
                if !ok {
4✔
824
                        log.Warnf("Gossip syncer for peer=%x not found",
×
825
                                peer.PubKey())
×
826

×
827
                        errChan <- ErrGossipSyncerNotFound
×
828
                        return errChan
×
829
                }
×
830

831
                // If we've found the message target, then we'll dispatch the
832
                // message directly to it.
833
                syncer.ProcessQueryMsg(m, peer.QuitSignal())
4✔
834

4✔
835
                errChan <- nil
4✔
836
                return errChan
4✔
837

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

×
846
                        errChan <- ErrGossipSyncerNotFound
×
847
                        return errChan
×
848
                }
×
849

850
                // If we've found the message target, then we'll dispatch the
851
                // message directly to it.
852
                if err := syncer.ApplyGossipFilter(m); err != nil {
4✔
853
                        log.Warnf("Unable to apply gossip filter for peer=%x: "+
×
854
                                "%v", peer.PubKey(), err)
×
855

×
856
                        errChan <- err
×
857
                        return errChan
×
858
                }
×
859

860
                errChan <- nil
4✔
861
                return errChan
4✔
862

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

223✔
871
                if bytes.Equal(m.NodeID1[:], ownKey) ||
223✔
872
                        bytes.Equal(m.NodeID2[:], ownKey) {
229✔
873

6✔
874
                        log.Warn(ownErr)
6✔
875
                        errChan <- ownErr
6✔
876
                        return errChan
6✔
877
                }
6✔
878
        }
879

880
        nMsg := &networkMsg{
286✔
881
                msg:      msg,
286✔
882
                isRemote: true,
286✔
883
                peer:     peer,
286✔
884
                source:   peer.IdentityKey(),
286✔
885
                err:      errChan,
286✔
886
        }
286✔
887

286✔
888
        select {
286✔
889
        case d.networkMsgs <- nMsg:
286✔
890

891
        // If the peer that sent us this error is quitting, then we don't need
892
        // to send back an error and can return immediately.
893
        case <-peer.QuitSignal():
×
894
                return nil
×
895
        case <-d.quit:
1✔
896
                nMsg.err <- ErrGossiperShuttingDown
1✔
897
        }
898

899
        return nMsg.err
286✔
900
}
901

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

51✔
912
        optionalMsgFields := &optionalMsgFields{}
51✔
913
        optionalMsgFields.apply(optionalFields...)
51✔
914

51✔
915
        nMsg := &networkMsg{
51✔
916
                msg:               msg,
51✔
917
                optionalMsgFields: optionalMsgFields,
51✔
918
                isRemote:          false,
51✔
919
                source:            d.selfKey,
51✔
920
                err:               make(chan error, 1),
51✔
921
        }
51✔
922

51✔
923
        select {
51✔
924
        case d.networkMsgs <- nMsg:
51✔
925
        case <-d.quit:
×
926
                nMsg.err <- ErrGossiperShuttingDown
×
927
        }
928

929
        return nMsg.err
51✔
930
}
931

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

940
        // Flags least-significant bit must be set to 0 if the creating node
941
        // corresponds to the first node in the previously sent channel
942
        // announcement and 1 otherwise.
943
        flags lnwire.ChanUpdateChanFlags
944
}
945

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

954
        // isLocal is true if this was a message that originated locally. We'll
955
        // use this to bypass our normal checks to ensure we prioritize sending
956
        // out our own updates.
957
        isLocal bool
958

959
        // sender is the set of peers that sent us this message.
960
        senders map[route.Vertex]struct{}
961
}
962

963
// mergeSyncerMap is used to merge the set of senders of a particular message
964
// with peers that we have an active GossipSyncer with. We do this to ensure
965
// that we don't broadcast messages to any peers that we have active gossip
966
// syncers for.
967
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
28✔
968
        for peerPub := range syncers {
32✔
969
                m.senders[peerPub] = struct{}{}
4✔
970
        }
4✔
971
}
972

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

984
        // channelUpdates are identified by the channel update id field.
985
        channelUpdates map[channelUpdateID]msgWithSenders
986

987
        // nodeAnnouncements are identified by the Vertex field.
988
        nodeAnnouncements map[route.Vertex]msgWithSenders
989

990
        sync.Mutex
991
}
992

993
// Reset operates on deDupedAnnouncements to reset the storage of
994
// announcements.
995
func (d *deDupedAnnouncements) Reset() {
33✔
996
        d.Lock()
33✔
997
        defer d.Unlock()
33✔
998

33✔
999
        d.reset()
33✔
1000
}
33✔
1001

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

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

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

1027
        // Channel announcements are identified by the short channel id field.
1028
        case *lnwire.ChannelAnnouncement1:
26✔
1029
                deDupKey := msg.ShortChannelID
26✔
1030
                sender := route.NewVertex(message.source)
26✔
1031

26✔
1032
                mws, ok := d.channelAnnouncements[deDupKey]
26✔
1033
                if !ok {
51✔
1034
                        mws = msgWithSenders{
25✔
1035
                                msg:     msg,
25✔
1036
                                isLocal: !message.isRemote,
25✔
1037
                                senders: make(map[route.Vertex]struct{}),
25✔
1038
                        }
25✔
1039
                        mws.senders[sender] = struct{}{}
25✔
1040

25✔
1041
                        d.channelAnnouncements[deDupKey] = mws
25✔
1042

25✔
1043
                        return
25✔
1044
                }
25✔
1045

1046
                mws.msg = msg
1✔
1047
                mws.senders[sender] = struct{}{}
1✔
1048
                d.channelAnnouncements[deDupKey] = mws
1✔
1049

1050
        // Channel updates are identified by the (short channel id,
1051
        // channelflags) tuple.
1052
        case *lnwire.ChannelUpdate1:
46✔
1053
                sender := route.NewVertex(message.source)
46✔
1054
                deDupKey := channelUpdateID{
46✔
1055
                        msg.ShortChannelID,
46✔
1056
                        msg.ChannelFlags,
46✔
1057
                }
46✔
1058

46✔
1059
                oldTimestamp := uint32(0)
46✔
1060
                mws, ok := d.channelUpdates[deDupKey]
46✔
1061
                if ok {
49✔
1062
                        // If we already have seen this message, record its
3✔
1063
                        // timestamp.
3✔
1064
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1065
                        if !ok {
3✔
1066
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1067
                                        "got: %T", mws.msg)
×
1068

×
1069
                                return
×
1070
                        }
×
1071

1072
                        oldTimestamp = update.Timestamp
3✔
1073
                }
1074

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

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

44✔
1093
                        // We'll mark the sender of the message in the
44✔
1094
                        // senders map.
44✔
1095
                        mws.senders[sender] = struct{}{}
44✔
1096

44✔
1097
                        d.channelUpdates[deDupKey] = mws
44✔
1098

44✔
1099
                        return
44✔
1100
                }
44✔
1101

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

1110
        // Node announcements are identified by the Vertex field.  Use the
1111
        // NodeID to create the corresponding Vertex.
1112
        case *lnwire.NodeAnnouncement:
26✔
1113
                sender := route.NewVertex(message.source)
26✔
1114
                deDupKey := route.Vertex(msg.NodeID)
26✔
1115

26✔
1116
                // We do the same for node announcements as we did for channel
26✔
1117
                // updates, as they also carry a timestamp.
26✔
1118
                oldTimestamp := uint32(0)
26✔
1119
                mws, ok := d.nodeAnnouncements[deDupKey]
26✔
1120
                if ok {
35✔
1121
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
9✔
1122
                }
9✔
1123

1124
                // Discard the message if it's old.
1125
                if oldTimestamp > msg.Timestamp {
30✔
1126
                        return
4✔
1127
                }
4✔
1128

1129
                // Replace if it's newer.
1130
                if oldTimestamp < msg.Timestamp {
48✔
1131
                        mws = msgWithSenders{
22✔
1132
                                msg:     msg,
22✔
1133
                                isLocal: !message.isRemote,
22✔
1134
                                senders: make(map[route.Vertex]struct{}),
22✔
1135
                        }
22✔
1136

22✔
1137
                        mws.senders[sender] = struct{}{}
22✔
1138

22✔
1139
                        d.nodeAnnouncements[deDupKey] = mws
22✔
1140

22✔
1141
                        return
22✔
1142
                }
22✔
1143

1144
                // Add to senders map if it's the same as we had.
1145
                mws.msg = msg
8✔
1146
                mws.senders[sender] = struct{}{}
8✔
1147
                d.nodeAnnouncements[deDupKey] = mws
8✔
1148
        }
1149
}
1150

1151
// AddMsgs is a helper method to add multiple messages to the announcement
1152
// batch.
1153
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
58✔
1154
        d.Lock()
58✔
1155
        defer d.Unlock()
58✔
1156

58✔
1157
        for _, msg := range msgs {
148✔
1158
                d.addMsg(msg)
90✔
1159
        }
90✔
1160
}
1161

1162
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1163
// to broadcast next into messages that are locally sourced and those that are
1164
// sourced remotely.
1165
type msgsToBroadcast struct {
1166
        // localMsgs is the set of messages we created locally.
1167
        localMsgs []msgWithSenders
1168

1169
        // remoteMsgs is the set of messages that we received from a remote
1170
        // party.
1171
        remoteMsgs []msgWithSenders
1172
}
1173

1174
// addMsg adds a new message to the appropriate sub-slice.
1175
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
75✔
1176
        if msg.isLocal {
126✔
1177
                m.localMsgs = append(m.localMsgs, msg)
51✔
1178
        } else {
79✔
1179
                m.remoteMsgs = append(m.remoteMsgs, msg)
28✔
1180
        }
28✔
1181
}
1182

1183
// isEmpty returns true if the batch is empty.
1184
func (m *msgsToBroadcast) isEmpty() bool {
290✔
1185
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
290✔
1186
}
290✔
1187

1188
// length returns the length of the combined message set.
1189
func (m *msgsToBroadcast) length() int {
1✔
1190
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1191
}
1✔
1192

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

291✔
1203
        // Get the total number of announcements.
291✔
1204
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
291✔
1205
                len(d.nodeAnnouncements)
291✔
1206

291✔
1207
        // Create an empty array of lnwire.Messages with a length equal to
291✔
1208
        // the total number of announcements.
291✔
1209
        msgs := msgsToBroadcast{
291✔
1210
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
291✔
1211
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
291✔
1212
        }
291✔
1213

291✔
1214
        // Add the channel announcements to the array first.
291✔
1215
        for _, message := range d.channelAnnouncements {
313✔
1216
                msgs.addMsg(message)
22✔
1217
        }
22✔
1218

1219
        // Then add the channel updates.
1220
        for _, message := range d.channelUpdates {
331✔
1221
                msgs.addMsg(message)
40✔
1222
        }
40✔
1223

1224
        // Finally add the node announcements.
1225
        for _, message := range d.nodeAnnouncements {
312✔
1226
                msgs.addMsg(message)
21✔
1227
        }
21✔
1228

1229
        d.reset()
291✔
1230

291✔
1231
        // Return the array of lnwire.messages.
291✔
1232
        return msgs
291✔
1233
}
1234

1235
// calculateSubBatchSize is a helper function that calculates the size to break
1236
// down the batchSize into.
1237
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1238
        minimumBatchSize, batchSize int) int {
17✔
1239
        if subBatchDelay > totalDelay {
19✔
1240
                return batchSize
2✔
1241
        }
2✔
1242

1243
        subBatchSize := (batchSize*int(subBatchDelay) +
15✔
1244
                int(totalDelay) - 1) / int(totalDelay)
15✔
1245

15✔
1246
        if subBatchSize < minimumBatchSize {
20✔
1247
                return minimumBatchSize
5✔
1248
        }
5✔
1249

1250
        return subBatchSize
10✔
1251
}
1252

1253
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1254
// this variable so the function can be mocked in our test.
1255
var batchSizeCalculator = calculateSubBatchSize
1256

1257
// splitAnnouncementBatches takes an exiting list of announcements and
1258
// decomposes it into sub batches controlled by the `subBatchSize`.
1259
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1260
        announcementBatch []msgWithSenders) [][]msgWithSenders {
73✔
1261

73✔
1262
        subBatchSize := batchSizeCalculator(
73✔
1263
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
73✔
1264
                d.cfg.MinimumBatchSize, len(announcementBatch),
73✔
1265
        )
73✔
1266

73✔
1267
        var splitAnnouncementBatch [][]msgWithSenders
73✔
1268

73✔
1269
        for subBatchSize < len(announcementBatch) {
198✔
1270
                // For slicing with minimal allocation
125✔
1271
                // https://github.com/golang/go/wiki/SliceTricks
125✔
1272
                announcementBatch, splitAnnouncementBatch =
125✔
1273
                        announcementBatch[subBatchSize:],
125✔
1274
                        append(splitAnnouncementBatch,
125✔
1275
                                announcementBatch[0:subBatchSize:subBatchSize])
125✔
1276
        }
125✔
1277
        splitAnnouncementBatch = append(
73✔
1278
                splitAnnouncementBatch, announcementBatch,
73✔
1279
        )
73✔
1280

73✔
1281
        return splitAnnouncementBatch
73✔
1282
}
1283

1284
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1285
// split size, and then sends out all items to the set of target peers. Locally
1286
// generated announcements are always sent before remotely generated
1287
// announcements.
1288
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(
1289
        annBatch msgsToBroadcast) {
35✔
1290

35✔
1291
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
35✔
1292
        // duration to delay the sending of next announcement batch.
35✔
1293
        delayNextBatch := func() {
101✔
1294
                select {
66✔
1295
                case <-time.After(d.cfg.SubBatchDelay):
49✔
1296
                case <-d.quit:
17✔
1297
                        return
17✔
1298
                }
1299
        }
1300

1301
        // Fetch the local and remote announcements.
1302
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
35✔
1303
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
35✔
1304

35✔
1305
        d.wg.Add(1)
35✔
1306
        go func() {
70✔
1307
                defer d.wg.Done()
35✔
1308

35✔
1309
                log.Debugf("Broadcasting %v new local announcements in %d "+
35✔
1310
                        "sub batches", len(annBatch.localMsgs),
35✔
1311
                        len(localBatches))
35✔
1312

35✔
1313
                // Send out the local announcements first.
35✔
1314
                for _, annBatch := range localBatches {
70✔
1315
                        d.sendLocalBatch(annBatch)
35✔
1316
                        delayNextBatch()
35✔
1317
                }
35✔
1318

1319
                log.Debugf("Broadcasting %v new remote announcements in %d "+
35✔
1320
                        "sub batches", len(annBatch.remoteMsgs),
35✔
1321
                        len(remoteBatches))
35✔
1322

35✔
1323
                // Now send the remote announcements.
35✔
1324
                for _, annBatch := range remoteBatches {
70✔
1325
                        d.sendRemoteBatch(annBatch)
35✔
1326
                        delayNextBatch()
35✔
1327
                }
35✔
1328
        }()
1329
}
1330

1331
// sendLocalBatch broadcasts a list of locally generated announcements to our
1332
// peers. For local announcements, we skip the filter and dedup logic and just
1333
// send the announcements out to all our coonnected peers.
1334
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
35✔
1335
        msgsToSend := lnutils.Map(
35✔
1336
                annBatch, func(m msgWithSenders) lnwire.Message {
82✔
1337
                        return m.msg
47✔
1338
                },
47✔
1339
        )
1340

1341
        err := d.cfg.Broadcast(nil, msgsToSend...)
35✔
1342
        if err != nil {
35✔
1343
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1344
        }
×
1345
}
1346

1347
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1348
// peers.
1349
func (d *AuthenticatedGossiper) sendRemoteBatch(annBatch []msgWithSenders) {
35✔
1350
        syncerPeers := d.syncMgr.GossipSyncers()
35✔
1351

35✔
1352
        // We'll first attempt to filter out this new message for all peers
35✔
1353
        // that have active gossip syncers active.
35✔
1354
        for pub, syncer := range syncerPeers {
39✔
1355
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
4✔
1356
                syncer.FilterGossipMsgs(annBatch...)
4✔
1357
        }
4✔
1358

1359
        for _, msgChunk := range annBatch {
63✔
1360
                msgChunk := msgChunk
28✔
1361

28✔
1362
                // With the syncers taken care of, we'll merge the sender map
28✔
1363
                // with the set of syncers, so we don't send out duplicate
28✔
1364
                // messages.
28✔
1365
                msgChunk.mergeSyncerMap(syncerPeers)
28✔
1366

28✔
1367
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
28✔
1368
                if err != nil {
28✔
1369
                        log.Errorf("Unable to send batch "+
×
1370
                                "announcements: %v", err)
×
1371
                        continue
×
1372
                }
1373
        }
1374
}
1375

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

31✔
1385
        // Initialize empty deDupedAnnouncements to store announcement batch.
31✔
1386
        announcements := deDupedAnnouncements{}
31✔
1387
        announcements.Reset()
31✔
1388

31✔
1389
        d.cfg.RetransmitTicker.Resume()
31✔
1390
        defer d.cfg.RetransmitTicker.Stop()
31✔
1391

31✔
1392
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
31✔
1393
        defer trickleTimer.Stop()
31✔
1394

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

1401
        // We'll use this validation to ensure that we process jobs in their
1402
        // dependency order during parallel validation.
1403
        validationBarrier := graph.NewValidationBarrier(1000, d.quit)
31✔
1404

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

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

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

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

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

25✔
1450
                                if emittedAnnouncements != nil {
39✔
1451
                                        announcements.AddMsgs(
14✔
1452
                                                emittedAnnouncements...,
14✔
1453
                                        )
14✔
1454
                                }
14✔
1455
                                continue
25✔
1456
                        }
1457

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

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

1470
                        // We'll set up any dependent, and wait until a free
1471
                        // slot for this job opens up, this allow us to not
1472
                        // have thousands of goroutines active.
1473
                        validationBarrier.InitJobDependencies(announcement.msg)
313✔
1474

313✔
1475
                        d.wg.Add(1)
313✔
1476
                        go d.handleNetworkMessages(
313✔
1477
                                announcement, &announcements, validationBarrier,
313✔
1478
                        )
313✔
1479

1480
                // The trickle timer has ticked, which indicates we should
1481
                // flush to the network the pending batch of new announcements
1482
                // we've received since the last trickle tick.
1483
                case <-trickleTimer.C:
290✔
1484
                        // Emit the current batch of announcements from
290✔
1485
                        // deDupedAnnouncements.
290✔
1486
                        announcementBatch := announcements.Emit()
290✔
1487

290✔
1488
                        // If the current announcements batch is nil, then we
290✔
1489
                        // have no further work here.
290✔
1490
                        if announcementBatch.isEmpty() {
549✔
1491
                                continue
259✔
1492
                        }
1493

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

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

1514
                // The gossiper has been signalled to exit, to we exit our
1515
                // main loop so the wait group can be decremented.
1516
                case <-d.quit:
31✔
1517
                        return
31✔
1518
                }
1519
        }
1520
}
1521

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

313✔
1530
        defer d.wg.Done()
313✔
1531
        defer vb.CompleteJob()
313✔
1532

313✔
1533
        // We should only broadcast this message forward if it originated from
313✔
1534
        // us or it wasn't received as part of our initial historical sync.
313✔
1535
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
313✔
1536

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

×
1544
                if !graph.IsError(
×
1545
                        err,
×
1546
                        graph.ErrVBarrierShuttingDown,
×
1547
                        graph.ErrParentValidationFailed,
×
1548
                ) {
×
1549

×
1550
                        log.Warnf("unexpected error during validation "+
×
1551
                                "barrier shutdown: %v", err)
×
1552
                }
×
1553
                nMsg.err <- err
×
1554

×
1555
                return
×
1556
        }
1557

1558
        // Process the network announcement to determine if this is either a
1559
        // new announcement from our PoV or an edges to a prior vertex/edge we
1560
        // previously proceeded.
1561
        newAnns, allow := d.processNetworkAnnouncement(nMsg)
313✔
1562

313✔
1563
        log.Tracef("Processed network message %s, returned "+
313✔
1564
                "len(announcements)=%v, allowDependents=%v",
313✔
1565
                nMsg.msg.MsgType(), len(newAnns), allow)
313✔
1566

313✔
1567
        // If this message had any dependencies, then we can now signal them to
313✔
1568
        // continue.
313✔
1569
        vb.SignalDependants(nMsg.msg, allow)
313✔
1570

313✔
1571
        // If the announcement was accepted, then add the emitted announcements
313✔
1572
        // to our announce batch to be broadcast once the trickle timer ticks
313✔
1573
        // gain.
313✔
1574
        if newAnns != nil && shouldBroadcast {
349✔
1575
                // TODO(roasbeef): exclude peer that sent.
36✔
1576
                deDuped.AddMsgs(newAnns...)
36✔
1577
        } else if newAnns != nil {
322✔
1578
                log.Trace("Skipping broadcast of announcements received " +
5✔
1579
                        "during initial graph sync")
5✔
1580
        }
5✔
1581
}
1582

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

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

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

1600
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1601
// false otherwise, This avoids expensive reprocessing of the message.
1602
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1603
        peerPub [33]byte) bool {
277✔
1604

277✔
1605
        var scid uint64
277✔
1606
        switch m := msg.(type) {
277✔
1607
        case *lnwire.ChannelUpdate1:
46✔
1608
                scid = m.ShortChannelID.ToUint64()
46✔
1609

1610
        case *lnwire.ChannelAnnouncement1:
221✔
1611
                scid = m.ShortChannelID.ToUint64()
221✔
1612

1613
        default:
18✔
1614
                return false
18✔
1615
        }
1616

1617
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
263✔
1618
        return err != cache.ErrElementNotFound
263✔
1619
}
1620

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

32✔
1634
        var (
32✔
1635
                havePublicChannels bool
32✔
1636
                edgesToUpdate      []updateTuple
32✔
1637
        )
32✔
1638
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
32✔
1639
                info *models.ChannelEdgeInfo,
32✔
1640
                edge *models.ChannelEdgePolicy) error {
38✔
1641

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

1653
                // We make a note that we have at least one public channel. We
1654
                // use this to determine whether we should send a node
1655
                // announcement below.
1656
                havePublicChannels = true
5✔
1657

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

×
1667
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1668
                                info: info,
×
1669
                                edge: edge,
×
1670
                        })
×
1671
                        return nil
×
1672
                }
×
1673

1674
                timeElapsed := now.Sub(edge.LastUpdate)
5✔
1675

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

1686
                return nil
5✔
1687
        })
1688
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
32✔
1689
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1690
                        err)
×
1691
        }
×
1692

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

1704
                // If we have a valid announcement to transmit, then we'll send
1705
                // that along with the update.
1706
                if chanAnn != nil {
2✔
1707
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1708
                }
1✔
1709

1710
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1711
        }
1712

1713
        // If we don't have any public channels, we return as we don't want to
1714
        // broadcast anything that would reveal our existence.
1715
        if !havePublicChannels {
63✔
1716
                return nil
31✔
1717
        }
31✔
1718

1719
        // We'll also check that our NodeAnnouncement is not too old.
1720
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
5✔
1721
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
5✔
1722
        timeElapsed := now.Sub(timestamp)
5✔
1723

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

1734
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1735
                nodeAnnStr = " and our refreshed node announcement"
1✔
1736

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

1745
        // If we don't have any updates to re-broadcast, then we'll exit
1746
        // early.
1747
        if len(signedUpdates) == 0 {
9✔
1748
                return nil
4✔
1749
        }
4✔
1750

1751
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1752
                len(edgesToUpdate), nodeAnnStr)
1✔
1753

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

1760
        return nil
1✔
1761
}
1762

1763
// processChanPolicyUpdate generates a new set of channel updates for the
1764
// provided list of edges and updates the backing ChannelGraphSource.
1765
func (d *AuthenticatedGossiper) processChanPolicyUpdate(
1766
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
5✔
1767

5✔
1768
        var chanUpdates []networkMsg
5✔
1769
        for _, edgeInfo := range edgesToUpdate {
12✔
1770
                // Now that we've collected all the channels we need to update,
7✔
1771
                // we'll re-sign and update the backing ChannelGraphSource, and
7✔
1772
                // retrieve our ChannelUpdate to broadcast.
7✔
1773
                _, chanUpdate, err := d.updateChannel(
7✔
1774
                        edgeInfo.Info, edgeInfo.Edge,
7✔
1775
                )
7✔
1776
                if err != nil {
7✔
1777
                        return nil, err
×
1778
                }
×
1779

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

5✔
1794
                        var defaultAlias lnwire.ShortChannelID
5✔
1795
                        foundAlias, _ := d.cfg.GetAlias(chanID)
5✔
1796
                        if foundAlias != defaultAlias {
9✔
1797
                                chanUpdate.ShortChannelID = foundAlias
4✔
1798

4✔
1799
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
4✔
1800
                                if err != nil {
4✔
1801
                                        log.Errorf("Unable to sign alias "+
×
1802
                                                "update: %v", err)
×
1803
                                        continue
×
1804
                                }
1805

1806
                                lnSig, err := lnwire.NewSigFromSignature(sig)
4✔
1807
                                if err != nil {
4✔
1808
                                        log.Errorf("Unable to create sig: %v",
×
1809
                                                err)
×
1810
                                        continue
×
1811
                                }
1812

1813
                                chanUpdate.Signature = lnSig
4✔
1814
                        }
1815

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

1832
                // We set ourselves as the source of this message to indicate
1833
                // that we shouldn't skip any peers when sending this message.
1834
                chanUpdates = append(chanUpdates, networkMsg{
6✔
1835
                        source:   d.selfKey,
6✔
1836
                        isRemote: false,
6✔
1837
                        msg:      chanUpdate,
6✔
1838
                })
6✔
1839
        }
1840

1841
        return chanUpdates, nil
5✔
1842
}
1843

1844
// remotePubFromChanInfo returns the public key of the remote peer given a
1845
// ChannelEdgeInfo that describe a channel we have with them.
1846
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1847
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
16✔
1848

16✔
1849
        var remotePubKey [33]byte
16✔
1850
        switch {
16✔
1851
        case chanFlags&lnwire.ChanUpdateDirection == 0:
16✔
1852
                remotePubKey = chanInfo.NodeKey2Bytes
16✔
1853
        case chanFlags&lnwire.ChanUpdateDirection == 1:
4✔
1854
                remotePubKey = chanInfo.NodeKey1Bytes
4✔
1855
        }
1856

1857
        return remotePubKey
16✔
1858
}
1859

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

4✔
1871
        // First, we'll fetch the state of the channel as we know if from the
4✔
1872
        // database.
4✔
1873
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
4✔
1874
                chanAnnMsg.ShortChannelID,
4✔
1875
        )
4✔
1876
        if err != nil {
4✔
1877
                return nil, err
×
1878
        }
×
1879

1880
        // The edge is in the graph, and has a proof attached, then we'll just
1881
        // reject it as normal.
1882
        if chanInfo.AuthProof != nil {
8✔
1883
                return nil, nil
4✔
1884
        }
4✔
1885

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

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

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

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

×
1941
        }
×
1942

1943
        return announcements, nil
×
1944
}
1945

1946
// fetchPKScript fetches the output script for the given SCID.
1947
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
1948
        []byte, error) {
×
1949

×
1950
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
1951
}
×
1952

1953
// addNode processes the given node announcement, and adds it to our channel
1954
// graph.
1955
func (d *AuthenticatedGossiper) addNode(msg *lnwire.NodeAnnouncement,
1956
        op ...batch.SchedulerOption) error {
21✔
1957

21✔
1958
        if err := graph.ValidateNodeAnn(msg); err != nil {
22✔
1959
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
1960
                        err)
1✔
1961
        }
1✔
1962

1963
        timestamp := time.Unix(int64(msg.Timestamp), 0)
20✔
1964
        features := lnwire.NewFeatureVector(msg.Features, lnwire.Features)
20✔
1965
        node := &models.LightningNode{
20✔
1966
                HaveNodeAnnouncement: true,
20✔
1967
                LastUpdate:           timestamp,
20✔
1968
                Addresses:            msg.Addresses,
20✔
1969
                PubKeyBytes:          msg.NodeID,
20✔
1970
                Alias:                msg.Alias.String(),
20✔
1971
                AuthSigBytes:         msg.Signature.ToSignatureBytes(),
20✔
1972
                Features:             features,
20✔
1973
                Color:                msg.RGBColor,
20✔
1974
                ExtraOpaqueData:      msg.ExtraOpaqueData,
20✔
1975
        }
20✔
1976

20✔
1977
        return d.cfg.Graph.AddNode(node, op...)
20✔
1978
}
1979

1980
// isPremature decides whether a given network message has a block height+delta
1981
// value specified in the future. If so, the message will be added to the
1982
// future message map and be processed when the block height as reached.
1983
//
1984
// NOTE: must be used inside a lock.
1985
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
1986
        delta uint32, msg *networkMsg) bool {
283✔
1987
        // TODO(roasbeef) make height delta 6
283✔
1988
        //  * or configurable
283✔
1989

283✔
1990
        msgHeight := chanID.BlockHeight + delta
283✔
1991

283✔
1992
        // The message height is smaller or equal to our best known height,
283✔
1993
        // thus the message is mature.
283✔
1994
        if msgHeight <= d.bestHeight {
565✔
1995
                return false
282✔
1996
        }
282✔
1997

1998
        // Add the premature message to our future messages which will be
1999
        // resent once the block height has reached.
2000
        //
2001
        // Copy the networkMsgs since the old message's err chan will be
2002
        // consumed.
2003
        copied := &networkMsg{
2✔
2004
                peer:              msg.peer,
2✔
2005
                source:            msg.source,
2✔
2006
                msg:               msg.msg,
2✔
2007
                optionalMsgFields: msg.optionalMsgFields,
2✔
2008
                isRemote:          msg.isRemote,
2✔
2009
                err:               make(chan error, 1),
2✔
2010
        }
2✔
2011

2✔
2012
        // Create the cached message.
2✔
2013
        cachedMsg := &cachedFutureMsg{
2✔
2014
                msg:    copied,
2✔
2015
                height: msgHeight,
2✔
2016
        }
2✔
2017

2✔
2018
        // Increment the msg ID and add it to the cache.
2✔
2019
        nextMsgID := d.futureMsgs.nextMsgID()
2✔
2020
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
2✔
2021
        if err != nil {
2✔
2022
                log.Errorf("Adding future message got error: %v", err)
×
2023
        }
×
2024

2025
        log.Debugf("Network message: %v added to future messages for "+
2✔
2026
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
2✔
2027
                msgHeight, d.bestHeight)
2✔
2028

2✔
2029
        return true
2✔
2030
}
2031

2032
// processNetworkAnnouncement processes a new network relate authenticated
2033
// channel or node announcement or announcements proofs. If the announcement
2034
// didn't affect the internal state due to either being out of date, invalid,
2035
// or redundant, then nil is returned. Otherwise, the set of announcements will
2036
// be returned which should be broadcasted to the rest of the network. The
2037
// boolean returned indicates whether any dependents of the announcement should
2038
// attempt to be processed as well.
2039
func (d *AuthenticatedGossiper) processNetworkAnnouncement(
2040
        nMsg *networkMsg) ([]networkMsg, bool) {
334✔
2041

334✔
2042
        // If this is a remote update, we set the scheduler option to lazily
334✔
2043
        // add it to the graph.
334✔
2044
        var schedulerOp []batch.SchedulerOption
334✔
2045
        if nMsg.isRemote {
621✔
2046
                schedulerOp = append(schedulerOp, batch.LazyAdd())
287✔
2047
        }
287✔
2048

2049
        switch msg := nMsg.msg.(type) {
334✔
2050
        // A new node announcement has arrived which either presents new
2051
        // information about a node in one of the channels we know about, or a
2052
        // updating previously advertised information.
2053
        case *lnwire.NodeAnnouncement:
28✔
2054
                return d.handleNodeAnnouncement(nMsg, msg, schedulerOp)
28✔
2055

2056
        // A new channel announcement has arrived, this indicates the
2057
        // *creation* of a new channel within the network. This only advertises
2058
        // the existence of a channel and not yet the routing policies in
2059
        // either direction of the channel.
2060
        case *lnwire.ChannelAnnouncement1:
234✔
2061
                return d.handleChanAnnouncement(nMsg, msg, schedulerOp)
234✔
2062

2063
        // A new authenticated channel edge update has arrived. This indicates
2064
        // that the directional information for an already known channel has
2065
        // been updated.
2066
        case *lnwire.ChannelUpdate1:
59✔
2067
                return d.handleChanUpdate(nMsg, msg, schedulerOp)
59✔
2068

2069
        // A new signature announcement has been received. This indicates
2070
        // willingness of nodes involved in the funding of a channel to
2071
        // announce this new channel to the rest of the world.
2072
        case *lnwire.AnnounceSignatures1:
25✔
2073
                return d.handleAnnSig(nMsg, msg)
25✔
2074

2075
        default:
×
2076
                err := errors.New("wrong type of the announcement")
×
2077
                nMsg.err <- err
×
2078
                return nil, false
×
2079
        }
2080
}
2081

2082
// processZombieUpdate determines whether the provided channel update should
2083
// resurrect a given zombie edge.
2084
//
2085
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2086
// should be inspected.
2087
func (d *AuthenticatedGossiper) processZombieUpdate(
2088
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2089
        msg *lnwire.ChannelUpdate1) error {
7✔
2090

7✔
2091
        // The least-significant bit in the flag on the channel update tells us
7✔
2092
        // which edge is being updated.
7✔
2093
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
7✔
2094

7✔
2095
        // Since we've deemed the update as not stale above, before marking it
7✔
2096
        // live, we'll make sure it has been signed by the correct party. If we
7✔
2097
        // have both pubkeys, either party can resurrect the channel. If we've
7✔
2098
        // already marked this with the stricter, single-sided resurrection we
7✔
2099
        // will only have the pubkey of the node with the oldest timestamp.
7✔
2100
        var pubKey *btcec.PublicKey
7✔
2101
        switch {
7✔
2102
        case isNode1 && chanInfo.NodeKey1Bytes != emptyPubkey:
2✔
2103
                pubKey, _ = chanInfo.NodeKey1()
2✔
2104
        case !isNode1 && chanInfo.NodeKey2Bytes != emptyPubkey:
4✔
2105
                pubKey, _ = chanInfo.NodeKey2()
4✔
2106
        }
2107
        if pubKey == nil {
8✔
2108
                return fmt.Errorf("incorrect pubkey to resurrect zombie "+
1✔
2109
                        "with chan_id=%v", msg.ShortChannelID)
1✔
2110
        }
1✔
2111

2112
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
6✔
2113
        if err != nil {
7✔
2114
                return fmt.Errorf("unable to verify channel "+
1✔
2115
                        "update signature: %v", err)
1✔
2116
        }
1✔
2117

2118
        // With the signature valid, we'll proceed to mark the
2119
        // edge as live and wait for the channel announcement to
2120
        // come through again.
2121
        err = d.cfg.Graph.MarkEdgeLive(scid)
5✔
2122
        switch {
5✔
2123
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2124
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2125
                        "zombie index: %v", err)
×
2126

×
2127
                return nil
×
2128

2129
        case err != nil:
×
2130
                return fmt.Errorf("unable to remove edge with "+
×
2131
                        "chan_id=%v from zombie index: %v",
×
2132
                        msg.ShortChannelID, err)
×
2133

2134
        default:
5✔
2135
        }
2136

2137
        log.Debugf("Removed edge with chan_id=%v from zombie "+
5✔
2138
                "index", msg.ShortChannelID)
5✔
2139

5✔
2140
        return nil
5✔
2141
}
2142

2143
// fetchNodeAnn fetches the latest signed node announcement from our point of
2144
// view for the node with the given public key.
2145
func (d *AuthenticatedGossiper) fetchNodeAnn(
2146
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
24✔
2147

24✔
2148
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
24✔
2149
        if err != nil {
30✔
2150
                return nil, err
6✔
2151
        }
6✔
2152

2153
        return node.NodeAnnouncement(true)
18✔
2154
}
2155

2156
// isMsgStale determines whether a message retrieved from the backing
2157
// MessageStore is seen as stale by the current graph.
2158
func (d *AuthenticatedGossiper) isMsgStale(msg lnwire.Message) bool {
16✔
2159
        switch msg := msg.(type) {
16✔
2160
        case *lnwire.AnnounceSignatures1:
6✔
2161
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
6✔
2162
                        msg.ShortChannelID,
6✔
2163
                )
6✔
2164

6✔
2165
                // If the channel cannot be found, it is most likely a leftover
6✔
2166
                // message for a channel that was closed, so we can consider it
6✔
2167
                // stale.
6✔
2168
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
10✔
2169
                        return true
4✔
2170
                }
4✔
2171
                if err != nil {
6✔
2172
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2173
                                "%v", chanInfo.ChannelID, err)
×
2174
                        return false
×
2175
                }
×
2176

2177
                // If the proof exists in the graph, then we have successfully
2178
                // received the remote proof and assembled the full proof, so we
2179
                // can safely delete the local proof from the database.
2180
                return chanInfo.AuthProof != nil
6✔
2181

2182
        case *lnwire.ChannelUpdate1:
14✔
2183
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
14✔
2184

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

2197
                // Otherwise, we'll retrieve the correct policy that we
2198
                // currently have stored within our graph to check if this
2199
                // message is stale by comparing its timestamp.
2200
                var p *models.ChannelEdgePolicy
14✔
2201
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
28✔
2202
                        p = p1
14✔
2203
                } else {
18✔
2204
                        p = p2
4✔
2205
                }
4✔
2206

2207
                // If the policy is still unknown, then we can consider this
2208
                // policy fresh.
2209
                if p == nil {
14✔
2210
                        return false
×
2211
                }
×
2212

2213
                timestamp := time.Unix(int64(msg.Timestamp), 0)
14✔
2214
                return p.LastUpdate.After(timestamp)
14✔
2215

2216
        default:
×
2217
                // We'll make sure to not mark any unsupported messages as stale
×
2218
                // to ensure they are not removed.
×
2219
                return false
×
2220
        }
2221
}
2222

2223
// updateChannel creates a new fully signed update for the channel, and updates
2224
// the underlying graph with the new state.
2225
func (d *AuthenticatedGossiper) updateChannel(info *models.ChannelEdgeInfo,
2226
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2227
        *lnwire.ChannelUpdate1, error) {
8✔
2228

8✔
2229
        // Parse the unsigned edge into a channel update.
8✔
2230
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
8✔
2231

8✔
2232
        // We'll generate a new signature over a digest of the channel
8✔
2233
        // announcement itself and update the timestamp to ensure it propagate.
8✔
2234
        err := netann.SignChannelUpdate(
8✔
2235
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
8✔
2236
                netann.ChanUpdSetTimestamp,
8✔
2237
        )
8✔
2238
        if err != nil {
8✔
2239
                return nil, nil, err
×
2240
        }
×
2241

2242
        // Next, we'll set the new signature in place, and update the reference
2243
        // in the backing slice.
2244
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
8✔
2245
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
8✔
2246

8✔
2247
        // To ensure that our signature is valid, we'll verify it ourself
8✔
2248
        // before committing it to the slice returned.
8✔
2249
        err = netann.ValidateChannelUpdateAnn(
8✔
2250
                d.selfKey, info.Capacity, chanUpdate,
8✔
2251
        )
8✔
2252
        if err != nil {
8✔
2253
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2254
                        "update sig: %v", err)
×
2255
        }
×
2256

2257
        // Finally, we'll write the new edge policy to disk.
2258
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
8✔
2259
                return nil, nil, err
×
2260
        }
×
2261

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

2304
        return chanAnn, chanUpdate, err
8✔
2305
}
2306

2307
// SyncManager returns the gossiper's SyncManager instance.
2308
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
4✔
2309
        return d.syncMgr
4✔
2310
}
4✔
2311

2312
// IsKeepAliveUpdate determines whether this channel update is considered a
2313
// keep-alive update based on the previous channel update processed for the same
2314
// direction.
2315
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2316
        prev *models.ChannelEdgePolicy) bool {
18✔
2317

18✔
2318
        // Both updates should be from the same direction.
18✔
2319
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
18✔
2320
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
18✔
2321

×
2322
                return false
×
2323
        }
×
2324

2325
        // The timestamp should always increase for a keep-alive update.
2326
        timestamp := time.Unix(int64(update.Timestamp), 0)
18✔
2327
        if !timestamp.After(prev.LastUpdate) {
22✔
2328
                return false
4✔
2329
        }
4✔
2330

2331
        // None of the remaining fields should change for a keep-alive update.
2332
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
22✔
2333
                return false
4✔
2334
        }
4✔
2335
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
34✔
2336
                return false
16✔
2337
        }
16✔
2338
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
10✔
2339
                return false
4✔
2340
        }
4✔
2341
        if update.TimeLockDelta != prev.TimeLockDelta {
6✔
2342
                return false
×
2343
        }
×
2344
        if update.HtlcMinimumMsat != prev.MinHTLC {
6✔
2345
                return false
×
2346
        }
×
2347
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
6✔
2348
                return false
×
2349
        }
×
2350
        if update.HtlcMaximumMsat != prev.MaxHTLC {
6✔
2351
                return false
×
2352
        }
×
2353
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
10✔
2354
                return false
4✔
2355
        }
4✔
2356
        return true
6✔
2357
}
2358

2359
// latestHeight returns the gossiper's latest height known of the chain.
2360
func (d *AuthenticatedGossiper) latestHeight() uint32 {
4✔
2361
        d.Lock()
4✔
2362
        defer d.Unlock()
4✔
2363
        return d.bestHeight
4✔
2364
}
4✔
2365

2366
// handleNodeAnnouncement processes a new node announcement.
2367
func (d *AuthenticatedGossiper) handleNodeAnnouncement(nMsg *networkMsg,
2368
        nodeAnn *lnwire.NodeAnnouncement,
2369
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
28✔
2370

28✔
2371
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
28✔
2372

28✔
2373
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
28✔
2374
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
28✔
2375

28✔
2376
        // We'll quickly ask the router if it already has a newer update for
28✔
2377
        // this node so we can skip validating signatures if not required.
28✔
2378
        if d.cfg.Graph.IsStaleNode(nodeAnn.NodeID, timestamp) {
40✔
2379
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
12✔
2380
                nMsg.err <- nil
12✔
2381
                return nil, true
12✔
2382
        }
12✔
2383

2384
        if err := d.addNode(nodeAnn, ops...); err != nil {
24✔
2385
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
4✔
2386
                        err)
4✔
2387

4✔
2388
                if !graph.IsError(
4✔
2389
                        err,
4✔
2390
                        graph.ErrOutdated,
4✔
2391
                        graph.ErrIgnored,
4✔
2392
                        graph.ErrVBarrierShuttingDown,
4✔
2393
                ) {
4✔
UNCOV
2394

×
UNCOV
2395
                        log.Error(err)
×
UNCOV
2396
                }
×
2397

2398
                nMsg.err <- err
4✔
2399
                return nil, false
4✔
2400
        }
2401

2402
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2403
        // quick check to ensure this node intends to publicly advertise itself
2404
        // to the network.
2405
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
20✔
2406
        if err != nil {
20✔
2407
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2408
                        nodeAnn.NodeID, err)
×
2409
                nMsg.err <- err
×
2410
                return nil, false
×
2411
        }
×
2412

2413
        var announcements []networkMsg
20✔
2414

20✔
2415
        // If it does, we'll add their announcement to our batch so that it can
20✔
2416
        // be broadcast to the rest of our peers.
20✔
2417
        if isPublic {
27✔
2418
                announcements = append(announcements, networkMsg{
7✔
2419
                        peer:     nMsg.peer,
7✔
2420
                        isRemote: nMsg.isRemote,
7✔
2421
                        source:   nMsg.source,
7✔
2422
                        msg:      nodeAnn,
7✔
2423
                })
7✔
2424
        } else {
24✔
2425
                log.Tracef("Skipping broadcasting node announcement for %x "+
17✔
2426
                        "due to being unadvertised", nodeAnn.NodeID)
17✔
2427
        }
17✔
2428

2429
        nMsg.err <- nil
20✔
2430
        // TODO(roasbeef): get rid of the above
20✔
2431

20✔
2432
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
20✔
2433
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
20✔
2434

20✔
2435
        return announcements, true
20✔
2436
}
2437

2438
// handleChanAnnouncement processes a new channel announcement.
2439
func (d *AuthenticatedGossiper) handleChanAnnouncement(nMsg *networkMsg,
2440
        ann *lnwire.ChannelAnnouncement1,
2441
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
234✔
2442

234✔
2443
        scid := ann.ShortChannelID
234✔
2444

234✔
2445
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
234✔
2446
                nMsg.peer, scid.ToUint64())
234✔
2447

234✔
2448
        // We'll ignore any channel announcements that target any chain other
234✔
2449
        // than the set of chains we know of.
234✔
2450
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
234✔
2451
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2452
                        ", gossiper on chain=%v", ann.ChainHash,
×
2453
                        d.cfg.ChainHash)
×
2454
                log.Errorf(err.Error())
×
2455

×
2456
                key := newRejectCacheKey(
×
2457
                        scid.ToUint64(),
×
2458
                        sourceToPub(nMsg.source),
×
2459
                )
×
2460
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2461

×
2462
                nMsg.err <- err
×
2463
                return nil, false
×
2464
        }
×
2465

2466
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2467
        // reject the announcement. Since the router accepts alias SCIDs,
2468
        // not erroring out would be a DoS vector.
2469
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
234✔
2470
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2471
                log.Errorf(err.Error())
×
2472

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

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

2483
        // If the advertised inclusionary block is beyond our knowledge of the
2484
        // chain tip, then we'll ignore it for now.
2485
        d.Lock()
234✔
2486
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
235✔
2487
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2488
                        "advertises height %v, only height %v is known",
1✔
2489
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2490
                d.Unlock()
1✔
2491
                nMsg.err <- nil
1✔
2492
                return nil, false
1✔
2493
        }
1✔
2494
        d.Unlock()
233✔
2495

233✔
2496
        // At this point, we'll now ask the router if this is a zombie/known
233✔
2497
        // edge. If so we can skip all the processing below.
233✔
2498
        if d.cfg.Graph.IsKnownEdge(scid) {
238✔
2499
                nMsg.err <- nil
5✔
2500
                return nil, true
5✔
2501
        }
5✔
2502

2503
        // Check if the channel is already closed in which case we can ignore
2504
        // it.
2505
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
232✔
2506
        if err != nil {
232✔
2507
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2508
                        err)
×
2509
                nMsg.err <- err
×
2510

×
2511
                return nil, false
×
2512
        }
×
2513

2514
        if closed {
233✔
2515
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2516
                log.Error(err)
1✔
2517

1✔
2518
                // If this is an announcement from us, we'll just ignore it.
1✔
2519
                if !nMsg.isRemote {
1✔
2520
                        nMsg.err <- err
×
2521
                        return nil, false
×
2522
                }
×
2523

2524
                // Increment the peer's ban score if they are sending closed
2525
                // channel announcements.
2526
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2527

1✔
2528
                // If the peer is banned and not a channel peer, we'll
1✔
2529
                // disconnect them.
1✔
2530
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2531
                if dcErr != nil {
1✔
2532
                        log.Errorf("failed to check if we should disconnect "+
×
2533
                                "peer: %v", dcErr)
×
2534
                        nMsg.err <- dcErr
×
2535

×
2536
                        return nil, false
×
2537
                }
×
2538

2539
                if shouldDc {
1✔
2540
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2541
                }
×
2542

2543
                nMsg.err <- err
1✔
2544

1✔
2545
                return nil, false
1✔
2546
        }
2547

2548
        // If this is a remote channel announcement, then we'll validate all
2549
        // the signatures within the proof as it should be well formed.
2550
        var proof *models.ChannelAuthProof
231✔
2551
        if nMsg.isRemote {
448✔
2552
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
217✔
2553
                if err != nil {
217✔
2554
                        err := fmt.Errorf("unable to validate announcement: "+
×
2555
                                "%v", err)
×
2556

×
2557
                        key := newRejectCacheKey(
×
2558
                                scid.ToUint64(),
×
2559
                                sourceToPub(nMsg.source),
×
2560
                        )
×
2561
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2562

×
2563
                        log.Error(err)
×
2564
                        nMsg.err <- err
×
2565
                        return nil, false
×
2566
                }
×
2567

2568
                // If the proof checks out, then we'll save the proof itself to
2569
                // the database so we can fetch it later when gossiping with
2570
                // other nodes.
2571
                proof = &models.ChannelAuthProof{
217✔
2572
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
217✔
2573
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
217✔
2574
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
217✔
2575
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
217✔
2576
                }
217✔
2577
        }
2578

2579
        // With the proof validated (if necessary), we can now store it within
2580
        // the database for our path finding and syncing needs.
2581
        var featureBuf bytes.Buffer
231✔
2582
        if err := ann.Features.Encode(&featureBuf); err != nil {
231✔
2583
                log.Errorf("unable to encode features: %v", err)
×
2584
                nMsg.err <- err
×
2585
                return nil, false
×
2586
        }
×
2587

2588
        edge := &models.ChannelEdgeInfo{
231✔
2589
                ChannelID:        scid.ToUint64(),
231✔
2590
                ChainHash:        ann.ChainHash,
231✔
2591
                NodeKey1Bytes:    ann.NodeID1,
231✔
2592
                NodeKey2Bytes:    ann.NodeID2,
231✔
2593
                BitcoinKey1Bytes: ann.BitcoinKey1,
231✔
2594
                BitcoinKey2Bytes: ann.BitcoinKey2,
231✔
2595
                AuthProof:        proof,
231✔
2596
                Features:         featureBuf.Bytes(),
231✔
2597
                ExtraOpaqueData:  ann.ExtraOpaqueData,
231✔
2598
        }
231✔
2599

231✔
2600
        // If there were any optional message fields provided, we'll include
231✔
2601
        // them in its serialized disk representation now.
231✔
2602
        if nMsg.optionalMsgFields != nil {
249✔
2603
                if nMsg.optionalMsgFields.capacity != nil {
23✔
2604
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
5✔
2605
                }
5✔
2606
                if nMsg.optionalMsgFields.channelPoint != nil {
26✔
2607
                        cp := *nMsg.optionalMsgFields.channelPoint
8✔
2608
                        edge.ChannelPoint = cp
8✔
2609
                }
8✔
2610

2611
                // Optional tapscript root for custom channels.
2612
                edge.TapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
18✔
2613
        }
2614

2615
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
231✔
2616

231✔
2617
        // We will add the edge to the channel router. If the nodes present in
231✔
2618
        // this channel are not present in the database, a partial node will be
231✔
2619
        // added to represent each node while we wait for a node announcement.
231✔
2620
        //
231✔
2621
        // Before we add the edge to the database, we obtain the mutex for this
231✔
2622
        // channel ID. We do this to ensure no other goroutine has read the
231✔
2623
        // database and is now making decisions based on this DB state, before
231✔
2624
        // it writes to the DB.
231✔
2625
        d.channelMtx.Lock(scid.ToUint64())
231✔
2626
        err = d.cfg.Graph.AddEdge(edge, ops...)
231✔
2627
        if err != nil {
437✔
2628
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
206✔
2629
                        scid.ToUint64(), err)
206✔
2630

206✔
2631
                defer d.channelMtx.Unlock(scid.ToUint64())
206✔
2632

206✔
2633
                // If the edge was rejected due to already being known, then it
206✔
2634
                // may be the case that this new message has a fresh channel
206✔
2635
                // proof, so we'll check.
206✔
2636
                switch {
206✔
2637
                case graph.IsError(err, graph.ErrIgnored):
4✔
2638
                        // Attempt to process the rejected message to see if we
4✔
2639
                        // get any new announcements.
4✔
2640
                        anns, rErr := d.processRejectedEdge(ann, proof)
4✔
2641
                        if rErr != nil {
4✔
2642
                                key := newRejectCacheKey(
×
2643
                                        scid.ToUint64(),
×
2644
                                        sourceToPub(nMsg.source),
×
2645
                                )
×
2646
                                cr := &cachedReject{}
×
2647
                                _, _ = d.recentRejects.Put(key, cr)
×
2648

×
2649
                                nMsg.err <- rErr
×
2650
                                return nil, false
×
2651
                        }
×
2652

2653
                        log.Debugf("Extracted %v announcements from rejected "+
4✔
2654
                                "msgs", len(anns))
4✔
2655

4✔
2656
                        // If while processing this rejected edge, we realized
4✔
2657
                        // there's a set of announcements we could extract,
4✔
2658
                        // then we'll return those directly.
4✔
2659
                        //
4✔
2660
                        // NOTE: since this is an ErrIgnored, we can return
4✔
2661
                        // true here to signal "allow" to its dependants.
4✔
2662
                        nMsg.err <- nil
4✔
2663

4✔
2664
                        return anns, true
4✔
2665

2666
                case graph.IsError(
2667
                        err, graph.ErrNoFundingTransaction,
2668
                        graph.ErrInvalidFundingOutput,
2669
                ):
200✔
2670
                        key := newRejectCacheKey(
200✔
2671
                                scid.ToUint64(),
200✔
2672
                                sourceToPub(nMsg.source),
200✔
2673
                        )
200✔
2674
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
200✔
2675

200✔
2676
                        // Increment the peer's ban score. We check isRemote
200✔
2677
                        // so we don't actually ban the peer in case of a local
200✔
2678
                        // bug.
200✔
2679
                        if nMsg.isRemote {
400✔
2680
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
200✔
2681
                        }
200✔
2682

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

1✔
2690
                        // Since this channel has already been closed, we'll
1✔
2691
                        // add it to the graph's closed channel index such that
1✔
2692
                        // we won't attempt to do expensive validation checks
1✔
2693
                        // on it again.
1✔
2694
                        // TODO: Populate the ScidCloser by using closed
1✔
2695
                        // channel notifications.
1✔
2696
                        dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
1✔
2697
                        if dbErr != nil {
1✔
2698
                                log.Errorf("failed to mark scid(%v) as "+
×
2699
                                        "closed: %v", scid, dbErr)
×
2700

×
2701
                                nMsg.err <- dbErr
×
2702

×
2703
                                return nil, false
×
2704
                        }
×
2705

2706
                        // Increment the peer's ban score. We check isRemote
2707
                        // so we don't accidentally ban ourselves in case of a
2708
                        // bug.
2709
                        if nMsg.isRemote {
2✔
2710
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2711
                        }
1✔
2712

2713
                default:
1✔
2714
                        // Otherwise, this is just a regular rejected edge.
1✔
2715
                        key := newRejectCacheKey(
1✔
2716
                                scid.ToUint64(),
1✔
2717
                                sourceToPub(nMsg.source),
1✔
2718
                        )
1✔
2719
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2720
                }
2721

2722
                if !nMsg.isRemote {
202✔
2723
                        log.Errorf("failed to add edge for local channel: %v",
×
2724
                                err)
×
2725
                        nMsg.err <- err
×
2726

×
2727
                        return nil, false
×
2728
                }
×
2729

2730
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
202✔
2731
                if dcErr != nil {
202✔
2732
                        log.Errorf("failed to check if we should disconnect "+
×
2733
                                "peer: %v", dcErr)
×
2734
                        nMsg.err <- dcErr
×
2735

×
2736
                        return nil, false
×
2737
                }
×
2738

2739
                if shouldDc {
203✔
2740
                        nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2741
                }
1✔
2742

2743
                nMsg.err <- err
202✔
2744

202✔
2745
                return nil, false
202✔
2746
        }
2747

2748
        // If err is nil, release the lock immediately.
2749
        d.channelMtx.Unlock(scid.ToUint64())
29✔
2750

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

29✔
2753
        // If we earlier received any ChannelUpdates for this channel, we can
29✔
2754
        // now process them, as the channel is added to the graph.
29✔
2755
        var channelUpdates []*processedNetworkMsg
29✔
2756

29✔
2757
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
29✔
2758
        if err == nil {
35✔
2759
                // There was actually an entry in the map, so we'll accumulate
6✔
2760
                // it. We don't worry about deletion, since it'll eventually
6✔
2761
                // fall out anyway.
6✔
2762
                chanMsgs := earlyChanUpdates
6✔
2763
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
6✔
2764
        }
6✔
2765

2766
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2767
        // ensure we don't block here, as we can handle only one announcement
2768
        // at a time.
2769
        for _, cu := range channelUpdates {
35✔
2770
                // Skip if already processed.
6✔
2771
                if cu.processed {
6✔
UNCOV
2772
                        continue
×
2773
                }
2774

2775
                // Mark the ChannelUpdate as processed. This ensures that a
2776
                // subsequent announcement in the option-scid-alias case does
2777
                // not re-use an old ChannelUpdate.
2778
                cu.processed = true
6✔
2779

6✔
2780
                d.wg.Add(1)
6✔
2781
                go func(updMsg *networkMsg) {
12✔
2782
                        defer d.wg.Done()
6✔
2783

6✔
2784
                        switch msg := updMsg.msg.(type) {
6✔
2785
                        // Reprocess the message, making sure we return an
2786
                        // error to the original caller in case the gossiper
2787
                        // shuts down.
2788
                        case *lnwire.ChannelUpdate1:
6✔
2789
                                log.Debugf("Reprocessing ChannelUpdate for "+
6✔
2790
                                        "shortChanID=%v", scid.ToUint64())
6✔
2791

6✔
2792
                                select {
6✔
2793
                                case d.networkMsgs <- updMsg:
6✔
2794
                                case <-d.quit:
×
2795
                                        updMsg.err <- ErrGossiperShuttingDown
×
2796
                                }
2797

2798
                        // We don't expect any other message type than
2799
                        // ChannelUpdate to be in this cache.
2800
                        default:
×
2801
                                log.Errorf("Unsupported message type found "+
×
2802
                                        "among ChannelUpdates: %T", msg)
×
2803
                        }
2804
                }(cu.msg)
2805
        }
2806

2807
        // Channel announcement was successfully processed and now it might be
2808
        // broadcast to other connected nodes if it was an announcement with
2809
        // proof (remote).
2810
        var announcements []networkMsg
29✔
2811

29✔
2812
        if proof != nil {
44✔
2813
                announcements = append(announcements, networkMsg{
15✔
2814
                        peer:     nMsg.peer,
15✔
2815
                        isRemote: nMsg.isRemote,
15✔
2816
                        source:   nMsg.source,
15✔
2817
                        msg:      ann,
15✔
2818
                })
15✔
2819
        }
15✔
2820

2821
        nMsg.err <- nil
29✔
2822

29✔
2823
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
29✔
2824
                nMsg.peer, scid.ToUint64())
29✔
2825

29✔
2826
        return announcements, true
29✔
2827
}
2828

2829
// handleChanUpdate processes a new channel update.
2830
func (d *AuthenticatedGossiper) handleChanUpdate(nMsg *networkMsg,
2831
        upd *lnwire.ChannelUpdate1,
2832
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
59✔
2833

59✔
2834
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
59✔
2835
                nMsg.peer, upd.ShortChannelID.ToUint64())
59✔
2836

59✔
2837
        // We'll ignore any channel updates that target any chain other than
59✔
2838
        // the set of chains we know of.
59✔
2839
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
59✔
2840
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2841
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2842
                log.Errorf(err.Error())
×
2843

×
2844
                key := newRejectCacheKey(
×
2845
                        upd.ShortChannelID.ToUint64(),
×
2846
                        sourceToPub(nMsg.source),
×
2847
                )
×
2848
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2849

×
2850
                nMsg.err <- err
×
2851
                return nil, false
×
2852
        }
×
2853

2854
        blockHeight := upd.ShortChannelID.BlockHeight
59✔
2855
        shortChanID := upd.ShortChannelID.ToUint64()
59✔
2856

59✔
2857
        // If the advertised inclusionary block is beyond our knowledge of the
59✔
2858
        // chain tip, then we'll put the announcement in limbo to be fully
59✔
2859
        // verified once we advance forward in the chain. If the update has an
59✔
2860
        // alias SCID, we'll skip the isPremature check. This is necessary
59✔
2861
        // since aliases start at block height 16_000_000.
59✔
2862
        d.Lock()
59✔
2863
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
59✔
2864
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
60✔
2865

1✔
2866
                log.Warnf("Update announcement for short_chan_id(%v), is "+
1✔
2867
                        "premature: advertises height %v, only height %v is "+
1✔
2868
                        "known", shortChanID, blockHeight, d.bestHeight)
1✔
2869
                d.Unlock()
1✔
2870
                nMsg.err <- nil
1✔
2871
                return nil, false
1✔
2872
        }
1✔
2873
        d.Unlock()
59✔
2874

59✔
2875
        // Before we perform any of the expensive checks below, we'll check
59✔
2876
        // whether this update is stale or is for a zombie channel in order to
59✔
2877
        // quickly reject it.
59✔
2878
        timestamp := time.Unix(int64(upd.Timestamp), 0)
59✔
2879

59✔
2880
        // Fetch the SCID we should be using to lock the channelMtx and make
59✔
2881
        // graph queries with.
59✔
2882
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
59✔
2883
        if err != nil {
118✔
2884
                // Fallback and set the graphScid to the peer-provided SCID.
59✔
2885
                // This will occur for non-option-scid-alias channels and for
59✔
2886
                // public option-scid-alias channels after 6 confirmations.
59✔
2887
                // Once public option-scid-alias channels have 6 confs, we'll
59✔
2888
                // ignore ChannelUpdates with one of their aliases.
59✔
2889
                graphScid = upd.ShortChannelID
59✔
2890
        }
59✔
2891

2892
        if d.cfg.Graph.IsStaleEdgePolicy(
59✔
2893
                graphScid, timestamp, upd.ChannelFlags,
59✔
2894
        ) {
65✔
2895

6✔
2896
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
6✔
2897
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
6✔
2898
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
6✔
2899
                )
6✔
2900

6✔
2901
                nMsg.err <- nil
6✔
2902
                return nil, true
6✔
2903
        }
6✔
2904

2905
        // Check that the ChanUpdate is not too far into the future, this could
2906
        // reveal some faulty implementation therefore we log an error.
2907
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
57✔
2908
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
2909
                        "short_chan_id(%v), timestamp too far in the future: "+
×
2910
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
2911
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
2912
                        nMsg.isRemote,
×
2913
                )
×
2914

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

×
2918
                return nil, false
×
2919
        }
×
2920

2921
        // Get the node pub key as far since we don't have it in the channel
2922
        // update announcement message. We'll need this to properly verify the
2923
        // message's signature.
2924
        //
2925
        // We make sure to obtain the mutex for this channel ID before we
2926
        // access the database. This ensures the state we read from the
2927
        // database has not changed between this point and when we call
2928
        // UpdateEdge() later.
2929
        d.channelMtx.Lock(graphScid.ToUint64())
57✔
2930
        defer d.channelMtx.Unlock(graphScid.ToUint64())
57✔
2931

57✔
2932
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
57✔
2933
        switch {
57✔
2934
        // No error, break.
2935
        case err == nil:
53✔
2936
                break
53✔
2937

2938
        case errors.Is(err, graphdb.ErrZombieEdge):
7✔
2939
                err = d.processZombieUpdate(chanInfo, graphScid, upd)
7✔
2940
                if err != nil {
9✔
2941
                        log.Debug(err)
2✔
2942
                        nMsg.err <- err
2✔
2943
                        return nil, false
2✔
2944
                }
2✔
2945

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

6✔
2975
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
6✔
2976
                switch {
6✔
2977
                // Nothing in the cache yet, we can just directly insert this
2978
                // element.
2979
                case err == cache.ErrElementNotFound:
6✔
2980
                        _, _ = d.prematureChannelUpdates.Put(
6✔
2981
                                shortChanID, &cachedNetworkMsg{
6✔
2982
                                        msgs: []*processedNetworkMsg{pMsg},
6✔
2983
                                })
6✔
2984

2985
                // There's already something in the cache, so we'll combine the
2986
                // set of messages into a single value.
2987
                default:
4✔
2988
                        msgs := earlyMsgs.msgs
4✔
2989
                        msgs = append(msgs, pMsg)
4✔
2990
                        _, _ = d.prematureChannelUpdates.Put(
4✔
2991
                                shortChanID, &cachedNetworkMsg{
4✔
2992
                                        msgs: msgs,
4✔
2993
                                })
4✔
2994
                }
2995

2996
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
6✔
2997
                        "(shortChanID=%v), saving for reprocessing later",
6✔
2998
                        shortChanID)
6✔
2999

6✔
3000
                // NOTE: We don't return anything on the error channel for this
6✔
3001
                // message, as we expect that will be done when this
6✔
3002
                // ChannelUpdate is later reprocessed.
6✔
3003
                return nil, false
6✔
3004

3005
        default:
×
3006
                err := fmt.Errorf("unable to validate channel update "+
×
3007
                        "short_chan_id=%v: %v", shortChanID, err)
×
3008
                log.Error(err)
×
3009
                nMsg.err <- err
×
3010

×
3011
                key := newRejectCacheKey(
×
3012
                        upd.ShortChannelID.ToUint64(),
×
3013
                        sourceToPub(nMsg.source),
×
3014
                )
×
3015
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3016

×
3017
                return nil, false
×
3018
        }
3019

3020
        // The least-significant bit in the flag on the channel update
3021
        // announcement tells us "which" side of the channels directed edge is
3022
        // being updated.
3023
        var (
53✔
3024
                pubKey       *btcec.PublicKey
53✔
3025
                edgeToUpdate *models.ChannelEdgePolicy
53✔
3026
        )
53✔
3027
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
53✔
3028
        switch direction {
53✔
3029
        case 0:
38✔
3030
                pubKey, _ = chanInfo.NodeKey1()
38✔
3031
                edgeToUpdate = e1
38✔
3032
        case 1:
19✔
3033
                pubKey, _ = chanInfo.NodeKey2()
19✔
3034
                edgeToUpdate = e2
19✔
3035
        }
3036

3037
        log.Debugf("Validating ChannelUpdate: channel=%v, from node=%x, has "+
53✔
3038
                "edge=%v", chanInfo.ChannelID, pubKey.SerializeCompressed(),
53✔
3039
                edgeToUpdate != nil)
53✔
3040

53✔
3041
        // Validate the channel announcement with the expected public key and
53✔
3042
        // channel capacity. In the case of an invalid channel update, we'll
53✔
3043
        // return an error to the caller and exit early.
53✔
3044
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
53✔
3045
        if err != nil {
57✔
3046
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3047
                        "announcement for short_chan_id=%v: %v",
4✔
3048
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3049

4✔
3050
                log.Error(rErr)
4✔
3051
                nMsg.err <- rErr
4✔
3052
                return nil, false
4✔
3053
        }
4✔
3054

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

16✔
3097
                        if !rls[direction].Allow() {
25✔
3098
                                log.Debugf("Rate limiting update for channel "+
9✔
3099
                                        "%v from direction %x", shortChanID,
9✔
3100
                                        pubKey.SerializeCompressed())
9✔
3101
                                nMsg.err <- nil
9✔
3102
                                return nil, false
9✔
3103
                        }
9✔
3104
                }
3105
        }
3106

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

43✔
3128
        if err := d.cfg.Graph.UpdateEdge(update, ops...); err != nil {
47✔
3129
                if graph.IsError(
4✔
3130
                        err, graph.ErrOutdated,
4✔
3131
                        graph.ErrIgnored,
4✔
3132
                        graph.ErrVBarrierShuttingDown,
4✔
3133
                ) {
8✔
3134

4✔
3135
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
4✔
3136
                                shortChanID, err)
4✔
3137
                } else {
4✔
3138
                        // Since we know the stored SCID in the graph, we'll
×
3139
                        // cache that SCID.
×
3140
                        key := newRejectCacheKey(
×
3141
                                chanInfo.ChannelID,
×
3142
                                sourceToPub(nMsg.source),
×
3143
                        )
×
3144
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3145

×
3146
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3147
                                shortChanID, err)
×
3148
                }
×
3149

3150
                nMsg.err <- err
4✔
3151
                return nil, false
4✔
3152
        }
3153

3154
        // If this is a local ChannelUpdate without an AuthProof, it means it
3155
        // is an update to a channel that is not (yet) supposed to be announced
3156
        // to the greater network. However, our channel counter party will need
3157
        // to be given the update, so we'll try sending the update directly to
3158
        // the remote peer.
3159
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
58✔
3160
                if nMsg.optionalMsgFields != nil {
30✔
3161
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
15✔
3162
                        if remoteAlias != nil {
19✔
3163
                                // The remoteAlias field was specified, meaning
4✔
3164
                                // that we should replace the SCID in the
4✔
3165
                                // update with the remote's alias. We'll also
4✔
3166
                                // need to re-sign the channel update. This is
4✔
3167
                                // required for option-scid-alias feature-bit
4✔
3168
                                // negotiated channels.
4✔
3169
                                upd.ShortChannelID = *remoteAlias
4✔
3170

4✔
3171
                                sig, err := d.cfg.SignAliasUpdate(upd)
4✔
3172
                                if err != nil {
4✔
3173
                                        log.Error(err)
×
3174
                                        nMsg.err <- err
×
3175
                                        return nil, false
×
3176
                                }
×
3177

3178
                                lnSig, err := lnwire.NewSigFromSignature(sig)
4✔
3179
                                if err != nil {
4✔
3180
                                        log.Error(err)
×
3181
                                        nMsg.err <- err
×
3182
                                        return nil, false
×
3183
                                }
×
3184

3185
                                upd.Signature = lnSig
4✔
3186
                        }
3187
                }
3188

3189
                // Get our peer's public key.
3190
                remotePubKey := remotePubFromChanInfo(
15✔
3191
                        chanInfo, upd.ChannelFlags,
15✔
3192
                )
15✔
3193

15✔
3194
                log.Debugf("The message %v has no AuthProof, sending the "+
15✔
3195
                        "update to remote peer %x", upd.MsgType(), remotePubKey)
15✔
3196

15✔
3197
                // Now we'll attempt to send the channel update message
15✔
3198
                // reliably to the remote peer in the background, so that we
15✔
3199
                // don't block if the peer happens to be offline at the moment.
15✔
3200
                err := d.reliableSender.sendMessage(upd, remotePubKey)
15✔
3201
                if err != nil {
15✔
3202
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3203
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3204
                                upd.ShortChannelID, remotePubKey, err)
×
3205
                        nMsg.err <- err
×
3206
                        return nil, false
×
3207
                }
×
3208
        }
3209

3210
        // Channel update announcement was successfully processed and now it
3211
        // can be broadcast to the rest of the network. However, we'll only
3212
        // broadcast the channel update announcement if it has an attached
3213
        // authentication proof. We also won't broadcast the update if it
3214
        // contains an alias because the network would reject this.
3215
        var announcements []networkMsg
43✔
3216
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
66✔
3217
                announcements = append(announcements, networkMsg{
23✔
3218
                        peer:     nMsg.peer,
23✔
3219
                        source:   nMsg.source,
23✔
3220
                        isRemote: nMsg.isRemote,
23✔
3221
                        msg:      upd,
23✔
3222
                })
23✔
3223
        }
23✔
3224

3225
        nMsg.err <- nil
43✔
3226

43✔
3227
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
43✔
3228
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
43✔
3229
                timestamp)
43✔
3230
        return announcements, true
43✔
3231
}
3232

3233
// handleAnnSig processes a new announcement signatures message.
3234
func (d *AuthenticatedGossiper) handleAnnSig(nMsg *networkMsg,
3235
        ann *lnwire.AnnounceSignatures1) ([]networkMsg, bool) {
25✔
3236

25✔
3237
        needBlockHeight := ann.ShortChannelID.BlockHeight +
25✔
3238
                d.cfg.ProofMatureDelta
25✔
3239
        shortChanID := ann.ShortChannelID.ToUint64()
25✔
3240

25✔
3241
        prefix := "local"
25✔
3242
        if nMsg.isRemote {
40✔
3243
                prefix = "remote"
15✔
3244
        }
15✔
3245

3246
        log.Infof("Received new %v announcement signature for %v", prefix,
25✔
3247
                ann.ShortChannelID)
25✔
3248

25✔
3249
        // By the specification, channel announcement proofs should be sent
25✔
3250
        // after some number of confirmations after channel was registered in
25✔
3251
        // bitcoin blockchain. Therefore, we check if the proof is mature.
25✔
3252
        d.Lock()
25✔
3253
        premature := d.isPremature(
25✔
3254
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
25✔
3255
        )
25✔
3256
        if premature {
26✔
3257
                log.Warnf("Premature proof announcement, current block height"+
1✔
3258
                        "lower than needed: %v < %v", d.bestHeight,
1✔
3259
                        needBlockHeight)
1✔
3260
                d.Unlock()
1✔
3261
                nMsg.err <- nil
1✔
3262
                return nil, false
1✔
3263
        }
1✔
3264
        d.Unlock()
25✔
3265

25✔
3266
        // Ensure that we know of a channel with the target channel ID before
25✔
3267
        // proceeding further.
25✔
3268
        //
25✔
3269
        // We must acquire the mutex for this channel ID before getting the
25✔
3270
        // channel from the database, to ensure what we read does not change
25✔
3271
        // before we call AddProof() later.
25✔
3272
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
25✔
3273
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
25✔
3274

25✔
3275
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
25✔
3276
                ann.ShortChannelID,
25✔
3277
        )
25✔
3278
        if err != nil {
30✔
3279
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
5✔
3280
                if err != nil {
9✔
3281
                        err := fmt.Errorf("unable to store the proof for "+
4✔
3282
                                "short_chan_id=%v: %v", shortChanID, err)
4✔
3283
                        log.Error(err)
4✔
3284
                        nMsg.err <- err
4✔
3285

4✔
3286
                        return nil, false
4✔
3287
                }
4✔
3288

3289
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
5✔
3290
                err := d.cfg.WaitingProofStore.Add(proof)
5✔
3291
                if err != nil {
5✔
3292
                        err := fmt.Errorf("unable to store the proof for "+
×
3293
                                "short_chan_id=%v: %v", shortChanID, err)
×
3294
                        log.Error(err)
×
3295
                        nMsg.err <- err
×
3296
                        return nil, false
×
3297
                }
×
3298

3299
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
5✔
3300
                        ", adding to waiting batch", prefix, shortChanID)
5✔
3301
                nMsg.err <- nil
5✔
3302
                return nil, false
5✔
3303
        }
3304

3305
        nodeID := nMsg.source.SerializeCompressed()
24✔
3306
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
24✔
3307
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
24✔
3308

24✔
3309
        // Ensure that channel that was retrieved belongs to the peer which
24✔
3310
        // sent the proof announcement.
24✔
3311
        if !(isFirstNode || isSecondNode) {
24✔
3312
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3313
                        "to the peer which sent the proof, short_chan_id=%v",
×
3314
                        shortChanID)
×
3315
                log.Error(err)
×
3316
                nMsg.err <- err
×
3317
                return nil, false
×
3318
        }
×
3319

3320
        // If proof was sent by a local sub-system, then we'll send the
3321
        // announcement signature to the remote node so they can also
3322
        // reconstruct the full channel announcement.
3323
        if !nMsg.isRemote {
38✔
3324
                var remotePubKey [33]byte
14✔
3325
                if isFirstNode {
28✔
3326
                        remotePubKey = chanInfo.NodeKey2Bytes
14✔
3327
                } else {
18✔
3328
                        remotePubKey = chanInfo.NodeKey1Bytes
4✔
3329
                }
4✔
3330

3331
                // Since the remote peer might not be online we'll call a
3332
                // method that will attempt to deliver the proof when it comes
3333
                // online.
3334
                err := d.reliableSender.sendMessage(ann, remotePubKey)
14✔
3335
                if err != nil {
14✔
3336
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3337
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3338
                                ann.ShortChannelID, remotePubKey, err)
×
3339
                        nMsg.err <- err
×
3340
                        return nil, false
×
3341
                }
×
3342
        }
3343

3344
        // Check if we already have the full proof for this channel.
3345
        if chanInfo.AuthProof != nil {
29✔
3346
                // If we already have the fully assembled proof, then the peer
5✔
3347
                // sending us their proof has probably not received our local
5✔
3348
                // proof yet. So be kind and send them the full proof.
5✔
3349
                if nMsg.isRemote {
10✔
3350
                        peerID := nMsg.source.SerializeCompressed()
5✔
3351
                        log.Debugf("Got AnnounceSignatures for channel with " +
5✔
3352
                                "full proof.")
5✔
3353

5✔
3354
                        d.wg.Add(1)
5✔
3355
                        go func() {
10✔
3356
                                defer d.wg.Done()
5✔
3357

5✔
3358
                                log.Debugf("Received half proof for channel "+
5✔
3359
                                        "%v with existing full proof. Sending"+
5✔
3360
                                        " full proof to peer=%x",
5✔
3361
                                        ann.ChannelID, peerID)
5✔
3362

5✔
3363
                                ca, _, _, err := netann.CreateChanAnnouncement(
5✔
3364
                                        chanInfo.AuthProof, chanInfo, e1, e2,
5✔
3365
                                )
5✔
3366
                                if err != nil {
5✔
3367
                                        log.Errorf("unable to gen ann: %v",
×
3368
                                                err)
×
3369
                                        return
×
3370
                                }
×
3371

3372
                                err = nMsg.peer.SendMessage(false, ca)
5✔
3373
                                if err != nil {
5✔
3374
                                        log.Errorf("Failed sending full proof"+
×
3375
                                                " to peer=%x: %v", peerID, err)
×
3376
                                        return
×
3377
                                }
×
3378

3379
                                log.Debugf("Full proof sent to peer=%x for "+
5✔
3380
                                        "chanID=%v", peerID, ann.ChannelID)
5✔
3381
                        }()
3382
                }
3383

3384
                log.Debugf("Already have proof for channel with chanID=%v",
5✔
3385
                        ann.ChannelID)
5✔
3386
                nMsg.err <- nil
5✔
3387
                return nil, true
5✔
3388
        }
3389

3390
        // Check that we received the opposite proof. If so, then we're now
3391
        // able to construct the full proof, and create the channel
3392
        // announcement. If we didn't receive the opposite half of the proof
3393
        // then we should store this one, and wait for the opposite to be
3394
        // received.
3395
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
23✔
3396
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
23✔
3397
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
23✔
3398
                err := fmt.Errorf("unable to get the opposite proof for "+
×
3399
                        "short_chan_id=%v: %v", shortChanID, err)
×
3400
                log.Error(err)
×
3401
                nMsg.err <- err
×
3402
                return nil, false
×
3403
        }
×
3404

3405
        if err == channeldb.ErrWaitingProofNotFound {
36✔
3406
                err := d.cfg.WaitingProofStore.Add(proof)
13✔
3407
                if err != nil {
13✔
3408
                        err := fmt.Errorf("unable to store the proof for "+
×
3409
                                "short_chan_id=%v: %v", shortChanID, err)
×
3410
                        log.Error(err)
×
3411
                        nMsg.err <- err
×
3412
                        return nil, false
×
3413
                }
×
3414

3415
                log.Infof("1/2 of channel ann proof received for "+
13✔
3416
                        "short_chan_id=%v, waiting for other half",
13✔
3417
                        shortChanID)
13✔
3418

13✔
3419
                nMsg.err <- nil
13✔
3420
                return nil, false
13✔
3421
        }
3422

3423
        // We now have both halves of the channel announcement proof, then
3424
        // we'll reconstruct the initial announcement so we can validate it
3425
        // shortly below.
3426
        var dbProof models.ChannelAuthProof
14✔
3427
        if isFirstNode {
19✔
3428
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
5✔
3429
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
5✔
3430
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
5✔
3431
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
5✔
3432
        } else {
18✔
3433
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
13✔
3434
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
13✔
3435
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
13✔
3436
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
13✔
3437
        }
13✔
3438

3439
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
14✔
3440
                &dbProof, chanInfo, e1, e2,
14✔
3441
        )
14✔
3442
        if err != nil {
14✔
3443
                log.Error(err)
×
3444
                nMsg.err <- err
×
3445
                return nil, false
×
3446
        }
×
3447

3448
        // With all the necessary components assembled validate the full
3449
        // channel announcement proof.
3450
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
14✔
3451
        if err != nil {
14✔
3452
                err := fmt.Errorf("channel announcement proof for "+
×
3453
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3454

×
3455
                log.Error(err)
×
3456
                nMsg.err <- err
×
3457
                return nil, false
×
3458
        }
×
3459

3460
        // If the channel was returned by the router it means that existence of
3461
        // funding point and inclusion of nodes bitcoin keys in it already
3462
        // checked by the router. In this stage we should check that node keys
3463
        // attest to the bitcoin keys by validating the signatures of
3464
        // announcement. If proof is valid then we'll populate the channel edge
3465
        // with it, so we can announce it on peer connect.
3466
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
14✔
3467
        if err != nil {
14✔
3468
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
3469
                        " %v", ann.ChannelID, err)
×
3470
                log.Error(err)
×
3471
                nMsg.err <- err
×
3472
                return nil, false
×
3473
        }
×
3474

3475
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
14✔
3476
        if err != nil {
14✔
3477
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3478
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3479
                log.Error(err)
×
3480
                nMsg.err <- err
×
3481
                return nil, false
×
3482
        }
×
3483

3484
        // Proof was successfully created and now can announce the channel to
3485
        // the remain network.
3486
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
14✔
3487
                ", adding to next ann batch", shortChanID)
14✔
3488

14✔
3489
        // Assemble the necessary announcements to add to the next broadcasting
14✔
3490
        // batch.
14✔
3491
        var announcements []networkMsg
14✔
3492
        announcements = append(announcements, networkMsg{
14✔
3493
                peer:   nMsg.peer,
14✔
3494
                source: nMsg.source,
14✔
3495
                msg:    chanAnn,
14✔
3496
        })
14✔
3497
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
27✔
3498
                announcements = append(announcements, networkMsg{
13✔
3499
                        peer:   nMsg.peer,
13✔
3500
                        source: src,
13✔
3501
                        msg:    e1Ann,
13✔
3502
                })
13✔
3503
        }
13✔
3504
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
26✔
3505
                announcements = append(announcements, networkMsg{
12✔
3506
                        peer:   nMsg.peer,
12✔
3507
                        source: src,
12✔
3508
                        msg:    e2Ann,
12✔
3509
                })
12✔
3510
        }
12✔
3511

3512
        // We'll also send along the node announcements for each channel
3513
        // participant if we know of them. To ensure our node announcement
3514
        // propagates to our channel counterparty, we'll set the source for
3515
        // each announcement to the node it belongs to, otherwise we won't send
3516
        // it since the source gets skipped. This isn't necessary for channel
3517
        // updates and announcement signatures since we send those directly to
3518
        // our channel counterparty through the gossiper's reliable sender.
3519
        node1Ann, err := d.fetchNodeAnn(chanInfo.NodeKey1Bytes)
14✔
3520
        if err != nil {
20✔
3521
                log.Debugf("Unable to fetch node announcement for %x: %v",
6✔
3522
                        chanInfo.NodeKey1Bytes, err)
6✔
3523
        } else {
18✔
3524
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
24✔
3525
                        announcements = append(announcements, networkMsg{
12✔
3526
                                peer:   nMsg.peer,
12✔
3527
                                source: nodeKey1,
12✔
3528
                                msg:    node1Ann,
12✔
3529
                        })
12✔
3530
                }
12✔
3531
        }
3532

3533
        node2Ann, err := d.fetchNodeAnn(chanInfo.NodeKey2Bytes)
14✔
3534
        if err != nil {
22✔
3535
                log.Debugf("Unable to fetch node announcement for %x: %v",
8✔
3536
                        chanInfo.NodeKey2Bytes, err)
8✔
3537
        } else {
18✔
3538
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
20✔
3539
                        announcements = append(announcements, networkMsg{
10✔
3540
                                peer:   nMsg.peer,
10✔
3541
                                source: nodeKey2,
10✔
3542
                                msg:    node2Ann,
10✔
3543
                        })
10✔
3544
                }
10✔
3545
        }
3546

3547
        nMsg.err <- nil
14✔
3548
        return announcements, true
14✔
3549
}
3550

3551
// isBanned returns true if the peer identified by pubkey is banned for sending
3552
// invalid channel announcements.
3553
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
209✔
3554
        return d.banman.isBanned(pubkey)
209✔
3555
}
209✔
3556

3557
// ShouldDisconnect returns true if we should disconnect the peer identified by
3558
// pubkey.
3559
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3560
        bool, error) {
207✔
3561

207✔
3562
        pubkeySer := pubkey.SerializeCompressed()
207✔
3563

207✔
3564
        var pubkeyBytes [33]byte
207✔
3565
        copy(pubkeyBytes[:], pubkeySer)
207✔
3566

207✔
3567
        // If the public key is banned, check whether or not this is a channel
207✔
3568
        // peer.
207✔
3569
        if d.isBanned(pubkeyBytes) {
209✔
3570
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3571
                if err != nil {
2✔
3572
                        return false, err
×
3573
                }
×
3574

3575
                // We should only disconnect non-channel peers.
3576
                if !isChanPeer {
3✔
3577
                        return true, nil
1✔
3578
                }
1✔
3579
        }
3580

3581
        return false, nil
206✔
3582
}
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