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

lightningnetwork / lnd / 15561477203

10 Jun 2025 01:54PM UTC coverage: 58.351% (-10.1%) from 68.487%
15561477203

Pull #9356

github

web-flow
Merge 6440b25db into c6d6d4c0b
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

33 of 36 new or added lines in 2 files covered. (91.67%)

28366 existing lines in 455 files now uncovered.

97715 of 167461 relevant lines covered (58.35%)

1.81 hits per line

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

68.48
/discovery/gossiper.go
1
package discovery
2

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

13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
15
        "github.com/btcsuite/btcd/btcutil"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
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/v2"
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/input"
29
        "github.com/lightningnetwork/lnd/keychain"
30
        "github.com/lightningnetwork/lnd/lnpeer"
31
        "github.com/lightningnetwork/lnd/lnutils"
32
        "github.com/lightningnetwork/lnd/lnwallet"
33
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
34
        "github.com/lightningnetwork/lnd/lnwallet/chanvalidate"
35
        "github.com/lightningnetwork/lnd/lnwire"
36
        "github.com/lightningnetwork/lnd/multimutex"
37
        "github.com/lightningnetwork/lnd/netann"
38
        "github.com/lightningnetwork/lnd/routing/route"
39
        "github.com/lightningnetwork/lnd/ticker"
40
        "golang.org/x/time/rate"
41
)
42

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

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

54
        // maxPrematureUpdates tracks the max amount of premature channel
55
        // updates that we'll hold onto.
56
        maxPrematureUpdates = 100
57

58
        // maxFutureMessages tracks the max amount of future messages that
59
        // we'll hold onto.
60
        maxFutureMessages = 1000
61

62
        // DefaultSubBatchDelay is the default delay we'll use when
63
        // broadcasting the next announcement batch.
64
        DefaultSubBatchDelay = 5 * time.Second
65

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

71
        // DefaultProofMatureDelta specifies the default value used for
72
        // ProofMatureDelta, which is the number of confirmations needed before
73
        // processing the announcement signatures.
74
        DefaultProofMatureDelta = 6
75
)
76

77
var (
78
        // ErrGossiperShuttingDown is an error that is returned if the gossiper
79
        // is in the process of being shut down.
80
        ErrGossiperShuttingDown = errors.New("gossiper is shutting down")
81

82
        // ErrGossipSyncerNotFound signals that we were unable to find an active
83
        // gossip syncer corresponding to a gossip query message received from
84
        // the remote peer.
85
        ErrGossipSyncerNotFound = errors.New("gossip syncer not found")
86

87
        // ErrNoFundingTransaction is returned when we are unable to find the
88
        // funding transaction described by the short channel ID on chain.
89
        ErrNoFundingTransaction = errors.New(
90
                "unable to find the funding transaction",
91
        )
92

93
        // ErrInvalidFundingOutput is returned if the channel funding output
94
        // fails validation.
95
        ErrInvalidFundingOutput = errors.New(
96
                "channel funding output validation failed",
97
        )
98

99
        // ErrChannelSpent is returned when we go to validate a channel, but
100
        // the purported funding output has actually already been spent on
101
        // chain.
102
        ErrChannelSpent = errors.New("channel output has been spent")
103

104
        // emptyPubkey is used to compare compressed pubkeys against an empty
105
        // byte array.
106
        emptyPubkey [33]byte
107
)
108

109
// optionalMsgFields is a set of optional message fields that external callers
110
// can provide that serve useful when processing a specific network
111
// announcement.
112
type optionalMsgFields struct {
113
        capacity      *btcutil.Amount
114
        channelPoint  *wire.OutPoint
115
        remoteAlias   *lnwire.ShortChannelID
116
        tapscriptRoot fn.Option[chainhash.Hash]
117
}
118

119
// apply applies the optional fields within the functional options.
120
func (f *optionalMsgFields) apply(optionalMsgFields ...OptionalMsgField) {
3✔
121
        for _, optionalMsgField := range optionalMsgFields {
6✔
122
                optionalMsgField(f)
3✔
123
        }
3✔
124
}
125

126
// OptionalMsgField is a functional option parameter that can be used to provide
127
// external information that is not included within a network message but serves
128
// useful when processing it.
129
type OptionalMsgField func(*optionalMsgFields)
130

131
// ChannelCapacity is an optional field that lets the gossiper know of the
132
// capacity of a channel.
133
func ChannelCapacity(capacity btcutil.Amount) OptionalMsgField {
3✔
134
        return func(f *optionalMsgFields) {
6✔
135
                f.capacity = &capacity
3✔
136
        }
3✔
137
}
138

139
// ChannelPoint is an optional field that lets the gossiper know of the outpoint
140
// of a channel.
141
func ChannelPoint(op wire.OutPoint) OptionalMsgField {
3✔
142
        return func(f *optionalMsgFields) {
6✔
143
                f.channelPoint = &op
3✔
144
        }
3✔
145
}
146

147
// TapscriptRoot is an optional field that lets the gossiper know of the root of
148
// the tapscript tree for a custom channel.
149
func TapscriptRoot(root fn.Option[chainhash.Hash]) OptionalMsgField {
3✔
150
        return func(f *optionalMsgFields) {
6✔
151
                f.tapscriptRoot = root
3✔
152
        }
3✔
153
}
154

155
// RemoteAlias is an optional field that lets the gossiper know that a locally
156
// sent channel update is actually an update for the peer that should replace
157
// the ShortChannelID field with the remote's alias. This is only used for
158
// channels with peers where the option-scid-alias feature bit was negotiated.
159
// The channel update will be added to the graph under the original SCID, but
160
// will be modified and re-signed with this alias.
161
func RemoteAlias(alias *lnwire.ShortChannelID) OptionalMsgField {
3✔
162
        return func(f *optionalMsgFields) {
6✔
163
                f.remoteAlias = alias
3✔
164
        }
3✔
165
}
166

167
// networkMsg couples a routing related wire message with the peer that
168
// originally sent it.
169
type networkMsg struct {
170
        peer              lnpeer.Peer
171
        source            *btcec.PublicKey
172
        msg               lnwire.Message
173
        optionalMsgFields *optionalMsgFields
174

175
        isRemote bool
176

177
        err chan error
178
}
179

180
// chanPolicyUpdateRequest is a request that is sent to the server when a caller
181
// wishes to update a particular set of channels. New ChannelUpdate messages
182
// will be crafted to be sent out during the next broadcast epoch and the fee
183
// updates committed to the lower layer.
184
type chanPolicyUpdateRequest struct {
185
        edgesToUpdate []EdgeWithInfo
186
        errChan       chan error
187
}
188

189
// PinnedSyncers is a set of node pubkeys for which we will maintain an active
190
// syncer at all times.
191
type PinnedSyncers map[route.Vertex]struct{}
192

193
// Config defines the configuration for the service. ALL elements within the
194
// configuration MUST be non-nil for the service to carry out its duties.
195
type Config struct {
196
        // ChainHash is a hash that indicates which resident chain of the
197
        // AuthenticatedGossiper. Any announcements that don't match this
198
        // chain hash will be ignored.
199
        //
200
        // TODO(roasbeef): eventually make into map so can de-multiplex
201
        // incoming announcements
202
        //   * also need to do same for Notifier
203
        ChainHash chainhash.Hash
204

205
        // Graph is the subsystem which is responsible for managing the
206
        // topology of lightning network. After incoming channel, node, channel
207
        // updates announcements are validated they are sent to the router in
208
        // order to be included in the LN graph.
209
        Graph graph.ChannelGraphSource
210

211
        // ChainIO represents an abstraction over a source that can query the
212
        // blockchain.
213
        ChainIO lnwallet.BlockChainIO
214

215
        // ChanSeries is an interfaces that provides access to a time series
216
        // view of the current known channel graph. Each GossipSyncer enabled
217
        // peer will utilize this in order to create and respond to channel
218
        // graph time series queries.
219
        ChanSeries ChannelGraphTimeSeries
220

221
        // Notifier is used for receiving notifications of incoming blocks.
222
        // With each new incoming block found we process previously premature
223
        // announcements.
224
        //
225
        // TODO(roasbeef): could possibly just replace this with an epoch
226
        // channel.
227
        Notifier chainntnfs.ChainNotifier
228

229
        // Broadcast broadcasts a particular set of announcements to all peers
230
        // that the daemon is connected to. If supplied, the exclude parameter
231
        // indicates that the target peer should be excluded from the
232
        // broadcast.
233
        Broadcast func(skips map[route.Vertex]struct{},
234
                msg ...lnwire.Message) error
235

236
        // NotifyWhenOnline is a function that allows the gossiper to be
237
        // notified when a certain peer comes online, allowing it to
238
        // retry sending a peer message.
239
        //
240
        // NOTE: The peerChan channel must be buffered.
241
        NotifyWhenOnline func(peerPubKey [33]byte, peerChan chan<- lnpeer.Peer)
242

243
        // NotifyWhenOffline is a function that allows the gossiper to be
244
        // notified when a certain peer disconnects, allowing it to request a
245
        // notification for when it reconnects.
246
        NotifyWhenOffline func(peerPubKey [33]byte) <-chan struct{}
247

248
        // FetchSelfAnnouncement retrieves our current node announcement, for
249
        // use when determining whether we should update our peers about our
250
        // presence in the network.
251
        FetchSelfAnnouncement func() lnwire.NodeAnnouncement
252

253
        // UpdateSelfAnnouncement produces a new announcement for our node with
254
        // an updated timestamp which can be broadcast to our peers.
255
        UpdateSelfAnnouncement func() (lnwire.NodeAnnouncement, error)
256

257
        // ProofMatureDelta the number of confirmations which is needed before
258
        // exchange the channel announcement proofs.
259
        ProofMatureDelta uint32
260

261
        // TrickleDelay the period of trickle timer which flushes to the
262
        // network the pending batch of new announcements we've received since
263
        // the last trickle tick.
264
        TrickleDelay time.Duration
265

266
        // RetransmitTicker is a ticker that ticks with a period which
267
        // indicates that we should check if we need re-broadcast any of our
268
        // personal channels.
269
        RetransmitTicker ticker.Ticker
270

271
        // RebroadcastInterval is the maximum time we wait between sending out
272
        // channel updates for our active channels and our own node
273
        // announcement. We do this to ensure our active presence on the
274
        // network is known, and we are not being considered a zombie node or
275
        // having zombie channels.
276
        RebroadcastInterval time.Duration
277

278
        // WaitingProofStore is a persistent storage of partial channel proof
279
        // announcement messages. We use it to buffer half of the material
280
        // needed to reconstruct a full authenticated channel announcement.
281
        // Once we receive the other half the channel proof, we'll be able to
282
        // properly validate it and re-broadcast it out to the network.
283
        //
284
        // TODO(wilmer): make interface to prevent channeldb dependency.
285
        WaitingProofStore *channeldb.WaitingProofStore
286

287
        // MessageStore is a persistent storage of gossip messages which we will
288
        // use to determine which messages need to be resent for a given peer.
289
        MessageStore GossipMessageStore
290

291
        // AnnSigner is an instance of the MessageSigner interface which will
292
        // be used to manually sign any outgoing channel updates. The signer
293
        // implementation should be backed by the public key of the backing
294
        // Lightning node.
295
        //
296
        // TODO(roasbeef): extract ann crafting + sign from fundingMgr into
297
        // here?
298
        AnnSigner lnwallet.MessageSigner
299

300
        // ScidCloser is an instance of ClosedChannelTracker that helps the
301
        // gossiper cut down on spam channel announcements for already closed
302
        // channels.
303
        ScidCloser ClosedChannelTracker
304

305
        // NumActiveSyncers is the number of peers for which we should have
306
        // active syncers with. After reaching NumActiveSyncers, any future
307
        // gossip syncers will be passive.
308
        NumActiveSyncers int
309

310
        // NoTimestampQueries will prevent the GossipSyncer from querying
311
        // timestamps of announcement messages from the peer and from replying
312
        // to timestamp queries.
313
        NoTimestampQueries bool
314

315
        // RotateTicker is a ticker responsible for notifying the SyncManager
316
        // when it should rotate its active syncers. A single active syncer with
317
        // a chansSynced state will be exchanged for a passive syncer in order
318
        // to ensure we don't keep syncing with the same peers.
319
        RotateTicker ticker.Ticker
320

321
        // HistoricalSyncTicker is a ticker responsible for notifying the
322
        // syncManager when it should attempt a historical sync with a gossip
323
        // sync peer.
324
        HistoricalSyncTicker ticker.Ticker
325

326
        // ActiveSyncerTimeoutTicker is a ticker responsible for notifying the
327
        // syncManager when it should attempt to start the next pending
328
        // activeSyncer due to the current one not completing its state machine
329
        // within the timeout.
330
        ActiveSyncerTimeoutTicker ticker.Ticker
331

332
        // MinimumBatchSize is minimum size of a sub batch of announcement
333
        // messages.
334
        MinimumBatchSize int
335

336
        // SubBatchDelay is the delay between sending sub batches of
337
        // gossip messages.
338
        SubBatchDelay time.Duration
339

340
        // IgnoreHistoricalFilters will prevent syncers from replying with
341
        // historical data when the remote peer sets a gossip_timestamp_range.
342
        // This prevents ranges with old start times from causing us to dump the
343
        // graph on connect.
344
        IgnoreHistoricalFilters bool
345

346
        // PinnedSyncers is a set of peers that will always transition to
347
        // ActiveSync upon connection. These peers will never transition to
348
        // PassiveSync.
349
        PinnedSyncers PinnedSyncers
350

351
        // MaxChannelUpdateBurst specifies the maximum number of updates for a
352
        // specific channel and direction that we'll accept over an interval.
353
        MaxChannelUpdateBurst int
354

355
        // ChannelUpdateInterval specifies the interval we'll use to determine
356
        // how often we should allow a new update for a specific channel and
357
        // direction.
358
        ChannelUpdateInterval time.Duration
359

360
        // IsAlias returns true if a given ShortChannelID is an alias for
361
        // option_scid_alias channels.
362
        IsAlias func(scid lnwire.ShortChannelID) bool
363

364
        // SignAliasUpdate is used to re-sign a channel update using the
365
        // remote's alias if the option-scid-alias feature bit was negotiated.
366
        SignAliasUpdate func(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
367
                error)
368

369
        // FindBaseByAlias finds the SCID stored in the graph by an alias SCID.
370
        // This is used for channels that have negotiated the option-scid-alias
371
        // feature bit.
372
        FindBaseByAlias func(alias lnwire.ShortChannelID) (
373
                lnwire.ShortChannelID, error)
374

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

380
        // FindChannel allows the gossiper to find a channel that we're party
381
        // to without iterating over the entire set of open channels.
382
        FindChannel func(node *btcec.PublicKey, chanID lnwire.ChannelID) (
383
                *channeldb.OpenChannel, error)
384

385
        // IsStillZombieChannel takes the timestamps of the latest channel
386
        // updates for a channel and returns true if the channel should be
387
        // considered a zombie based on these timestamps.
388
        IsStillZombieChannel func(time.Time, time.Time) bool
389

390
        // AssumeChannelValid toggles whether the gossiper will check for
391
        // spent-ness of channel outpoints. For neutrino, this saves long
392
        // rescans from blocking initial usage of the daemon.
393
        AssumeChannelValid bool
394

395
        // MsgRateBytes is the rate limit for the number of bytes per second
396
        // that we'll allocate to outbound gossip messages.
397
        MsgRateBytes uint64
398

399
        // MsgBurstBytes is the allotted burst amount in bytes. This is the
400
        // number of starting tokens in our token bucket algorithm.
401
        MsgBurstBytes uint64
402
}
403

404
// processedNetworkMsg is a wrapper around networkMsg and a boolean. It is
405
// used to let the caller of the lru.Cache know if a message has already been
406
// processed or not.
407
type processedNetworkMsg struct {
408
        processed bool
409
        msg       *networkMsg
410
}
411

412
// cachedNetworkMsg is a wrapper around a network message that can be used with
413
// *lru.Cache.
414
type cachedNetworkMsg struct {
415
        msgs []*processedNetworkMsg
416
}
417

418
// Size returns the "size" of an entry. We return the number of items as we
419
// just want to limit the total amount of entries rather than do accurate size
420
// accounting.
421
func (c *cachedNetworkMsg) Size() (uint64, error) {
3✔
422
        return uint64(len(c.msgs)), nil
3✔
423
}
3✔
424

425
// rejectCacheKey is the cache key that we'll use to track announcements we've
426
// recently rejected.
427
type rejectCacheKey struct {
428
        pubkey [33]byte
429
        chanID uint64
430
}
431

432
// newRejectCacheKey returns a new cache key for the reject cache.
433
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
3✔
434
        k := rejectCacheKey{
3✔
435
                chanID: cid,
3✔
436
                pubkey: pub,
3✔
437
        }
3✔
438

3✔
439
        return k
3✔
440
}
3✔
441

442
// sourceToPub returns a serialized-compressed public key for use in the reject
443
// cache.
444
func sourceToPub(pk *btcec.PublicKey) [33]byte {
3✔
445
        var pub [33]byte
3✔
446
        copy(pub[:], pk.SerializeCompressed())
3✔
447
        return pub
3✔
448
}
3✔
449

450
// cachedReject is the empty value used to track the value for rejects.
451
type cachedReject struct {
452
}
453

454
// Size returns the "size" of an entry. We return 1 as we just want to limit
455
// the total size.
UNCOV
456
func (c *cachedReject) Size() (uint64, error) {
×
UNCOV
457
        return 1, nil
×
UNCOV
458
}
×
459

460
// AuthenticatedGossiper is a subsystem which is responsible for receiving
461
// announcements, validating them and applying the changes to router, syncing
462
// lightning network with newly connected nodes, broadcasting announcements
463
// after validation, negotiating the channel announcement proofs exchange and
464
// handling the premature announcements. All outgoing announcements are
465
// expected to be properly signed as dictated in BOLT#7, additionally, all
466
// incoming message are expected to be well formed and signed. Invalid messages
467
// will be rejected by this struct.
468
type AuthenticatedGossiper struct {
469
        // Parameters which are needed to properly handle the start and stop of
470
        // the service.
471
        started sync.Once
472
        stopped sync.Once
473

474
        // bestHeight is the height of the block at the tip of the main chain
475
        // as we know it. Accesses *MUST* be done with the gossiper's lock
476
        // held.
477
        bestHeight uint32
478

479
        // cfg is a copy of the configuration struct that the gossiper service
480
        // was initialized with.
481
        cfg *Config
482

483
        // blockEpochs encapsulates a stream of block epochs that are sent at
484
        // every new block height.
485
        blockEpochs *chainntnfs.BlockEpochEvent
486

487
        // prematureChannelUpdates is a map of ChannelUpdates we have received
488
        // that wasn't associated with any channel we know about.  We store
489
        // them temporarily, such that we can reprocess them when a
490
        // ChannelAnnouncement for the channel is received.
491
        prematureChannelUpdates *lru.Cache[uint64, *cachedNetworkMsg]
492

493
        // banman tracks our peer's ban status.
494
        banman *banman
495

496
        // networkMsgs is a channel that carries new network broadcasted
497
        // message from outside the gossiper service to be processed by the
498
        // networkHandler.
499
        networkMsgs chan *networkMsg
500

501
        // futureMsgs is a list of premature network messages that have a block
502
        // height specified in the future. We will save them and resend it to
503
        // the chan networkMsgs once the block height has reached. The cached
504
        // map format is,
505
        //   {msgID1: msg1, msgID2: msg2, ...}
506
        futureMsgs *futureMsgCache
507

508
        // chanPolicyUpdates is a channel that requests to update the
509
        // forwarding policy of a set of channels is sent over.
510
        chanPolicyUpdates chan *chanPolicyUpdateRequest
511

512
        // selfKey is the identity public key of the backing Lightning node.
513
        selfKey *btcec.PublicKey
514

515
        // selfKeyLoc is the locator for the identity public key of the backing
516
        // Lightning node.
517
        selfKeyLoc keychain.KeyLocator
518

519
        // channelMtx is used to restrict the database access to one
520
        // goroutine per channel ID. This is done to ensure that when
521
        // the gossiper is handling an announcement, the db state stays
522
        // consistent between when the DB is first read until it's written.
523
        channelMtx *multimutex.Mutex[uint64]
524

525
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
526

527
        // syncMgr is a subsystem responsible for managing the gossip syncers
528
        // for peers currently connected. When a new peer is connected, the
529
        // manager will create its accompanying gossip syncer and determine
530
        // whether it should have an activeSync or passiveSync sync type based
531
        // on how many other gossip syncers are currently active. Any activeSync
532
        // gossip syncers are started in a round-robin manner to ensure we're
533
        // not syncing with multiple peers at the same time.
534
        syncMgr *SyncManager
535

536
        // reliableSender is a subsystem responsible for handling reliable
537
        // message send requests to peers. This should only be used for channels
538
        // that are unadvertised at the time of handling the message since if it
539
        // is advertised, then peers should be able to get the message from the
540
        // network.
541
        reliableSender *reliableSender
542

543
        // chanUpdateRateLimiter contains rate limiters for each direction of
544
        // a channel update we've processed. We'll use these to determine
545
        // whether we should accept a new update for a specific channel and
546
        // direction.
547
        //
548
        // NOTE: This map must be synchronized with the main
549
        // AuthenticatedGossiper lock.
550
        chanUpdateRateLimiter map[uint64][2]*rate.Limiter
551

552
        // vb is used to enforce job dependency ordering of gossip messages.
553
        vb *ValidationBarrier
554

555
        sync.Mutex
556

557
        cancel fn.Option[context.CancelFunc]
558
        quit   chan struct{}
559
        wg     sync.WaitGroup
560
}
561

