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

lightningnetwork / lnd / 12118348650

02 Dec 2024 11:25AM UTC coverage: 58.552% (-0.4%) from 58.977%
12118348650

Pull #9175

github

ellemouton
lnwire: add NodeAnnouncement2
Pull Request #9175: lnwire+netann: update structure of g175 messages to be pure TLV

405 of 571 new or added lines in 11 files covered. (70.93%)

1754 existing lines in 33 files now uncovered.

133774 of 228469 relevant lines covered (58.55%)

19422.52 hits per line

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

80.04
/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"
15
        "github.com/btcsuite/btcd/chaincfg/chainhash"
16
        "github.com/btcsuite/btcd/txscript"
17
        "github.com/btcsuite/btcd/wire"
18
        "github.com/davecgh/go-spew/spew"
19
        "github.com/lightninglabs/neutrino/cache"
20
        "github.com/lightninglabs/neutrino/cache/lru"
21
        "github.com/lightningnetwork/lnd/batch"
22
        "github.com/lightningnetwork/lnd/chainntnfs"
23
        "github.com/lightningnetwork/lnd/channeldb"
24
        "github.com/lightningnetwork/lnd/fn"
25
        "github.com/lightningnetwork/lnd/graph"
26
        graphdb "github.com/lightningnetwork/lnd/graph/db"
27
        "github.com/lightningnetwork/lnd/graph/db/models"
28
        "github.com/lightningnetwork/lnd/keychain"
29
        "github.com/lightningnetwork/lnd/lnpeer"
30
        "github.com/lightningnetwork/lnd/lnutils"
31
        "github.com/lightningnetwork/lnd/lnwallet"
32
        "github.com/lightningnetwork/lnd/lnwire"
33
        "github.com/lightningnetwork/lnd/multimutex"
34
        "github.com/lightningnetwork/lnd/netann"
35
        "github.com/lightningnetwork/lnd/routing/route"
36
        "github.com/lightningnetwork/lnd/ticker"
37
        "golang.org/x/time/rate"
38
)
39

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

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

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

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

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

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

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

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

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

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

94
// apply applies the optional fields within the functional options.
95
func (f *optionalMsgFields) apply(optionalMsgFields ...OptionalMsgField) {
51✔
96
        for _, optionalMsgField := range optionalMsgFields {
60✔
97
                optionalMsgField(f)
9✔
98
        }
9✔
99
}
100

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

106
// ChannelCapacity is an optional field that lets the gossiper know of the
107
// capacity of a channel.
108
func ChannelCapacity(capacity btcutil.Amount) OptionalMsgField {
31✔
109
        return func(f *optionalMsgFields) {
36✔
110
                f.capacity = &capacity
5✔
111
        }
5✔
112
}
113

114
// ChannelPoint is an optional field that lets the gossiper know of the outpoint
115
// of a channel.
116
func ChannelPoint(op wire.OutPoint) OptionalMsgField {
34✔
117
        return func(f *optionalMsgFields) {
42✔
118
                f.channelPoint = &op
8✔
119
        }
8✔
120
}
121

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

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

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

150
        isRemote bool
151

152
        err chan error
153
}
154

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

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

168
// Config defines the configuration for the service. ALL elements within the
169
// configuration MUST be non-nil for the service to carry out its duties.
170
type Config struct {
171
        // ChainParams holds the chain parameters for the active network this
172
        // node is participating on.
173
        ChainParams *chaincfg.Params
174

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

181
        // ChainIO represents an abstraction over a source that can query the
182
        // blockchain.
183
        ChainIO lnwallet.BlockChainIO
184

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

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

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

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

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

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

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

227
        // ProofMatureDelta the number of confirmations which is needed before
228
        // exchange the channel announcement proofs.
229
        ProofMatureDelta uint32
230

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

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

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

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

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

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

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

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

280
        // NoTimestampQueries will prevent the GossipSyncer from querying
281
        // timestamps of announcement messages from the peer and from replying
282
        // to timestamp queries.
283
        NoTimestampQueries bool
284

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

291
        // HistoricalSyncTicker is a ticker responsible for notifying the
292
        // syncManager when it should attempt a historical sync with a gossip
293
        // sync peer.
294
        HistoricalSyncTicker ticker.Ticker
295

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

302
        // MinimumBatchSize is minimum size of a sub batch of announcement
303
        // messages.
304
        MinimumBatchSize int
305

306
        // SubBatchDelay is the delay between sending sub batches of
307
        // gossip messages.
308
        SubBatchDelay time.Duration
309

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

316
        // PinnedSyncers is a set of peers that will always transition to
317
        // ActiveSync upon connection. These peers will never transition to
318
        // PassiveSync.
319
        PinnedSyncers PinnedSyncers
320

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

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

330
        // IsAlias returns true if a given ShortChannelID is an alias for
331
        // option_scid_alias channels.
332
        IsAlias func(scid lnwire.ShortChannelID) bool
333

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

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

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

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

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

360
        // chainHash is a hash that indicates which resident chain of the
361
        // AuthenticatedGossiper. Any announcements that don't match this
362
        // chain hash will be ignored. This is an internal config value obtained
363
        // from ChainParams.
364
        chainHash *chainhash.Hash
365
}
366

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

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

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

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

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

466✔
402
        return k
466✔
403
}
466✔
404

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

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

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

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

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

442
        quit chan struct{}
443
        wg   sync.WaitGroup
444

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

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

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

459
        // banman tracks our peer's ban status.
460
        banman *banman
461

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

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

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

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

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

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

491
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
492

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

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

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

518
        sync.Mutex
519
}
520

521
// New creates a new AuthenticatedGossiper instance, initialized with the
522
// passed configuration parameters.
523
func New(cfg Config, selfKeyDesc *keychain.KeyDescriptor) *AuthenticatedGossiper {
31✔
524
        cfg.chainHash = cfg.ChainParams.GenesisHash
31✔
525

31✔
526
        gossiper := &AuthenticatedGossiper{
31✔
527
                selfKey:           selfKeyDesc.PubKey,
31✔
528
                selfKeyLoc:        selfKeyDesc.KeyLocator,
31✔
529
                cfg:               &cfg,
31✔
530
                networkMsgs:       make(chan *networkMsg),
31✔
531
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
31✔
532
                quit:              make(chan struct{}),
31✔
533
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
31✔
534
                prematureChannelUpdates: lru.NewCache[uint64, *cachedNetworkMsg]( //nolint: lll
31✔
535
                        maxPrematureUpdates,
31✔
536
                ),
31✔
537
                channelMtx: multimutex.NewMutex[uint64](),
31✔
538
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
31✔
539
                        maxRejectedUpdates,
31✔
540
                ),
31✔
541
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
31✔
542
                banman:                newBanman(),
31✔
543
        }
31✔
544

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

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

31✔
565
        return gossiper
31✔
566
}
31✔
567

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

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

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

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

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

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

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

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

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

635
        d.syncMgr.Start()
31✔
636

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

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

31✔
644
        return nil
31✔
645
}
646

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

743
                return true
1✔
744
        }
745

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

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

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

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

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

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

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

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

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

793
        d.syncMgr.Stop()
31✔
794

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

904
        return nMsg.err
286✔
905
}
906

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

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

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

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

934
        return nMsg.err
51✔
935
}
936

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

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

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

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

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

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

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

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

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

995
        sync.Mutex
996
}
997

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

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

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

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

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

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

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

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

25✔
1048
                        return
25✔
1049
                }
25✔
1050

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

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

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

×
1074
                                return
×
1075
                        }
×
1076

1077
                        oldTimestamp = update.Timestamp
3✔
1078
                }
1079

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

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

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

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

44✔
1104
                        return
44✔
1105
                }
44✔
1106

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

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

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

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

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

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

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

22✔
1146
                        return
22✔
1147
                }
22✔
1148

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

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

58✔
1162
        for _, msg := range msgs {
148✔
1163
                d.addMsg(msg)
90✔
1164
        }
90✔
1165
}
1166

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

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

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

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

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

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

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

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

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

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

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

1234
        d.reset()
291✔
1235

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

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

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

15✔
1251
        if subBatchSize < minimumBatchSize {
20✔
1252
                return minimumBatchSize
5✔
1253
        }
5✔
1254

1255
        return subBatchSize
10✔
1256
}
1257

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

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

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

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

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

73✔
1286
        return splitAnnouncementBatch
73✔
1287
}
1288

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

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

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

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

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

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

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

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

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

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

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

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

1364
        for _, msgChunk := range annBatch {
63✔
1365
                msgChunk := msgChunk
28✔
1366

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

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

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

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

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

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

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

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

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

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

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

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

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

25✔
1455
                                if emittedAnnouncements != nil {
39✔
1456
                                        announcements.AddMsgs(
14✔
1457
                                                emittedAnnouncements...,
14✔
1458
                                        )
14✔
1459
                                }
14✔
1460
                                continue
25✔
1461
                        }
1462

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1560
                return
×
1561
        }
1562

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1765
        return nil
1✔
1766
}
1767

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

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

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

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

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

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

1818
                                chanUpdate.Signature = lnSig
4✔
1819
                        }
1820

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

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

1846
        return chanUpdates, nil
5✔
1847
}
1848

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

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

1862
        return remotePubKey
16✔
1863
}
1864

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

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

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

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

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

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

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

×
1946
        }
×
1947

1948
        return announcements, nil
×
1949
}
1950

1951
// fetchPKScript fetches the output script for the given SCID.
1952
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
NEW
1953
        txscript.ScriptClass, btcutil.Address, error) {
×
NEW
1954

×
NEW
1955
        pkScript, err := lnwallet.FetchPKScriptWithQuit(
×
NEW
1956
                d.cfg.ChainIO, chanID, d.quit,
×
NEW
1957
        )
×
NEW
1958
        if err != nil {
×
NEW
1959
                return txscript.WitnessUnknownTy, nil, err
×
NEW
1960
        }
×
1961

NEW
1962
        scriptClass, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
NEW
1963
                pkScript, d.cfg.ChainParams,
×
NEW
1964
        )
×
NEW
1965
        if err != nil {
×
NEW
1966
                return txscript.WitnessUnknownTy, nil, err
×
NEW
1967
        }
×
1968

NEW
1969
        if len(addrs) != 1 {
×
NEW
1970
                return txscript.WitnessUnknownTy, nil, fmt.Errorf("expected "+
×
NEW
1971
                        "1 address, got: %d", len(addrs))
×
NEW
1972
        }
×
1973

NEW
1974
        return scriptClass, addrs[0], nil
×
1975
}
1976

1977
// addNode processes the given node announcement, and adds it to our channel
1978
// graph.
1979
func (d *AuthenticatedGossiper) addNode(msg *lnwire.NodeAnnouncement,
1980
        op ...batch.SchedulerOption) error {
21✔
1981

21✔
1982
        if err := graph.ValidateNodeAnn(msg); err != nil {
22✔
1983
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
1984
                        err)
1✔
1985
        }
1✔
1986

1987
        timestamp := time.Unix(int64(msg.Timestamp), 0)
20✔
1988
        features := lnwire.NewFeatureVector(msg.Features, lnwire.Features)
20✔
1989
        node := &models.LightningNode{
20✔
1990
                HaveNodeAnnouncement: true,
20✔
1991
                LastUpdate:           timestamp,
20✔
1992
                Addresses:            msg.Addresses,
20✔
1993
                PubKeyBytes:          msg.NodeID,
20✔
1994
                Alias:                msg.Alias.String(),
20✔
1995
                AuthSigBytes:         msg.Signature.ToSignatureBytes(),
20✔
1996
                Features:             features,
20✔
1997
                Color:                msg.RGBColor,
20✔
1998
                ExtraOpaqueData:      msg.ExtraOpaqueData,
20✔
1999
        }
20✔
2000

20✔
2001
        return d.cfg.Graph.AddNode(node, op...)
20✔
2002
}
2003

2004
// isPremature decides whether a given network message has a block height+delta
2005
// value specified in the future. If so, the message will be added to the
2006
// future message map and be processed when the block height as reached.
2007
//
2008
// NOTE: must be used inside a lock.
2009
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2010
        delta uint32, msg *networkMsg) bool {
283✔
2011
        // TODO(roasbeef) make height delta 6
283✔
2012
        //  * or configurable
283✔
2013

283✔
2014
        msgHeight := chanID.BlockHeight + delta
283✔
2015

283✔
2016
        // The message height is smaller or equal to our best known height,
283✔
2017
        // thus the message is mature.
283✔
2018
        if msgHeight <= d.bestHeight {
565✔
2019
                return false
282✔
2020
        }
282✔
2021

2022
        // Add the premature message to our future messages which will be
2023
        // resent once the block height has reached.
2024
        //
2025
        // Copy the networkMsgs since the old message's err chan will be
2026
        // consumed.
2027
        copied := &networkMsg{
2✔
2028
                peer:              msg.peer,
2✔
2029
                source:            msg.source,
2✔
2030
                msg:               msg.msg,
2✔
2031
                optionalMsgFields: msg.optionalMsgFields,
2✔
2032
                isRemote:          msg.isRemote,
2✔
2033
                err:               make(chan error, 1),
2✔
2034
        }
2✔
2035

2✔
2036
        // Create the cached message.
2✔
2037
        cachedMsg := &cachedFutureMsg{
2✔
2038
                msg:    copied,
2✔
2039
                height: msgHeight,
2✔
2040
        }
2✔
2041

2✔
2042
        // Increment the msg ID and add it to the cache.
2✔
2043
        nextMsgID := d.futureMsgs.nextMsgID()
2✔
2044
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
2✔
2045
        if err != nil {
2✔
2046
                log.Errorf("Adding future message got error: %v", err)
×
2047
        }
×
2048

2049
        log.Debugf("Network message: %v added to future messages for "+
2✔
2050
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
2✔
2051
                msgHeight, d.bestHeight)
2✔
2052

2✔
2053
        return true
2✔
2054
}
2055

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