562
// New creates a new AuthenticatedGossiper instance, initialized with the
563
// passed configuration parameters.
564
func New(cfg Config, selfKeyDesc *keychain.KeyDescriptor) *AuthenticatedGossiper {
3✔
565
        gossiper := &AuthenticatedGossiper{
3✔
566
                selfKey:           selfKeyDesc.PubKey,
3✔
567
                selfKeyLoc:        selfKeyDesc.KeyLocator,
3✔
568
                cfg:               &cfg,
3✔
569
                networkMsgs:       make(chan *networkMsg),
3✔
570
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
3✔
571
                quit:              make(chan struct{}),
3✔
572
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
3✔
573
                prematureChannelUpdates: lru.NewCache[uint64, *cachedNetworkMsg]( //nolint: ll
3✔
574
                        maxPrematureUpdates,
3✔
575
                ),
3✔
576
                channelMtx: multimutex.NewMutex[uint64](),
3✔
577
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
3✔
578
                        maxRejectedUpdates,
3✔
579
                ),
3✔
580
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
3✔
581
                banman:                newBanman(),
3✔
582
        }
3✔
583

3✔
584
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
3✔
585

3✔
586
        gossiper.syncMgr = newSyncManager(&SyncManagerCfg{
3✔
587
                ChainHash:                cfg.ChainHash,
3✔
588
                ChanSeries:               cfg.ChanSeries,
3✔
589
                RotateTicker:             cfg.RotateTicker,
3✔
590
                HistoricalSyncTicker:     cfg.HistoricalSyncTicker,
3✔
591
                NumActiveSyncers:         cfg.NumActiveSyncers,
3✔
592
                NoTimestampQueries:       cfg.NoTimestampQueries,
3✔
593
                IgnoreHistoricalFilters:  cfg.IgnoreHistoricalFilters,
3✔
594
                BestHeight:               gossiper.latestHeight,
3✔
595
                PinnedSyncers:            cfg.PinnedSyncers,
3✔
596
                IsStillZombieChannel:     cfg.IsStillZombieChannel,
3✔
597
                AllotedMsgBytesPerSecond: cfg.MsgRateBytes,
3✔
598
                AllotedMsgBytesBurst:     cfg.MsgBurstBytes,
3✔
599
        })
3✔
600

3✔
601
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
3✔
602
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
3✔
603
                NotifyWhenOffline: cfg.NotifyWhenOffline,
3✔
604
                MessageStore:      cfg.MessageStore,
3✔
605
                IsMsgStale:        gossiper.isMsgStale,
3✔
606
        })
3✔
607

3✔
608
        return gossiper
3✔
609
}
3✔
610

611
// EdgeWithInfo contains the information that is required to update an edge.
612
type EdgeWithInfo struct {
613
        // Info describes the channel.
614
        Info *models.ChannelEdgeInfo
615

616
        // Edge describes the policy in one direction of the channel.
617
        Edge *models.ChannelEdgePolicy
618
}
619

620
// PropagateChanPolicyUpdate signals the AuthenticatedGossiper to perform the
621
// specified edge updates. Updates are done in two stages: first, the
622
// AuthenticatedGossiper ensures the update has been committed by dependent
623
// sub-systems, then it signs and broadcasts new updates to the network. A
624
// mapping between outpoints and updated channel policies is returned, which is
625
// used to update the forwarding policies of the underlying links.
626
func (d *AuthenticatedGossiper) PropagateChanPolicyUpdate(
627
        edgesToUpdate []EdgeWithInfo) error {
3✔
628

3✔
629
        errChan := make(chan error, 1)
3✔
630
        policyUpdate := &chanPolicyUpdateRequest{
3✔
631
                edgesToUpdate: edgesToUpdate,
3✔
632
                errChan:       errChan,
3✔
633
        }
3✔
634

3✔
635
        select {
3✔
636
        case d.chanPolicyUpdates <- policyUpdate:
3✔
637
                err := <-errChan
3✔
638
                return err
3✔
639
        case <-d.quit:
×
640
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
641
        }
642
}
643

644
// Start spawns network messages handler goroutine and registers on new block
645
// notifications in order to properly handle the premature announcements.
646
func (d *AuthenticatedGossiper) Start() error {
3✔
647
        var err error
3✔
648
        d.started.Do(func() {
6✔
649
                ctx, cancel := context.WithCancel(context.Background())
3✔
650
                d.cancel = fn.Some(cancel)
3✔
651

3✔
652
                log.Info("Authenticated Gossiper starting")
3✔
653
                err = d.start(ctx)
3✔
654
        })
3✔
655
        return err
3✔
656
}
657

658
func (d *AuthenticatedGossiper) start(ctx context.Context) error {
3✔
659
        // First we register for new notifications of newly discovered blocks.
3✔
660
        // We do this immediately so we'll later be able to consume any/all
3✔
661
        // blocks which were discovered.
3✔
662
        blockEpochs, err := d.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
663
        if err != nil {
3✔
664
                return err
×
665
        }
×
666
        d.blockEpochs = blockEpochs
3✔
667

3✔
668
        height, err := d.cfg.Graph.CurrentBlockHeight()
3✔
669
        if err != nil {
3✔
670
                return err
×
671
        }
×
672
        d.bestHeight = height
3✔
673

3✔
674
        // Start the reliable sender. In case we had any pending messages ready
3✔
675
        // to be sent when the gossiper was last shut down, we must continue on
3✔
676
        // our quest to deliver them to their respective peers.
3✔
677
        if err := d.reliableSender.Start(); err != nil {
3✔
678
                return err
×
679
        }
×
680

681
        d.syncMgr.Start()
3✔
682

3✔
683
        d.banman.start()
3✔
684

3✔
685
        // Start receiving blocks in its dedicated goroutine.
3✔
686
        d.wg.Add(2)
3✔
687
        go d.syncBlockHeight()
3✔
688
        go d.networkHandler(ctx)
3✔
689

3✔
690
        return nil
3✔
691
}
692

693
// syncBlockHeight syncs the best block height for the gossiper by reading
694
// blockEpochs.
695
//
696
// NOTE: must be run as a goroutine.
697
func (d *AuthenticatedGossiper) syncBlockHeight() {
3✔
698
        defer d.wg.Done()
3✔
699

3✔
700
        for {
6✔
701
                select {
3✔
702
                // A new block has arrived, so we can re-process the previously
703
                // premature announcements.
704
                case newBlock, ok := <-d.blockEpochs.Epochs:
3✔
705
                        // If the channel has been closed, then this indicates
3✔
706
                        // the daemon is shutting down, so we exit ourselves.
3✔
707
                        if !ok {
6✔
708
                                return
3✔
709
                        }
3✔
710

711
                        // Once a new block arrives, we update our running
712
                        // track of the height of the chain tip.
713
                        d.Lock()
3✔
714
                        blockHeight := uint32(newBlock.Height)
3✔
715
                        d.bestHeight = blockHeight
3✔
716
                        d.Unlock()
3✔
717

3✔
718
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
3✔
719
                                newBlock.Hash)
3✔
720

3✔
721
                        // Resend future messages, if any.
3✔
722
                        d.resendFutureMessages(blockHeight)
3✔
723

UNCOV
724
                case <-d.quit:
×
UNCOV
725
                        return
×
726
                }
727
        }
728
}
729

730
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
731
// the unique ID when saving the message.
732
type futureMsgCache struct {
733
        *lru.Cache[uint64, *cachedFutureMsg]
734

735
        // msgID is a monotonically increased integer.
736
        msgID atomic.Uint64
737
}
738

739
// nextMsgID returns a unique message ID.
740
func (f *futureMsgCache) nextMsgID() uint64 {
3✔
741
        return f.msgID.Add(1)
3✔
742
}
3✔
743

744
// newFutureMsgCache creates a new future message cache with the underlying lru
745
// cache being initialized with the specified capacity.
746
func newFutureMsgCache(capacity uint64) *futureMsgCache {
3✔
747
        // Create a new cache.
3✔
748
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
3✔
749

3✔
750
        return &futureMsgCache{
3✔
751
                Cache: cache,
3✔
752
        }
3✔
753
}
3✔
754

755
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
756
type cachedFutureMsg struct {
757
        // msg is the network message.
758
        msg *networkMsg
759

760
        // height is the block height.
761
        height uint32
762
}
763

764
// Size returns the size of the message.
765
func (c *cachedFutureMsg) Size() (uint64, error) {
3✔
766
        // Return a constant 1.
3✔
767
        return 1, nil
3✔
768
}
3✔
769

770
// resendFutureMessages takes a block height, resends all the future messages
771
// found below and equal to that height and deletes those messages found in the
772
// gossiper's futureMsgs.
773
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
3✔
774
        var (
3✔
775
                // msgs are the target messages.
3✔
776
                msgs []*networkMsg
3✔
777

3✔
778
                // keys are the target messages' caching keys.
3✔
779
                keys []uint64
3✔
780
        )
3✔
781

3✔
782
        // filterMsgs is the visitor used when iterating the future cache.
3✔
783
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
6✔
784
                if cmsg.height <= height {
6✔
785
                        msgs = append(msgs, cmsg.msg)
3✔
786
                        keys = append(keys, k)
3✔
787
                }
3✔
788

789
                return true
3✔
790
        }
791

792
        // Filter out the target messages.
793
        d.futureMsgs.Range(filterMsgs)
3✔
794

3✔
795
        // Return early if no messages found.
3✔
796
        if len(msgs) == 0 {
6✔
797
                return
3✔
798
        }
3✔
799

800
        // Remove the filtered messages.
801
        for _, key := range keys {
6✔
802
                d.futureMsgs.Delete(key)
3✔
803
        }
3✔
804

805
        log.Debugf("Resending %d network messages at height %d",
3✔
806
                len(msgs), height)
3✔
807

3✔
808
        for _, msg := range msgs {
6✔
809
                select {
3✔
810
                case d.networkMsgs <- msg:
3✔
811
                case <-d.quit:
×
812
                        msg.err <- ErrGossiperShuttingDown
×
813
                }
814
        }
815
}
816

817
// Stop signals any active goroutines for a graceful closure.
818
func (d *AuthenticatedGossiper) Stop() error {
3✔
819
        d.stopped.Do(func() {
6✔
820
                log.Info("Authenticated gossiper shutting down...")
3✔
821
                defer log.Debug("Authenticated gossiper shutdown complete")
3✔
822

3✔
823
                d.stop()
3✔
824
        })
3✔
825
        return nil
3✔
826
}
827

828
func (d *AuthenticatedGossiper) stop() {
3✔
829
        log.Debug("Authenticated Gossiper is stopping")
3✔
830
        defer log.Debug("Authenticated Gossiper stopped")
3✔
831

3✔
832
        // `blockEpochs` is only initialized in the start routine so we make
3✔
833
        // sure we don't panic here in the case where the `Stop` method is
3✔
834
        // called when the `Start` method does not complete.
3✔
835
        if d.blockEpochs != nil {
6✔
836
                d.blockEpochs.Cancel()
3✔
837
        }
3✔
838

839
        d.syncMgr.Stop()
3✔
840

3✔
841
        d.banman.stop()
3✔
842

3✔
843
        d.cancel.WhenSome(func(fn context.CancelFunc) { fn() })
6✔
844
        close(d.quit)
3✔
845
        d.wg.Wait()
3✔
846

3✔
847
        // We'll stop our reliable sender after all of the gossiper's goroutines
3✔
848
        // have exited to ensure nothing can cause it to continue executing.
3✔
849
        d.reliableSender.Stop()
3✔
850
}
851

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

855
// ProcessRemoteAnnouncement sends a new remote announcement message along with
856
// the peer that sent the routing message. The announcement will be processed
857
// then added to a queue for batched trickled announcement to all connected
858
// peers.  Remote channel announcements should contain the announcement proof
859
// and be fully validated.
860
func (d *AuthenticatedGossiper) ProcessRemoteAnnouncement(ctx context.Context,
861
        msg lnwire.Message, peer lnpeer.Peer) chan error {
3✔
862

3✔
863
        errChan := make(chan error, 1)
3✔
864

3✔
865
        // For messages in the known set of channel series queries, we'll
3✔
866
        // dispatch the message directly to the GossipSyncer, and skip the main
3✔
867
        // processing loop.
3✔
868
        switch m := msg.(type) {
3✔
869
        case *lnwire.QueryShortChanIDs,
870
                *lnwire.QueryChannelRange,
871
                *lnwire.ReplyChannelRange,
872
                *lnwire.ReplyShortChanIDsEnd:
3✔
873

3✔
874
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
875
                if !ok {
3✔
876
                        log.Warnf("Gossip syncer for peer=%x not found",
×
877
                                peer.PubKey())
×
878

×
879
                        errChan <- ErrGossipSyncerNotFound
×
880
                        return errChan
×
881
                }
×
882

883
                // If we've found the message target, then we'll dispatch the
884
                // message directly to it.
885
                err := syncer.ProcessQueryMsg(m, peer.QuitSignal())
3✔
886
                if err != nil {
3✔
887
                        log.Errorf("Process query msg from peer %x got %v",
×
888
                                peer.PubKey(), err)
×
889
                }
×
890

891
                errChan <- err
3✔
892
                return errChan
3✔
893

894
        // If a peer is updating its current update horizon, then we'll dispatch
895
        // that directly to the proper GossipSyncer.
896
        case *lnwire.GossipTimestampRange:
3✔
897
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
898
                if !ok {
3✔
899
                        log.Warnf("Gossip syncer for peer=%x not found",
×
900
                                peer.PubKey())
×
901

×
902
                        errChan <- ErrGossipSyncerNotFound
×
903
                        return errChan
×
904
                }
×
905

906
                // If we've found the message target, then we'll dispatch the
907
                // message directly to it.
908
                if err := syncer.ApplyGossipFilter(ctx, m); err != nil {
3✔
909
                        log.Warnf("Unable to apply gossip filter for peer=%x: "+
×
910
                                "%v", peer.PubKey(), err)
×
911

×
912
                        errChan <- err
×
913
                        return errChan
×
914
                }
×
915

916
                errChan <- nil
3✔
917
                return errChan
3✔
918

919
        // To avoid inserting edges in the graph for our own channels that we
920
        // have already closed, we ignore such channel announcements coming
921
        // from the remote.
922
        case *lnwire.ChannelAnnouncement1:
3✔
923
                ownKey := d.selfKey.SerializeCompressed()
3✔
924
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
3✔
925
                        "for own channel")
3✔
926

3✔
927
                if bytes.Equal(m.NodeID1[:], ownKey) ||
3✔
928
                        bytes.Equal(m.NodeID2[:], ownKey) {
6✔
929

3✔
930
                        log.Warn(ownErr)
3✔
931
                        errChan <- ownErr
3✔
932
                        return errChan
3✔
933
                }
3✔
934
        }
935

936
        nMsg := &networkMsg{
3✔
937
                msg:      msg,
3✔
938
                isRemote: true,
3✔
939
                peer:     peer,
3✔
940
                source:   peer.IdentityKey(),
3✔
941
                err:      errChan,
3✔
942
        }
3✔
943

3✔
944
        select {
3✔
945
        case d.networkMsgs <- nMsg:
3✔
946

947
        // If the peer that sent us this error is quitting, then we don't need
948
        // to send back an error and can return immediately.
949
        // TODO(elle): the peer should now just rely on canceling the passed
950
        //  context.
951
        case <-peer.QuitSignal():
×
952
                return nil
×
953
        case <-ctx.Done():
×
954
                return nil
×
955
        case <-d.quit:
×
956
                nMsg.err <- ErrGossiperShuttingDown
×
957
        }
958

959
        return nMsg.err
3✔
960
}
961

962
// ProcessLocalAnnouncement sends a new remote announcement message along with
963
// the peer that sent the routing message. The announcement will be processed
964
// then added to a queue for batched trickled announcement to all connected
965
// peers.  Local channel announcements don't contain the announcement proof and
966
// will not be fully validated. Once the channel proofs are received, the
967
// entire channel announcement and update messages will be re-constructed and
968
// broadcast to the rest of the network.
969
func (d *AuthenticatedGossiper) ProcessLocalAnnouncement(msg lnwire.Message,
970
        optionalFields ...OptionalMsgField) chan error {
3✔
971

3✔
972
        optionalMsgFields := &optionalMsgFields{}
3✔
973
        optionalMsgFields.apply(optionalFields...)
3✔
974

3✔
975
        nMsg := &networkMsg{
3✔
976
                msg:               msg,
3✔
977
                optionalMsgFields: optionalMsgFields,
3✔
978
                isRemote:          false,
3✔
979
                source:            d.selfKey,
3✔
980
                err:               make(chan error, 1),
3✔
981
        }
3✔
982

3✔
983
        select {
3✔
984
        case d.networkMsgs <- nMsg:
3✔
985
        case <-d.quit:
×
986
                nMsg.err <- ErrGossiperShuttingDown
×
987
        }
988

989
        return nMsg.err
3✔
990
}
991

992
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
993
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
994
// tuple.
995
type channelUpdateID struct {
996
        // channelID represents the set of data which is needed to
997
        // retrieve all necessary data to validate the channel existence.
998
        channelID lnwire.ShortChannelID
999

1000
        // Flags least-significant bit must be set to 0 if the creating node
1001
        // corresponds to the first node in the previously sent channel
1002
        // announcement and 1 otherwise.
1003
        flags lnwire.ChanUpdateChanFlags
1004
}
1005

1006
// msgWithSenders is a wrapper struct around a message, and the set of peers
1007
// that originally sent us this message. Using this struct, we can ensure that
1008
// we don't re-send a message to the peer that sent it to us in the first
1009
// place.
1010
type msgWithSenders struct {
1011
        // msg is the wire message itself.
1012
        msg lnwire.Message
1013

1014
        // isLocal is true if this was a message that originated locally. We'll
1015
        // use this to bypass our normal checks to ensure we prioritize sending
1016
        // out our own updates.
1017
        isLocal bool
1018

1019
        // sender is the set of peers that sent us this message.
1020
        senders map[route.Vertex]struct{}
1021
}
1022