334✔
2066
        // If this is a remote update, we set the scheduler option to lazily
334✔
2067
        // add it to the graph.
334✔
2068
        var schedulerOp []batch.SchedulerOption
334✔
2069
        if nMsg.isRemote {
621✔
2070
                schedulerOp = append(schedulerOp, batch.LazyAdd())
287✔
2071
        }
287✔
2072

2073
        switch msg := nMsg.msg.(type) {
334✔
2074
        // A new node announcement has arrived which either presents new
2075
        // information about a node in one of the channels we know about, or a
2076
        // updating previously advertised information.
2077
        case *lnwire.NodeAnnouncement:
28✔
2078
                return d.handleNodeAnnouncement(nMsg, msg, schedulerOp)
28✔
2079

2080
        // A new channel announcement has arrived, this indicates the
2081
        // *creation* of a new channel within the network. This only advertises
2082
        // the existence of a channel and not yet the routing policies in
2083
        // either direction of the channel.
2084
        case *lnwire.ChannelAnnouncement1:
234✔
2085
                return d.handleChanAnnouncement(nMsg, msg, schedulerOp)
234✔
2086

2087
        // A new authenticated channel edge update has arrived. This indicates
2088
        // that the directional information for an already known channel has
2089
        // been updated.
2090
        case *lnwire.ChannelUpdate1:
59✔
2091
                return d.handleChanUpdate(nMsg, msg, schedulerOp)
59✔
2092

2093
        // A new signature announcement has been received. This indicates
2094
        // willingness of nodes involved in the funding of a channel to
2095
        // announce this new channel to the rest of the world.
2096
        case *lnwire.AnnounceSignatures1:
25✔
2097
                return d.handleAnnSig(nMsg, msg)
25✔
2098

2099
        default:
×
2100
                err := errors.New("wrong type of the announcement")
×
2101
                nMsg.err <- err
×
2102
                return nil, false
×
2103
        }
2104
}
2105

2106
// processZombieUpdate determines whether the provided channel update should
2107
// resurrect a given zombie edge.
2108
//
2109
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2110
// should be inspected.
2111
func (d *AuthenticatedGossiper) processZombieUpdate(
2112
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2113
        msg *lnwire.ChannelUpdate1) error {
7✔
2114

7✔
2115
        // The least-significant bit in the flag on the channel update tells us
7✔
2116
        // which edge is being updated.
7✔
2117
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
7✔
2118

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

2136
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
6✔
2137
        if err != nil {
7✔
2138
                return fmt.Errorf("unable to verify channel "+
1✔
2139
                        "update signature: %v", err)
1✔
2140
        }
1✔
2141

2142
        // With the signature valid, we'll proceed to mark the
2143
        // edge as live and wait for the channel announcement to
2144
        // come through again.
2145
        err = d.cfg.Graph.MarkEdgeLive(scid)
5✔
2146
        switch {
5✔
2147
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2148
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2149
                        "zombie index: %v", err)
×
2150

×
2151
                return nil
×
2152

2153
        case err != nil:
×
2154
                return fmt.Errorf("unable to remove edge with "+
×
2155
                        "chan_id=%v from zombie index: %v",
×
2156
                        msg.ShortChannelID, err)
×
2157

2158
        default:
5✔
2159
        }
2160

2161
        log.Debugf("Removed edge with chan_id=%v from zombie "+
5✔
2162
                "index", msg.ShortChannelID)
5✔
2163

5✔
2164
        return nil
5✔
2165
}
2166

2167
// fetchNodeAnn fetches the latest signed node announcement from our point of
2168
// view for the node with the given public key.
2169
func (d *AuthenticatedGossiper) fetchNodeAnn(
2170
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
24✔
2171

24✔
2172
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
24✔
2173
        if err != nil {
30✔
2174
                return nil, err
6✔
2175
        }
6✔
2176

2177
        return node.NodeAnnouncement(true)
18✔
2178
}
2179

2180
// isMsgStale determines whether a message retrieved from the backing
2181
// MessageStore is seen as stale by the current graph.
2182
func (d *AuthenticatedGossiper) isMsgStale(msg lnwire.Message) bool {
16✔
2183
        switch msg := msg.(type) {
16✔
2184
        case *lnwire.AnnounceSignatures1:
6✔
2185
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
6✔
2186
                        msg.ShortChannelID,
6✔
2187
                )
6✔
2188

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

2201
                // If the proof exists in the graph, then we have successfully
2202
                // received the remote proof and assembled the full proof, so we
2203
                // can safely delete the local proof from the database.
2204
                return chanInfo.AuthProof != nil
6✔
2205

2206
        case *lnwire.ChannelUpdate1:
14✔
2207
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
14✔
2208

14✔
2209
                // If the channel cannot be found, it is most likely a leftover
14✔
2210
                // message for a channel that was closed, so we can consider it
14✔
2211
                // stale.
14✔
2212
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
18✔
2213
                        return true
4✔
2214
                }
4✔
2215
                if err != nil {
14✔
2216
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2217
                                "%v", msg.ShortChannelID, err)
×
2218
                        return false
×
2219
                }
×
2220

2221
                // Otherwise, we'll retrieve the correct policy that we
2222
                // currently have stored within our graph to check if this
2223
                // message is stale by comparing its timestamp.
2224
                var p *models.ChannelEdgePolicy
14✔
2225
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
28✔
2226
                        p = p1
14✔
2227
                } else {
18✔
2228
                        p = p2
4✔
2229
                }
4✔
2230

2231
                // If the policy is still unknown, then we can consider this
2232
                // policy fresh.
2233
                if p == nil {
14✔
2234
                        return false
×
2235
                }
×
2236

2237
                timestamp := time.Unix(int64(msg.Timestamp), 0)
14✔
2238
                return p.LastUpdate.After(timestamp)