1023
// mergeSyncerMap is used to merge the set of senders of a particular message
1024
// with peers that we have an active GossipSyncer with. We do this to ensure
1025
// that we don't broadcast messages to any peers that we have active gossip
1026
// syncers for.
1027
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
3✔
1028
        for peerPub := range syncers {
6✔
1029
                m.senders[peerPub] = struct{}{}
3✔
1030
        }
3✔
1031
}
1032

1033
// deDupedAnnouncements de-duplicates announcements that have been added to the
1034
// batch. Internally, announcements are stored in three maps
1035
// (one each for channel announcements, channel updates, and node
1036
// announcements). These maps keep track of unique announcements and ensure no
1037
// announcements are duplicated. We keep the three message types separate, such
1038
// that we can send channel announcements first, then channel updates, and
1039
// finally node announcements when it's time to broadcast them.
1040
type deDupedAnnouncements struct {
1041
        // channelAnnouncements are identified by the short channel id field.
1042
        channelAnnouncements map[lnwire.ShortChannelID]msgWithSenders
1043

1044
        // channelUpdates are identified by the channel update id field.
1045
        channelUpdates map[channelUpdateID]msgWithSenders
1046

1047
        // nodeAnnouncements are identified by the Vertex field.
1048
        nodeAnnouncements map[route.Vertex]msgWithSenders
1049

1050
        sync.Mutex
1051
}
1052

1053
// Reset operates on deDupedAnnouncements to reset the storage of
1054
// announcements.
1055
func (d *deDupedAnnouncements) Reset() {
3✔
1056
        d.Lock()
3✔
1057
        defer d.Unlock()
3✔
1058

3✔
1059
        d.reset()
3✔
1060
}
3✔
1061

1062
// reset is the private version of the Reset method. We have this so we can
1063
// call this method within method that are already holding the lock.
1064
func (d *deDupedAnnouncements) reset() {
3✔
1065
        // Storage of each type of announcement (channel announcements, channel
3✔
1066
        // updates, node announcements) is set to an empty map where the
3✔
1067
        // appropriate key points to the corresponding lnwire.Message.
3✔
1068
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
3✔
1069
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
3✔
1070
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
3✔
1071
}
3✔
1072

1073
// addMsg adds a new message to the current batch. If the message is already
1074
// present in the current batch, then this new instance replaces the latter,
1075
// and the set of senders is updated to reflect which node sent us this
1076
// message.
1077
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
3✔
1078
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
3✔
1079

3✔
1080
        // Depending on the message type (channel announcement, channel update,
3✔
1081
        // or node announcement), the message is added to the corresponding map
3✔
1082
        // in deDupedAnnouncements. Because each identifying key can have at
3✔
1083
        // most one value, the announcements are de-duplicated, with newer ones
3✔
1084
        // replacing older ones.
3✔
1085
        switch msg := message.msg.(type) {
3✔
1086

1087
        // Channel announcements are identified by the short channel id field.
1088
        case *lnwire.ChannelAnnouncement1:
3✔
1089
                deDupKey := msg.ShortChannelID
3✔
1090
                sender := route.NewVertex(message.source)
3✔
1091

3✔
1092
                mws, ok := d.channelAnnouncements[deDupKey]
3✔
1093
                if !ok {
6✔
1094
                        mws = msgWithSenders{
3✔
1095
                                msg:     msg,
3✔
1096
                                isLocal: !message.isRemote,
3✔
1097
                                senders: make(map[route.Vertex]struct{}),
3✔
1098
                        }
3✔
1099
                        mws.senders[sender] = struct{}{}
3✔
1100

3✔
1101
                        d.channelAnnouncements[deDupKey] = mws
3✔
1102

3✔
1103
                        return
3✔
1104
                }
3✔
1105

UNCOV
1106
                mws.msg = msg
×
UNCOV
1107
                mws.senders[sender] = struct{}{}
×
UNCOV
1108
                d.channelAnnouncements[deDupKey] = mws
×
1109

1110
        // Channel updates are identified by the (short channel id,
1111
        // channelflags) tuple.
1112
        case *lnwire.ChannelUpdate1:
3✔
1113
                sender := route.NewVertex(message.source)
3✔
1114
                deDupKey := channelUpdateID{
3✔
1115
                        msg.ShortChannelID,
3✔
1116
                        msg.ChannelFlags,
3✔
1117
                }
3✔
1118

3✔
1119
                oldTimestamp := uint32(0)
3✔
1120
                mws, ok := d.channelUpdates[deDupKey]
3✔
1121
                if ok {
3✔
UNCOV
1122
                        // If we already have seen this message, record its
×
UNCOV
1123
                        // timestamp.
×
UNCOV
1124
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
×
UNCOV
1125
                        if !ok {
×
1126
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1127
                                        "got: %T", mws.msg)
×
1128

×
1129
                                return
×
1130
                        }
×
1131

UNCOV
1132
                        oldTimestamp = update.Timestamp
×
1133
                }
1134

1135
                // If we already had this message with a strictly newer
1136
                // timestamp, then we'll just discard the message we got.
1137
                if oldTimestamp > msg.Timestamp {
3✔
UNCOV
1138
                        log.Debugf("Ignored outdated network message: "+
×
UNCOV
1139
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
×
UNCOV
1140
                        return
×
UNCOV
1141
                }
×
1142

1143
                // If the message we just got is newer than what we previously
1144
                // have seen, or this is the first time we see it, then we'll
1145
                // add it to our map of announcements.
1146
                if oldTimestamp < msg.Timestamp {
6✔
1147
                        mws = msgWithSenders{
3✔
1148
                                msg:     msg,
3✔
1149
                                isLocal: !message.isRemote,
3✔
1150
                                senders: make(map[route.Vertex]struct{}),
3✔
1151
                        }
3✔
1152

3✔
1153
                        // We'll mark the sender of the message in the
3✔
1154
                        // senders map.
3✔
1155
                        mws.senders[sender] = struct{}{}
3✔
1156

3✔
1157
                        d.channelUpdates[deDupKey] = mws
3✔
1158

3✔
1159
                        return
3✔
1160
                }
3✔
1161

1162
                // Lastly, if we had seen this exact message from before, with
1163
                // the same timestamp, we'll add the sender to the map of
1164
                // senders, such that we can skip sending this message back in
1165
                // the next batch.
UNCOV
1166
                mws.msg = msg
×
UNCOV
1167
                mws.senders[sender] = struct{}{}
×
UNCOV
1168
                d.channelUpdates[deDupKey] = mws
×
1169

1170
        // Node announcements are identified by the Vertex field.  Use the
1171
        // NodeID to create the corresponding Vertex.
1172
        case *lnwire.NodeAnnouncement:
3✔
1173
                sender := route.NewVertex(message.source)
3✔
1174
                deDupKey := route.Vertex(msg.NodeID)
3✔
1175

3✔
1176
                // We do the same for node announcements as we did for channel
3✔
1177
                // updates, as they also carry a timestamp.
3✔
1178
                oldTimestamp := uint32(0)
3✔
1179
                mws, ok := d.nodeAnnouncements[deDupKey]
3✔
1180
                if ok {
6✔
1181
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
3✔
1182
                }
3✔
1183

1184
                // Discard the message if it's old.
1185
                if oldTimestamp > msg.Timestamp {
6✔
1186
                        return
3✔
1187
                }
3✔
1188

1189
                // Replace if it's newer.
1190
                if oldTimestamp < msg.Timestamp {
6✔
1191
                        mws = msgWithSenders{
3✔
1192
                                msg:     msg,
3✔
1193
                                isLocal: !message.isRemote,
3✔
1194
                                senders: make(map[route.Vertex]struct{}),
3✔
1195
                        }
3✔
1196

3✔
1197
                        mws.senders[sender] = struct{}{}
3✔
1198

3✔
1199
                        d.nodeAnnouncements[deDupKey] = mws
3✔
1200

3✔
1201
                        return
3✔
1202
                }
3✔
1203

1204
                // Add to senders map if it's the same as we had.
1205
                mws.msg = msg
3✔
1206
                mws.senders[sender] = struct{}{}
3✔
1207
                d.nodeAnnouncements[deDupKey] = mws
3✔
1208
        }
1209
}
1210

1211
// AddMsgs is a helper method to add multiple messages to the announcement
1212
// batch.
1213
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
3✔
1214
        d.Lock()
3✔
1215
        defer d.Unlock()
3✔
1216

3✔
1217
        for _, msg := range msgs {
6✔
1218
                d.addMsg(msg)
3✔
1219
        }
3✔
1220
}
1221

1222
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1223
// to broadcast next into messages that are locally sourced and those that are
1224
// sourced remotely.
1225
type msgsToBroadcast struct {
1226
        // localMsgs is the set of messages we created locally.
1227
        localMsgs []msgWithSenders
1228

1229
        // remoteMsgs is the set of messages that we received from a remote
1230
        // party.
1231
        remoteMsgs []msgWithSenders
1232
}
1233

1234
// addMsg adds a new message to the appropriate sub-slice.
1235
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
3✔
1236
        if msg.isLocal {
6✔
1237
                m.localMsgs = append(m.localMsgs, msg)
3✔
1238
        } else {
6✔
1239
                m.remoteMsgs = append(m.remoteMsgs, msg)
3✔
1240
        }
3✔
1241
}
1242

1243
// isEmpty returns true if the batch is empty.
1244
func (m *msgsToBroadcast) isEmpty() bool {
3✔
1245
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
3✔
1246
}
3✔
1247

1248
// length returns the length of the combined message set.
UNCOV
1249
func (m *msgsToBroadcast) length() int {
×
UNCOV
1250
        return len(m.localMsgs) + len(m.remoteMsgs)
×
UNCOV
1251
}
×
1252

1253
// Emit returns the set of de-duplicated announcements to be sent out during
1254
// the next announcement epoch, in the order of channel announcements, channel
1255
// updates, and node announcements. Each message emitted, contains the set of
1256
// peers that sent us the message. This way, we can ensure that we don't waste
1257
// bandwidth by re-sending a message to the peer that sent it to us in the
1258
// first place. Additionally, the set of stored messages are reset.
1259
func (d *deDupedAnnouncements) Emit() msgsToBroadcast {
3✔
1260
        d.Lock()
3✔
1261
        defer d.Unlock()
3✔
1262

3✔
1263
        // Get the total number of announcements.
3✔
1264
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
3✔
1265
                len(d.nodeAnnouncements)
3✔
1266

3✔
1267
        // Create an empty array of lnwire.Messages with a length equal to
3✔
1268
        // the total number of announcements.
3✔
1269
        msgs := msgsToBroadcast{
3✔
1270
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
3✔
1271
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
3✔
1272
        }
3✔
1273

3✔
1274
        // Add the channel announcements to the array first.
3✔
1275
        for _, message := range d.channelAnnouncements {
6✔
1276
                msgs.addMsg(message)
3✔
1277
        }
3✔
1278

1279
        // Then add the channel updates.
1280
        for _, message := range d.channelUpdates {
6✔
1281
                msgs.addMsg(message)
3✔
1282
        }
3✔
1283

1284
        // Finally add the node announcements.
1285
        for _, message := range d.nodeAnnouncements {
6✔
1286
                msgs.addMsg(message)
3✔
1287
        }
3✔
1288

1289
        d.reset()
3✔
1290

3✔
1291
        // Return the array of lnwire.messages.
3✔
1292
        return msgs
3✔
1293
}
1294

1295
// calculateSubBatchSize is a helper function that calculates the size to break
1296
// down the batchSize into.
1297
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1298
        minimumBatchSize, batchSize int) int {
3✔
1299
        if subBatchDelay > totalDelay {
3✔
UNCOV
1300
                return batchSize
×
UNCOV
1301
        }
×
1302

1303
        subBatchSize := (batchSize*int(subBatchDelay) +
3✔
1304
                int(totalDelay) - 1) / int(totalDelay)
3✔
1305

3✔
1306
        if subBatchSize < minimumBatchSize {
6✔
1307
                return minimumBatchSize
3✔
1308
        }
3✔
1309

UNCOV
1310
        return subBatchSize
×
1311
}
1312

1313
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1314
// this variable so the function can be mocked in our test.
1315
var batchSizeCalculator = calculateSubBatchSize
1316

1317
// splitAnnouncementBatches takes an exiting list of announcements and
1318
// decomposes it into sub batches controlled by the `subBatchSize`.
1319
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1320
        announcementBatch []msgWithSenders) [][]msgWithSenders {
3✔
1321

3✔
1322
        subBatchSize := batchSizeCalculator(
3✔
1323
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
3✔
1324
                d.cfg.MinimumBatchSize, len(announcementBatch),
3✔
1325
        )
3✔
1326

3✔
1327
        var splitAnnouncementBatch [][]msgWithSenders
3✔
1328

3✔
1329
        for subBatchSize < len(announcementBatch) {
6✔
1330
                // For slicing with minimal allocation
3✔
1331
                // https://github.com/golang/go/wiki/SliceTricks
3✔
1332
                announcementBatch, splitAnnouncementBatch =
3✔
1333
                        announcementBatch[subBatchSize:],
3✔
1334
                        append(splitAnnouncementBatch,
3✔
1335
                                announcementBatch[0:subBatchSize:subBatchSize])
3✔
1336
        }
3✔
1337
        splitAnnouncementBatch = append(
3✔
1338
                splitAnnouncementBatch, announcementBatch,
3✔
1339
        )
3✔
1340

3✔
1341
        return splitAnnouncementBatch
3✔
1342
}
1343

1344
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1345
// split size, and then sends out all items to the set of target peers. Locally
1346
// generated announcements are always sent before remotely generated
1347
// announcements.
1348
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(ctx context.Context,
1349
        annBatch msgsToBroadcast) {
3✔
1350

3✔
1351
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
3✔
1352
        // duration to delay the sending of next announcement batch.
3✔
1353
        delayNextBatch := func() {
6✔
1354
                select {
3✔
1355
                case <-time.After(d.cfg.SubBatchDelay):
3✔
UNCOV
1356
                case <-d.quit:
×
UNCOV
1357
                        return
×
1358
                }
1359
        }
1360

1361
        // Fetch the local and remote announcements.
1362
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
3✔
1363
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
3✔
1364

3✔
1365
        d.wg.Add(1)
3✔
1366
        go func() {
6✔
1367
                defer d.wg.Done()
3✔
1368

3✔
1369
                log.Debugf("Broadcasting %v new local announcements in %d "+
3✔
1370
                        "sub batches", len(annBatch.localMsgs),
3✔
1371
                        len(localBatches))
3✔
1372

3✔
1373
                // Send out the local announcements first.
3✔
1374
                for _, annBatch := range localBatches {
6✔
1375
                        d.sendLocalBatch(annBatch)
3✔
1376
                        delayNextBatch()
3✔
1377
                }
3✔
1378

1379
                log.Debugf("Broadcasting %v new remote announcements in %d "+
3✔
1380
                        "sub batches", len(annBatch.remoteMsgs),
3✔
1381
                        len(remoteBatches))
3✔
1382

3✔
1383
                // Now send the remote announcements.
3✔
1384
                for _, annBatch := range remoteBatches {
6✔
1385
                        d.sendRemoteBatch(ctx, annBatch)
3✔
1386
                        delayNextBatch()
3✔
1387
                }
3✔
1388
        }()
1389
}
1390

1391
// sendLocalBatch broadcasts a list of locally generated announcements to our
1392
// peers. For local announcements, we skip the filter and dedup logic and just
1393
// send the announcements out to all our coonnected peers.
1394
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
3✔
1395
        msgsToSend := lnutils.Map(
3✔
1396
                annBatch, func(m msgWithSenders) lnwire.Message {
6✔
1397
                        return m.msg
3✔
1398
                },
3✔
1399
        )
1400

1401
        err := d.cfg.Broadcast(nil, msgsToSend...)
3✔
1402
        if err != nil {
3✔
1403
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1404
        }
×
1405
}
1406

1407
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1408
// peers.
1409
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1410
        annBatch []msgWithSenders) {
3✔
1411

3✔
1412
        syncerPeers := d.syncMgr.GossipSyncers()
3✔
1413

3✔
1414
        // We'll first attempt to filter out this new message for all peers
3✔
1415
        // that have active gossip syncers active.
3✔
1416
        for pub, syncer := range syncerPeers {
6✔
1417
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
3✔
1418
                syncer.FilterGossipMsgs(ctx, annBatch...)
3✔
1419
        }
3✔
1420

1421
        for _, msgChunk := range annBatch {
6✔
1422
                msgChunk := msgChunk
3✔
1423

3✔
1424
                // With the syncers taken care of, we'll merge the sender map
3✔
1425
                // with the set of syncers, so we don't send out duplicate
3✔
1426
                // messages.
3✔
1427
                msgChunk.mergeSyncerMap(syncerPeers)
3✔
1428

3✔
1429
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
3✔
1430
                if err != nil {
3✔
1431
                        log.Errorf("Unable to send batch "+
×
1432
                                "announcements: %v", err)
×
1433
                        continue
×
1434
                }
1435
        }
1436
}
1437

1438
// networkHandler is the primary goroutine that drives this service. The roles
1439
// of this goroutine includes answering queries related to the state of the
1440
// network, syncing up newly connected peers, and also periodically
1441
// broadcasting our latest topology state to all connected peers.
1442
//
1443
// NOTE: This MUST be run as a goroutine.
1444
func (d *AuthenticatedGossiper) networkHandler(ctx context.Context) {
3✔
1445
        defer d.wg.Done()
3✔
1446

3✔
1447
        // Initialize empty deDupedAnnouncements to store announcement batch.
3✔
1448
        announcements := deDupedAnnouncements{}
3✔
1449
        announcements.Reset()
3✔
1450

3✔
1451
        d.cfg.RetransmitTicker.Resume()
3✔
1452
        defer d.cfg.RetransmitTicker.Stop()
3✔
1453

3✔
1454
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
3✔
1455
        defer trickleTimer.Stop()
3✔
1456

3✔
1457
        // To start, we'll first check to see if there are any stale channel or
3✔
1458
        // node announcements that we need to re-transmit.
3✔
1459
        if err := d.retransmitStaleAnns(ctx, time.Now()); err != nil {
3✔
1460
                log.Errorf("Unable to rebroadcast stale announcements: %v", err)
×
1461
        }
×
1462

1463
        for {
6✔
1464
                select {
3✔
1465
                // A new policy update has arrived. We'll commit it to the
1466
                // sub-systems below us, then craft, sign, and broadcast a new
1467
                // ChannelUpdate for the set of affected clients.
1468
                case policyUpdate := <-d.chanPolicyUpdates:
3✔
1469
                        log.Tracef("Received channel %d policy update requests",
3✔
1470
                                len(policyUpdate.edgesToUpdate))
3✔
1471

3✔
1472
                        // First, we'll now create new fully signed updates for
3✔
1473
                        // the affected channels and also update the underlying
3✔
1474
                        // graph with the new state.
3✔
1475
                        newChanUpdates, err := d.processChanPolicyUpdate(
3✔
1476
                                ctx, policyUpdate.edgesToUpdate,
3✔
1477
                        )
3✔
1478
                        policyUpdate.errChan <- err
3✔
1479
                        if err != nil {
3✔
1480
                                log.Errorf("Unable to craft policy updates: %v",
×
1481
                                        err)
×
1482
                                continue
×
1483
                        }
1484

1485
                        // Finally, with the updates committed, we'll now add
1486
                        // them to the announcement batch to be flushed at the
1487
                        // start of the next epoch.
1488
                        announcements.AddMsgs(newChanUpdates...)
3✔
1489

1490
                case announcement := <-d.networkMsgs:
3✔
1491
                        log.Tracef("Received network message: "+
3✔
1492
                                "peer=%v, msg=%s, is_remote=%v",
3✔
1493
                                announcement.peer, announcement.msg.MsgType(),
3✔
1494
                                announcement.isRemote)
3✔
1495

3✔
1496
                        switch announcement.msg.(type) {
3✔
1497
                        // Channel announcement signatures are amongst the only
1498
                        // messages that we'll process serially.
1499
                        case *lnwire.AnnounceSignatures1:
3✔
1500
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
3✔
1501
                                        ctx, announcement,
3✔
1502
                                )
3✔
1503
                                log.Debugf("Processed network message %s, "+
3✔
1504
                                        "returned len(announcements)=%v",
3✔
1505
                                        announcement.msg.MsgType(),
3✔
1506
                                        len(emittedAnnouncements))
3✔
1507

3✔
1508
                                if emittedAnnouncements != nil {
6✔
1509
                                        announcements.AddMsgs(
3✔
1510
                                                emittedAnnouncements...,
3✔
1511
                                        )
3✔
1512
                                }
3✔
1513
                                continue
3✔
1514
                        }
1515

1516
                        // If this message was recently rejected, then we won't
1517
                        // attempt to re-process it.
1518
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
3✔
1519
                                announcement.msg,
3✔
1520
                                sourceToPub(announcement.source),
3✔
1521
                        ) {
3✔
UNCOV
1522

×
UNCOV
1523
                                announcement.err <- fmt.Errorf("recently " +
×
UNCOV
1524
                                        "rejected")
×
UNCOV
1525
                                continue
×
1526
                        }
1527

1528
                        // We'll set up any dependent, and wait until a free
1529
                        // slot for this job opens up, this allow us to not
1530
                        // have thousands of goroutines active.
1531
                        annJobID, err := d.vb.InitJobDependencies(
3✔
1532
                                announcement.msg,
3✔
1533
                        )
3✔
1534
                        if err != nil {
3✔
1535
                                announcement.err <- err
×
1536
                                continue
×
1537
                        }
1538

1539
                        d.wg.Add(1)
3✔
1540
                        go d.handleNetworkMessages(
3✔
1541
                                ctx, announcement, &announcements, annJobID,
3✔
1542
                        )
3✔
1543

1544
                // The trickle timer has ticked, which indicates we should
1545
                // flush to the network the pending batch of new announcements
1546
                // we've received since the last trickle tick.
1547
                case <-trickleTimer.C:
3✔
1548
                        // Emit the current batch of announcements from
3✔
1549
                        // deDupedAnnouncements.
3✔
1550
                        announcementBatch := announcements.Emit()
3✔
1551

3✔
1552
                        // If the current announcements batch is nil, then we
3✔
1553
                        // have no further work here.
3✔
1554
                        if announcementBatch.isEmpty() {
6✔
1555
                                continue
3✔
1556
                        }
1557

1558
                        // At this point, we have the set of local and remote
1559
                        // announcements we want to send out. We'll do the
1560
                        // batching as normal for both, but for local
1561
                        // announcements, we'll blast them out w/o regard for
1562
                        // our peer's policies so we ensure they propagate
1563
                        // properly.
1564
                        d.splitAndSendAnnBatch(ctx, announcementBatch)
3✔
1565

1566
                // The retransmission timer has ticked which indicates that we
1567
                // should check if we need to prune or re-broadcast any of our
1568
                // personal channels or node announcement. This addresses the
1569
                // case of "zombie" channels and channel advertisements that
1570
                // have been dropped, or not properly propagated through the
1571
                // network.
UNCOV
1572
                case tick := <-d.cfg.RetransmitTicker.Ticks():
×
UNCOV
1573
                        if err := d.retransmitStaleAnns(ctx, tick); err != nil {
×
1574
                                log.Errorf("unable to rebroadcast stale "+
×
1575
                                        "announcements: %v", err)
×
1576
                        }
×
1577

1578
                // The gossiper has been signalled to exit, to we exit our
1579
                // main loop so the wait group can be decremented.
1580
                case <-d.quit:
3✔
1581
                        return
3✔
1582
                }
1583
        }
1584
}
1585

1586
// handleNetworkMessages is responsible for waiting for dependencies for a
1587
// given network message and processing the message. Once processed, it will
1588
// signal its dependants and add the new announcements to the announce batch.
1589
//
1590
// NOTE: must be run as a goroutine.
1591
func (d *AuthenticatedGossiper) handleNetworkMessages(ctx context.Context,
1592
        nMsg *networkMsg, deDuped *deDupedAnnouncements, jobID JobID) {
3✔
1593

3✔
1594
        defer d.wg.Done()
3✔
1595
        defer d.vb.CompleteJob()
3✔
1596

3✔
1597
        // We should only broadcast this message forward if it originated from
3✔
1598
        // us or it wasn't received as part of our initial historical sync.
3✔
1599
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
3✔
1600

3✔
1601
        // If this message has an existing dependency, then we'll wait until
3✔
1602
        // that has been fully validated before we proceed.
3✔
1603
        err := d.vb.WaitForParents(jobID, nMsg.msg)
3✔
1604
        if err != nil {
3✔
1605
                log.Debugf("Validating network message %s got err: %v",
×
1606
                        nMsg.msg.MsgType(), err)
×
1607

×
1608
                if errors.Is(err, ErrVBarrierShuttingDown) {
×
1609
                        log.Warnf("unexpected error during validation "+
×
1610
                                "barrier shutdown: %v", err)
×
1611
                }
×
1612
                nMsg.err <- err
×
1613

×
1614
                return
×
1615
        }
1616

1617
        // Process the network announcement to determine if this is either a
1618
        // new announcement from our PoV or an edges to a prior vertex/edge we
1619
        // previously proceeded.
1620
        newAnns, allow := d.processNetworkAnnouncement(ctx, nMsg)
3✔
1621

3✔
1622
        log.Tracef("Processed network message %s, returned "+
3✔
1623
                "len(announcements)=%v, allowDependents=%v",
3✔
1624
                nMsg.msg.MsgType(), len(newAnns), allow)
3✔
1625

3✔
1626
        // If this message had any dependencies, then we can now signal them to
3✔
1627
        // continue.
3✔
1628
        err = d.vb.SignalDependents(nMsg.msg, jobID)
3✔
1629
        if err != nil {
3✔
1630
                // Something is wrong if SignalDependents returns an error.
×
1631
                log.Errorf("SignalDependents returned error for msg=%v with "+
×
1632
                        "JobID=%v", spew.Sdump(nMsg.msg), jobID)
×
1633

×
1634
                nMsg.err <- err
×
1635

×
1636
                return
×
1637
        }
×
1638

1639
        // If the announcement was accepted, then add the emitted announcements
1640
        // to our announce batch to be broadcast once the trickle timer ticks
1641
        // gain.
1642
        if newAnns != nil && shouldBroadcast {
6✔
1643
                // TODO(roasbeef): exclude peer that sent.
3✔
1644
                deDuped.AddMsgs(newAnns...)
3✔
1645
        } else if newAnns != nil {
9✔
1646
                log.Trace("Skipping broadcast of announcements received " +
3✔
1647
                        "during initial graph sync")
3✔
1648
        }
3✔
1649
}
1650

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

1653
// InitSyncState is called by outside sub-systems when a connection is
1654
// established to a new peer that understands how to perform channel range
1655
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1656
// needed to handle new queries.
1657
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
3✔
1658
        d.syncMgr.InitSyncState(syncPeer)
3✔
1659
}
3✔
1660

1661
// PruneSyncState is called by outside sub-systems once a peer that we were
1662
// previously connected to has been disconnected. In this case we can stop the
1663
// existing GossipSyncer assigned to the peer and free up resources.
1664
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
3✔
1665
        d.syncMgr.PruneSyncState(peer)
3✔
1666
}
3✔
1667

1668
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1669
// false otherwise, This avoids expensive reprocessing of the message.
1670
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1671
        peerPub [33]byte) bool {
3✔
1672

3✔
1673
        var scid uint64
3✔
1674
        switch m := msg.(type) {
3✔
1675
        case *lnwire.ChannelUpdate1:
3✔
1676
                scid = m.ShortChannelID.ToUint64()
3✔
1677

1678
        case *lnwire.ChannelAnnouncement1:
3✔
1679
                scid = m.ShortChannelID.ToUint64()
3✔
1680

1681
        default:
3✔
1682
                return false
3✔
1683
        }
1684

1685
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
3✔
1686
        return err != cache.ErrElementNotFound
3✔
1687
}
1688

1689
// retransmitStaleAnns examines all outgoing channels that the source node is
1690
// known to maintain to check to see if any of them are "stale". A channel is
1691
// stale iff, the last timestamp of its rebroadcast is older than the
1692
// RebroadcastInterval. We also check if a refreshed node announcement should
1693
// be resent.
1694
func (d *AuthenticatedGossiper) retransmitStaleAnns(ctx context.Context,
1695
        now time.Time) error {
3✔
1696

3✔
1697
        // Iterate over all of our channels and check if any of them fall
3✔
1698
        // within the prune interval or re-broadcast interval.
3✔
1699
        type updateTuple struct {
3✔
1700
                info *models.ChannelEdgeInfo
3✔
1701
                edge *models.ChannelEdgePolicy
3✔
1702
        }
3✔
1703

3✔
1704
        var (
3✔
1705
                havePublicChannels bool
3✔
1706
                edgesToUpdate      []updateTuple
3✔
1707
        )
3✔
1708
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
3✔
1709
                info *models.ChannelEdgeInfo,
3✔
1710
                edge *models.ChannelEdgePolicy) error {
6✔
1711

3✔
1712
                // If there's no auth proof attached to this edge, it means
3✔
1713
                // that it is a private channel not meant to be announced to
3✔
1714
                // the greater network, so avoid sending channel updates for
3✔
1715
                // this channel to not leak its
3✔
1716
                // existence.
3✔
1717
                if info.AuthProof == nil {
6✔
1718
                        log.Debugf("Skipping retransmission of channel "+
3✔
1719
                                "without AuthProof: %v", info.ChannelID)
3✔
1720
                        return nil
3✔
1721
                }
3✔
1722

1723
                // We make a note that we have at least one public channel. We
1724
                // use this to determine whether we should send a node
1725
                // announcement below.
1726
                havePublicChannels = true
3✔
1727

3✔
1728
                // If this edge has a ChannelUpdate that was created before the
3✔
1729
                // introduction of the MaxHTLC field, then we'll update this
3✔
1730
                // edge to propagate this information in the network.
3✔
1731
                if !edge.MessageFlags.HasMaxHtlc() {
3✔
1732
                        // We'll make sure we support the new max_htlc field if
×
1733
                        // not already present.
×
1734
                        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
×
1735
                        edge.MaxHTLC = lnwire.NewMSatFromSatoshis(info.Capacity)
×
1736

×
1737
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1738
                                info: info,
×
1739
                                edge: edge,
×
1740
                        })
×
1741
                        return nil
×
1742
                }
×
1743

1744
                timeElapsed := now.Sub(edge.LastUpdate)
3✔
1745

3✔
1746
                // If it's been longer than RebroadcastInterval since we've
3✔
1747
                // re-broadcasted the channel, add the channel to the set of
3✔
1748
                // edges we need to update.
3✔
1749
                if timeElapsed >= d.cfg.RebroadcastInterval {
3✔
UNCOV
1750
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
UNCOV
1751
                                info: info,
×
UNCOV
1752
                                edge: edge,
×
UNCOV
1753
                        })
×
UNCOV
1754
                }
×
1755

1756
                return nil
3✔
1757
        })
1758
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
1759
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1760
                        err)
×
1761
        }
×
1762

1763
        var signedUpdates []lnwire.Message
3✔
1764
        for _, chanToUpdate := range edgesToUpdate {
3✔
UNCOV
1765
                // Re-sign and update the channel on disk and retrieve our
×
UNCOV
1766
                // ChannelUpdate to broadcast.
×
UNCOV
1767
                chanAnn, chanUpdate, err := d.updateChannel(
×
UNCOV
1768
                        ctx, chanToUpdate.info, chanToUpdate.edge,
×
UNCOV
1769
                )
×
UNCOV
1770
                if err != nil {
×
1771
                        return fmt.Errorf("unable to update channel: %w", err)
×
1772
                }
×
1773

1774
                // If we have a valid announcement to transmit, then we'll send
1775
                // that along with the update.
UNCOV
1776
                if chanAnn != nil {
×
UNCOV
1777
                        signedUpdates = append(signedUpdates, chanAnn)
×
UNCOV
1778
                }
×
1779

UNCOV
1780
                signedUpdates = append(signedUpdates, chanUpdate)
×
1781
        }
1782

1783
        // If we don't have any public channels, we return as we don't want to
1784
        // broadcast anything that would reveal our existence.
1785
        if !havePublicChannels {
6✔
1786
                return nil
3✔
1787
        }
3✔
1788

1789
        // We'll also check that our NodeAnnouncement is not too old.
1790
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
3✔
1791
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
3✔
1792
        timeElapsed := now.Sub(timestamp)
3✔
1793

3✔
1794
        // If it's been a full day since we've re-broadcasted the
3✔
1795
        // node announcement, refresh it and resend it.
3✔
1796
        nodeAnnStr := ""
3✔
1797
        if timeElapsed >= d.cfg.RebroadcastInterval {
3✔
UNCOV
1798
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
×
UNCOV
1799
                if err != nil {
×
1800
                        return fmt.Errorf("unable to get refreshed node "+
×
1801
                                "announcement: %v", err)
×
1802
                }
×
1803

UNCOV
1804
                signedUpdates = append(signedUpdates, &newNodeAnn)
×
UNCOV
1805
                nodeAnnStr = " and our refreshed node announcement"
×
UNCOV
1806

×
UNCOV
1807
                // Before broadcasting the refreshed node announcement, add it
×
UNCOV
1808
                // to our own graph.
×
UNCOV
1809
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
×
UNCOV
1810
                        log.Errorf("Unable to add refreshed node announcement "+
×
UNCOV
1811
                                "to graph: %v", err)
×
UNCOV
1812
                }
×
1813
        }
1814

1815
        // If we don't have any updates to re-broadcast, then we'll exit
1816
        // early.
1817
        if len(signedUpdates) == 0 {
6✔
1818
                return nil
3✔
1819
        }
3✔
1820

UNCOV
1821
        log.Infof("Retransmitting %v outgoing channels%v",
×
UNCOV
1822
                len(edgesToUpdate), nodeAnnStr)
×
UNCOV
1823

×
UNCOV
1824
        // With all the wire announcements properly crafted, we'll broadcast
×
UNCOV
1825
        // our known outgoing channels to all our immediate peers.
×
UNCOV
1826
        if err := d.cfg.Broadcast(nil, signedUpdates...); err != nil {
×
1827
                return fmt.Errorf("unable to re-broadcast channels: %w", err)
×
1828
        }
×
1829

UNCOV
1830
        return nil
×
1831
}
1832

1833
// processChanPolicyUpdate generates a new set of channel updates for the
1834
// provided list of edges and updates the backing ChannelGraphSource.
1835
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1836
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
3✔
1837

3✔
1838
        var chanUpdates []networkMsg
3✔
1839
        for _, edgeInfo := range edgesToUpdate {
6✔
1840
                // Now that we've collected all the channels we need to update,
3✔
1841
                // we'll re-sign and update the backing ChannelGraphSource, and
3✔
1842
                // retrieve our ChannelUpdate to broadcast.
3✔
1843
                _, chanUpdate, err := d.updateChannel(
3✔
1844
                        ctx, edgeInfo.Info, edgeInfo.Edge,
3✔
1845
                )
3✔
1846
                if err != nil {
3✔
1847
                        return nil, err
×
1848
                }
×
1849

1850
                // We'll avoid broadcasting any updates for private channels to
1851
                // avoid directly giving away their existence. Instead, we'll
1852
                // send the update directly to the remote party.
1853
                if edgeInfo.Info.AuthProof == nil {
6✔
1854
                        // If AuthProof is nil and an alias was found for this
3✔
1855
                        // ChannelID (meaning the option-scid-alias feature was
3✔
1856
                        // negotiated), we'll replace the ShortChannelID in the
3✔
1857
                        // update with the peer's alias. We do this after
3✔
1858
                        // updateChannel so that the alias isn't persisted to
3✔
1859
                        // the database.
3✔
1860
                        chanID := lnwire.NewChanIDFromOutPoint(
3✔
1861
                                edgeInfo.Info.ChannelPoint,
3✔
1862
                        )
3✔
1863

3✔
1864
                        var defaultAlias lnwire.ShortChannelID
3✔
1865
                        foundAlias, _ := d.cfg.GetAlias(chanID)
3✔
1866
                        if foundAlias != defaultAlias {
6✔
1867
                                chanUpdate.ShortChannelID = foundAlias
3✔
1868

3✔
1869
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
3✔
1870
                                if err != nil {
3✔
1871
                                        log.Errorf("Unable to sign alias "+
×
1872
                                                "update: %v", err)
×
1873
                                        continue
×
1874
                                }
1875

1876
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1877
                                if err != nil {
3✔
1878
                                        log.Errorf("Unable to create sig: %v",
×
1879
                                                err)
×
1880
                                        continue
×
1881
                                }
1882

1883
                                chanUpdate.Signature = lnSig
3✔
1884
                        }
1885

1886
                        remotePubKey := remotePubFromChanInfo(
3✔
1887
                                edgeInfo.Info, chanUpdate.ChannelFlags,
3✔
1888
                        )
3✔
1889
                        err := d.reliableSender.sendMessage(
3✔
1890
                                ctx, chanUpdate, remotePubKey,
3✔
1891
                        )
3✔
1892
                        if err != nil {
3✔
1893
                                log.Errorf("Unable to reliably send %v for "+
×
1894
                                        "channel=%v to peer=%x: %v",
×
1895
                                        chanUpdate.MsgType(),
×
1896
                                        chanUpdate.ShortChannelID,
×
1897
                                        remotePubKey, err)
×
1898
                        }
×
1899
                        continue
3✔
1900
                }
1901

1902
                // We set ourselves as the source of this message to indicate
1903
                // that we shouldn't skip any peers when sending this message.
1904
                chanUpdates = append(chanUpdates, networkMsg{
3✔
1905
                        source:   d.selfKey,
3✔
1906
                        isRemote: false,
3✔
1907
                        msg:      chanUpdate,
3✔
1908
                })
3✔
1909
        }
1910

1911
        return chanUpdates, nil
3✔
1912
}
1913

1914
// remotePubFromChanInfo returns the public key of the remote peer given a
1915
// ChannelEdgeInfo that describe a channel we have with them.
1916
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1917
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
3✔
1918

3✔
1919
        var remotePubKey [33]byte
3✔
1920
        switch {
3✔
1921
        case chanFlags&lnwire.ChanUpdateDirection == 0:
3✔
1922
                remotePubKey = chanInfo.NodeKey2Bytes
3✔
1923
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1924
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1925
        }
1926

1927
        return remotePubKey
3✔
1928
}
1929

1930
// processRejectedEdge examines a rejected edge to see if we can extract any
1931
// new announcements from it.  An edge will get rejected if we already added
1932
// the same edge without AuthProof to the graph. If the received announcement
1933
// contains a proof, we can add this proof to our edge.  We can end up in this
1934
// situation in the case where we create a channel, but for some reason fail
1935
// to receive the remote peer's proof, while the remote peer is able to fully
1936
// assemble the proof and craft the ChannelAnnouncement.
1937
func (d *AuthenticatedGossiper) processRejectedEdge(_ context.Context,
1938
        chanAnnMsg *lnwire.ChannelAnnouncement1,
1939
        proof *models.ChannelAuthProof) ([]networkMsg, error) {
3✔
1940

3✔
1941
        // First, we'll fetch the state of the channel as we know if from the
3✔
1942
        // database.
3✔
1943
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
1944
                chanAnnMsg.ShortChannelID,
3✔
1945
        )
3✔
1946
        if err != nil {
3✔
1947
                return nil, err
×
1948
        }
×
1949

1950
        // The edge is in the graph, and has a proof attached, then we'll just
1951
        // reject it as normal.
1952
        if chanInfo.AuthProof != nil {
6✔
1953
                return nil, nil
3✔
1954
        }
3✔
1955

1956
        // Otherwise, this means that the edge is within the graph, but it
1957
        // doesn't yet have a proper proof attached. If we did not receive