14✔
2239

2240
        default:
×
2241
                // We'll make sure to not mark any unsupported messages as stale
×
2242
                // to ensure they are not removed.
×
2243
                return false
×
2244
        }
2245
}
2246

2247
// updateChannel creates a new fully signed update for the channel, and updates
2248
// the underlying graph with the new state.
2249
func (d *AuthenticatedGossiper) updateChannel(info *models.ChannelEdgeInfo,
2250
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2251
        *lnwire.ChannelUpdate1, error) {
8✔
2252

8✔
2253
        // Parse the unsigned edge into a channel update.
8✔
2254
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
8✔
2255

8✔
2256
        // We'll generate a new signature over a digest of the channel
8✔
2257
        // announcement itself and update the timestamp to ensure it propagate.
8✔
2258
        err := netann.SignChannelUpdate(
8✔
2259
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
8✔
2260
                netann.ChanUpdSetTimestamp,
8✔
2261
        )
8✔
2262
        if err != nil {
8✔
2263
                return nil, nil, err
×
2264
        }
×
2265

2266
        // Next, we'll set the new signature in place, and update the reference
2267
        // in the backing slice.
2268
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
8✔
2269
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
8✔
2270

8✔
2271
        // To ensure that our signature is valid, we'll verify it ourself
8✔
2272
        // before committing it to the slice returned.
8✔
2273
        err = netann.ValidateChannelUpdateAnn(
8✔
2274
                d.selfKey, info.Capacity, chanUpdate,
8✔
2275
        )
8✔
2276
        if err != nil {
8✔
2277
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2278
                        "update sig: %v", err)
×
2279
        }
×
2280

2281
        // Finally, we'll write the new edge policy to disk.
2282
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
8✔
2283
                return nil, nil, err
×
2284
        }
×
2285

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

2328
        return chanAnn, chanUpdate, err
8✔
2329
}
2330

2331
// SyncManager returns the gossiper's SyncManager instance.
2332
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
4✔
2333
        return d.syncMgr
4✔
2334
}
4✔
2335

2336
// IsKeepAliveUpdate determines whether this channel update is considered a
2337
// keep-alive update based on the previous channel update processed for the same
2338
// direction.
2339
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2340
        prev *models.ChannelEdgePolicy) bool {
18✔
2341

18✔
2342
        // Both updates should be from the same direction.
18✔
2343
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
18✔
2344
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
18✔
2345

×
2346
                return false
×
2347
        }
×
2348

2349
        // The timestamp should always increase for a keep-alive update.
2350
        timestamp := time.Unix(int64(update.Timestamp), 0)
18✔
2351
        if !timestamp.After(prev.LastUpdate) {
22✔
2352
                return false
4✔
2353
        }
4✔
2354

2355
        // None of the remaining fields should change for a keep-alive update.
2356
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
22✔
2357
                return false
4✔
2358
        }
4✔
2359
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
34✔
2360
                return false
16✔
2361
        }
16✔
2362
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
10✔
2363
                return false
4✔
2364
        }
4✔
2365
        if update.TimeLockDelta != prev.TimeLockDelta {
6✔
2366
                return false
×
2367
        }
×
2368
        if update.HtlcMinimumMsat != prev.MinHTLC {
6✔
2369
                return false
×
2370
        }
×
2371
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
6✔
2372
                return false
×
2373
        }
×
2374
        if update.HtlcMaximumMsat != prev.MaxHTLC {
6✔
2375
                return false
×
2376
        }
×
2377
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
10✔
2378
                return false
4✔
2379
        }
4✔
2380
        return true
6✔
2381
}
2382

2383
// latestHeight returns the gossiper's latest height known of the chain.
2384
func (d *AuthenticatedGossiper) latestHeight() uint32 {
4✔
2385
        d.Lock()
4✔
2386
        defer d.Unlock()
4✔
2387
        return d.bestHeight
4✔
2388
}
4✔
2389

2390
// handleNodeAnnouncement processes a new node announcement.
2391
func (d *AuthenticatedGossiper) handleNodeAnnouncement(nMsg *networkMsg,
2392
        nodeAnn *lnwire.NodeAnnouncement,
2393
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
28✔
2394

28✔
2395
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
28✔
2396

28✔
2397
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
28✔
2398
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
28✔
2399

28✔
2400
        // We'll quickly ask the router if it already has a newer update for
28✔
2401
        // this node so we can skip validating signatures if not required.
28✔
2402
        if d.cfg.Graph.IsStaleNode(nodeAnn.NodeID, timestamp) {
40✔
2403
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
12✔
2404
                nMsg.err <- nil
12✔
2405
                return nil, true
12✔
2406
        }
12✔
2407

2408
        if err := d.addNode(nodeAnn, ops...); err != nil {
24✔
2409
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
4✔
2410
                        err)
4✔
2411

4✔
2412
                if !graph.IsError(
4✔
2413
                        err,
4✔
2414
                        graph.ErrOutdated,
4✔
2415
                        graph.ErrIgnored,
4✔
2416
                        graph.ErrVBarrierShuttingDown,
4✔
2417
                ) {
4✔
2418

×
2419
                        log.Error(err)
×
2420
                }
×
2421

2422
                nMsg.err <- err
4✔
2423
                return nil, false
4✔
2424
        }
2425

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

2437
        var announcements []networkMsg
20✔
2438

20✔
2439
        // If it does, we'll add their announcement to our batch so that it can
20✔
2440
        // be broadcast to the rest of our peers.
20✔
2441
        if isPublic {
27✔
2442
                announcements = append(announcements, networkMsg{
7✔
2443
                        peer:     nMsg.peer,
7✔
2444
                        isRemote: nMsg.isRemote,
7✔
2445
                        source:   nMsg.source,
7✔
2446
                        msg:      nodeAnn,
7✔
2447
                })
7✔
2448
        } else {
24✔
2449
                log.Tracef("Skipping broadcasting node announcement for %x "+
17✔
2450
                        "due to being unadvertised", nodeAnn.NodeID)
17✔
2451
        }
17✔
2452

2453
        nMsg.err <- nil
20✔
2454
        // TODO(roasbeef): get rid of the above
20✔
2455

20✔
2456
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
20✔
2457
                "node=%x", nMsg.peer, timestamp, nodeAnn.NodeID)
20✔
2458

20✔
2459
        return announcements, true
20✔
2460
}
2461

2462
// handleChanAnnouncement processes a new channel announcement.
2463
func (d *AuthenticatedGossiper) handleChanAnnouncement(nMsg *networkMsg,
2464
        ann *lnwire.ChannelAnnouncement1,
2465
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
234✔
2466

234✔
2467
        scid := ann.ShortChannelID
234✔
2468

234✔
2469
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
234✔
2470
                nMsg.peer, scid.ToUint64())