1958
        // the proof such that we now can add it, there's nothing more we
1959
        // can do.
1960
        if proof == nil {
×
1961
                return nil, nil
×
1962
        }
×
1963

1964
        // We'll then create then validate the new fully assembled
1965
        // announcement.
1966
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
×
1967
                proof, chanInfo, e1, e2,
×
1968
        )
×
1969
        if err != nil {
×
1970
                return nil, err
×
1971
        }
×
1972
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
×
1973
        if err != nil {
×
1974
                err := fmt.Errorf("assembled channel announcement proof "+
×
1975
                        "for shortChanID=%v isn't valid: %v",
×
1976
                        chanAnnMsg.ShortChannelID, err)
×
1977
                log.Error(err)
×
1978
                return nil, err
×
1979
        }
×
1980

1981
        // If everything checks out, then we'll add the fully assembled proof
1982
        // to the database.
1983
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
1984
        if err != nil {
×
1985
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
1986
                        chanAnnMsg.ShortChannelID, err)
×
1987
                log.Error(err)
×
1988
                return nil, err
×
1989
        }
×
1990

1991
        // As we now have a complete channel announcement for this channel,
1992
        // we'll construct the announcement so they can be broadcast out to all
1993
        // our peers.
1994
        announcements := make([]networkMsg, 0, 3)
×
1995
        announcements = append(announcements, networkMsg{
×
1996
                source: d.selfKey,
×
1997
                msg:    chanAnn,
×
1998
        })
×
1999
        if e1Ann != nil {
×
2000
                announcements = append(announcements, networkMsg{
×
2001
                        source: d.selfKey,
×
2002
                        msg:    e1Ann,
×
2003
                })
×
2004
        }
×
2005
        if e2Ann != nil {
×
2006
                announcements = append(announcements, networkMsg{
×
2007
                        source: d.selfKey,
×
2008
                        msg:    e2Ann,
×
2009
                })
×
2010

×
2011
        }
×
2012

2013
        return announcements, nil
×
2014
}
2015

2016
// fetchPKScript fetches the output script for the given SCID.
2017
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2018
        []byte, error) {
×
2019

×
2020
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2021
}
×
2022

2023
// addNode processes the given node announcement, and adds it to our channel
2024
// graph.
2025
func (d *AuthenticatedGossiper) addNode(_ context.Context,
2026
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
3✔
2027

3✔
2028
        if err := netann.ValidateNodeAnn(msg); err != nil {
3✔
UNCOV
2029
                return fmt.Errorf("unable to validate node announcement: %w",
×
UNCOV
2030
                        err)
×
UNCOV
2031
        }
×
2032

2033
        return d.cfg.Graph.AddNode(models.NodeFromWireAnnouncement(msg), op...)
3✔
2034
}
2035

2036
// isPremature decides whether a given network message has a block height+delta
2037
// value specified in the future. If so, the message will be added to the
2038
// future message map and be processed when the block height as reached.
2039
//
2040
// NOTE: must be used inside a lock.
2041
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2042
        delta uint32, msg *networkMsg) bool {
3✔
2043

3✔
2044
        // The channel is already confirmed at chanID.BlockHeight so we minus
3✔
2045
        // one block. For instance, if the required confirmation for this
3✔
2046
        // channel announcement is 6, we then only need to wait for 5 more
3✔
2047
        // blocks once the funding tx is confirmed.
3✔
2048
        if delta > 0 {
6✔
2049
                delta--
3✔
2050
        }
3✔
2051

2052
        msgHeight := chanID.BlockHeight + delta
3✔
2053

3✔
2054
        // The message height is smaller or equal to our best known height,
3✔
2055
        // thus the message is mature.
3✔
2056
        if msgHeight <= d.bestHeight {
6✔
2057
                return false
3✔
2058
        }
3✔
2059

2060
        // Add the premature message to our future messages which will be
2061
        // resent once the block height has reached.
2062
        //
2063
        // Copy the networkMsgs since the old message's err chan will be
2064
        // consumed.
2065
        copied := &networkMsg{
3✔
2066
                peer:              msg.peer,
3✔
2067
                source:            msg.source,
3✔
2068
                msg:               msg.msg,
3✔
2069
                optionalMsgFields: msg.optionalMsgFields,
3✔
2070
                isRemote:          msg.isRemote,
3✔
2071
                err:               make(chan error, 1),
3✔
2072
        }
3✔
2073

3✔
2074
        // Create the cached message.
3✔
2075
        cachedMsg := &cachedFutureMsg{
3✔
2076
                msg:    copied,
3✔
2077
                height: msgHeight,
3✔
2078
        }
3✔
2079

3✔
2080
        // Increment the msg ID and add it to the cache.
3✔
2081
        nextMsgID := d.futureMsgs.nextMsgID()
3✔
2082
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
3✔
2083
        if err != nil {
3✔
2084
                log.Errorf("Adding future message got error: %v", err)
×
2085
        }
×
2086

2087
        log.Debugf("Network message: %v added to future messages for "+
3✔
2088
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
3✔
2089
                msgHeight, d.bestHeight)
3✔
2090

3✔
2091
        return true
3✔
2092
}
2093

2094
// processNetworkAnnouncement processes a new network relate authenticated
2095
// channel or node announcement or announcements proofs. If the announcement
2096
// didn't affect the internal state due to either being out of date, invalid,
2097
// or redundant, then nil is returned. Otherwise, the set of announcements will
2098
// be returned which should be broadcasted to the rest of the network. The
2099
// boolean returned indicates whether any dependents of the announcement should
2100
// attempt to be processed as well.
2101
func (d *AuthenticatedGossiper) processNetworkAnnouncement(ctx context.Context,
2102
        nMsg *networkMsg) ([]networkMsg, bool) {
3✔
2103

3✔
2104
        // If this is a remote update, we set the scheduler option to lazily
3✔
2105
        // add it to the graph.
3✔
2106
        var schedulerOp []batch.SchedulerOption
3✔
2107
        if nMsg.isRemote {
6✔
2108
                schedulerOp = append(schedulerOp, batch.LazyAdd())
3✔
2109
        }
3✔
2110

2111
        switch msg := nMsg.msg.(type) {
3✔
2112
        // A new node announcement has arrived which either presents new
2113
        // information about a node in one of the channels we know about, or a
2114
        // updating previously advertised information.
2115
        case *lnwire.NodeAnnouncement:
3✔
2116
                return d.handleNodeAnnouncement(ctx, nMsg, msg, schedulerOp)
3✔
2117

2118
        // A new channel announcement has arrived, this indicates the
2119
        // *creation* of a new channel within the network. This only advertises
2120
        // the existence of a channel and not yet the routing policies in
2121
        // either direction of the channel.
2122
        case *lnwire.ChannelAnnouncement1:
3✔
2123
                return d.handleChanAnnouncement(ctx, nMsg, msg, schedulerOp...)
3✔
2124

2125
        // A new authenticated channel edge update has arrived. This indicates
2126
        // that the directional information for an already known channel has
2127
        // been updated.
2128
        case *lnwire.ChannelUpdate1:
3✔
2129
                return d.handleChanUpdate(ctx, nMsg, msg, schedulerOp)
3✔
2130

2131
        // A new signature announcement has been received. This indicates
2132
        // willingness of nodes involved in the funding of a channel to
2133
        // announce this new channel to the rest of the world.
2134
        case *lnwire.AnnounceSignatures1:
3✔
2135
                return d.handleAnnSig(ctx, nMsg, msg)
3✔
2136

2137
        default:
×
2138
                err := errors.New("wrong type of the announcement")
×
2139
                nMsg.err <- err
×
2140
                return nil, false
×
2141
        }
2142
}
2143

2144
// processZombieUpdate determines whether the provided channel update should
2145
// resurrect a given zombie edge.
2146
//
2147
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2148
// should be inspected.
2149
func (d *AuthenticatedGossiper) processZombieUpdate(_ context.Context,
2150
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
UNCOV
2151
        msg *lnwire.ChannelUpdate1) error {
×
UNCOV
2152

×
UNCOV
2153
        // The least-significant bit in the flag on the channel update tells us
×
UNCOV
2154
        // which edge is being updated.
×
UNCOV
2155
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
×
UNCOV
2156

×
UNCOV
2157
        // Since we've deemed the update as not stale above, before marking it
×
UNCOV
2158
        // live, we'll make sure it has been signed by the correct party. If we
×
UNCOV
2159
        // have both pubkeys, either party can resurrect the channel. If we've
×
UNCOV
2160
        // already marked this with the stricter, single-sided resurrection we
×
UNCOV
2161
        // will only have the pubkey of the node with the oldest timestamp.
×
UNCOV
2162
        var pubKey *btcec.PublicKey
×
UNCOV
2163
        switch {
×
2164
        case isNode1 && chanInfo.NodeKey1Bytes != emptyPubkey:
×
2165
                pubKey, _ = chanInfo.NodeKey1()
×
UNCOV
2166
        case !isNode1 && chanInfo.NodeKey2Bytes != emptyPubkey:
×
UNCOV
2167
                pubKey, _ = chanInfo.NodeKey2()
×
2168
        }
UNCOV
2169
        if pubKey == nil {
×
UNCOV
2170
                return fmt.Errorf("incorrect pubkey to resurrect zombie "+
×
UNCOV
2171
                        "with chan_id=%v", msg.ShortChannelID)
×
UNCOV
2172
        }
×
2173

UNCOV
2174
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
×
UNCOV
2175
        if err != nil {
×
UNCOV
2176
                return fmt.Errorf("unable to verify channel "+
×
UNCOV
2177
                        "update signature: %v", err)
×
UNCOV
2178
        }
×
2179

2180
        // With the signature valid, we'll proceed to mark the
2181
        // edge as live and wait for the channel announcement to
2182
        // come through again.
UNCOV
2183
        err = d.cfg.Graph.MarkEdgeLive(scid)
×
UNCOV
2184
        switch {
×
2185
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2186
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2187
                        "zombie index: %v", err)
×
2188

×
2189
                return nil
×
2190

2191
        case err != nil:
×
2192
                return fmt.Errorf("unable to remove edge with "+
×
2193
                        "chan_id=%v from zombie index: %v",
×
2194
                        msg.ShortChannelID, err)
×
2195

UNCOV
2196
        default:
×
2197
        }
2198

UNCOV
2199
        log.Debugf("Removed edge with chan_id=%v from zombie "+
×
UNCOV
2200
                "index", msg.ShortChannelID)
×
UNCOV
2201

×
UNCOV
2202
        return nil
×
2203
}
2204

2205
// fetchNodeAnn fetches the latest signed node announcement from our point of
2206
// view for the node with the given public key.
2207
func (d *AuthenticatedGossiper) fetchNodeAnn(_ context.Context,
2208
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
3✔
2209

3✔
2210
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
3✔
2211
        if err != nil {
3✔
UNCOV
2212
                return nil, err
×
UNCOV
2213
        }
×
2214

2215
        return node.NodeAnnouncement(true)
3✔
2216
}
2217

2218
// isMsgStale determines whether a message retrieved from the backing
2219
// MessageStore is seen as stale by the current graph.
2220
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2221
        msg lnwire.Message) bool {
3✔
2222

3✔
2223
        switch msg := msg.(type) {
3✔
2224
        case *lnwire.AnnounceSignatures1:
3✔
2225
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
3✔
2226
                        msg.ShortChannelID,
3✔
2227
                )
3✔
2228

3✔
2229
                // If the channel cannot be found, it is most likely a leftover
3✔
2230
                // message for a channel that was closed, so we can consider it
3✔
2231
                // stale.
3✔
2232
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
6✔
2233
                        return true
3✔
2234
                }
3✔
2235
                if err != nil {
3✔
2236
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2237
                                "%v", chanInfo.ChannelID, err)
×
2238
                        return false
×
2239
                }
×
2240

2241
                // If the proof exists in the graph, then we have successfully
2242
                // received the remote proof and assembled the full proof, so we
2243
                // can safely delete the local proof from the database.
2244
                return chanInfo.AuthProof != nil
3✔
2245

2246
        case *lnwire.ChannelUpdate1:
3✔
2247
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
3✔
2248

3✔
2249
                // If the channel cannot be found, it is most likely a leftover
3✔
2250
                // message for a channel that was closed, so we can consider it
3✔
2251
                // stale.
3✔
2252
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
6✔
2253
                        return true
3✔
2254
                }
3✔
2255
                if err != nil {
3✔
2256
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2257
                                "%v", msg.ShortChannelID, err)
×
2258
                        return false
×
2259
                }
×
2260

2261
                // Otherwise, we'll retrieve the correct policy that we
2262
                // currently have stored within our graph to check if this
2263
                // message is stale by comparing its timestamp.
2264
                var p *models.ChannelEdgePolicy
3✔
2265
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2266
                        p = p1
3✔
2267
                } else {
6✔
2268
                        p = p2
3✔
2269
                }
3✔
2270

2271
                // If the policy is still unknown, then we can consider this
2272
                // policy fresh.
2273
                if p == nil {
3✔
2274
                        return false
×
2275
                }
×
2276

2277
                timestamp := time.Unix(int64(msg.Timestamp), 0)
3✔
2278
                return p.LastUpdate.After(timestamp)
3✔
2279

2280
        default:
×
2281
                // We'll make sure to not mark any unsupported messages as stale
×
2282
                // to ensure they are not removed.
×
2283
                return false
×
2284
        }
2285
}
2286

2287
// updateChannel creates a new fully signed update for the channel, and updates
2288
// the underlying graph with the new state.
2289
func (d *AuthenticatedGossiper) updateChannel(_ context.Context,
2290
        info *models.ChannelEdgeInfo,
2291
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2292
        *lnwire.ChannelUpdate1, error) {
3✔
2293

3✔
2294
        // Parse the unsigned edge into a channel update.
3✔
2295
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
3✔
2296

3✔
2297
        // We'll generate a new signature over a digest of the channel
3✔
2298
        // announcement itself and update the timestamp to ensure it propagate.
3✔
2299
        err := netann.SignChannelUpdate(
3✔
2300
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
3✔
2301
                netann.ChanUpdSetTimestamp,
3✔
2302
        )
3✔
2303
        if err != nil {
3✔
2304
                return nil, nil, err
×
2305
        }
×
2306

2307
        // Next, we'll set the new signature in place, and update the reference
2308
        // in the backing slice.
2309
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
3✔
2310
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
3✔
2311

3✔
2312
        // To ensure that our signature is valid, we'll verify it ourself
3✔
2313
        // before committing it to the slice returned.
3✔
2314
        err = netann.ValidateChannelUpdateAnn(
3✔
2315
                d.selfKey, info.Capacity, chanUpdate,
3✔
2316
        )
3✔
2317
        if err != nil {
3✔
2318
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2319
                        "update sig: %v", err)
×
2320
        }
×
2321

2322
        // Finally, we'll write the new edge policy to disk.
2323
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
3✔
2324
                return nil, nil, err
×
2325
        }
×
2326

2327
        // We'll also create the original channel announcement so the two can
2328
        // be broadcast along side each other (if necessary), but only if we
2329
        // have a full channel announcement for this channel.
2330
        var chanAnn *lnwire.ChannelAnnouncement1
3✔
2331
        if info.AuthProof != nil {
6✔
2332
                chanID := lnwire.NewShortChanIDFromInt(info.ChannelID)
3✔
2333
                chanAnn = &lnwire.ChannelAnnouncement1{
3✔
2334
                        ShortChannelID:  chanID,
3✔
2335
                        NodeID1:         info.NodeKey1Bytes,
3✔
2336
                        NodeID2:         info.NodeKey2Bytes,
3✔
2337
                        ChainHash:       info.ChainHash,
3✔
2338
                        BitcoinKey1:     info.BitcoinKey1Bytes,
3✔
2339
                        Features:        lnwire.NewRawFeatureVector(),
3✔
2340
                        BitcoinKey2:     info.BitcoinKey2Bytes,
3✔
2341
                        ExtraOpaqueData: info.ExtraOpaqueData,
3✔
2342
                }
3✔
2343
                chanAnn.NodeSig1, err = lnwire.NewSigFromECDSARawSignature(
3✔
2344
                        info.AuthProof.NodeSig1Bytes,
3✔
2345
                )
3✔
2346
                if err != nil {
3✔
2347
                        return nil, nil, err
×
2348
                }
×
2349
                chanAnn.NodeSig2, err = lnwire.NewSigFromECDSARawSignature(
3✔
2350
                        info.AuthProof.NodeSig2Bytes,
3✔
2351
                )
3✔
2352
                if err != nil {
3✔
2353
                        return nil, nil, err
×
2354
                }
×
2355
                chanAnn.BitcoinSig1, err = lnwire.NewSigFromECDSARawSignature(
3✔
2356
                        info.AuthProof.BitcoinSig1Bytes,
3✔
2357
                )
3✔
2358
                if err != nil {
3✔
2359
                        return nil, nil, err
×
2360
                }
×
2361
                chanAnn.BitcoinSig2, err = lnwire.NewSigFromECDSARawSignature(
3✔
2362
                        info.AuthProof.BitcoinSig2Bytes,
3✔
2363
                )
3✔
2364
                if err != nil {
3✔
2365
                        return nil, nil, err
×
2366
                }
×
2367
        }
2368

2369
        return chanAnn, chanUpdate, err
3✔
2370
}
2371

2372
// SyncManager returns the gossiper's SyncManager instance.
2373
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2374
        return d.syncMgr
3✔
2375
}
3✔
2376

2377
// IsKeepAliveUpdate determines whether this channel update is considered a
2378
// keep-alive update based on the previous channel update processed for the same
2379
// direction.
2380
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2381
        prev *models.ChannelEdgePolicy) bool {
3✔
2382

3✔
2383
        // Both updates should be from the same direction.
3✔
2384
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
3✔
2385
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
3✔
2386

×
2387
                return false
×
2388
        }
×
2389

2390
        // The timestamp should always increase for a keep-alive update.
2391
        timestamp := time.Unix(int64(update.Timestamp), 0)
3✔
2392
        if !timestamp.After(prev.LastUpdate) {
3✔
2393
                return false
×
2394
        }
×
2395

2396
        // None of the remaining fields should change for a keep-alive update.
2397
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
6✔
2398
                return false
3✔
2399
        }
3✔
2400
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
6✔
2401
                return false
3✔
2402
        }
3✔
2403
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
6✔
2404
                return false
3✔
2405
        }
3✔
2406
        if update.TimeLockDelta != prev.TimeLockDelta {
3✔
2407
                return false
×
2408
        }
×
2409
        if update.HtlcMinimumMsat != prev.MinHTLC {
3✔
2410
                return false
×
2411
        }
×
2412
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
3✔
2413
                return false
×
2414
        }
×
2415
        if update.HtlcMaximumMsat != prev.MaxHTLC {
3✔
2416
                return false
×
2417
        }
×
2418
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
6✔
2419
                return false
3✔
2420
        }
3✔
2421
        return true
3✔
2422
}
2423

2424
// latestHeight returns the gossiper's latest height known of the chain.
2425
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2426
        d.Lock()
3✔
2427
        defer d.Unlock()
3✔
2428
        return d.bestHeight
3✔
2429
}
3✔
2430

2431
// handleNodeAnnouncement processes a new node announcement.
2432
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2433
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2434
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2435

3✔
2436
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
3✔
2437

3✔
2438
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
3✔
2439
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
3✔
2440
                nMsg.source.SerializeCompressed())
3✔
2441

3✔
2442
        // We'll quickly ask the router if it already has a newer update for
3✔
2443
        // this node so we can skip validating signatures if not required.
3✔
2444
        if d.cfg.Graph.IsStaleNode(nodeAnn.NodeID, timestamp) {
6✔
2445
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
3✔
2446
                nMsg.err <- nil
3✔
2447
                return nil, true
3✔
2448
        }
3✔
2449

2450
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
6✔
2451
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2452
                        err)
3✔
2453

3✔
2454
                if !graph.IsError(
3✔
2455
                        err,
3✔
2456
                        graph.ErrOutdated,
3✔
2457
                        graph.ErrIgnored,
3✔
2458
                ) {
3✔
2459

×
2460
                        log.Error(err)
×
2461
                }
×
2462

2463
                nMsg.err <- err
3✔
2464
                return nil, false
3✔
2465
        }
2466

2467
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2468
        // quick check to ensure this node intends to publicly advertise itself
2469
        // to the network.
2470
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
3✔
2471
        if err != nil {
3✔
2472
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2473
                        nodeAnn.NodeID, err)
×
2474
                nMsg.err <- err
×
2475
                return nil, false
×
2476
        }
×
2477

2478
        var announcements []networkMsg
3✔
2479

3✔
2480
        // If it does, we'll add their announcement to our batch so that it can
3✔
2481
        // be broadcast to the rest of our peers.
3✔
2482
        if isPublic {
6✔
2483
                announcements = append(announcements, networkMsg{
3✔
2484
                        peer:     nMsg.peer,
3✔
2485
                        isRemote: nMsg.isRemote,
3✔
2486
                        source:   nMsg.source,
3✔
2487
                        msg:      nodeAnn,
3✔
2488
                })
3✔
2489
        } else {
6✔
2490
                log.Tracef("Skipping broadcasting node announcement for %x "+
3✔
2491
                        "due to being unadvertised", nodeAnn.NodeID)
3✔
2492
        }
3✔
2493

2494
        nMsg.err <- nil
3✔
2495
        // TODO(roasbeef): get rid of the above
3✔
2496

3✔
2497
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
3✔
2498
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
3✔
2499
                nMsg.source.SerializeCompressed())
3✔
2500

3✔
2501
        return announcements, true
3✔
2502
}
2503

2504
// handleChanAnnouncement processes a new channel announcement.
2505
//
2506
//nolint:funlen
2507
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2508
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2509
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2510

3✔
2511
        scid := ann.ShortChannelID
3✔
2512

3✔
2513
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
3✔
2514
                nMsg.peer, scid.ToUint64())
3✔
2515

3✔
2516
        // We'll ignore any channel announcements that target any chain other
3✔
2517
        // than the set of chains we know of.
3✔
2518
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
3✔
2519
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2520
                        ", gossiper on chain=%v", ann.ChainHash,
×
2521
                        d.cfg.ChainHash)
×
2522
                log.Errorf(err.Error())
×
2523

×
2524
                key := newRejectCacheKey(
×
2525
                        scid.ToUint64(),
×
2526
                        sourceToPub(nMsg.source),
×
2527
                )
×
2528
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2529

×
2530
                nMsg.err <- err
×
2531
                return nil, false
×
2532
        }
×
2533

2534
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2535
        // reject the announcement. Since the router accepts alias SCIDs,
2536
        // not erroring out would be a DoS vector.
2537
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
3✔
2538
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2539
                log.Errorf(err.Error())
×
2540

×
2541
                key := newRejectCacheKey(
×
2542
                        scid.ToUint64(),
×
2543
                        sourceToPub(nMsg.source),
×
2544
                )
×
2545
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2546

×
2547
                nMsg.err <- err
×
2548
                return nil, false
×
2549
        }
×
2550

2551
        // If the advertised inclusionary block is beyond our knowledge of the
2552
        // chain tip, then we'll ignore it for now.
2553
        d.Lock()
3✔
2554
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
3✔
UNCOV
2555
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
×
UNCOV
2556
                        "advertises height %v, only height %v is known",
×
UNCOV
2557
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
×
UNCOV
2558
                d.Unlock()
×
UNCOV
2559
                nMsg.err <- nil
×
UNCOV
2560
                return nil, false
×
UNCOV
2561
        }
×
2562
        d.Unlock()
3✔
2563

3✔
2564
        // At this point, we'll now ask the router if this is a zombie/known
3✔
2565
        // edge. If so we can skip all the processing below.
3✔
2566
        if d.cfg.Graph.IsKnownEdge(scid) {
6✔
2567
                nMsg.err <- nil
3✔
2568
                return nil, true
3✔
2569
        }
3✔
2570

2571
        // Check if the channel is already closed in which case we can ignore
2572
        // it.
2573
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
3✔
2574
        if err != nil {
3✔
2575
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2576
                        err)
×
2577
                nMsg.err <- err
×
2578

×
2579
                return nil, false
×
2580
        }
×
2581

2582
        if closed {
3✔
UNCOV
2583
                err = fmt.Errorf("ignoring closed channel %v", scid)
×
UNCOV
2584
                log.Error(err)
×
UNCOV
2585

×
UNCOV
2586
                // If this is an announcement from us, we'll just ignore it.
×
UNCOV
2587
                if !nMsg.isRemote {
×
2588
                        nMsg.err <- err
×
2589
                        return nil, false
×
2590
                }
×
2591

2592
                // Increment the peer's ban score if they are sending closed
2593
                // channel announcements.
UNCOV
2594
                d.banman.incrementBanScore(nMsg.peer.PubKey())
×
UNCOV
2595

×
UNCOV
2596
                // If the peer is banned and not a channel peer, we'll
×
UNCOV
2597
                // disconnect them.
×
UNCOV
2598
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
×
UNCOV
2599
                if dcErr != nil {
×
2600
                        log.Errorf("failed to check if we should disconnect "+
×
2601
                                "peer: %v", dcErr)
×
2602
                        nMsg.err <- dcErr
×
2603

×
2604
                        return nil, false
×
2605
                }
×
2606

UNCOV
2607
                if shouldDc {
×
2608
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2609
                }
×
2610

UNCOV
2611
                nMsg.err <- err
×
UNCOV
2612

×
UNCOV
2613
                return nil, false
×
2614
        }
2615

2616
        // If this is a remote channel announcement, then we'll validate all
2617
        // the signatures within the proof as it should be well formed.
2618
        var proof *models.ChannelAuthProof
3✔
2619
        if nMsg.isRemote {
6✔
2620
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
3✔
2621
                if err != nil {
3✔
2622
                        err := fmt.Errorf("unable to validate announcement: "+
×
2623
                                "%v", err)
×
2624

×
2625
                        key := newRejectCacheKey(
×
2626
                                scid.ToUint64(),
×
2627
                                sourceToPub(nMsg.source),
×
2628
                        )
×
2629
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2630

×
2631
                        log.Error(err)
×
2632
                        nMsg.err <- err
×
2633
                        return nil, false
×
2634
                }
×
2635

2636
                // If the proof checks out, then we'll save the proof itself to
2637
                // the database so we can fetch it later when gossiping with
2638
                // other nodes.
2639
                proof = &models.ChannelAuthProof{
3✔
2640
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
3✔
2641
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
3✔
2642
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
3✔
2643
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
3✔
2644
                }
3✔
2645
        }
2646

2647
        // With the proof validated (if necessary), we can now store it within
2648
        // the database for our path finding and syncing needs.
2649
        var featureBuf bytes.Buffer
3✔
2650
        if err := ann.Features.Encode(&featureBuf); err != nil {
3✔
2651
                log.Errorf("unable to encode features: %v", err)
×
2652
                nMsg.err <- err
×
2653
                return nil, false
×
2654
        }
×
2655

2656
        edge := &models.ChannelEdgeInfo{
3✔
2657
                ChannelID:        scid.ToUint64(),
3✔
2658
                ChainHash:        ann.ChainHash,
3✔
2659
                NodeKey1Bytes:    ann.NodeID1,
3✔
2660
                NodeKey2Bytes:    ann.NodeID2,
3✔
2661
                BitcoinKey1Bytes: ann.BitcoinKey1,
3✔
2662
                BitcoinKey2Bytes: ann.BitcoinKey2,
3✔
2663
                AuthProof:        proof,
3✔
2664
                Features:         featureBuf.Bytes(),
3✔
2665
                ExtraOpaqueData:  ann.ExtraOpaqueData,
3✔
2666
        }
3✔
2667

3✔
2668
        // If there were any optional message fields provided, we'll include
3✔
2669
        // them in its serialized disk representation now.
3✔
2670
        var tapscriptRoot fn.Option[chainhash.Hash]
3✔
2671
        if nMsg.optionalMsgFields != nil {
6✔
2672
                if nMsg.optionalMsgFields.capacity != nil {
6✔
2673
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
3✔
2674
                }
3✔
2675
                if nMsg.optionalMsgFields.channelPoint != nil {
6✔
2676
                        cp := *nMsg.optionalMsgFields.channelPoint
3✔
2677
                        edge.ChannelPoint = cp
3✔
2678
                }
3✔
2679

2680
                // Optional tapscript root for custom channels.
2681
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
3✔
2682
        }
2683

2684
        // Before we start validation or add the edge to the database, we obtain
2685
        // the mutex for this channel ID. We do this to ensure no other
2686
        // goroutine has read the database and is now making decisions based on
2687
        // this DB state, before it writes to the DB. It also ensures that we
2688
        // don't perform the expensive validation check on the same channel
2689
        // announcement at the same time.
2690
        d.channelMtx.Lock(scid.ToUint64())
3✔
2691

3✔
2692
        // If AssumeChannelValid is present, then we are unable to perform any
3✔
2693
        // of the expensive checks below, so we'll short-circuit our path
3✔
2694
        // straight to adding the edge to our graph. If the passed
3✔
2695
        // ShortChannelID is an alias, then we'll skip validation as it will
3✔
2696
        // not map to a legitimate tx. This is not a DoS vector as only we can
3✔
2697
        // add an alias ChannelAnnouncement from the gossiper.
3✔
2698
        if !(d.cfg.AssumeChannelValid || d.cfg.IsAlias(scid)) { //nolint:nestif
6✔
2699
                op, capacity, script, err := d.validateFundingTransaction(
3✔
2700
                        ctx, ann, tapscriptRoot,
3✔
2701
                )
3✔
2702
                if err != nil {
3✔
UNCOV
2703
                        defer d.channelMtx.Unlock(scid.ToUint64())
×
UNCOV
2704

×
UNCOV
2705
                        switch {
×
2706
                        case errors.Is(err, ErrNoFundingTransaction),
UNCOV
2707
                                errors.Is(err, ErrInvalidFundingOutput):
×
UNCOV
2708

×
UNCOV
2709
                                key := newRejectCacheKey(
×
UNCOV
2710
                                        scid.ToUint64(),
×
UNCOV
2711
                                        sourceToPub(nMsg.source),
×
UNCOV
2712
                                )
×
UNCOV
2713
                                _, _ = d.recentRejects.Put(
×
UNCOV
2714
                                        key, &cachedReject{},
×
UNCOV
2715
                                )
×
UNCOV
2716

×
UNCOV
2717
                                // Increment the peer's ban score. We check
×
UNCOV
2718
                                // isRemote so we don't actually ban the peer in
×
UNCOV
2719
                                // case of a local bug.
×
UNCOV
2720
                                if nMsg.isRemote {
×
UNCOV
2721
                                        d.banman.incrementBanScore(
×
UNCOV
2722
                                                nMsg.peer.PubKey(),
×
UNCOV
2723
                                        )
×
UNCOV
2724
                                }
×
2725

UNCOV
2726
                        case errors.Is(err, ErrChannelSpent):
×
UNCOV
2727
                                key := newRejectCacheKey(
×
UNCOV
2728
                                        scid.ToUint64(),
×
UNCOV
2729
                                        sourceToPub(nMsg.source),
×
UNCOV
2730
                                )
×
UNCOV
2731
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
UNCOV
2732

×
UNCOV
2733
                                // Since this channel has already been closed,
×
UNCOV
2734
                                // we'll add it to the graph's closed channel
×
UNCOV
2735
                                // index such that we won't attempt to do
×
UNCOV
2736
                                // expensive validation checks on it again.
×
UNCOV
2737
                                // TODO: Populate the ScidCloser by using closed
×
UNCOV
2738
                                // channel notifications.
×
UNCOV
2739
                                dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
×
UNCOV
2740
                                if dbErr != nil {
×
2741
                                        log.Errorf("failed to mark scid(%v) "+
×
2742
                                                "as closed: %v", scid, dbErr)
×
2743

×
2744
                                        nMsg.err <- dbErr
×
2745

×
2746
                                        return nil, false
×
2747
                                }
×
2748

2749
                                // Increment the peer's ban score. We check
2750
                                // isRemote so we don't accidentally ban
2751
                                // ourselves in case of a bug.
UNCOV
2752
                                if nMsg.isRemote {
×
UNCOV
2753
                                        d.banman.incrementBanScore(
×
UNCOV
2754
                                                nMsg.peer.PubKey(),
×
UNCOV
2755
                                        )
×
UNCOV
2756
                                }
×
2757

2758
                        default:
×
2759
                                // Otherwise, this is just a regular rejected
×
2760
                                // edge.
×
2761
                                key := newRejectCacheKey(
×
2762
                                        scid.ToUint64(),
×
2763
                                        sourceToPub(nMsg.source),
×
2764
                                )
×
2765
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2766
                        }
2767

UNCOV
2768
                        if !nMsg.isRemote {
×
2769
                                log.Errorf("failed to add edge for local "+
×
2770
                                        "channel: %v", err)
×
2771
                                nMsg.err <- err
×
2772

×
2773
                                return nil, false
×
2774
                        }
×
2775

UNCOV
2776
                        shouldDc, dcErr := d.ShouldDisconnect(
×
UNCOV
2777
                                nMsg.peer.IdentityKey(),
×
UNCOV
2778
                        )
×
UNCOV
2779
                        if dcErr != nil {
×
2780
                                log.Errorf("failed to check if we should "+
×
2781
                                        "disconnect peer: %v", dcErr)
×
2782
                                nMsg.err <- dcErr
×
2783

×
2784
                                return nil, false
×
2785
                        }
×
2786

UNCOV
2787
                        if shouldDc {
×
UNCOV
2788
                                nMsg.peer.Disconnect(ErrPeerBanned)
×
UNCOV
2789
                        }
×
2790

UNCOV
2791
                        nMsg.err <- err
×
UNCOV
2792

×
UNCOV
2793
                        return nil, false
×
2794
                }
2795

2796
                edge.FundingScript = fn.Some(script)
3✔
2797

3✔
2798
                // TODO(roasbeef): this is a hack, needs to be removed after
3✔
2799
                //  commitment fees are dynamic.
3✔
2800
                edge.Capacity = capacity
3✔
2801
                edge.ChannelPoint = op
3✔
2802
        }
2803

2804
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
3✔
2805

3✔
2806
        // We will add the edge to the channel router. If the nodes present in
3✔
2807
        // this channel are not present in the database, a partial node will be
3✔
2808
        // added to represent each node while we wait for a node announcement.
3✔
2809
        err = d.cfg.Graph.AddEdge(edge, ops...)
3✔
2810
        if err != nil {
6✔
2811
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
3✔
2812
                        scid.ToUint64(), err)
3✔
2813

3✔
2814
                defer d.channelMtx.Unlock(scid.ToUint64())
3✔
2815

3✔
2816
                // If the edge was rejected due to already being known, then it
3✔
2817
                // may be the case that this new message has a fresh channel
3✔
2818
                // proof, so we'll check.
3✔
2819
                if graph.IsError(err, graph.ErrIgnored) {
6✔
2820
                        // Attempt to process the rejected message to see if we
3✔
2821
                        // get any new announcements.
3✔
2822
                        anns, rErr := d.processRejectedEdge(ctx, ann, proof)
3✔
2823
                        if rErr != nil {
3✔
2824
                                key := newRejectCacheKey(
×
2825
                                        scid.ToUint64(),
×
2826
                                        sourceToPub(nMsg.source),
×
2827
                                )
×
2828
                                cr := &cachedReject{}
×
2829
                                _, _ = d.recentRejects.Put(key, cr)
×
2830

×
2831
                                nMsg.err <- rErr
×
2832

×
2833
                                return nil, false
×
2834
                        }
×
2835

2836
                        log.Debugf("Extracted %v announcements from rejected "+
3✔
2837
                                "msgs", len(anns))
3✔
2838

3✔
2839
                        // If while processing this rejected edge, we realized
3✔
2840
                        // there's a set of announcements we could extract,
3✔
2841
                        // then we'll return those directly.
3✔
2842
                        //
3✔
2843
                        // NOTE: since this is an ErrIgnored, we can return
3✔
2844
                        // true here to signal "allow" to its dependants.
3✔
2845
                        nMsg.err <- nil
3✔
2846

3✔
2847
                        return anns, true
3✔
2848
                }
2849

2850
                // Otherwise, this is just a regular rejected edge.
UNCOV
2851
                key := newRejectCacheKey(
×
UNCOV
2852
                        scid.ToUint64(),
×
UNCOV
2853
                        sourceToPub(nMsg.source),
×
UNCOV
2854
                )
×
UNCOV
2855
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
UNCOV
2856

×
UNCOV
2857
                if !nMsg.isRemote {
×
2858
                        log.Errorf("failed to add edge for local channel: %v",
×
2859
                                err)
×
2860
                        nMsg.err <- err
×
2861

×
2862
                        return nil, false
×
2863
                }
×
2864

UNCOV
2865
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
×
UNCOV
2866
                if dcErr != nil {
×
2867
                        log.Errorf("failed to check if we should disconnect "+
×
2868
                                "peer: %v", dcErr)
×
2869
                        nMsg.err <- dcErr
×
2870

×
2871
                        return nil, false
×
2872
                }
×
2873

UNCOV
2874
                if shouldDc {
×
2875
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2876
                }
×
2877

UNCOV
2878
                nMsg.err <- err
×
UNCOV
2879

×
UNCOV
2880
                return nil, false
×
2881
        }
2882

2883
        // If err is nil, release the lock immediately.
2884
        d.channelMtx.Unlock(scid.ToUint64())
3✔
2885

3✔
2886
        log.Debugf("Finish adding edge for short_chan_id: %v", scid.ToUint64())
3✔
2887

3✔
2888
        // If we earlier received any ChannelUpdates for this channel, we can
3✔
2889
        // now process them, as the channel is added to the graph.
3✔
2890
        var channelUpdates []*processedNetworkMsg
3✔
2891

3✔
2892
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
3✔
2893
        if err == nil {
6✔
2894
                // There was actually an entry in the map, so we'll accumulate
3✔
2895
                // it. We don't worry about deletion, since it'll eventually
3✔
2896
                // fall out anyway.
3✔
2897
                chanMsgs := earlyChanUpdates
3✔
2898
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
3✔
2899
        }
3✔
2900

2901
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2902
        // ensure we don't block here, as we can handle only one announcement
2903
        // at a time.
2904
        for _, cu := range channelUpdates {
6✔
2905
                // Skip if already processed.
3✔
2906
                if cu.processed {
5✔
2907
                        continue
2✔
2908
                }
2909

2910
                // Mark the ChannelUpdate as processed. This ensures that a
2911
                // subsequent announcement in the option-scid-alias case does
2912
                // not re-use an old ChannelUpdate.
2913
                cu.processed = true
3✔
2914

3✔
2915
                d.wg.Add(1)
3✔
2916
                go func(updMsg *networkMsg) {
6✔
2917
                        defer d.wg.Done()
3✔
2918

3✔
2919
                        switch msg := updMsg.msg.(type) {
3✔
2920
                        // Reprocess the message, making sure we return an
2921
                        // error to the original caller in case the gossiper
2922
                        // shuts down.
2923
                        case *lnwire.ChannelUpdate1:
3✔
2924
                                log.Debugf("Reprocessing ChannelUpdate for "+
3✔
2925
                                        "shortChanID=%v", scid.ToUint64())
3✔
2926

3✔
2927
                                select {
3✔
2928
                                case d.networkMsgs <- updMsg:
3✔
2929
                                case <-d.quit:
×
2930
                                        updMsg.err <- ErrGossiperShuttingDown
×
2931
                                }
2932

2933
                        // We don't expect any other message type than
2934
                        // ChannelUpdate to be in this cache.
2935
                        default:
×
2936
                                log.Errorf("Unsupported message type found "+
×
2937
                                        "among ChannelUpdates: %T", msg)
×
2938
                        }
2939
                }(cu.msg)
2940
        }