234✔
2471

234✔
2472
        // We'll ignore any channel announcements that target any chain other
234✔
2473
        // than the set of chains we know of.
234✔
2474
        if !bytes.Equal(ann.ChainHash[:], d.cfg.chainHash[:]) {
234✔
2475
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2476
                        ", gossiper on chain=%v", ann.ChainHash,
×
NEW
2477
                        d.cfg.chainHash)
×
2478
                log.Errorf(err.Error())
×
2479

×
2480
                key := newRejectCacheKey(
×
2481
                        scid.ToUint64(),
×
2482
                        sourceToPub(nMsg.source),
×
2483
                )
×
2484
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2485

×
2486
                nMsg.err <- err
×
2487
                return nil, false
×
2488
        }
×
2489

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

×
2497
                key := newRejectCacheKey(
×
2498
                        scid.ToUint64(),
×
2499
                        sourceToPub(nMsg.source),
×
2500
                )
×
2501
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2502

×
2503
                nMsg.err <- err
×
2504
                return nil, false
×
2505
        }
×
2506

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

233✔
2520
        // At this point, we'll now ask the router if this is a zombie/known
233✔
2521
        // edge. If so we can skip all the processing below.
233✔
2522
        if d.cfg.Graph.IsKnownEdge(scid) {
238✔
2523
                nMsg.err <- nil
5✔
2524
                return nil, true
5✔
2525
        }
5✔
2526

2527
        // Check if the channel is already closed in which case we can ignore
2528
        // it.
2529
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
232✔
2530
        if err != nil {
232✔
2531
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2532
                        err)
×
2533
                nMsg.err <- err
×
2534

×
2535
                return nil, false
×
2536
        }
×
2537

2538
        if closed {
233✔
2539
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2540
                log.Error(err)
1✔
2541

1✔
2542
                // If this is an announcement from us, we'll just ignore it.
1✔
2543
                if !nMsg.isRemote {
1✔
2544
                        nMsg.err <- err
×
2545
                        return nil, false
×
2546
                }
×
2547

2548
                // Increment the peer's ban score if they are sending closed
2549
                // channel announcements.
2550
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2551

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

×
2560
                        return nil, false
×
2561
                }
×
2562

2563
                if shouldDc {
1✔
2564
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2565
                }
×
2566

2567
                nMsg.err <- err
1✔
2568

1✔
2569
                return nil, false
1✔
2570
        }
2571

2572
        // If this is a remote channel announcement, then we'll validate all
2573
        // the signatures within the proof as it should be well formed.
2574
        var proof *models.ChannelAuthProof
231✔
2575
        if nMsg.isRemote {
448✔
2576
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
217✔
2577
                if err != nil {
217✔
2578
                        err := fmt.Errorf("unable to validate announcement: "+
×
2579
                                "%v", err)
×
2580

×
2581
                        key := newRejectCacheKey(
×
2582
                                scid.ToUint64(),
×
2583
                                sourceToPub(nMsg.source),
×
2584
                        )
×
2585
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2586

×
2587
                        log.Error(err)
×
2588
                        nMsg.err <- err
×
2589
                        return nil, false
×
2590
                }
×
2591

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

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

2612
        edge := &models.ChannelEdgeInfo{
231✔
2613
                ChannelID:        scid.ToUint64(),
231✔
2614
                ChainHash:        ann.ChainHash,
231✔
2615
                NodeKey1Bytes:    ann.NodeID1,
231✔
2616
                NodeKey2Bytes:    ann.NodeID2,
231✔
2617
                BitcoinKey1Bytes: ann.BitcoinKey1,
231✔
2618
                BitcoinKey2Bytes: ann.BitcoinKey2,
231✔
2619
                AuthProof:        proof,
231✔
2620
                Features:         featureBuf.Bytes(),
231✔
2621
                ExtraOpaqueData:  ann.ExtraOpaqueData,
231✔
2622
        }
231✔
2623

231✔
2624
        // If there were any optional message fields provided, we'll include
231✔
2625
        // them in its serialized disk representation now.
231✔
2626
        if nMsg.optionalMsgFields != nil {
249✔
2627
                if nMsg.optionalMsgFields.capacity != nil {
23✔
2628
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
5✔
2629
                }
5✔
2630
                if nMsg.optionalMsgFields.channelPoint != nil {
26✔
2631
                        cp := *nMsg.optionalMsgFields.channelPoint
8✔
2632
                        edge.ChannelPoint = cp
8✔
2633
                }
8✔
2634

2635
                // Optional tapscript root for custom channels.
2636
                edge.TapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
18✔
2637
        }
2638

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

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

206✔
2655
                defer d.channelMtx.Unlock(scid.ToUint64())
206✔
2656

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

×
2673
                                nMsg.err <- rErr
×
2674
                                return nil, false
×
2675
                        }
×
2676

2677
                        log.Debugf("Extracted %v announcements from rejected "+
4✔
2678
                                "msgs", len(anns))
4✔
2679

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

4✔
2688
                        return anns, true
4✔
2689

2690
                case graph.IsError(
2691
                        err, graph.ErrNoFundingTransaction,
2692
                        graph.ErrInvalidFundingOutput,
2693
                ):
200✔
2694
                        key := newRejectCacheKey(
200✔
2695
                                scid.ToUint64(),
200✔
2696
                                sourceToPub(nMsg.source),
200✔
2697
                        )
200✔
2698
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
200✔
2699

200✔
2700
                        // Increment the peer's ban score. We check isRemote
200✔
2701
                        // so we don't actually ban the peer in case of a local
200✔
2702
                        // bug.
200✔
2703
                        if nMsg.isRemote {
400✔
2704
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
200✔
2705
                        }
200✔
2706

2707
                case graph.IsError(err, graph.ErrChannelSpent):
1✔
2708
                        key := newRejectCacheKey(
1✔
2709
                                scid.ToUint64(),
1✔
2710
                                sourceToPub(nMsg.source),
1✔
2711
                        )
1✔
2712
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2713

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

×
2725
                                nMsg.err <- dbErr
×
2726

×
2727
                                return nil, false
×
2728
                        }
×
2729

2730
                        // Increment the peer's ban score. We check isRemote
2731
                        // so we don't accidentally ban ourselves in case of a
2732
                        // bug.
2733
                        if nMsg.isRemote {
2✔
2734
                                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2735
                        }
1✔
2736

2737
                default:
1✔
2738
                        // Otherwise, this is just a regular rejected edge.
1✔
2739
                        key := newRejectCacheKey(
1✔
2740
                                scid.ToUint64(),
1✔
2741
                                sourceToPub(nMsg.source),
1✔
2742
                        )
1✔
2743
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2744
                }
2745

2746
                if !nMsg.isRemote {
202✔
2747
                        log.Errorf("failed to add edge for local channel: %v",
×
2748
                                err)
×
2749
                        nMsg.err <- err
×
2750

×
2751
                        return nil, false
×
2752
                }
×
2753

2754
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
202✔
2755
                if dcErr != nil {
202✔
2756
                        log.Errorf("failed to check if we should disconnect "+
×
2757
                                "peer: %v", dcErr)
×
2758
                        nMsg.err <- dcErr
×
2759

×
2760
                        return nil, false
×
2761
                }
×
2762

2763
                if shouldDc {
203✔
2764
                        nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2765
                }
1✔
2766

2767
                nMsg.err <- err
202✔
2768

202✔
2769
                return nil, false
202✔
2770
        }
2771

2772
        // If err is nil, release the lock immediately.
2773
        d.channelMtx.Unlock(scid.ToUint64())
29✔
2774

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

29✔
2777
        // If we earlier received any ChannelUpdates for this channel, we can
29✔
2778
        // now process them, as the channel is added to the graph.
29✔
2779
        var channelUpdates []*processedNetworkMsg
29✔
2780

29✔
2781
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
29✔
2782
        if err == nil {
35✔
2783
                // There was actually an entry in the map, so we'll accumulate
6✔
2784
                // it. We don't worry about deletion, since it'll eventually
6✔
2785
                // fall out anyway.
6✔
2786
                chanMsgs := earlyChanUpdates
6✔
2787
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
6✔
2788
        }
6✔
2789

2790
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2791
        // ensure we don't block here, as we can handle only one announcement
2792
        // at a time.
2793
        for _, cu := range channelUpdates {
35✔
2794
                // Skip if already processed.
6✔
2795
                if cu.processed {
8✔
2796
                        continue
2✔
2797
                }
2798

2799
                // Mark the ChannelUpdate as processed. This ensures that a
2800
                // subsequent announcement in the option-scid-alias case does
2801
                // not re-use an old ChannelUpdate.
2802
                cu.processed = true
6✔
2803

6✔
2804
                d.wg.Add(1)
6✔
2805
                go func(updMsg *networkMsg) {
12✔
2806
                        defer d.wg.Done()
6✔
2807

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

6✔
2816
                                select {
6✔
2817
                                case d.networkMsgs <- updMsg:
6✔
2818
                                case <-d.quit:
×
2819
                                        updMsg.err <- ErrGossiperShuttingDown
×
2820
                                }
2821

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

2831
        // Channel announcement was successfully processed and now it might be
2832
        // broadcast to other connected nodes if it was an announcement with
2833
        // proof (remote).
2834
        var announcements []networkMsg
29✔
2835

29✔
2836
        if proof != nil {
44✔
2837
                announcements = append(announcements, networkMsg{
15✔
2838
                        peer:     nMsg.peer,
15✔
2839
                        isRemote: nMsg.isRemote,
15✔
2840
                        source:   nMsg.source,
15✔
2841
                        msg:      ann,
15✔
2842
                })
15✔
2843
        }
15✔
2844

2845
        nMsg.err <- nil
29✔
2846

29✔
2847
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
29✔
2848
                nMsg.peer, scid.ToUint64())
29✔
2849

29✔
2850
        return announcements, true
29✔
2851
}
2852

2853
// handleChanUpdate processes a new channel update.
2854
func (d *AuthenticatedGossiper) handleChanUpdate(nMsg *networkMsg,
2855
        upd *lnwire.ChannelUpdate1,
2856
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
59✔
2857

59✔
2858
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
59✔
2859
                nMsg.peer, upd.ShortChannelID.ToUint64())
59✔
2860

59✔
2861
        // We'll ignore any channel updates that target any chain other than
59✔
2862
        // the set of chains we know of.
59✔
2863
        if !bytes.Equal(upd.ChainHash[:], d.cfg.chainHash[:]) {
59✔
2864
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
NEW
2865
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.chainHash)
×
2866
                log.Errorf(err.Error())
×
2867

×
2868
                key := newRejectCacheKey(
×
2869
                        upd.ShortChannelID.ToUint64(),
×
2870
                        sourceToPub(nMsg.source),
×
2871
                )
×
2872
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2873

×
2874
                nMsg.err <- err
×
2875
                return nil, false
×
2876
        }
×
2877

2878
        blockHeight := upd.ShortChannelID.BlockHeight
59✔
2879
        shortChanID := upd.ShortChannelID.ToUint64()
59✔
2880

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

1✔
2890
                log.Warnf("Update announcement for short_chan_id(%v), is "+
1✔
2891
                        "premature: advertises height %v, only height %v is "+
1✔
2892
                        "known", shortChanID, blockHeight, d.bestHeight)
1✔
2893
                d.Unlock()
1✔
2894
                nMsg.err <- nil
1✔
2895
                return nil, false
1✔
2896
        }
1✔
2897
        d.Unlock()
59✔
2898

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

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

2916
        if d.cfg.Graph.IsStaleEdgePolicy(
59✔
2917
                graphScid, timestamp, upd.ChannelFlags,
59✔
2918
        ) {
65✔
2919

6✔
2920
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
6✔
2921
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
6✔
2922
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
6✔
2923
                )
6✔
2924

6✔
2925
                nMsg.err <- nil
6✔
2926
                return nil, true
6✔
2927
        }
6✔
2928

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

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

×
2942
                return nil, false
×
2943
        }
×
2944

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

57✔
2956
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
57✔
2957
        switch {
57✔
2958
        // No error, break.
2959
        case err == nil:
53✔
2960
                break
53✔
2961

2962
        case errors.Is(err, graphdb.ErrZombieEdge):
7✔
2963
                err = d.processZombieUpdate(chanInfo, graphScid, upd)
7✔
2964
                if err != nil {
9✔
2965
                        log.Debug(err)
2✔
2966
                        nMsg.err <- err
2✔
2967
                        return nil, false
2✔
2968
                }
2✔
2969

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

6✔
2999
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
6✔
3000
                switch {
6✔
3001
                // Nothing in the cache yet, we can just directly insert this
3002
                // element.
3003
                case err == cache.ErrElementNotFound:
6✔
3004
                        _, _ = d.prematureChannelUpdates.Put(
6✔
3005
                                shortChanID, &cachedNetworkMsg{
6✔
3006
                                        msgs: []*processedNetworkMsg{pMsg},
6✔
3007
                                })
6✔
3008

3009
                // There's already something in the cache, so we'll combine the
3010
                // set of messages into a single value.
3011
                default:
4✔
3012
                        msgs := earlyMsgs.msgs
4✔
3013
                        msgs = append(msgs, pMsg)
4✔
3014
                        _, _ = d.prematureChannelUpdates.Put(
4✔
3015
                                shortChanID, &cachedNetworkMsg{
4✔
3016
                                        msgs: msgs,
4✔
3017
                                })
4✔
3018
                }
3019

3020
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
6✔
3021
                        "(shortChanID=%v), saving for reprocessing later",
6✔
3022
                        shortChanID)