2941

2942
        // Channel announcement was successfully processed and now it might be
2943
        // broadcast to other connected nodes if it was an announcement with
2944
        // proof (remote).
2945
        var announcements []networkMsg
3✔
2946

3✔
2947
        if proof != nil {
6✔
2948
                announcements = append(announcements, networkMsg{
3✔
2949
                        peer:     nMsg.peer,
3✔
2950
                        isRemote: nMsg.isRemote,
3✔
2951
                        source:   nMsg.source,
3✔
2952
                        msg:      ann,
3✔
2953
                })
3✔
2954
        }
3✔
2955

2956
        nMsg.err <- nil
3✔
2957

3✔
2958
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
3✔
2959
                nMsg.peer, scid.ToUint64())
3✔
2960

3✔
2961
        return announcements, true
3✔
2962
}
2963

2964
// handleChanUpdate processes a new channel update.
2965
//
2966
//nolint:funlen
2967
func (d *AuthenticatedGossiper) handleChanUpdate(ctx context.Context,
2968
        nMsg *networkMsg, upd *lnwire.ChannelUpdate1,
2969
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2970

3✔
2971
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
3✔
2972
                nMsg.peer, upd.ShortChannelID.ToUint64())
3✔
2973

3✔
2974
        // We'll ignore any channel updates that target any chain other than
3✔
2975
        // the set of chains we know of.
3✔
2976
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
3✔
2977
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2978
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2979
                log.Errorf(err.Error())
×
2980

×
2981
                key := newRejectCacheKey(
×
2982
                        upd.ShortChannelID.ToUint64(),
×
2983
                        sourceToPub(nMsg.source),
×
2984
                )
×
2985
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2986

×
2987
                nMsg.err <- err
×
2988
                return nil, false
×
2989
        }
×
2990

2991
        blockHeight := upd.ShortChannelID.BlockHeight
3✔
2992
        shortChanID := upd.ShortChannelID.ToUint64()
3✔
2993

3✔
2994
        // If the advertised inclusionary block is beyond our knowledge of the
3✔
2995
        // chain tip, then we'll put the announcement in limbo to be fully
3✔
2996
        // verified once we advance forward in the chain. If the update has an
3✔
2997
        // alias SCID, we'll skip the isPremature check. This is necessary
3✔
2998
        // since aliases start at block height 16_000_000.
3✔
2999
        d.Lock()
3✔
3000
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
3✔
3001
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
3✔
UNCOV
3002

×
UNCOV
3003
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
UNCOV
3004
                        "premature: advertises height %v, only height %v is "+
×
UNCOV
3005
                        "known", shortChanID, blockHeight, d.bestHeight)
×
UNCOV
3006
                d.Unlock()
×
UNCOV
3007
                nMsg.err <- nil
×
UNCOV
3008
                return nil, false
×
UNCOV
3009
        }
×
3010
        d.Unlock()
3✔
3011

3✔
3012
        // Before we perform any of the expensive checks below, we'll check
3✔
3013
        // whether this update is stale or is for a zombie channel in order to
3✔
3014
        // quickly reject it.
3✔
3015
        timestamp := time.Unix(int64(upd.Timestamp), 0)
3✔
3016

3✔
3017
        // Fetch the SCID we should be using to lock the channelMtx and make
3✔
3018
        // graph queries with.
3✔
3019
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
3✔
3020
        if err != nil {
6✔
3021
                // Fallback and set the graphScid to the peer-provided SCID.
3✔
3022
                // This will occur for non-option-scid-alias channels and for
3✔
3023
                // public option-scid-alias channels after 6 confirmations.
3✔
3024
                // Once public option-scid-alias channels have 6 confs, we'll
3✔
3025
                // ignore ChannelUpdates with one of their aliases.
3✔
3026
                graphScid = upd.ShortChannelID
3✔
3027
        }
3✔
3028

3029
        // We make sure to obtain the mutex for this channel ID before we access
3030
        // the database. This ensures the state we read from the database has
3031
        // not changed between this point and when we call UpdateEdge() later.
3032
        d.channelMtx.Lock(graphScid.ToUint64())
3✔
3033
        defer d.channelMtx.Unlock(graphScid.ToUint64())
3✔
3034

3✔
3035
        if d.cfg.Graph.IsStaleEdgePolicy(
3✔
3036
                graphScid, timestamp, upd.ChannelFlags,
3✔
3037
        ) {
6✔
3038

3✔
3039
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
3✔
3040
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
3✔
3041
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
3✔
3042
                )
3✔
3043

3✔
3044
                nMsg.err <- nil
3✔
3045
                return nil, true
3✔
3046
        }
3✔
3047

3048
        // Check that the ChanUpdate is not too far into the future, this could
3049
        // reveal some faulty implementation therefore we log an error.
3050
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
3✔
3051
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
3052
                        "short_chan_id(%v), timestamp too far in the future: "+
×
3053
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
3054
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
3055
                        nMsg.isRemote,
×
3056
                )
×
3057

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

×
3061
                return nil, false
×
3062
        }
×
3063

3064
        // Get the node pub key as far since we don't have it in the channel
3065
        // update announcement message. We'll need this to properly verify the
3066
        // message's signature.
3067
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
3✔
3068
        switch {
3✔
3069
        // No error, break.
3070
        case err == nil:
3✔
3071
                break
3✔
3072

UNCOV
3073
        case errors.Is(err, graphdb.ErrZombieEdge):
×
UNCOV
3074
                err = d.processZombieUpdate(ctx, chanInfo, graphScid, upd)
×
UNCOV
3075
                if err != nil {
×
UNCOV
3076
                        log.Debug(err)
×
UNCOV
3077
                        nMsg.err <- err
×
UNCOV
3078
                        return nil, false
×
UNCOV
3079
                }
×
3080

3081
                // We'll fallthrough to ensure we stash the update until we
3082
                // receive its corresponding ChannelAnnouncement. This is
3083
                // needed to ensure the edge exists in the graph before
3084
                // applying the update.
UNCOV
3085
                fallthrough
×
UNCOV
3086
        case errors.Is(err, graphdb.ErrGraphNotFound):
×
UNCOV
3087
                fallthrough
×
UNCOV
3088
        case errors.Is(err, graphdb.ErrGraphNoEdgesFound):
×
UNCOV
3089
                fallthrough
×
3090
        case errors.Is(err, graphdb.ErrEdgeNotFound):
3✔
3091
                // If the edge corresponding to this ChannelUpdate was not
3✔
3092
                // found in the graph, this might be a channel in the process
3✔
3093
                // of being opened, and we haven't processed our own
3✔
3094
                // ChannelAnnouncement yet, hence it is not not found in the
3✔
3095
                // graph. This usually gets resolved after the channel proofs
3✔
3096
                // are exchanged and the channel is broadcasted to the rest of
3✔
3097
                // the network, but in case this is a private channel this
3✔
3098
                // won't ever happen. This can also happen in the case of a
3✔
3099
                // zombie channel with a fresh update for which we don't have a
3✔
3100
                // ChannelAnnouncement for since we reject them. Because of
3✔
3101
                // this, we temporarily add it to a map, and reprocess it after
3✔
3102
                // our own ChannelAnnouncement has been processed.
3✔
3103
                //
3✔
3104
                // The shortChanID may be an alias, but it is fine to use here
3✔
3105
                // since we don't have an edge in the graph and if the peer is
3✔
3106
                // not buggy, we should be able to use it once the gossiper
3✔
3107
                // receives the local announcement.
3✔
3108
                pMsg := &processedNetworkMsg{msg: nMsg}
3✔
3109

3✔
3110
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
3✔
3111
                switch {
3✔
3112
                // Nothing in the cache yet, we can just directly insert this
3113
                // element.
3114
                case err == cache.ErrElementNotFound:
3✔
3115
                        _, _ = d.prematureChannelUpdates.Put(
3✔
3116
                                shortChanID, &cachedNetworkMsg{
3✔
3117
                                        msgs: []*processedNetworkMsg{pMsg},
3✔
3118
                                })
3✔
3119

3120
                // There's already something in the cache, so we'll combine the
3121
                // set of messages into a single value.
3122
                default:
3✔
3123
                        msgs := earlyMsgs.msgs
3✔
3124
                        msgs = append(msgs, pMsg)
3✔
3125
                        _, _ = d.prematureChannelUpdates.Put(
3✔
3126
                                shortChanID, &cachedNetworkMsg{
3✔
3127
                                        msgs: msgs,
3✔
3128
                                })
3✔
3129
                }
3130

3131
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
3✔
3132
                        "(shortChanID=%v), saving for reprocessing later",
3✔
3133
                        shortChanID)
3✔
3134

3✔
3135
                // NOTE: We don't return anything on the error channel for this
3✔
3136
                // message, as we expect that will be done when this
3✔
3137
                // ChannelUpdate is later reprocessed.
3✔
3138
                return nil, false
3✔
3139

3140
        default:
×
3141
                err := fmt.Errorf("unable to validate channel update "+
×
3142
                        "short_chan_id=%v: %v", shortChanID, err)
×
3143
                log.Error(err)
×
3144
                nMsg.err <- err
×
3145

×
3146
                key := newRejectCacheKey(
×
3147
                        upd.ShortChannelID.ToUint64(),
×
3148
                        sourceToPub(nMsg.source),
×
3149
                )
×
3150
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3151

×
3152
                return nil, false
×
3153
        }
3154

3155
        // The least-significant bit in the flag on the channel update
3156
        // announcement tells us "which" side of the channels directed edge is
3157
        // being updated.
3158
        var (
3✔
3159
                pubKey       *btcec.PublicKey
3✔
3160
                edgeToUpdate *models.ChannelEdgePolicy
3✔
3161
        )
3✔
3162
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
3✔
3163
        switch direction {
3✔
3164
        case 0:
3✔
3165
                pubKey, _ = chanInfo.NodeKey1()
3✔
3166
                edgeToUpdate = e1
3✔
3167
        case 1:
3✔
3168
                pubKey, _ = chanInfo.NodeKey2()
3✔
3169
                edgeToUpdate = e2
3✔
3170
        }
3171

3172
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
3✔
3173
                "edge policy=%v", chanInfo.ChannelID,
3✔
3174
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
3✔
3175

3✔
3176
        // Validate the channel announcement with the expected public key and
3✔
3177
        // channel capacity. In the case of an invalid channel update, we'll
3✔
3178
        // return an error to the caller and exit early.
3✔
3179
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
3✔
3180
        if err != nil {
3✔
UNCOV
3181
                rErr := fmt.Errorf("unable to validate channel update "+
×
UNCOV
3182
                        "announcement for short_chan_id=%v: %v",
×
UNCOV
3183
                        spew.Sdump(upd.ShortChannelID), err)
×
UNCOV
3184

×
UNCOV
3185
                log.Error(rErr)
×
UNCOV
3186
                nMsg.err <- rErr
×
UNCOV
3187
                return nil, false
×
UNCOV
3188
        }
×
3189

3190
        // If we have a previous version of the edge being updated, we'll want
3191
        // to rate limit its updates to prevent spam throughout the network.
3192
        if nMsg.isRemote && edgeToUpdate != nil {
6✔
3193
                // If it's a keep-alive update, we'll only propagate one if
3✔
3194
                // it's been a day since the previous. This follows our own
3✔
3195
                // heuristic of sending keep-alive updates after the same
3✔
3196
                // duration (see retransmitStaleAnns).
3✔
3197
                timeSinceLastUpdate := timestamp.Sub(edgeToUpdate.LastUpdate)
3✔
3198
                if IsKeepAliveUpdate(upd, edgeToUpdate) {
6✔
3199
                        if timeSinceLastUpdate < d.cfg.RebroadcastInterval {
6✔
3200
                                log.Debugf("Ignoring keep alive update not "+
3✔
3201
                                        "within %v period for channel %v",
3✔
3202
                                        d.cfg.RebroadcastInterval, shortChanID)
3✔
3203
                                nMsg.err <- nil
3✔
3204
                                return nil, false
3✔
3205
                        }
3✔
3206
                } else {
3✔
3207
                        // If it's not, we'll allow an update per minute with a
3✔
3208
                        // maximum burst of 10. If we haven't seen an update
3✔
3209
                        // for this channel before, we'll need to initialize a
3✔
3210
                        // rate limiter for each direction.
3✔
3211
                        //
3✔
3212
                        // Since the edge exists in the graph, we'll create a
3✔
3213
                        // rate limiter for chanInfo.ChannelID rather then the
3✔
3214
                        // SCID the peer sent. This is because there may be
3✔
3215
                        // multiple aliases for a channel and we may otherwise
3✔
3216
                        // rate-limit only a single alias of the channel,
3✔
3217
                        // instead of the whole channel.
3✔
3218
                        baseScid := chanInfo.ChannelID
3✔
3219
                        d.Lock()
3✔
3220
                        rls, ok := d.chanUpdateRateLimiter[baseScid]
3✔
3221
                        if !ok {
6✔
3222
                                r := rate.Every(d.cfg.ChannelUpdateInterval)
3✔
3223
                                b := d.cfg.MaxChannelUpdateBurst
3✔
3224
                                rls = [2]*rate.Limiter{
3✔
3225
                                        rate.NewLimiter(r, b),
3✔
3226
                                        rate.NewLimiter(r, b),
3✔
3227
                                }
3✔
3228
                                d.chanUpdateRateLimiter[baseScid] = rls
3✔
3229
                        }
3✔
3230
                        d.Unlock()
3✔
3231

3✔
3232
                        if !rls[direction].Allow() {
6✔
3233
                                log.Debugf("Rate limiting update for channel "+
3✔
3234
                                        "%v from direction %x", shortChanID,
3✔
3235
                                        pubKey.SerializeCompressed())
3✔
3236
                                nMsg.err <- nil
3✔
3237
                                return nil, false
3✔
3238
                        }
3✔
3239
                }
3240
        }
3241

3242
        // We'll use chanInfo.ChannelID rather than the peer-supplied
3243
        // ShortChannelID in the ChannelUpdate to avoid the router having to
3244
        // lookup the stored SCID. If we're sending the update, we'll always
3245
        // use the SCID stored in the database rather than a potentially
3246
        // different alias. This might mean that SigBytes is incorrect as it
3247
        // signs a different SCID than the database SCID, but since there will
3248
        // only be a difference if AuthProof == nil, this is fine.
3249
        update := &models.ChannelEdgePolicy{
3✔
3250
                SigBytes:                  upd.Signature.ToSignatureBytes(),
3✔
3251
                ChannelID:                 chanInfo.ChannelID,
3✔
3252
                LastUpdate:                timestamp,
3✔
3253
                MessageFlags:              upd.MessageFlags,
3✔
3254
                ChannelFlags:              upd.ChannelFlags,
3✔
3255
                TimeLockDelta:             upd.TimeLockDelta,
3✔
3256
                MinHTLC:                   upd.HtlcMinimumMsat,
3✔
3257
                MaxHTLC:                   upd.HtlcMaximumMsat,
3✔
3258
                FeeBaseMSat:               lnwire.MilliSatoshi(upd.BaseFee),
3✔
3259
                FeeProportionalMillionths: lnwire.MilliSatoshi(upd.FeeRate),
3✔
3260
                ExtraOpaqueData:           upd.ExtraOpaqueData,
3✔
3261
        }
3✔
3262

3✔
3263
        if err := d.cfg.Graph.UpdateEdge(update, ops...); err != nil {
3✔
3264
                if graph.IsError(
×
3265
                        err, graph.ErrOutdated,
×
3266
                        graph.ErrIgnored,
×
3267
                ) {
×
3268

×
3269
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
×
3270
                                shortChanID, err)
×
3271
                } else {
×
3272
                        // Since we know the stored SCID in the graph, we'll
×
3273
                        // cache that SCID.
×
3274
                        key := newRejectCacheKey(
×
3275
                                chanInfo.ChannelID,
×
3276
                                sourceToPub(nMsg.source),
×
3277
                        )
×
3278
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3279

×
3280
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3281
                                shortChanID, err)
×
3282
                }
×
3283

3284
                nMsg.err <- err
×
3285
                return nil, false
×
3286
        }
3287

3288
        // If this is a local ChannelUpdate without an AuthProof, it means it
3289
        // is an update to a channel that is not (yet) supposed to be announced
3290
        // to the greater network. However, our channel counter party will need
3291
        // to be given the update, so we'll try sending the update directly to
3292
        // the remote peer.
3293
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
6✔
3294
                if nMsg.optionalMsgFields != nil {
6✔
3295
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
3✔
3296
                        if remoteAlias != nil {
6✔
3297
                                // The remoteAlias field was specified, meaning
3✔
3298
                                // that we should replace the SCID in the
3✔
3299
                                // update with the remote's alias. We'll also
3✔
3300
                                // need to re-sign the channel update. This is
3✔
3301
                                // required for option-scid-alias feature-bit
3✔
3302
                                // negotiated channels.
3✔
3303
                                upd.ShortChannelID = *remoteAlias
3✔
3304

3✔
3305
                                sig, err := d.cfg.SignAliasUpdate(upd)
3✔
3306
                                if err != nil {
3✔
3307
                                        log.Error(err)
×
3308
                                        nMsg.err <- err
×
3309
                                        return nil, false
×
3310
                                }
×
3311

3312
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
3313
                                if err != nil {
3✔
3314
                                        log.Error(err)
×
3315
                                        nMsg.err <- err
×
3316
                                        return nil, false
×
3317
                                }
×
3318

3319
                                upd.Signature = lnSig
3✔
3320
                        }
3321
                }
3322

3323
                // Get our peer's public key.
3324
                remotePubKey := remotePubFromChanInfo(
3✔
3325
                        chanInfo, upd.ChannelFlags,
3✔
3326
                )
3✔
3327

3✔
3328
                log.Debugf("The message %v has no AuthProof, sending the "+
3✔
3329
                        "update to remote peer %x", upd.MsgType(), remotePubKey)
3✔
3330

3✔
3331
                // Now we'll attempt to send the channel update message
3✔
3332
                // reliably to the remote peer in the background, so that we
3✔
3333
                // don't block if the peer happens to be offline at the moment.
3✔
3334
                err := d.reliableSender.sendMessage(ctx, upd, remotePubKey)
3✔
3335
                if err != nil {
3✔
3336
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3337
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3338
                                upd.ShortChannelID, remotePubKey, err)
×
3339
                        nMsg.err <- err
×
3340
                        return nil, false
×
3341
                }
×
3342
        }
3343

3344
        // Channel update announcement was successfully processed and now it
3345
        // can be broadcast to the rest of the network. However, we'll only
3346
        // broadcast the channel update announcement if it has an attached
3347
        // authentication proof. We also won't broadcast the update if it
3348
        // contains an alias because the network would reject this.
3349
        var announcements []networkMsg
3✔
3350
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
6✔
3351
                announcements = append(announcements, networkMsg{
3✔
3352
                        peer:     nMsg.peer,
3✔
3353
                        source:   nMsg.source,
3✔
3354
                        isRemote: nMsg.isRemote,
3✔
3355
                        msg:      upd,
3✔
3356
                })
3✔
3357
        }
3✔
3358

3359
        nMsg.err <- nil
3✔
3360

3✔
3361
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
3✔
3362
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
3✔
3363
                timestamp)
3✔
3364
        return announcements, true
3✔
3365
}
3366