6✔
3023

6✔
3024
                // NOTE: We don't return anything on the error channel for this
6✔
3025
                // message, as we expect that will be done when this
6✔
3026
                // ChannelUpdate is later reprocessed.
6✔
3027
                return nil, false
6✔
3028

3029
        default:
×
3030
                err := fmt.Errorf("unable to validate channel update "+
×
3031
                        "short_chan_id=%v: %v", shortChanID, err)
×
3032
                log.Error(err)
×
3033
                nMsg.err <- err
×
3034

×
3035
                key := newRejectCacheKey(
×
3036
                        upd.ShortChannelID.ToUint64(),
×
3037
                        sourceToPub(nMsg.source),
×
3038
                )
×
3039
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3040

×
3041
                return nil, false
×
3042
        }
3043

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

3061
        log.Debugf("Validating ChannelUpdate: channel=%v, from node=%x, has "+
53✔
3062
                "edge=%v", chanInfo.ChannelID, pubKey.SerializeCompressed(),
53✔
3063
                edgeToUpdate != nil)
53✔
3064

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

4✔
3074
                log.Error(rErr)
4✔
3075
                nMsg.err <- rErr
4✔
3076
                return nil, false
4✔
3077
        }
4✔
3078

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

16✔
3121
                        if !rls[direction].Allow() {
25✔
3122
                                log.Debugf("Rate limiting update for channel "+
9✔
3123
                                        "%v from direction %x", shortChanID,
9✔
3124
                                        pubKey.SerializeCompressed())
9✔
3125
                                nMsg.err <- nil
9✔
3126
                                return nil, false
9✔
3127
                        }
9✔
3128
                }
3129
        }
3130

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

43✔
3152
        if err := d.cfg.Graph.UpdateEdge(update, ops...); err != nil {
47✔
3153
                if graph.IsError(
4✔
3154
                        err, graph.ErrOutdated,
4✔
3155
                        graph.ErrIgnored,
4✔
3156
                        graph.ErrVBarrierShuttingDown,
4✔
3157
                ) {
8✔
3158

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

×
3170
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3171
                                shortChanID, err)
×
3172
                }
×
3173

3174
                nMsg.err <- err
4✔
3175
                return nil, false
4✔
3176
        }
3177

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

4✔
3195
                                sig, err := d.cfg.SignAliasUpdate(upd)
4✔
3196
                                if err != nil {
4✔
3197
                                        log.Error(err)
×
3198
                                        nMsg.err <- err
×
3199
                                        return nil, false
×
3200
                                }
×
3201

3202
                                lnSig, err := lnwire.NewSigFromSignature(sig)
4✔
3203
                                if err != nil {
4✔
3204
                                        log.Error(err)
×
3205
                                        nMsg.err <- err
×
3206
                                        return nil, false
×
3207
                                }
×
3208

3209
                                upd.Signature = lnSig
4✔
3210
                        }
3211
                }
3212

3213
                // Get our peer's public key.
3214
                remotePubKey := remotePubFromChanInfo(
15✔
3215
                        chanInfo, upd.ChannelFlags,
15✔
3216
                )
15✔
3217

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

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

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

3249
        nMsg.err <- nil
43✔
3250

43✔
3251
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
43✔
3252
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
43✔
3253
                timestamp)
43✔
3254
        return announcements, true
43✔
3255
}
3256

3257
// handleAnnSig processes a new announcement signatures message.
3258
func (d *AuthenticatedGossiper) handleAnnSig(nMsg *networkMsg,
3259
        ann *lnwire.AnnounceSignatures1) ([]networkMsg, bool) {
25✔
3260

25✔
3261
        needBlockHeight := ann.ShortChannelID.BlockHeight +
25✔
3262
                d.cfg.ProofMatureDelta
25✔
3263
        shortChanID := ann.ShortChannelID.ToUint64()
25✔
3264

25✔
3265
        prefix := "local"
25✔
3266
        if nMsg.isRemote {
40✔
3267
                prefix = "remote"
15✔
3268
        }
15✔
3269

3270
        log.Infof("Received new %v announcement signature for %v", prefix,
25✔
3271
                ann.ShortChannelID)
25✔
3272

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

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

25✔
3299
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
25✔
3300
                ann.ShortChannelID,
25✔
3301
        )
25✔
3302
        if err != nil {
30✔
3303
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
5✔
3304
                if err != nil {
9✔
3305
                        err := fmt.Errorf("unable to store the proof for "+
4✔
3306
                                "short_chan_id=%v: %v", shortChanID, err)
4✔
3307
                        log.Error(err)
4✔
3308
                        nMsg.err <- err
4✔
3309

4✔
3310
                        return nil, false
4✔
3311
                }
4✔
3312

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

3323
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
5✔
3324
                        ", adding to waiting batch", prefix, shortChanID)
5✔
3325
                nMsg.err <- nil
5✔
3326
                return nil, false
5✔
3327
        }
3328

3329
        nodeID := nMsg.source.SerializeCompressed()
24✔
3330
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
24✔
3331
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
24✔
3332

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

3344
        // If proof was sent by a local sub-system, then we'll send the
3345
        // announcement signature to the remote node so they can also
3346
        // reconstruct the full channel announcement.
3347
        if !nMsg.isRemote {
38✔
3348
                var remotePubKey [33]byte
14✔
3349
                if isFirstNode {
28✔
3350
                        remotePubKey = chanInfo.NodeKey2Bytes
14✔
3351
                } else {
18✔
3352
                        remotePubKey = chanInfo.NodeKey1Bytes
4✔
3353
                }
4✔
3354

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

3368
        // Check if we already have the full proof for this channel.
3369
        if chanInfo.AuthProof != nil {
29✔
3370
                // If we already have the fully assembled proof, then the peer
5✔
3371
                // sending us their proof has probably not received our local
5✔
3372
                // proof yet. So be kind and send them the full proof.
5✔
3373
                if nMsg.isRemote {
10✔
3374
                        peerID := nMsg.source.SerializeCompressed()
5✔
3375
                        log.Debugf("Got AnnounceSignatures for channel with " +
5✔
3376
                                "full proof.")
5✔
3377

5✔
3378
                        d.wg.Add(1)
5✔
3379
                        go func() {
10✔
3380
                                defer d.wg.Done()
5✔
3381

5✔
3382
                                log.Debugf("Received half proof for channel "+
5✔
3383
                                        "%v with existing full proof. Sending"+
5✔
3384
                                        " full proof to peer=%x",
5✔
3385
                                        ann.ChannelID, peerID)
5✔
3386

5✔
3387
                                ca, _, _, err := netann.CreateChanAnnouncement(
5✔
3388
                                        chanInfo.AuthProof, chanInfo, e1, e2,
5✔
3389
                                )
5✔
3390
                                if err != nil {
5✔
3391
                                        log.Errorf("unable to gen ann: %v",
×
3392
                                                err)
×
3393
                                        return
×
3394
                                }
×
3395

3396
                                err = nMsg.peer.SendMessage(false, ca)
5✔
3397
                                if err != nil {
5✔
3398
                                        log.Errorf("Failed sending full proof"+
×
3399
                                                " to peer=%x: %v", peerID, err)
×
3400
                                        return
×
3401
                                }
×
3402

3403
                                log.Debugf("Full proof sent to peer=%x for "+
5✔
3404
                                        "chanID=%v", peerID, ann.ChannelID)
5✔
3405
                        }()
3406
                }
3407

3408
                log.Debugf("Already have proof for channel with chanID=%v",
5✔
3409
                        ann.ChannelID)
5✔
3410
                nMsg.err <- nil
5✔
3411
                return nil, true
5✔
3412
        }
3413

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

3429
        if err == channeldb.ErrWaitingProofNotFound {
36✔
3430
                err := d.cfg.WaitingProofStore.Add(proof)
13✔
3431
                if err != nil {
13✔
3432
                        err := fmt.Errorf("unable to store the proof for "+
×
3433
                                "short_chan_id=%v: %v", shortChanID, err)
×
3434
                        log.Error(err)
×
3435
                        nMsg.err <- err
×
3436
                        return nil, false
×
3437
                }
×
3438

3439
                log.Infof("1/2 of channel ann proof received for "+
13✔
3440
                        "short_chan_id=%v, waiting for other half",
13✔
3441
                        shortChanID)
13✔
3442

13✔
3443
                nMsg.err <- nil
13✔
3444
                return nil, false
13✔
3445
        }
3446

3447
        // We now have both halves of the channel announcement proof, then
3448
        // we'll reconstruct the initial announcement so we can validate it
3449
        // shortly below.
3450
        var dbProof models.ChannelAuthProof
14✔
3451
        if isFirstNode {
19✔
3452
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
5✔
3453
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
5✔
3454
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
5✔
3455
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
5✔
3456
        } else {
18✔
3457
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
13✔
3458
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
13✔
3459
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
13✔
3460
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
13✔
3461
        }
13✔
3462

3463
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
14✔
3464
                &dbProof, chanInfo, e1, e2,
14✔
3465
        )
14✔
3466
        if err != nil {
14✔
3467
                log.Error(err)
×
3468
                nMsg.err <- err
×
3469
                return nil, false
×
3470
        }
×
3471

3472
        // With all the necessary components assembled validate the full
3473
        // channel announcement proof.
3474
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
14✔
3475
        if err != nil {
14✔
3476
                err := fmt.Errorf("channel announcement proof for "+
×
3477
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3478

×
3479
                log.Error(err)
×
3480
                nMsg.err <- err
×
3481
                return nil, false
×
3482
        }
×
3483

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

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

3508
        // Proof was successfully created and now can announce the channel to
3509
        // the remain network.
3510
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
14✔
3511
                ", adding to next ann batch", shortChanID)
14✔
3512

14✔
3513
        // Assemble the necessary announcements to add to the next broadcasting
14✔
3514
        // batch.
14✔
3515
        var announcements []networkMsg
14✔
3516
        announcements = append(announcements, networkMsg{
14✔
3517
                peer:   nMsg.peer,
14✔
3518
                source: nMsg.source,
14✔
3519
                msg:    chanAnn,
14✔
3520
        })
14✔
3521
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
27✔
3522
                announcements = append(announcements, networkMsg{
13✔
3523
                        peer:   nMsg.peer,
13✔
3524
                        source: src,
13✔
3525
                        msg:    e1Ann,
13✔
3526
                })
13✔
3527
        }
13✔
3528
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
26✔
3529
                announcements = append(announcements, networkMsg{
12✔
3530
                        peer:   nMsg.peer,
12✔
3531
                        source: src,
12✔
3532
                        msg:    e2Ann,
12✔
3533
                })
12✔
3534
        }
12✔
3535

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

3557
        node2Ann, err := d.fetchNodeAnn(chanInfo.NodeKey2Bytes)
14✔
3558
        if err != nil {
22✔
3559
                log.Debugf("Unable to fetch node announcement for %x: %v",
8✔
3560
                        chanInfo.NodeKey2Bytes, err)
8✔
3561
        } else {
18✔
3562
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
20✔
3563
                        announcements = append(announcements, networkMsg{
10✔
3564
                                peer:   nMsg.peer,
10✔
3565
                                source: nodeKey2,
10✔
3566
                                msg:    node2Ann,
10✔
3567
                        })
10✔
3568
                }
10✔
3569
        }
3570

3571
        nMsg.err <- nil
14✔
3572
        return announcements, true
14✔
3573
}
3574

3575
// isBanned returns true if the peer identified by pubkey is banned for sending
3576
// invalid channel announcements.
3577
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
209✔
3578
        return d.banman.isBanned(pubkey)
209✔
3579
}
209✔
3580

3581
// ShouldDisconnect returns true if we should disconnect the peer identified by
3582
// pubkey.
3583
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3584
        bool, error) {
207✔
3585

207✔
3586
        pubkeySer := pubkey.SerializeCompressed()
207✔
3587

207✔
3588
        var pubkeyBytes [33]byte
207✔
3589
        copy(pubkeyBytes[:], pubkeySer)
207✔
3590

207✔
3591
        // If the public key is banned, check whether or not this is a channel
207✔
3592
        // peer.
207✔
3593
        if d.isBanned(pubkeyBytes) {
209✔
3594
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3595
                if err != nil {
2✔
3596
                        return false, err
×
3597
                }
×
3598

3599
                // We should only disconnect non-channel peers.
3600
                if !isChanPeer {
3✔
3601
                        return true, nil
1✔
3602
                }
1✔
3603
        }
3604

3605
        return false, nil
206✔
3606
}
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