3367
// handleAnnSig processes a new announcement signatures message.
3368
//
3369
//nolint:funlen
3370
func (d *AuthenticatedGossiper) handleAnnSig(ctx context.Context,
3371
        nMsg *networkMsg, ann *lnwire.AnnounceSignatures1) ([]networkMsg,
3372
        bool) {
3✔
3373

3✔
3374
        needBlockHeight := ann.ShortChannelID.BlockHeight +
3✔
3375
                d.cfg.ProofMatureDelta
3✔
3376
        shortChanID := ann.ShortChannelID.ToUint64()
3✔
3377

3✔
3378
        prefix := "local"
3✔
3379
        if nMsg.isRemote {
6✔
3380
                prefix = "remote"
3✔
3381
        }
3✔
3382

3383
        log.Infof("Received new %v announcement signature for %v", prefix,
3✔
3384
                ann.ShortChannelID)
3✔
3385

3✔
3386
        // By the specification, channel announcement proofs should be sent
3✔
3387
        // after some number of confirmations after channel was registered in
3✔
3388
        // bitcoin blockchain. Therefore, we check if the proof is mature.
3✔
3389
        d.Lock()
3✔
3390
        premature := d.isPremature(
3✔
3391
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
3✔
3392
        )
3✔
3393
        if premature {
6✔
3394
                log.Warnf("Premature proof announcement, current block height"+
3✔
3395
                        "lower than needed: %v < %v", d.bestHeight,
3✔
3396
                        needBlockHeight)
3✔
3397
                d.Unlock()
3✔
3398
                nMsg.err <- nil
3✔
3399
                return nil, false
3✔
3400
        }
3✔
3401
        d.Unlock()
3✔
3402

3✔
3403
        // Ensure that we know of a channel with the target channel ID before
3✔
3404
        // proceeding further.
3✔
3405
        //
3✔
3406
        // We must acquire the mutex for this channel ID before getting the
3✔
3407
        // channel from the database, to ensure what we read does not change
3✔
3408
        // before we call AddProof() later.
3✔
3409
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
3✔
3410
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
3✔
3411

3✔
3412
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
3413
                ann.ShortChannelID,
3✔
3414
        )
3✔
3415
        if err != nil {
6✔
3416
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
3✔
3417
                if err != nil {
6✔
3418
                        err := fmt.Errorf("unable to store the proof for "+
3✔
3419
                                "short_chan_id=%v: %v", shortChanID, err)
3✔
3420
                        log.Error(err)
3✔
3421
                        nMsg.err <- err
3✔
3422

3✔
3423
                        return nil, false
3✔
3424
                }
3✔
3425

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

3436
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
3✔
3437
                        ", adding to waiting batch", prefix, shortChanID)
3✔
3438
                nMsg.err <- nil
3✔
3439
                return nil, false
3✔
3440
        }
3441

3442
        nodeID := nMsg.source.SerializeCompressed()
3✔
3443
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
3✔
3444
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
3✔
3445

3✔
3446
        // Ensure that channel that was retrieved belongs to the peer which
3✔
3447
        // sent the proof announcement.
3✔
3448
        if !(isFirstNode || isSecondNode) {
3✔
3449
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3450
                        "to the peer which sent the proof, short_chan_id=%v",
×
3451
                        shortChanID)
×
3452
                log.Error(err)
×
3453
                nMsg.err <- err
×
3454
                return nil, false
×
3455
        }
×
3456

3457
        // If proof was sent by a local sub-system, then we'll send the
3458
        // announcement signature to the remote node so they can also
3459
        // reconstruct the full channel announcement.
3460
        if !nMsg.isRemote {
6✔
3461
                var remotePubKey [33]byte
3✔
3462
                if isFirstNode {
6✔
3463
                        remotePubKey = chanInfo.NodeKey2Bytes
3✔
3464
                } else {
6✔
3465
                        remotePubKey = chanInfo.NodeKey1Bytes
3✔
3466
                }
3✔
3467

3468
                // Since the remote peer might not be online we'll call a
3469
                // method that will attempt to deliver the proof when it comes
3470
                // online.
3471
                err := d.reliableSender.sendMessage(ctx, ann, remotePubKey)
3✔
3472
                if err != nil {
3✔
3473
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3474
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3475
                                ann.ShortChannelID, remotePubKey, err)
×
3476
                        nMsg.err <- err
×
3477
                        return nil, false
×
3478
                }
×
3479
        }
3480

3481
        // Check if we already have the full proof for this channel.
3482
        if chanInfo.AuthProof != nil {
6✔
3483
                // If we already have the fully assembled proof, then the peer
3✔
3484
                // sending us their proof has probably not received our local
3✔
3485
                // proof yet. So be kind and send them the full proof.
3✔
3486
                if nMsg.isRemote {
6✔
3487
                        peerID := nMsg.source.SerializeCompressed()
3✔
3488
                        log.Debugf("Got AnnounceSignatures for channel with " +
3✔
3489
                                "full proof.")
3✔
3490

3✔
3491
                        d.wg.Add(1)
3✔
3492
                        go func() {
6✔
3493
                                defer d.wg.Done()
3✔
3494

3✔
3495
                                log.Debugf("Received half proof for channel "+
3✔
3496
                                        "%v with existing full proof. Sending"+
3✔
3497
                                        " full proof to peer=%x",
3✔
3498
                                        ann.ChannelID, peerID)
3✔
3499

3✔
3500
                                ca, _, _, err := netann.CreateChanAnnouncement(
3✔
3501
                                        chanInfo.AuthProof, chanInfo, e1, e2,
3✔
3502
                                )
3✔
3503
                                if err != nil {
3✔
3504
                                        log.Errorf("unable to gen ann: %v",
×
3505
                                                err)
×
3506
                                        return
×
3507
                                }
×
3508

3509
                                err = nMsg.peer.SendMessage(false, ca)
3✔
3510
                                if err != nil {
3✔
3511
                                        log.Errorf("Failed sending full proof"+
×
3512
                                                " to peer=%x: %v", peerID, err)
×
3513
                                        return
×
3514
                                }
×
3515

3516
                                log.Debugf("Full proof sent to peer=%x for "+
3✔
3517
                                        "chanID=%v", peerID, ann.ChannelID)
3✔
3518
                        }()
3519
                }
3520

3521
                log.Debugf("Already have proof for channel with chanID=%v",
3✔
3522
                        ann.ChannelID)
3✔
3523
                nMsg.err <- nil
3✔
3524
                return nil, true
3✔
3525
        }
3526

3527
        // Check that we received the opposite proof. If so, then we're now
3528
        // able to construct the full proof, and create the channel
3529
        // announcement. If we didn't receive the opposite half of the proof
3530
        // then we should store this one, and wait for the opposite to be
3531
        // received.
3532
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
3✔
3533
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
3✔
3534
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
3✔
3535
                err := fmt.Errorf("unable to get the opposite proof for "+
×
3536
                        "short_chan_id=%v: %v", shortChanID, err)
×
3537
                log.Error(err)
×
3538
                nMsg.err <- err
×
3539
                return nil, false
×
3540
        }
×
3541

3542
        if err == channeldb.ErrWaitingProofNotFound {
6✔
3543
                err := d.cfg.WaitingProofStore.Add(proof)
3✔
3544
                if err != nil {
3✔
3545
                        err := fmt.Errorf("unable to store the proof for "+
×
3546
                                "short_chan_id=%v: %v", shortChanID, err)
×
3547
                        log.Error(err)
×
3548
                        nMsg.err <- err
×
3549
                        return nil, false
×
3550
                }
×
3551

3552
                log.Infof("1/2 of channel ann proof received for "+
3✔
3553
                        "short_chan_id=%v, waiting for other half",
3✔
3554
                        shortChanID)
3✔
3555

3✔
3556
                nMsg.err <- nil
3✔
3557
                return nil, false
3✔
3558
        }
3559

3560
        // We now have both halves of the channel announcement proof, then
3561
        // we'll reconstruct the initial announcement so we can validate it
3562
        // shortly below.
3563
        var dbProof models.ChannelAuthProof
3✔
3564
        if isFirstNode {
6✔
3565
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
3✔
3566
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
3✔
3567
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
3✔
3568
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
3✔
3569
        } else {
6✔
3570
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
3✔
3571
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
3✔
3572
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
3✔
3573
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
3✔
3574
        }
3✔
3575

3576
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
3✔
3577
                &dbProof, chanInfo, e1, e2,
3✔
3578
        )
3✔
3579
        if err != nil {
3✔
3580
                log.Error(err)
×
3581
                nMsg.err <- err
×
3582
                return nil, false
×
3583
        }
×
3584

3585
        // With all the necessary components assembled validate the full
3586
        // channel announcement proof.
3587
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
3✔
3588
        if err != nil {
3✔
3589
                err := fmt.Errorf("channel announcement proof for "+
×
3590
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3591

×
3592
                log.Error(err)
×
3593
                nMsg.err <- err
×
3594
                return nil, false
×
3595
        }
×
3596

3597
        // If the channel was returned by the router it means that existence of
3598
        // funding point and inclusion of nodes bitcoin keys in it already
3599
        // checked by the router. In this stage we should check that node keys
3600
        // attest to the bitcoin keys by validating the signatures of
3601
        // announcement. If proof is valid then we'll populate the channel edge
3602
        // with it, so we can announce it on peer connect.
3603
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
3✔
3604
        if err != nil {
3✔
3605
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
3606
                        " %v", ann.ChannelID, err)
×
3607
                log.Error(err)
×
3608
                nMsg.err <- err
×
3609
                return nil, false
×
3610
        }
×
3611

3612
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
3✔
3613
        if err != nil {
3✔
3614
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3615
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3616
                log.Error(err)
×
3617
                nMsg.err <- err
×
3618
                return nil, false
×
3619
        }
×
3620

3621
        // Proof was successfully created and now can announce the channel to
3622
        // the remain network.
3623
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
3✔
3624
                ", adding to next ann batch", shortChanID)
3✔
3625

3✔
3626
        // Assemble the necessary announcements to add to the next broadcasting
3✔
3627
        // batch.
3✔
3628
        var announcements []networkMsg
3✔
3629
        announcements = append(announcements, networkMsg{
3✔
3630
                peer:   nMsg.peer,
3✔
3631
                source: nMsg.source,
3✔
3632
                msg:    chanAnn,
3✔
3633
        })
3✔
3634
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
6✔
3635
                announcements = append(announcements, networkMsg{
3✔
3636
                        peer:   nMsg.peer,
3✔
3637
                        source: src,
3✔
3638
                        msg:    e1Ann,
3✔
3639
                })
3✔
3640
        }
3✔
3641
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
6✔
3642
                announcements = append(announcements, networkMsg{
3✔
3643
                        peer:   nMsg.peer,
3✔
3644
                        source: src,
3✔
3645
                        msg:    e2Ann,
3✔
3646
                })
3✔
3647
        }
3✔
3648

3649
        // We'll also send along the node announcements for each channel
3650
        // participant if we know of them. To ensure our node announcement
3651
        // propagates to our channel counterparty, we'll set the source for
3652
        // each announcement to the node it belongs to, otherwise we won't send
3653
        // it since the source gets skipped. This isn't necessary for channel
3654
        // updates and announcement signatures since we send those directly to
3655
        // our channel counterparty through the gossiper's reliable sender.
3656
        node1Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey1Bytes)
3✔
3657
        if err != nil {
6✔
3658
                log.Debugf("Unable to fetch node announcement for %x: %v",
3✔
3659
                        chanInfo.NodeKey1Bytes, err)
3✔
3660
        } else {
6✔
3661
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
6✔
3662
                        announcements = append(announcements, networkMsg{
3✔
3663
                                peer:   nMsg.peer,
3✔
3664
                                source: nodeKey1,
3✔
3665
                                msg:    node1Ann,
3✔
3666
                        })
3✔
3667
                }
3✔
3668
        }
3669

3670
        node2Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey2Bytes)
3✔
3671
        if err != nil {
6✔
3672
                log.Debugf("Unable to fetch node announcement for %x: %v",
3✔
3673
                        chanInfo.NodeKey2Bytes, err)
3✔
3674
        } else {
6✔
3675
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
6✔
3676
                        announcements = append(announcements, networkMsg{
3✔
3677
                                peer:   nMsg.peer,
3✔
3678
                                source: nodeKey2,
3✔
3679
                                msg:    node2Ann,
3✔
3680
                        })
3✔
3681
                }
3✔
3682
        }
3683

3684
        nMsg.err <- nil
3✔
3685
        return announcements, true
3✔
3686
}
3687

3688
// isBanned returns true if the peer identified by pubkey is banned for sending
3689
// invalid channel announcements.
3690
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
3✔
3691
        return d.banman.isBanned(pubkey)
3✔
3692
}
3✔
3693

3694
// ShouldDisconnect returns true if we should disconnect the peer identified by
3695
// pubkey.
3696
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3697
        bool, error) {
3✔
3698

3✔
3699
        pubkeySer := pubkey.SerializeCompressed()
3✔
3700

3✔
3701
        var pubkeyBytes [33]byte
3✔
3702
        copy(pubkeyBytes[:], pubkeySer)
3✔
3703

3✔
3704
        // If the public key is banned, check whether or not this is a channel
3✔
3705
        // peer.
3✔
3706
        if d.isBanned(pubkeyBytes) {
3✔
UNCOV
3707
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
×
UNCOV
3708
                if err != nil {
×
3709
                        return false, err
×
3710
                }
×
3711

3712
                // We should only disconnect non-channel peers.
UNCOV
3713
                if !isChanPeer {
×
UNCOV
3714
                        return true, nil
×
UNCOV
3715
                }
×
3716
        }
3717

3718
        return false, nil
3✔
3719
}
3720

3721
// validateFundingTransaction fetches the channel announcements claimed funding
3722
// transaction from chain to ensure that it exists, is not spent and matches
3723
// the channel announcement proof. The transaction's outpoint and value are
3724
// returned if we can glean them from the work done in this method.
3725
func (d *AuthenticatedGossiper) validateFundingTransaction(_ context.Context,
3726
        ann *lnwire.ChannelAnnouncement1,
3727
        tapscriptRoot fn.Option[chainhash.Hash]) (wire.OutPoint, btcutil.Amount,
3728
        []byte, error) {
3✔
3729

3✔
3730
        scid := ann.ShortChannelID
3✔
3731

3✔
3732
        // Before we can add the channel to the channel graph, we need to obtain
3✔
3733
        // the full funding outpoint that's encoded within the channel ID.
3✔
3734
        fundingTx, err := lnwallet.FetchFundingTxWrapper(
3✔
3735
                d.cfg.ChainIO, &scid, d.quit,
3✔
3736
        )
3✔
3737
        if err != nil {
3✔
UNCOV
3738
                //nolint:ll
×
UNCOV
3739
                //
×
UNCOV
3740
                // In order to ensure we don't erroneously mark a channel as a
×
UNCOV
3741
                // zombie due to an RPC failure, we'll attempt to string match
×
UNCOV
3742
                // for the relevant errors.
×
UNCOV
3743
                //
×
UNCOV
3744
                // * btcd:
×
UNCOV
3745
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
×
UNCOV
3746
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
×
UNCOV
3747
                // * bitcoind:
×
UNCOV
3748
                //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
×
UNCOV
3749
                //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
×
UNCOV
3750
                switch {
×
UNCOV
3751
                case strings.Contains(err.Error(), "not found"):
×
UNCOV
3752
                        fallthrough
×
3753

UNCOV
3754
                case strings.Contains(err.Error(), "out of range"):
×
UNCOV
3755
                        // If the funding transaction isn't found at all, then
×
UNCOV
3756
                        // we'll mark the edge itself as a zombie so we don't
×
UNCOV
3757
                        // continue to request it. We use the "zero key" for
×
UNCOV
3758
                        // both node pubkeys so this edge can't be resurrected.
×
UNCOV
3759
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
×
UNCOV
3760
                        if zErr != nil {
×
3761
                                return wire.OutPoint{}, 0, nil, zErr
×
3762
                        }
×
3763

3764
                default:
×
3765
                }
3766

UNCOV
3767
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
×
UNCOV
3768
                        ErrNoFundingTransaction, err)
×
3769
        }
3770

3771
        // Recreate witness output to be sure that declared in channel edge
3772
        // bitcoin keys and channel value corresponds to the reality.
3773
        fundingPkScript, err := makeFundingScript(
3✔
3774
                ann.BitcoinKey1[:], ann.BitcoinKey2[:], ann.Features,
3✔
3775
                tapscriptRoot,
3✔
3776
        )
3✔
3777
        if err != nil {
3✔
3778
                return wire.OutPoint{}, 0, nil, err
×
3779
        }
×
3780

3781
        // Next we'll validate that this channel is actually well formed. If
3782
        // this check fails, then this channel either doesn't exist, or isn't
3783
        // the one that was meant to be created according to the passed channel
3784
        // proofs.
3785
        fundingPoint, err := chanvalidate.Validate(
3✔
3786
                &chanvalidate.Context{
3✔
3787
                        Locator: &chanvalidate.ShortChanIDChanLocator{
3✔
3788
                                ID: scid,
3✔
3789
                        },
3✔
3790
                        MultiSigPkScript: fundingPkScript,
3✔
3791
                        FundingTx:        fundingTx,
3✔
3792
                },
3✔
3793
        )
3✔
3794
        if err != nil {
3✔
UNCOV
3795
                // Mark the edge as a zombie so we won't try to re-validate it
×
UNCOV
3796
                // on start up.
×
UNCOV
3797
                zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
×
UNCOV
3798
                if zErr != nil {
×
3799
                        return wire.OutPoint{}, 0, nil, zErr
×
3800
                }
×
3801

UNCOV
3802
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
×
UNCOV
3803
                        ErrInvalidFundingOutput, err)
×
3804
        }
3805

3806
        // Now that we have the funding outpoint of the channel, ensure
3807
        // that it hasn't yet been spent. If so, then this channel has
3808
        // been closed so we'll ignore it.
3809
        chanUtxo, err := d.cfg.ChainIO.GetUtxo(
3✔
3810
                fundingPoint, fundingPkScript, scid.BlockHeight, d.quit,
3✔
3811
        )
3✔
3812
        if err != nil {
3✔
UNCOV
3813
                if errors.Is(err, btcwallet.ErrOutputSpent) {
×
UNCOV
3814
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
×
UNCOV
3815
                        if zErr != nil {
×
3816
                                return wire.OutPoint{}, 0, nil, zErr
×
3817
                        }
×
3818
                }
3819

UNCOV
3820
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: unable to "+
×
UNCOV
3821
                        "fetch utxo for chan_id=%v, chan_point=%v: %w",
×
UNCOV
3822
                        ErrChannelSpent, scid.ToUint64(), fundingPoint, err)
×
3823
        }
3824

3825
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
3✔
3826
                nil
3✔
3827
}
3828

3829
// makeFundingScript is used to make the funding script for both segwit v0 and
3830
// segwit v1 (taproot) channels.
3831
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3832
        features *lnwire.RawFeatureVector,
3833
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
3✔
3834

3✔
3835
        legacyFundingScript := func() ([]byte, error) {
6✔
3836
                witnessScript, err := input.GenMultiSigScript(
3✔
3837
                        bitcoinKey1, bitcoinKey2,
3✔
3838
                )
3✔
3839
                if err != nil {
3✔
3840
                        return nil, err
×
3841
                }
×
3842
                pkScript, err := input.WitnessScriptHash(witnessScript)
3✔
3843
                if err != nil {
3✔
3844
                        return nil, err
×
3845
                }
×
3846

3847
                return pkScript, nil
3✔
3848
        }
3849

3850
        if features.IsEmpty() {
6✔
3851
                return legacyFundingScript()
3✔
3852
        }
3✔
3853

3854
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
3✔
3855
        if chanFeatureBits.HasFeature(
3✔
3856
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
3857
        ) {
6✔
3858

3✔
3859
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
3860
                if err != nil {
3✔
3861
                        return nil, err
×
3862
                }
×
3863
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
3864
                if err != nil {
3✔
3865
                        return nil, err
×
3866
                }
×
3867

3868
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
3869
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
3870
                )
3✔
3871
                if err != nil {
3✔
3872
                        return nil, err
×
3873
                }
×
3874

3875
                // TODO(roasbeef): add tapscript root to gossip v1.5
3876

3877
                return fundingScript, nil
3✔
3878
        }
3879

3880
        return legacyFundingScript()
×
3881
}
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