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

lightningnetwork / lnd / 17459550471

04 Sep 2025 09:29AM UTC coverage: 66.646% (+0.003%) from 66.643%
17459550471

Pull #10189

github

web-flow
Merge 0b7074c3a into d08afa3ea
Pull Request #10189: bugfix error matching sweeper

13 of 18 new or added lines in 4 files covered. (72.22%)

74 existing lines in 24 files now uncovered.

136098 of 204211 relevant lines covered (66.65%)

21413.37 hits per line

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

78.97
/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) {
50✔
121
        for _, optionalMsgField := range optionalMsgFields {
58✔
122
                optionalMsgField(f)
8✔
123
        }
8✔
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 {
30✔
134
        return func(f *optionalMsgFields) {
34✔
135
                f.capacity = &capacity
4✔
136
        }
4✔
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 {
33✔
142
        return func(f *optionalMsgFields) {
40✔
143
                f.channelPoint = &op
7✔
144
        }
7✔
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 {
29✔
150
        return func(f *optionalMsgFields) {
32✔
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 {
29✔
162
        return func(f *optionalMsgFields) {
32✔
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
        // FilterConcurrency is the maximum number of concurrent gossip filter
404
        // applications that can be processed.
405
        FilterConcurrency int
406

407
        // BanThreshold is the score used to decide whether a given peer is
408
        // banned or not.
409
        BanThreshold uint64
410

411
        // PeerMsgRateBytes is the rate limit for the number of bytes per second
412
        // that we'll allocate to outbound gossip messages for a single peer.
413
        PeerMsgRateBytes uint64
414
}
415

416
// processedNetworkMsg is a wrapper around networkMsg and a boolean. It is
417
// used to let the caller of the lru.Cache know if a message has already been
418
// processed or not.
419
type processedNetworkMsg struct {
420
        processed bool
421
        msg       *networkMsg
422
}
423

424
// cachedNetworkMsg is a wrapper around a network message that can be used with
425
// *lru.Cache.
426
//
427
// NOTE: This struct is not thread safe which means you need to assure no
428
// concurrent read write access to it and all its contents which are pointers
429
// as well.
430
type cachedNetworkMsg struct {
431
        msgs []*processedNetworkMsg
432
}
433

434
// Size returns the "size" of an entry. We return the number of items as we
435
// just want to limit the total amount of entries rather than do accurate size
436
// accounting.
437
func (c *cachedNetworkMsg) Size() (uint64, error) {
5✔
438
        return uint64(len(c.msgs)), nil
5✔
439
}
5✔
440

441
// rejectCacheKey is the cache key that we'll use to track announcements we've
442
// recently rejected.
443
type rejectCacheKey struct {
444
        pubkey [33]byte
445
        chanID uint64
446
}
447

448
// newRejectCacheKey returns a new cache key for the reject cache.
449
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
475✔
450
        k := rejectCacheKey{
475✔
451
                chanID: cid,
475✔
452
                pubkey: pub,
475✔
453
        }
475✔
454

475✔
455
        return k
475✔
456
}
475✔
457

458
// sourceToPub returns a serialized-compressed public key for use in the reject
459
// cache.
460
func sourceToPub(pk *btcec.PublicKey) [33]byte {
489✔
461
        var pub [33]byte
489✔
462
        copy(pub[:], pk.SerializeCompressed())
489✔
463
        return pub
489✔
464
}
489✔
465

466
// cachedReject is the empty value used to track the value for rejects.
467
type cachedReject struct {
468
}
469

470
// Size returns the "size" of an entry. We return 1 as we just want to limit
471
// the total size.
472
func (c *cachedReject) Size() (uint64, error) {
206✔
473
        return 1, nil
206✔
474
}
206✔
475

476
// AuthenticatedGossiper is a subsystem which is responsible for receiving
477
// announcements, validating them and applying the changes to router, syncing
478
// lightning network with newly connected nodes, broadcasting announcements
479
// after validation, negotiating the channel announcement proofs exchange and
480
// handling the premature announcements. All outgoing announcements are
481
// expected to be properly signed as dictated in BOLT#7, additionally, all
482
// incoming message are expected to be well formed and signed. Invalid messages
483
// will be rejected by this struct.
484
type AuthenticatedGossiper struct {
485
        // Parameters which are needed to properly handle the start and stop of
486
        // the service.
487
        started sync.Once
488
        stopped sync.Once
489

490
        // bestHeight is the height of the block at the tip of the main chain
491
        // as we know it. Accesses *MUST* be done with the gossiper's lock
492
        // held.
493
        bestHeight uint32
494

495
        // cfg is a copy of the configuration struct that the gossiper service
496
        // was initialized with.
497
        cfg *Config
498

499
        // blockEpochs encapsulates a stream of block epochs that are sent at
500
        // every new block height.
501
        blockEpochs *chainntnfs.BlockEpochEvent
502

503
        // prematureChannelUpdates is a map of ChannelUpdates we have received
504
        // that wasn't associated with any channel we know about.  We store
505
        // them temporarily, such that we can reprocess them when a
506
        // ChannelAnnouncement for the channel is received.
507
        prematureChannelUpdates *lru.Cache[uint64, *cachedNetworkMsg]
508

509
        // banman tracks our peer's ban status.
510
        banman *banman
511

512
        // networkMsgs is a channel that carries new network broadcasted
513
        // message from outside the gossiper service to be processed by the
514
        // networkHandler.
515
        networkMsgs chan *networkMsg
516

517
        // futureMsgs is a list of premature network messages that have a block
518
        // height specified in the future. We will save them and resend it to
519
        // the chan networkMsgs once the block height has reached. The cached
520
        // map format is,
521
        //   {msgID1: msg1, msgID2: msg2, ...}
522
        futureMsgs *futureMsgCache
523

524
        // chanPolicyUpdates is a channel that requests to update the
525
        // forwarding policy of a set of channels is sent over.
526
        chanPolicyUpdates chan *chanPolicyUpdateRequest
527

528
        // selfKey is the identity public key of the backing Lightning node.
529
        selfKey *btcec.PublicKey
530

531
        // selfKeyLoc is the locator for the identity public key of the backing
532
        // Lightning node.
533
        selfKeyLoc keychain.KeyLocator
534

535
        // channelMtx is used to restrict the database access to one
536
        // goroutine per channel ID. This is done to ensure that when
537
        // the gossiper is handling an announcement, the db state stays
538
        // consistent between when the DB is first read until it's written.
539
        channelMtx *multimutex.Mutex[uint64]
540

541
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
542

543
        // syncMgr is a subsystem responsible for managing the gossip syncers
544
        // for peers currently connected. When a new peer is connected, the
545
        // manager will create its accompanying gossip syncer and determine
546
        // whether it should have an activeSync or passiveSync sync type based
547
        // on how many other gossip syncers are currently active. Any activeSync
548
        // gossip syncers are started in a round-robin manner to ensure we're
549
        // not syncing with multiple peers at the same time.
550
        syncMgr *SyncManager
551

552
        // reliableSender is a subsystem responsible for handling reliable
553
        // message send requests to peers. This should only be used for channels
554
        // that are unadvertised at the time of handling the message since if it
555
        // is advertised, then peers should be able to get the message from the
556
        // network.
557
        reliableSender *reliableSender
558

559
        // chanUpdateRateLimiter contains rate limiters for each direction of
560
        // a channel update we've processed. We'll use these to determine
561
        // whether we should accept a new update for a specific channel and
562
        // direction.
563
        //
564
        // NOTE: This map must be synchronized with the main
565
        // AuthenticatedGossiper lock.
566
        chanUpdateRateLimiter map[uint64][2]*rate.Limiter
567

568
        // vb is used to enforce job dependency ordering of gossip messages.
569
        vb *ValidationBarrier
570

571
        sync.Mutex
572

573
        cancel fn.Option[context.CancelFunc]
574
        quit   chan struct{}
575
        wg     sync.WaitGroup
576
}
577

578
// New creates a new AuthenticatedGossiper instance, initialized with the
579
// passed configuration parameters.
580
func New(cfg Config, selfKeyDesc *keychain.KeyDescriptor) *AuthenticatedGossiper {
33✔
581
        gossiper := &AuthenticatedGossiper{
33✔
582
                selfKey:           selfKeyDesc.PubKey,
33✔
583
                selfKeyLoc:        selfKeyDesc.KeyLocator,
33✔
584
                cfg:               &cfg,
33✔
585
                networkMsgs:       make(chan *networkMsg),
33✔
586
                futureMsgs:        newFutureMsgCache(maxFutureMessages),
33✔
587
                quit:              make(chan struct{}),
33✔
588
                chanPolicyUpdates: make(chan *chanPolicyUpdateRequest),
33✔
589
                prematureChannelUpdates: lru.NewCache[uint64, *cachedNetworkMsg]( //nolint: ll
33✔
590
                        maxPrematureUpdates,
33✔
591
                ),
33✔
592
                channelMtx: multimutex.NewMutex[uint64](),
33✔
593
                recentRejects: lru.NewCache[rejectCacheKey, *cachedReject](
33✔
594
                        maxRejectedUpdates,
33✔
595
                ),
33✔
596
                chanUpdateRateLimiter: make(map[uint64][2]*rate.Limiter),
33✔
597
                banman:                newBanman(cfg.BanThreshold),
33✔
598
        }
33✔
599

33✔
600
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
33✔
601

33✔
602
        gossiper.syncMgr = newSyncManager(&SyncManagerCfg{
33✔
603
                ChainHash:                cfg.ChainHash,
33✔
604
                ChanSeries:               cfg.ChanSeries,
33✔
605
                RotateTicker:             cfg.RotateTicker,
33✔
606
                HistoricalSyncTicker:     cfg.HistoricalSyncTicker,
33✔
607
                NumActiveSyncers:         cfg.NumActiveSyncers,
33✔
608
                NoTimestampQueries:       cfg.NoTimestampQueries,
33✔
609
                IgnoreHistoricalFilters:  cfg.IgnoreHistoricalFilters,
33✔
610
                BestHeight:               gossiper.latestHeight,
33✔
611
                PinnedSyncers:            cfg.PinnedSyncers,
33✔
612
                IsStillZombieChannel:     cfg.IsStillZombieChannel,
33✔
613
                AllotedMsgBytesPerSecond: cfg.MsgRateBytes,
33✔
614
                AllotedMsgBytesBurst:     cfg.MsgBurstBytes,
33✔
615
                FilterConcurrency:        cfg.FilterConcurrency,
33✔
616
                PeerMsgBytesPerSecond:    cfg.PeerMsgRateBytes,
33✔
617
        })
33✔
618

33✔
619
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
33✔
620
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
33✔
621
                NotifyWhenOffline: cfg.NotifyWhenOffline,
33✔
622
                MessageStore:      cfg.MessageStore,
33✔
623
                IsMsgStale:        gossiper.isMsgStale,
33✔
624
        })
33✔
625

33✔
626
        return gossiper
33✔
627
}
33✔
628

629
// EdgeWithInfo contains the information that is required to update an edge.
630
type EdgeWithInfo struct {
631
        // Info describes the channel.
632
        Info *models.ChannelEdgeInfo
633

634
        // Edge describes the policy in one direction of the channel.
635
        Edge *models.ChannelEdgePolicy
636
}
637

638
// PropagateChanPolicyUpdate signals the AuthenticatedGossiper to perform the
639
// specified edge updates. Updates are done in two stages: first, the
640
// AuthenticatedGossiper ensures the update has been committed by dependent
641
// sub-systems, then it signs and broadcasts new updates to the network. A
642
// mapping between outpoints and updated channel policies is returned, which is
643
// used to update the forwarding policies of the underlying links.
644
func (d *AuthenticatedGossiper) PropagateChanPolicyUpdate(
645
        edgesToUpdate []EdgeWithInfo) error {
4✔
646

4✔
647
        errChan := make(chan error, 1)
4✔
648
        policyUpdate := &chanPolicyUpdateRequest{
4✔
649
                edgesToUpdate: edgesToUpdate,
4✔
650
                errChan:       errChan,
4✔
651
        }
4✔
652

4✔
653
        select {
4✔
654
        case d.chanPolicyUpdates <- policyUpdate:
4✔
655
                err := <-errChan
4✔
656
                return err
4✔
657
        case <-d.quit:
×
658
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
659
        }
660
}
661

662
// Start spawns network messages handler goroutine and registers on new block
663
// notifications in order to properly handle the premature announcements.
664
func (d *AuthenticatedGossiper) Start() error {
33✔
665
        var err error
33✔
666
        d.started.Do(func() {
66✔
667
                ctx, cancel := context.WithCancel(context.Background())
33✔
668
                d.cancel = fn.Some(cancel)
33✔
669

33✔
670
                log.Info("Authenticated Gossiper starting")
33✔
671
                err = d.start(ctx)
33✔
672
        })
33✔
673
        return err
33✔
674
}
675

676
func (d *AuthenticatedGossiper) start(ctx context.Context) error {
33✔
677
        // First we register for new notifications of newly discovered blocks.
33✔
678
        // We do this immediately so we'll later be able to consume any/all
33✔
679
        // blocks which were discovered.
33✔
680
        blockEpochs, err := d.cfg.Notifier.RegisterBlockEpochNtfn(nil)
33✔
681
        if err != nil {
33✔
682
                return err
×
683
        }
×
684
        d.blockEpochs = blockEpochs
33✔
685

33✔
686
        height, err := d.cfg.Graph.CurrentBlockHeight()
33✔
687
        if err != nil {
33✔
688
                return err
×
689
        }
×
690
        d.bestHeight = height
33✔
691

33✔
692
        // Start the reliable sender. In case we had any pending messages ready
33✔
693
        // to be sent when the gossiper was last shut down, we must continue on
33✔
694
        // our quest to deliver them to their respective peers.
33✔
695
        if err := d.reliableSender.Start(); err != nil {
33✔
696
                return err
×
697
        }
×
698

699
        d.syncMgr.Start()
33✔
700

33✔
701
        d.banman.start()
33✔
702

33✔
703
        // Start receiving blocks in its dedicated goroutine.
33✔
704
        d.wg.Add(2)
33✔
705
        go d.syncBlockHeight()
33✔
706
        go d.networkHandler(ctx)
33✔
707

33✔
708
        return nil
33✔
709
}
710

711
// syncBlockHeight syncs the best block height for the gossiper by reading
712
// blockEpochs.
713
//
714
// NOTE: must be run as a goroutine.
715
func (d *AuthenticatedGossiper) syncBlockHeight() {
33✔
716
        defer d.wg.Done()
33✔
717

33✔
718
        for {
66✔
719
                select {
33✔
720
                // A new block has arrived, so we can re-process the previously
721
                // premature announcements.
722
                case newBlock, ok := <-d.blockEpochs.Epochs:
3✔
723
                        // If the channel has been closed, then this indicates
3✔
724
                        // the daemon is shutting down, so we exit ourselves.
3✔
725
                        if !ok {
6✔
726
                                return
3✔
727
                        }
3✔
728

729
                        // Once a new block arrives, we update our running
730
                        // track of the height of the chain tip.
731
                        d.Lock()
3✔
732
                        blockHeight := uint32(newBlock.Height)
3✔
733
                        d.bestHeight = blockHeight
3✔
734
                        d.Unlock()
3✔
735

3✔
736
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
3✔
737
                                newBlock.Hash)
3✔
738

3✔
739
                        // Resend future messages, if any.
3✔
740
                        d.resendFutureMessages(blockHeight)
3✔
741

742
                case <-d.quit:
30✔
743
                        return
30✔
744
                }
745
        }
746
}
747

748
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
749
// the unique ID when saving the message.
750
type futureMsgCache struct {
751
        *lru.Cache[uint64, *cachedFutureMsg]
752

753
        // msgID is a monotonically increased integer.
754
        msgID atomic.Uint64
755
}
756

757
// nextMsgID returns a unique message ID.
758
func (f *futureMsgCache) nextMsgID() uint64 {
6✔
759
        return f.msgID.Add(1)
6✔
760
}
6✔
761

762
// newFutureMsgCache creates a new future message cache with the underlying lru
763
// cache being initialized with the specified capacity.
764
func newFutureMsgCache(capacity uint64) *futureMsgCache {
34✔
765
        // Create a new cache.
34✔
766
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
34✔
767

34✔
768
        return &futureMsgCache{
34✔
769
                Cache: cache,
34✔
770
        }
34✔
771
}
34✔
772

773
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
774
type cachedFutureMsg struct {
775
        // msg is the network message.
776
        msg *networkMsg
777

778
        // height is the block height.
779
        height uint32
780
}
781

782
// Size returns the size of the message.
783
func (c *cachedFutureMsg) Size() (uint64, error) {
7✔
784
        // Return a constant 1.
7✔
785
        return 1, nil
7✔
786
}
7✔
787

788
// resendFutureMessages takes a block height, resends all the future messages
789
// found below and equal to that height and deletes those messages found in the
790
// gossiper's futureMsgs.
791
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
3✔
792
        var (
3✔
793
                // msgs are the target messages.
3✔
794
                msgs []*networkMsg
3✔
795

3✔
796
                // keys are the target messages' caching keys.
3✔
797
                keys []uint64
3✔
798
        )
3✔
799

3✔
800
        // filterMsgs is the visitor used when iterating the future cache.
3✔
801
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
6✔
802
                if cmsg.height <= height {
6✔
803
                        msgs = append(msgs, cmsg.msg)
3✔
804
                        keys = append(keys, k)
3✔
805
                }
3✔
806

807
                return true
3✔
808
        }
809

810
        // Filter out the target messages.
811
        d.futureMsgs.Range(filterMsgs)
3✔
812

3✔
813
        // Return early if no messages found.
3✔
814
        if len(msgs) == 0 {
6✔
815
                return
3✔
816
        }
3✔
817

818
        // Remove the filtered messages.
819
        for _, key := range keys {
6✔
820
                d.futureMsgs.Delete(key)
3✔
821
        }
3✔
822

823
        log.Debugf("Resending %d network messages at height %d",
3✔
824
                len(msgs), height)
3✔
825

3✔
826
        for _, msg := range msgs {
6✔
827
                select {
3✔
828
                case d.networkMsgs <- msg:
3✔
829
                case <-d.quit:
×
830
                        msg.err <- ErrGossiperShuttingDown
×
831
                }
832
        }
833
}
834

835
// Stop signals any active goroutines for a graceful closure.
836
func (d *AuthenticatedGossiper) Stop() error {
34✔
837
        d.stopped.Do(func() {
67✔
838
                log.Info("Authenticated gossiper shutting down...")
33✔
839
                defer log.Debug("Authenticated gossiper shutdown complete")
33✔
840

33✔
841
                d.stop()
33✔
842
        })
33✔
843
        return nil
34✔
844
}
845

846
func (d *AuthenticatedGossiper) stop() {
33✔
847
        log.Debug("Authenticated Gossiper is stopping")
33✔
848
        defer log.Debug("Authenticated Gossiper stopped")
33✔
849

33✔
850
        // `blockEpochs` is only initialized in the start routine so we make
33✔
851
        // sure we don't panic here in the case where the `Stop` method is
33✔
852
        // called when the `Start` method does not complete.
33✔
853
        if d.blockEpochs != nil {
66✔
854
                d.blockEpochs.Cancel()
33✔
855
        }
33✔
856

857
        d.syncMgr.Stop()
33✔
858

33✔
859
        d.banman.stop()
33✔
860

33✔
861
        d.cancel.WhenSome(func(fn context.CancelFunc) { fn() })
66✔
862
        close(d.quit)
33✔
863
        d.wg.Wait()
33✔
864

33✔
865
        // We'll stop our reliable sender after all of the gossiper's goroutines
33✔
866
        // have exited to ensure nothing can cause it to continue executing.
33✔
867
        d.reliableSender.Stop()
33✔
868
}
869

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

873
// ProcessRemoteAnnouncement sends a new remote announcement message along with
874
// the peer that sent the routing message. The announcement will be processed
875
// then added to a queue for batched trickled announcement to all connected
876
// peers.  Remote channel announcements should contain the announcement proof
877
// and be fully validated.
878
func (d *AuthenticatedGossiper) ProcessRemoteAnnouncement(ctx context.Context,
879
        msg lnwire.Message, peer lnpeer.Peer) chan error {
294✔
880

294✔
881
        errChan := make(chan error, 1)
294✔
882

294✔
883
        // For messages in the known set of channel series queries, we'll
294✔
884
        // dispatch the message directly to the GossipSyncer, and skip the main
294✔
885
        // processing loop.
294✔
886
        switch m := msg.(type) {
294✔
887
        case *lnwire.QueryShortChanIDs,
888
                *lnwire.QueryChannelRange,
889
                *lnwire.ReplyChannelRange,
890
                *lnwire.ReplyShortChanIDsEnd:
3✔
891

3✔
892
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
893
                if !ok {
3✔
894
                        log.Warnf("Gossip syncer for peer=%x not found",
×
895
                                peer.PubKey())
×
896

×
897
                        errChan <- ErrGossipSyncerNotFound
×
898
                        return errChan
×
899
                }
×
900

901
                // If we've found the message target, then we'll dispatch the
902
                // message directly to it.
903
                err := syncer.ProcessQueryMsg(m, peer.QuitSignal())
3✔
904
                if err != nil {
3✔
905
                        log.Errorf("Process query msg from peer %x got %v",
×
906
                                peer.PubKey(), err)
×
907
                }
×
908

909
                errChan <- err
3✔
910
                return errChan
3✔
911

912
        // If a peer is updating its current update horizon, then we'll dispatch
913
        // that directly to the proper GossipSyncer.
914
        case *lnwire.GossipTimestampRange:
3✔
915
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
916
                if !ok {
3✔
917
                        log.Warnf("Gossip syncer for peer=%x not found",
×
918
                                peer.PubKey())
×
919

×
920
                        errChan <- ErrGossipSyncerNotFound
×
921
                        return errChan
×
922
                }
×
923

924
                // Queue the message for asynchronous processing to prevent
925
                // blocking the gossiper when rate limiting is active.
926
                if !syncer.QueueTimestampRange(m) {
3✔
927
                        log.Warnf("Unable to queue gossip filter for peer=%x: "+
×
928
                                "queue full", peer.PubKey())
×
929

×
930
                        // Return nil to indicate we've handled the message,
×
931
                        // even though it was dropped. This prevents the peer
×
932
                        // from being disconnected.
×
933
                        errChan <- nil
×
934
                        return errChan
×
935
                }
×
936

937
                errChan <- nil
3✔
938
                return errChan
3✔
939

940
        // To avoid inserting edges in the graph for our own channels that we
941
        // have already closed, we ignore such channel announcements coming
942
        // from the remote.
943
        case *lnwire.ChannelAnnouncement1:
223✔
944
                ownKey := d.selfKey.SerializeCompressed()
223✔
945
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
223✔
946
                        "for own channel")
223✔
947

223✔
948
                if bytes.Equal(m.NodeID1[:], ownKey) ||
223✔
949
                        bytes.Equal(m.NodeID2[:], ownKey) {
228✔
950

5✔
951
                        log.Warn(ownErr)
5✔
952
                        errChan <- ownErr
5✔
953
                        return errChan
5✔
954
                }
5✔
955
        }
956

957
        nMsg := &networkMsg{
292✔
958
                msg:      msg,
292✔
959
                isRemote: true,
292✔
960
                peer:     peer,
292✔
961
                source:   peer.IdentityKey(),
292✔
962
                err:      errChan,
292✔
963
        }
292✔
964

292✔
965
        select {
292✔
966
        case d.networkMsgs <- nMsg:
292✔
967

968
        // If the peer that sent us this error is quitting, then we don't need
969
        // to send back an error and can return immediately.
970
        // TODO(elle): the peer should now just rely on canceling the passed
971
        //  context.
972
        case <-peer.QuitSignal():
×
973
                return nil
×
974
        case <-ctx.Done():
×
975
                return nil
×
976
        case <-d.quit:
×
977
                nMsg.err <- ErrGossiperShuttingDown
×
978
        }
979

980
        return nMsg.err
292✔
981
}
982

983
// ProcessLocalAnnouncement sends a new remote announcement message along with
984
// the peer that sent the routing message. The announcement will be processed
985
// then added to a queue for batched trickled announcement to all connected
986
// peers.  Local channel announcements don't contain the announcement proof and
987
// will not be fully validated. Once the channel proofs are received, the
988
// entire channel announcement and update messages will be re-constructed and
989
// broadcast to the rest of the network.
990
func (d *AuthenticatedGossiper) ProcessLocalAnnouncement(msg lnwire.Message,
991
        optionalFields ...OptionalMsgField) chan error {
50✔
992

50✔
993
        optionalMsgFields := &optionalMsgFields{}
50✔
994
        optionalMsgFields.apply(optionalFields...)
50✔
995

50✔
996
        nMsg := &networkMsg{
50✔
997
                msg:               msg,
50✔
998
                optionalMsgFields: optionalMsgFields,
50✔
999
                isRemote:          false,
50✔
1000
                source:            d.selfKey,
50✔
1001
                err:               make(chan error, 1),
50✔
1002
        }
50✔
1003

50✔
1004
        select {
50✔
1005
        case d.networkMsgs <- nMsg:
50✔
1006
        case <-d.quit:
×
1007
                nMsg.err <- ErrGossiperShuttingDown
×
1008
        }
1009

1010
        return nMsg.err
50✔
1011
}
1012

1013
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
1014
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
1015
// tuple.
1016
type channelUpdateID struct {
1017
        // channelID represents the set of data which is needed to
1018
        // retrieve all necessary data to validate the channel existence.
1019
        channelID lnwire.ShortChannelID
1020

1021
        // Flags least-significant bit must be set to 0 if the creating node
1022
        // corresponds to the first node in the previously sent channel
1023
        // announcement and 1 otherwise.
1024
        flags lnwire.ChanUpdateChanFlags
1025
}
1026

1027
// msgWithSenders is a wrapper struct around a message, and the set of peers
1028
// that originally sent us this message. Using this struct, we can ensure that
1029
// we don't re-send a message to the peer that sent it to us in the first
1030
// place.
1031
type msgWithSenders struct {
1032
        // msg is the wire message itself.
1033
        msg lnwire.Message
1034

1035
        // isLocal is true if this was a message that originated locally. We'll
1036
        // use this to bypass our normal checks to ensure we prioritize sending
1037
        // out our own updates.
1038
        isLocal bool
1039

1040
        // sender is the set of peers that sent us this message.
1041
        senders map[route.Vertex]struct{}
1042
}
1043

1044
// mergeSyncerMap is used to merge the set of senders of a particular message
1045
// with peers that we have an active GossipSyncer with. We do this to ensure
1046
// that we don't broadcast messages to any peers that we have active gossip
1047
// syncers for.
1048
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
32✔
1049
        for peerPub := range syncers {
35✔
1050
                m.senders[peerPub] = struct{}{}
3✔
1051
        }
3✔
1052
}
1053

1054
// deDupedAnnouncements de-duplicates announcements that have been added to the
1055
// batch. Internally, announcements are stored in three maps
1056
// (one each for channel announcements, channel updates, and node
1057
// announcements). These maps keep track of unique announcements and ensure no
1058
// announcements are duplicated. We keep the three message types separate, such
1059
// that we can send channel announcements first, then channel updates, and
1060
// finally node announcements when it's time to broadcast them.
1061
type deDupedAnnouncements struct {
1062
        // channelAnnouncements are identified by the short channel id field.
1063
        channelAnnouncements map[lnwire.ShortChannelID]msgWithSenders
1064

1065
        // channelUpdates are identified by the channel update id field.
1066
        channelUpdates map[channelUpdateID]msgWithSenders
1067

1068
        // nodeAnnouncements are identified by the Vertex field.
1069
        nodeAnnouncements map[route.Vertex]msgWithSenders
1070

1071
        sync.Mutex
1072
}
1073

1074
// Reset operates on deDupedAnnouncements to reset the storage of
1075
// announcements.
1076
func (d *deDupedAnnouncements) Reset() {
35✔
1077
        d.Lock()
35✔
1078
        defer d.Unlock()
35✔
1079

35✔
1080
        d.reset()
35✔
1081
}
35✔
1082

1083
// reset is the private version of the Reset method. We have this so we can
1084
// call this method within method that are already holding the lock.
1085
func (d *deDupedAnnouncements) reset() {
330✔
1086
        // Storage of each type of announcement (channel announcements, channel
330✔
1087
        // updates, node announcements) is set to an empty map where the
330✔
1088
        // appropriate key points to the corresponding lnwire.Message.
330✔
1089
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
330✔
1090
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
330✔
1091
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
330✔
1092
}
330✔
1093

1094
// addMsg adds a new message to the current batch. If the message is already
1095
// present in the current batch, then this new instance replaces the latter,
1096
// and the set of senders is updated to reflect which node sent us this
1097
// message.
1098
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
94✔
1099
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
94✔
1100

94✔
1101
        // Depending on the message type (channel announcement, channel update,
94✔
1102
        // or node announcement), the message is added to the corresponding map
94✔
1103
        // in deDupedAnnouncements. Because each identifying key can have at
94✔
1104
        // most one value, the announcements are de-duplicated, with newer ones
94✔
1105
        // replacing older ones.
94✔
1106
        switch msg := message.msg.(type) {
94✔
1107

1108
        // Channel announcements are identified by the short channel id field.
1109
        case *lnwire.ChannelAnnouncement1:
26✔
1110
                deDupKey := msg.ShortChannelID
26✔
1111
                sender := route.NewVertex(message.source)
26✔
1112

26✔
1113
                mws, ok := d.channelAnnouncements[deDupKey]
26✔
1114
                if !ok {
51✔
1115
                        mws = msgWithSenders{
25✔
1116
                                msg:     msg,
25✔
1117
                                isLocal: !message.isRemote,
25✔
1118
                                senders: make(map[route.Vertex]struct{}),
25✔
1119
                        }
25✔
1120
                        mws.senders[sender] = struct{}{}
25✔
1121

25✔
1122
                        d.channelAnnouncements[deDupKey] = mws
25✔
1123

25✔
1124
                        return
25✔
1125
                }
25✔
1126

1127
                mws.msg = msg
1✔
1128
                mws.senders[sender] = struct{}{}
1✔
1129
                d.channelAnnouncements[deDupKey] = mws
1✔
1130

1131
        // Channel updates are identified by the (short channel id,
1132
        // channelflags) tuple.
1133
        case *lnwire.ChannelUpdate1:
49✔
1134
                sender := route.NewVertex(message.source)
49✔
1135
                deDupKey := channelUpdateID{
49✔
1136
                        msg.ShortChannelID,
49✔
1137
                        msg.ChannelFlags,
49✔
1138
                }
49✔
1139

49✔
1140
                oldTimestamp := uint32(0)
49✔
1141
                mws, ok := d.channelUpdates[deDupKey]
49✔
1142
                if ok {
52✔
1143
                        // If we already have seen this message, record its
3✔
1144
                        // timestamp.
3✔
1145
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1146
                        if !ok {
3✔
1147
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1148
                                        "got: %T", mws.msg)
×
1149

×
1150
                                return
×
1151
                        }
×
1152

1153
                        oldTimestamp = update.Timestamp
3✔
1154
                }
1155

1156
                // If we already had this message with a strictly newer
1157
                // timestamp, then we'll just discard the message we got.
1158
                if oldTimestamp > msg.Timestamp {
50✔
1159
                        log.Debugf("Ignored outdated network message: "+
1✔
1160
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1161
                        return
1✔
1162
                }
1✔
1163

1164
                // If the message we just got is newer than what we previously
1165
                // have seen, or this is the first time we see it, then we'll
1166
                // add it to our map of announcements.
1167
                if oldTimestamp < msg.Timestamp {
95✔
1168
                        mws = msgWithSenders{
47✔
1169
                                msg:     msg,
47✔
1170
                                isLocal: !message.isRemote,
47✔
1171
                                senders: make(map[route.Vertex]struct{}),
47✔
1172
                        }
47✔
1173

47✔
1174
                        // We'll mark the sender of the message in the
47✔
1175
                        // senders map.
47✔
1176
                        mws.senders[sender] = struct{}{}
47✔
1177

47✔
1178
                        d.channelUpdates[deDupKey] = mws
47✔
1179

47✔
1180
                        return
47✔
1181
                }
47✔
1182

1183
                // Lastly, if we had seen this exact message from before, with
1184
                // the same timestamp, we'll add the sender to the map of
1185
                // senders, such that we can skip sending this message back in
1186
                // the next batch.
1187
                mws.msg = msg
1✔
1188
                mws.senders[sender] = struct{}{}
1✔
1189
                d.channelUpdates[deDupKey] = mws
1✔
1190

1191
        // Node announcements are identified by the Vertex field.  Use the
1192
        // NodeID to create the corresponding Vertex.
1193
        case *lnwire.NodeAnnouncement:
25✔
1194
                sender := route.NewVertex(message.source)
25✔
1195
                deDupKey := route.Vertex(msg.NodeID)
25✔
1196

25✔
1197
                // We do the same for node announcements as we did for channel
25✔
1198
                // updates, as they also carry a timestamp.
25✔
1199
                oldTimestamp := uint32(0)
25✔
1200
                mws, ok := d.nodeAnnouncements[deDupKey]
25✔
1201
                if ok {
33✔
1202
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
8✔
1203
                }
8✔
1204

1205
                // Discard the message if it's old.
1206
                if oldTimestamp > msg.Timestamp {
28✔
1207
                        return
3✔
1208
                }
3✔
1209

1210
                // Replace if it's newer.
1211
                if oldTimestamp < msg.Timestamp {
46✔
1212
                        mws = msgWithSenders{
21✔
1213
                                msg:     msg,
21✔
1214
                                isLocal: !message.isRemote,
21✔
1215
                                senders: make(map[route.Vertex]struct{}),
21✔
1216
                        }
21✔
1217

21✔
1218
                        mws.senders[sender] = struct{}{}
21✔
1219

21✔
1220
                        d.nodeAnnouncements[deDupKey] = mws
21✔
1221

21✔
1222
                        return
21✔
1223
                }
21✔
1224

1225
                // Add to senders map if it's the same as we had.
1226
                mws.msg = msg
7✔
1227
                mws.senders[sender] = struct{}{}
7✔
1228
                d.nodeAnnouncements[deDupKey] = mws
7✔
1229
        }
1230
}
1231

1232
// AddMsgs is a helper method to add multiple messages to the announcement
1233
// batch.
1234
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
62✔
1235
        d.Lock()
62✔
1236
        defer d.Unlock()
62✔
1237

62✔
1238
        for _, msg := range msgs {
156✔
1239
                d.addMsg(msg)
94✔
1240
        }
94✔
1241
}
1242

1243
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1244
// to broadcast next into messages that are locally sourced and those that are
1245
// sourced remotely.
1246
type msgsToBroadcast struct {
1247
        // localMsgs is the set of messages we created locally.
1248
        localMsgs []msgWithSenders
1249

1250
        // remoteMsgs is the set of messages that we received from a remote
1251
        // party.
1252
        remoteMsgs []msgWithSenders
1253
}
1254

1255
// addMsg adds a new message to the appropriate sub-slice.
1256
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
79✔
1257
        if msg.isLocal {
129✔
1258
                m.localMsgs = append(m.localMsgs, msg)
50✔
1259
        } else {
82✔
1260
                m.remoteMsgs = append(m.remoteMsgs, msg)
32✔
1261
        }
32✔
1262
}
1263

1264
// isEmpty returns true if the batch is empty.
1265
func (m *msgsToBroadcast) isEmpty() bool {
297✔
1266
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
297✔
1267
}
297✔
1268

1269
// length returns the length of the combined message set.
1270
func (m *msgsToBroadcast) length() int {
1✔
1271
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1272
}
1✔
1273

1274
// Emit returns the set of de-duplicated announcements to be sent out during
1275
// the next announcement epoch, in the order of channel announcements, channel
1276
// updates, and node announcements. Each message emitted, contains the set of
1277
// peers that sent us the message. This way, we can ensure that we don't waste
1278
// bandwidth by re-sending a message to the peer that sent it to us in the
1279
// first place. Additionally, the set of stored messages are reset.
1280
func (d *deDupedAnnouncements) Emit() msgsToBroadcast {
298✔
1281
        d.Lock()
298✔
1282
        defer d.Unlock()
298✔
1283

298✔
1284
        // Get the total number of announcements.
298✔
1285
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
298✔
1286
                len(d.nodeAnnouncements)
298✔
1287

298✔
1288
        // Create an empty array of lnwire.Messages with a length equal to
298✔
1289
        // the total number of announcements.
298✔
1290
        msgs := msgsToBroadcast{
298✔
1291
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
298✔
1292
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
298✔
1293
        }
298✔
1294

298✔
1295
        // Add the channel announcements to the array first.
298✔
1296
        for _, message := range d.channelAnnouncements {
320✔
1297
                msgs.addMsg(message)
22✔
1298
        }
22✔
1299

1300
        // Then add the channel updates.
1301
        for _, message := range d.channelUpdates {
341✔
1302
                msgs.addMsg(message)
43✔
1303
        }
43✔
1304

1305
        // Finally add the node announcements.
1306
        for _, message := range d.nodeAnnouncements {
318✔
1307
                msgs.addMsg(message)
20✔
1308
        }
20✔
1309

1310
        d.reset()
298✔
1311

298✔
1312
        // Return the array of lnwire.messages.
298✔
1313
        return msgs
298✔
1314
}
1315

1316
// calculateSubBatchSize is a helper function that calculates the size to break
1317
// down the batchSize into.
1318
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1319
        minimumBatchSize, batchSize int) int {
16✔
1320
        if subBatchDelay > totalDelay {
18✔
1321
                return batchSize
2✔
1322
        }
2✔
1323

1324
        subBatchSize := (batchSize*int(subBatchDelay) +
14✔
1325
                int(totalDelay) - 1) / int(totalDelay)
14✔
1326

14✔
1327
        if subBatchSize < minimumBatchSize {
18✔
1328
                return minimumBatchSize
4✔
1329
        }
4✔
1330

1331
        return subBatchSize
10✔
1332
}
1333

1334
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1335
// this variable so the function can be mocked in our test.
1336
var batchSizeCalculator = calculateSubBatchSize
1337

1338
// splitAnnouncementBatches takes an exiting list of announcements and
1339
// decomposes it into sub batches controlled by the `subBatchSize`.
1340
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1341
        announcementBatch []msgWithSenders) [][]msgWithSenders {
78✔
1342

78✔
1343
        subBatchSize := batchSizeCalculator(
78✔
1344
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
78✔
1345
                d.cfg.MinimumBatchSize, len(announcementBatch),
78✔
1346
        )
78✔
1347

78✔
1348
        var splitAnnouncementBatch [][]msgWithSenders
78✔
1349

78✔
1350
        for subBatchSize < len(announcementBatch) {
202✔
1351
                // For slicing with minimal allocation
124✔
1352
                // https://github.com/golang/go/wiki/SliceTricks
124✔
1353
                announcementBatch, splitAnnouncementBatch =
124✔
1354
                        announcementBatch[subBatchSize:],
124✔
1355
                        append(splitAnnouncementBatch,
124✔
1356
                                announcementBatch[0:subBatchSize:subBatchSize])
124✔
1357
        }
124✔
1358
        splitAnnouncementBatch = append(
78✔
1359
                splitAnnouncementBatch, announcementBatch,
78✔
1360
        )
78✔
1361

78✔
1362
        return splitAnnouncementBatch
78✔
1363
}
1364

1365
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1366
// split size, and then sends out all items to the set of target peers. Locally
1367
// generated announcements are always sent before remotely generated
1368
// announcements.
1369
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(ctx context.Context,
1370
        annBatch msgsToBroadcast) {
37✔
1371

37✔
1372
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
37✔
1373
        // duration to delay the sending of next announcement batch.
37✔
1374
        delayNextBatch := func() {
108✔
1375
                select {
71✔
1376
                case <-time.After(d.cfg.SubBatchDelay):
54✔
1377
                case <-d.quit:
17✔
1378
                        return
17✔
1379
                }
1380
        }
1381

1382
        // Fetch the local and remote announcements.
1383
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
37✔
1384
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
37✔
1385

37✔
1386
        d.wg.Add(1)
37✔
1387
        go func() {
74✔
1388
                defer d.wg.Done()
37✔
1389

37✔
1390
                log.Debugf("Broadcasting %v new local announcements in %d "+
37✔
1391
                        "sub batches", len(annBatch.localMsgs),
37✔
1392
                        len(localBatches))
37✔
1393

37✔
1394
                // Send out the local announcements first.
37✔
1395
                for _, annBatch := range localBatches {
74✔
1396
                        d.sendLocalBatch(annBatch)
37✔
1397
                        delayNextBatch()
37✔
1398
                }
37✔
1399

1400
                log.Debugf("Broadcasting %v new remote announcements in %d "+
37✔
1401
                        "sub batches", len(annBatch.remoteMsgs),
37✔
1402
                        len(remoteBatches))
37✔
1403

37✔
1404
                // Now send the remote announcements.
37✔
1405
                for _, annBatch := range remoteBatches {
74✔
1406
                        d.sendRemoteBatch(ctx, annBatch)
37✔
1407
                        delayNextBatch()
37✔
1408
                }
37✔
1409
        }()
1410
}
1411

1412
// sendLocalBatch broadcasts a list of locally generated announcements to our
1413
// peers. For local announcements, we skip the filter and dedup logic and just
1414
// send the announcements out to all our coonnected peers.
1415
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
37✔
1416
        msgsToSend := lnutils.Map(
37✔
1417
                annBatch, func(m msgWithSenders) lnwire.Message {
83✔
1418
                        return m.msg
46✔
1419
                },
46✔
1420
        )
1421

1422
        err := d.cfg.Broadcast(nil, msgsToSend...)
37✔
1423
        if err != nil {
37✔
1424
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1425
        }
×
1426
}
1427

1428
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1429
// peers.
1430
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1431
        annBatch []msgWithSenders) {
37✔
1432

37✔
1433
        syncerPeers := d.syncMgr.GossipSyncers()
37✔
1434

37✔
1435
        // We'll first attempt to filter out this new message for all peers
37✔
1436
        // that have active gossip syncers active.
37✔
1437
        for pub, syncer := range syncerPeers {
40✔
1438
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
3✔
1439
                syncer.FilterGossipMsgs(ctx, annBatch...)
3✔
1440
        }
3✔
1441

1442
        for _, msgChunk := range annBatch {
69✔
1443
                msgChunk := msgChunk
32✔
1444

32✔
1445
                // With the syncers taken care of, we'll merge the sender map
32✔
1446
                // with the set of syncers, so we don't send out duplicate
32✔
1447
                // messages.
32✔
1448
                msgChunk.mergeSyncerMap(syncerPeers)
32✔
1449

32✔
1450
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
32✔
1451
                if err != nil {
32✔
1452
                        log.Errorf("Unable to send batch "+
×
1453
                                "announcements: %v", err)
×
1454
                        continue
×
1455
                }
1456
        }
1457
}
1458

1459
// networkHandler is the primary goroutine that drives this service. The roles
1460
// of this goroutine includes answering queries related to the state of the
1461
// network, syncing up newly connected peers, and also periodically
1462
// broadcasting our latest topology state to all connected peers.
1463
//
1464
// NOTE: This MUST be run as a goroutine.
1465
func (d *AuthenticatedGossiper) networkHandler(ctx context.Context) {
33✔
1466
        defer d.wg.Done()
33✔
1467

33✔
1468
        // Initialize empty deDupedAnnouncements to store announcement batch.
33✔
1469
        announcements := deDupedAnnouncements{}
33✔
1470
        announcements.Reset()
33✔
1471

33✔
1472
        d.cfg.RetransmitTicker.Resume()
33✔
1473
        defer d.cfg.RetransmitTicker.Stop()
33✔
1474

33✔
1475
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
33✔
1476
        defer trickleTimer.Stop()
33✔
1477

33✔
1478
        // To start, we'll first check to see if there are any stale channel or
33✔
1479
        // node announcements that we need to re-transmit.
33✔
1480
        if err := d.retransmitStaleAnns(ctx, time.Now()); err != nil {
33✔
1481
                log.Errorf("Unable to rebroadcast stale announcements: %v", err)
×
1482
        }
×
1483

1484
        for {
700✔
1485
                select {
667✔
1486
                // A new policy update has arrived. We'll commit it to the
1487
                // sub-systems below us, then craft, sign, and broadcast a new
1488
                // ChannelUpdate for the set of affected clients.
1489
                case policyUpdate := <-d.chanPolicyUpdates:
4✔
1490
                        log.Tracef("Received channel %d policy update requests",
4✔
1491
                                len(policyUpdate.edgesToUpdate))
4✔
1492

4✔
1493
                        // First, we'll now create new fully signed updates for
4✔
1494
                        // the affected channels and also update the underlying
4✔
1495
                        // graph with the new state.
4✔
1496
                        newChanUpdates, err := d.processChanPolicyUpdate(
4✔
1497
                                ctx, policyUpdate.edgesToUpdate,
4✔
1498
                        )
4✔
1499
                        policyUpdate.errChan <- err
4✔
1500
                        if err != nil {
4✔
1501
                                log.Errorf("Unable to craft policy updates: %v",
×
1502
                                        err)
×
1503
                                continue
×
1504
                        }
1505

1506
                        // Finally, with the updates committed, we'll now add
1507
                        // them to the announcement batch to be flushed at the
1508
                        // start of the next epoch.
1509
                        announcements.AddMsgs(newChanUpdates...)
4✔
1510

1511
                case announcement := <-d.networkMsgs:
341✔
1512
                        log.Tracef("Received network message: "+
341✔
1513
                                "peer=%v, msg=%s, is_remote=%v",
341✔
1514
                                announcement.peer, announcement.msg.MsgType(),
341✔
1515
                                announcement.isRemote)
341✔
1516

341✔
1517
                        switch announcement.msg.(type) {
341✔
1518
                        // Channel announcement signatures are amongst the only
1519
                        // messages that we'll process serially.
1520
                        case *lnwire.AnnounceSignatures1:
24✔
1521
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
24✔
1522
                                        ctx, announcement,
24✔
1523
                                )
24✔
1524
                                log.Debugf("Processed network message %s, "+
24✔
1525
                                        "returned len(announcements)=%v",
24✔
1526
                                        announcement.msg.MsgType(),
24✔
1527
                                        len(emittedAnnouncements))
24✔
1528

24✔
1529
                                if emittedAnnouncements != nil {
37✔
1530
                                        announcements.AddMsgs(
13✔
1531
                                                emittedAnnouncements...,
13✔
1532
                                        )
13✔
1533
                                }
13✔
1534
                                continue
24✔
1535
                        }
1536

1537
                        // If this message was recently rejected, then we won't
1538
                        // attempt to re-process it.
1539
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
320✔
1540
                                announcement.msg,
320✔
1541
                                sourceToPub(announcement.source),
320✔
1542
                        ) {
321✔
1543

1✔
1544
                                announcement.err <- fmt.Errorf("recently " +
1✔
1545
                                        "rejected")
1✔
1546
                                continue
1✔
1547
                        }
1548

1549
                        // We'll set up any dependent, and wait until a free
1550
                        // slot for this job opens up, this allow us to not
1551
                        // have thousands of goroutines active.
1552
                        annJobID, err := d.vb.InitJobDependencies(
319✔
1553
                                announcement.msg,
319✔
1554
                        )
319✔
1555
                        if err != nil {
319✔
1556
                                announcement.err <- err
×
1557
                                continue
×
1558
                        }
1559

1560
                        d.wg.Add(1)
319✔
1561
                        go d.handleNetworkMessages(
319✔
1562
                                ctx, announcement, &announcements, annJobID,
319✔
1563
                        )
319✔
1564

1565
                // The trickle timer has ticked, which indicates we should
1566
                // flush to the network the pending batch of new announcements
1567
                // we've received since the last trickle tick.
1568
                case <-trickleTimer.C:
297✔
1569
                        // Emit the current batch of announcements from
297✔
1570
                        // deDupedAnnouncements.
297✔
1571
                        announcementBatch := announcements.Emit()
297✔
1572

297✔
1573
                        // If the current announcements batch is nil, then we
297✔
1574
                        // have no further work here.
297✔
1575
                        if announcementBatch.isEmpty() {
560✔
1576
                                continue
263✔
1577
                        }
1578

1579
                        // At this point, we have the set of local and remote
1580
                        // announcements we want to send out. We'll do the
1581
                        // batching as normal for both, but for local
1582
                        // announcements, we'll blast them out w/o regard for
1583
                        // our peer's policies so we ensure they propagate
1584
                        // properly.
1585
                        d.splitAndSendAnnBatch(ctx, announcementBatch)
37✔
1586

1587
                // The retransmission timer has ticked which indicates that we
1588
                // should check if we need to prune or re-broadcast any of our
1589
                // personal channels or node announcement. This addresses the
1590
                // case of "zombie" channels and channel advertisements that
1591
                // have been dropped, or not properly propagated through the
1592
                // network.
1593
                case tick := <-d.cfg.RetransmitTicker.Ticks():
1✔
1594
                        if err := d.retransmitStaleAnns(ctx, tick); err != nil {
1✔
1595
                                log.Errorf("unable to rebroadcast stale "+
×
1596
                                        "announcements: %v", err)
×
1597
                        }
×
1598

1599
                // The gossiper has been signalled to exit, to we exit our
1600
                // main loop so the wait group can be decremented.
1601
                case <-d.quit:
33✔
1602
                        return
33✔
1603
                }
1604
        }
1605
}
1606

1607
// handleNetworkMessages is responsible for waiting for dependencies for a
1608
// given network message and processing the message. Once processed, it will
1609
// signal its dependants and add the new announcements to the announce batch.
1610
//
1611
// NOTE: must be run as a goroutine.
1612
func (d *AuthenticatedGossiper) handleNetworkMessages(ctx context.Context,
1613
        nMsg *networkMsg, deDuped *deDupedAnnouncements, jobID JobID) {
319✔
1614

319✔
1615
        defer d.wg.Done()
319✔
1616
        defer d.vb.CompleteJob()
319✔
1617

319✔
1618
        // We should only broadcast this message forward if it originated from
319✔
1619
        // us or it wasn't received as part of our initial historical sync.
319✔
1620
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
319✔
1621

319✔
1622
        // If this message has an existing dependency, then we'll wait until
319✔
1623
        // that has been fully validated before we proceed.
319✔
1624
        err := d.vb.WaitForParents(jobID, nMsg.msg)
319✔
1625
        if err != nil {
319✔
1626
                log.Debugf("Validating network message %s got err: %v",
×
1627
                        nMsg.msg.MsgType(), err)
×
1628

×
1629
                if errors.Is(err, ErrVBarrierShuttingDown) {
×
1630
                        log.Warnf("unexpected error during validation "+
×
1631
                                "barrier shutdown: %v", err)
×
1632
                }
×
1633
                nMsg.err <- err
×
1634

×
1635
                return
×
1636
        }
1637

1638
        // Process the network announcement to determine if this is either a
1639
        // new announcement from our PoV or an edges to a prior vertex/edge we
1640
        // previously proceeded.
1641
        newAnns, allow := d.processNetworkAnnouncement(ctx, nMsg)
319✔
1642

319✔
1643
        log.Tracef("Processed network message %s, returned "+
319✔
1644
                "len(announcements)=%v, allowDependents=%v",
319✔
1645
                nMsg.msg.MsgType(), len(newAnns), allow)
319✔
1646

319✔
1647
        // If this message had any dependencies, then we can now signal them to
319✔
1648
        // continue.
319✔
1649
        err = d.vb.SignalDependents(nMsg.msg, jobID)
319✔
1650
        if err != nil {
319✔
1651
                // Something is wrong if SignalDependents returns an error.
×
1652
                log.Errorf("SignalDependents returned error for msg=%v with "+
×
1653
                        "JobID=%v", spew.Sdump(nMsg.msg), jobID)
×
1654

×
1655
                nMsg.err <- err
×
1656

×
1657
                return
×
1658
        }
×
1659

1660
        // If the announcement was accepted, then add the emitted announcements
1661
        // to our announce batch to be broadcast once the trickle timer ticks
1662
        // gain.
1663
        if newAnns != nil && shouldBroadcast {
359✔
1664
                // TODO(roasbeef): exclude peer that sent.
40✔
1665
                deDuped.AddMsgs(newAnns...)
40✔
1666
        } else if newAnns != nil {
326✔
1667
                log.Trace("Skipping broadcast of announcements received " +
4✔
1668
                        "during initial graph sync")
4✔
1669
        }
4✔
1670
}
1671

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

1674
// InitSyncState is called by outside sub-systems when a connection is
1675
// established to a new peer that understands how to perform channel range
1676
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1677
// needed to handle new queries.
1678
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
3✔
1679
        d.syncMgr.InitSyncState(syncPeer)
3✔
1680
}
3✔
1681

1682
// PruneSyncState is called by outside sub-systems once a peer that we were
1683
// previously connected to has been disconnected. In this case we can stop the
1684
// existing GossipSyncer assigned to the peer and free up resources.
1685
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
3✔
1686
        d.syncMgr.PruneSyncState(peer)
3✔
1687
}
3✔
1688

1689
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1690
// false otherwise, This avoids expensive reprocessing of the message.
1691
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1692
        peerPub [33]byte) bool {
283✔
1693

283✔
1694
        var scid uint64
283✔
1695
        switch m := msg.(type) {
283✔
1696
        case *lnwire.ChannelUpdate1:
51✔
1697
                scid = m.ShortChannelID.ToUint64()
51✔
1698

1699
        case *lnwire.ChannelAnnouncement1:
221✔
1700
                scid = m.ShortChannelID.ToUint64()
221✔
1701

1702
        default:
17✔
1703
                return false
17✔
1704
        }
1705

1706
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
269✔
1707
        return err != cache.ErrElementNotFound
269✔
1708
}
1709

1710
// retransmitStaleAnns examines all outgoing channels that the source node is
1711
// known to maintain to check to see if any of them are "stale". A channel is
1712
// stale iff, the last timestamp of its rebroadcast is older than the
1713
// RebroadcastInterval. We also check if a refreshed node announcement should
1714
// be resent.
1715
func (d *AuthenticatedGossiper) retransmitStaleAnns(ctx context.Context,
1716
        now time.Time) error {
34✔
1717

34✔
1718
        // Iterate over all of our channels and check if any of them fall
34✔
1719
        // within the prune interval or re-broadcast interval.
34✔
1720
        type updateTuple struct {
34✔
1721
                info *models.ChannelEdgeInfo
34✔
1722
                edge *models.ChannelEdgePolicy
34✔
1723
        }
34✔
1724

34✔
1725
        var (
34✔
1726
                havePublicChannels bool
34✔
1727
                edgesToUpdate      []updateTuple
34✔
1728
        )
34✔
1729
        err := d.cfg.Graph.ForAllOutgoingChannels(ctx, func(
34✔
1730
                info *models.ChannelEdgeInfo,
34✔
1731
                edge *models.ChannelEdgePolicy) error {
39✔
1732

5✔
1733
                // If there's no auth proof attached to this edge, it means
5✔
1734
                // that it is a private channel not meant to be announced to
5✔
1735
                // the greater network, so avoid sending channel updates for
5✔
1736
                // this channel to not leak its
5✔
1737
                // existence.
5✔
1738
                if info.AuthProof == nil {
9✔
1739
                        log.Debugf("Skipping retransmission of channel "+
4✔
1740
                                "without AuthProof: %v", info.ChannelID)
4✔
1741
                        return nil
4✔
1742
                }
4✔
1743

1744
                // We make a note that we have at least one public channel. We
1745
                // use this to determine whether we should send a node
1746
                // announcement below.
1747
                havePublicChannels = true
4✔
1748

4✔
1749
                // If this edge has a ChannelUpdate that was created before the
4✔
1750
                // introduction of the MaxHTLC field, then we'll update this
4✔
1751
                // edge to propagate this information in the network.
4✔
1752
                if !edge.MessageFlags.HasMaxHtlc() {
4✔
1753
                        // We'll make sure we support the new max_htlc field if
×
1754
                        // not already present.
×
1755
                        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
×
1756
                        edge.MaxHTLC = lnwire.NewMSatFromSatoshis(info.Capacity)
×
1757

×
1758
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1759
                                info: info,
×
1760
                                edge: edge,
×
1761
                        })
×
1762
                        return nil
×
1763
                }
×
1764

1765
                timeElapsed := now.Sub(edge.LastUpdate)
4✔
1766

4✔
1767
                // If it's been longer than RebroadcastInterval since we've
4✔
1768
                // re-broadcasted the channel, add the channel to the set of
4✔
1769
                // edges we need to update.
4✔
1770
                if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1771
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1772
                                info: info,
1✔
1773
                                edge: edge,
1✔
1774
                        })
1✔
1775
                }
1✔
1776

1777
                return nil
4✔
1778
        }, func() {
3✔
1779
                havePublicChannels = false
3✔
1780
                edgesToUpdate = nil
3✔
1781
        })
3✔
1782
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
34✔
1783
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1784
                        err)
×
1785
        }
×
1786

1787
        var signedUpdates []lnwire.Message
34✔
1788
        for _, chanToUpdate := range edgesToUpdate {
35✔
1789
                // Re-sign and update the channel on disk and retrieve our
1✔
1790
                // ChannelUpdate to broadcast.
1✔
1791
                chanAnn, chanUpdate, err := d.updateChannel(
1✔
1792
                        ctx, chanToUpdate.info, chanToUpdate.edge,
1✔
1793
                )
1✔
1794
                if err != nil {
1✔
1795
                        return fmt.Errorf("unable to update channel: %w", err)
×
1796
                }
×
1797

1798
                // If we have a valid announcement to transmit, then we'll send
1799
                // that along with the update.
1800
                if chanAnn != nil {
2✔
1801
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1802
                }
1✔
1803

1804
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1805
        }
1806

1807
        // If we don't have any public channels, we return as we don't want to
1808
        // broadcast anything that would reveal our existence.
1809
        if !havePublicChannels {
67✔
1810
                return nil
33✔
1811
        }
33✔
1812

1813
        // We'll also check that our NodeAnnouncement is not too old.
1814
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
4✔
1815
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
4✔
1816
        timeElapsed := now.Sub(timestamp)
4✔
1817

4✔
1818
        // If it's been a full day since we've re-broadcasted the
4✔
1819
        // node announcement, refresh it and resend it.
4✔
1820
        nodeAnnStr := ""
4✔
1821
        if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1822
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
1✔
1823
                if err != nil {
1✔
1824
                        return fmt.Errorf("unable to get refreshed node "+
×
1825
                                "announcement: %v", err)
×
1826
                }
×
1827

1828
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1829
                nodeAnnStr = " and our refreshed node announcement"
1✔
1830

1✔
1831
                // Before broadcasting the refreshed node announcement, add it
1✔
1832
                // to our own graph.
1✔
1833
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
2✔
1834
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1835
                                "to graph: %v", err)
1✔
1836
                }
1✔
1837
        }
1838

1839
        // If we don't have any updates to re-broadcast, then we'll exit
1840
        // early.
1841
        if len(signedUpdates) == 0 {
7✔
1842
                return nil
3✔
1843
        }
3✔
1844

1845
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1846
                len(edgesToUpdate), nodeAnnStr)
1✔
1847

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

1854
        return nil
1✔
1855
}
1856

1857
// processChanPolicyUpdate generates a new set of channel updates for the
1858
// provided list of edges and updates the backing ChannelGraphSource.
1859
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1860
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
4✔
1861

4✔
1862
        var chanUpdates []networkMsg
4✔
1863
        for _, edgeInfo := range edgesToUpdate {
10✔
1864
                // Now that we've collected all the channels we need to update,
6✔
1865
                // we'll re-sign and update the backing ChannelGraphSource, and
6✔
1866
                // retrieve our ChannelUpdate to broadcast.
6✔
1867
                _, chanUpdate, err := d.updateChannel(
6✔
1868
                        ctx, edgeInfo.Info, edgeInfo.Edge,
6✔
1869
                )
6✔
1870
                if err != nil {
6✔
1871
                        return nil, err
×
1872
                }
×
1873

1874
                // We'll avoid broadcasting any updates for private channels to
1875
                // avoid directly giving away their existence. Instead, we'll
1876
                // send the update directly to the remote party.
1877
                if edgeInfo.Info.AuthProof == nil {
10✔
1878
                        // If AuthProof is nil and an alias was found for this
4✔
1879
                        // ChannelID (meaning the option-scid-alias feature was
4✔
1880
                        // negotiated), we'll replace the ShortChannelID in the
4✔
1881
                        // update with the peer's alias. We do this after
4✔
1882
                        // updateChannel so that the alias isn't persisted to
4✔
1883
                        // the database.
4✔
1884
                        chanID := lnwire.NewChanIDFromOutPoint(
4✔
1885
                                edgeInfo.Info.ChannelPoint,
4✔
1886
                        )
4✔
1887

4✔
1888
                        var defaultAlias lnwire.ShortChannelID
4✔
1889
                        foundAlias, _ := d.cfg.GetAlias(chanID)
4✔
1890
                        if foundAlias != defaultAlias {
7✔
1891
                                chanUpdate.ShortChannelID = foundAlias
3✔
1892

3✔
1893
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
3✔
1894
                                if err != nil {
3✔
1895
                                        log.Errorf("Unable to sign alias "+
×
1896
                                                "update: %v", err)
×
1897
                                        continue
×
1898
                                }
1899

1900
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1901
                                if err != nil {
3✔
1902
                                        log.Errorf("Unable to create sig: %v",
×
1903
                                                err)
×
1904
                                        continue
×
1905
                                }
1906

1907
                                chanUpdate.Signature = lnSig
3✔
1908
                        }
1909

1910
                        remotePubKey := remotePubFromChanInfo(
4✔
1911
                                edgeInfo.Info, chanUpdate.ChannelFlags,
4✔
1912
                        )
4✔
1913
                        err := d.reliableSender.sendMessage(
4✔
1914
                                ctx, chanUpdate, remotePubKey,
4✔
1915
                        )
4✔
1916
                        if err != nil {
4✔
1917
                                log.Errorf("Unable to reliably send %v for "+
×
1918
                                        "channel=%v to peer=%x: %v",
×
1919
                                        chanUpdate.MsgType(),
×
1920
                                        chanUpdate.ShortChannelID,
×
1921
                                        remotePubKey, err)
×
1922
                        }
×
1923
                        continue
4✔
1924
                }
1925

1926
                // We set ourselves as the source of this message to indicate
1927
                // that we shouldn't skip any peers when sending this message.
1928
                chanUpdates = append(chanUpdates, networkMsg{
5✔
1929
                        source:   d.selfKey,
5✔
1930
                        isRemote: false,
5✔
1931
                        msg:      chanUpdate,
5✔
1932
                })
5✔
1933
        }
1934

1935
        return chanUpdates, nil
4✔
1936
}
1937

1938
// remotePubFromChanInfo returns the public key of the remote peer given a
1939
// ChannelEdgeInfo that describe a channel we have with them.
1940
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1941
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
15✔
1942

15✔
1943
        var remotePubKey [33]byte
15✔
1944
        switch {
15✔
1945
        case chanFlags&lnwire.ChanUpdateDirection == 0:
15✔
1946
                remotePubKey = chanInfo.NodeKey2Bytes
15✔
1947
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1948
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1949
        }
1950

1951
        return remotePubKey
15✔
1952
}
1953

1954
// processRejectedEdge examines a rejected edge to see if we can extract any
1955
// new announcements from it.  An edge will get rejected if we already added
1956
// the same edge without AuthProof to the graph. If the received announcement
1957
// contains a proof, we can add this proof to our edge.  We can end up in this
1958
// situation in the case where we create a channel, but for some reason fail
1959
// to receive the remote peer's proof, while the remote peer is able to fully
1960
// assemble the proof and craft the ChannelAnnouncement.
1961
func (d *AuthenticatedGossiper) processRejectedEdge(_ context.Context,
1962
        chanAnnMsg *lnwire.ChannelAnnouncement1,
1963
        proof *models.ChannelAuthProof) ([]networkMsg, error) {
3✔
1964

3✔
1965
        // First, we'll fetch the state of the channel as we know if from the
3✔
1966
        // database.
3✔
1967
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
1968
                chanAnnMsg.ShortChannelID,
3✔
1969
        )
3✔
1970
        if err != nil {
3✔
1971
                return nil, err
×
1972
        }
×
1973

1974
        // The edge is in the graph, and has a proof attached, then we'll just
1975
        // reject it as normal.
1976
        if chanInfo.AuthProof != nil {
6✔
1977
                return nil, nil
3✔
1978
        }
3✔
1979

1980
        // Otherwise, this means that the edge is within the graph, but it
1981
        // doesn't yet have a proper proof attached. If we did not receive
1982
        // the proof such that we now can add it, there's nothing more we
1983
        // can do.
1984
        if proof == nil {
×
1985
                return nil, nil
×
1986
        }
×
1987

1988
        // We'll then create then validate the new fully assembled
1989
        // announcement.
1990
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
×
1991
                proof, chanInfo, e1, e2,
×
1992
        )
×
1993
        if err != nil {
×
1994
                return nil, err
×
1995
        }
×
1996
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
×
1997
        if err != nil {
×
1998
                err := fmt.Errorf("assembled channel announcement proof "+
×
1999
                        "for shortChanID=%v isn't valid: %v",
×
2000
                        chanAnnMsg.ShortChannelID, err)
×
2001
                log.Error(err)
×
2002
                return nil, err
×
2003
        }
×
2004

2005
        // If everything checks out, then we'll add the fully assembled proof
2006
        // to the database.
2007
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
2008
        if err != nil {
×
2009
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
2010
                        chanAnnMsg.ShortChannelID, err)
×
2011
                log.Error(err)
×
2012
                return nil, err
×
2013
        }
×
2014

2015
        // As we now have a complete channel announcement for this channel,
2016
        // we'll construct the announcement so they can be broadcast out to all
2017
        // our peers.
2018
        announcements := make([]networkMsg, 0, 3)
×
2019
        announcements = append(announcements, networkMsg{
×
2020
                source: d.selfKey,
×
2021
                msg:    chanAnn,
×
2022
        })
×
2023
        if e1Ann != nil {
×
2024
                announcements = append(announcements, networkMsg{
×
2025
                        source: d.selfKey,
×
2026
                        msg:    e1Ann,
×
2027
                })
×
2028
        }
×
2029
        if e2Ann != nil {
×
2030
                announcements = append(announcements, networkMsg{
×
2031
                        source: d.selfKey,
×
2032
                        msg:    e2Ann,
×
2033
                })
×
2034

×
2035
        }
×
2036

2037
        return announcements, nil
×
2038
}
2039

2040
// fetchPKScript fetches the output script for the given SCID.
2041
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2042
        []byte, error) {
×
2043

×
2044
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2045
}
×
2046

2047
// addNode processes the given node announcement, and adds it to our channel
2048
// graph.
2049
func (d *AuthenticatedGossiper) addNode(ctx context.Context,
2050
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
20✔
2051

20✔
2052
        if err := netann.ValidateNodeAnn(msg); err != nil {
21✔
2053
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
2054
                        err)
1✔
2055
        }
1✔
2056

2057
        return d.cfg.Graph.AddNode(
19✔
2058
                ctx, models.NodeFromWireAnnouncement(msg), op...,
19✔
2059
        )
19✔
2060
}
2061

2062
// isPremature decides whether a given network message has a block height+delta
2063
// value specified in the future. If so, the message will be added to the
2064
// future message map and be processed when the block height as reached.
2065
//
2066
// NOTE: must be used inside a lock.
2067
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2068
        delta uint32, msg *networkMsg) bool {
292✔
2069

292✔
2070
        // The channel is already confirmed at chanID.BlockHeight so we minus
292✔
2071
        // one block. For instance, if the required confirmation for this
292✔
2072
        // channel announcement is 6, we then only need to wait for 5 more
292✔
2073
        // blocks once the funding tx is confirmed.
292✔
2074
        if delta > 0 {
295✔
2075
                delta--
3✔
2076
        }
3✔
2077

2078
        msgHeight := chanID.BlockHeight + delta
292✔
2079

292✔
2080
        // The message height is smaller or equal to our best known height,
292✔
2081
        // thus the message is mature.
292✔
2082
        if msgHeight <= d.bestHeight {
583✔
2083
                return false
291✔
2084
        }
291✔
2085

2086
        // Add the premature message to our future messages which will be
2087
        // resent once the block height has reached.
2088
        //
2089
        // Copy the networkMsgs since the old message's err chan will be
2090
        // consumed.
2091
        copied := &networkMsg{
4✔
2092
                peer:              msg.peer,
4✔
2093
                source:            msg.source,
4✔
2094
                msg:               msg.msg,
4✔
2095
                optionalMsgFields: msg.optionalMsgFields,
4✔
2096
                isRemote:          msg.isRemote,
4✔
2097
                err:               make(chan error, 1),
4✔
2098
        }
4✔
2099

4✔
2100
        // Create the cached message.
4✔
2101
        cachedMsg := &cachedFutureMsg{
4✔
2102
                msg:    copied,
4✔
2103
                height: msgHeight,
4✔
2104
        }
4✔
2105

4✔
2106
        // Increment the msg ID and add it to the cache.
4✔
2107
        nextMsgID := d.futureMsgs.nextMsgID()
4✔
2108
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
4✔
2109
        if err != nil {
4✔
2110
                log.Errorf("Adding future message got error: %v", err)
×
2111
        }
×
2112

2113
        log.Debugf("Network message: %v added to future messages for "+
4✔
2114
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
4✔
2115
                msgHeight, d.bestHeight)
4✔
2116

4✔
2117
        return true
4✔
2118
}
2119

2120
// processNetworkAnnouncement processes a new network relate authenticated
2121
// channel or node announcement or announcements proofs. If the announcement
2122
// didn't affect the internal state due to either being out of date, invalid,
2123
// or redundant, then nil is returned. Otherwise, the set of announcements will
2124
// be returned which should be broadcasted to the rest of the network. The
2125
// boolean returned indicates whether any dependents of the announcement should
2126
// attempt to be processed as well.
2127
func (d *AuthenticatedGossiper) processNetworkAnnouncement(ctx context.Context,
2128
        nMsg *networkMsg) ([]networkMsg, bool) {
340✔
2129

340✔
2130
        // If this is a remote update, we set the scheduler option to lazily
340✔
2131
        // add it to the graph.
340✔
2132
        var schedulerOp []batch.SchedulerOption
340✔
2133
        if nMsg.isRemote {
633✔
2134
                schedulerOp = append(schedulerOp, batch.LazyAdd())
293✔
2135
        }
293✔
2136

2137
        switch msg := nMsg.msg.(type) {
340✔
2138
        // A new node announcement has arrived which either presents new
2139
        // information about a node in one of the channels we know about, or a
2140
        // updating previously advertised information.
2141
        case *lnwire.NodeAnnouncement:
27✔
2142
                return d.handleNodeAnnouncement(ctx, nMsg, msg, schedulerOp)
27✔
2143

2144
        // A new channel announcement has arrived, this indicates the
2145
        // *creation* of a new channel within the network. This only advertises
2146
        // the existence of a channel and not yet the routing policies in
2147
        // either direction of the channel.
2148
        case *lnwire.ChannelAnnouncement1:
234✔
2149
                return d.handleChanAnnouncement(ctx, nMsg, msg, schedulerOp...)
234✔
2150

2151
        // A new authenticated channel edge update has arrived. This indicates
2152
        // that the directional information for an already known channel has
2153
        // been updated.
2154
        case *lnwire.ChannelUpdate1:
64✔
2155
                return d.handleChanUpdate(ctx, nMsg, msg, schedulerOp)
64✔
2156

2157
        // A new signature announcement has been received. This indicates
2158
        // willingness of nodes involved in the funding of a channel to
2159
        // announce this new channel to the rest of the world.
2160
        case *lnwire.AnnounceSignatures1:
24✔
2161
                return d.handleAnnSig(ctx, nMsg, msg)
24✔
2162

2163
        default:
×
2164
                err := errors.New("wrong type of the announcement")
×
2165
                nMsg.err <- err
×
2166
                return nil, false
×
2167
        }
2168
}
2169

2170
// processZombieUpdate determines whether the provided channel update should
2171
// resurrect a given zombie edge.
2172
//
2173
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2174
// should be inspected.
2175
func (d *AuthenticatedGossiper) processZombieUpdate(_ context.Context,
2176
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2177
        msg *lnwire.ChannelUpdate1) error {
3✔
2178

3✔
2179
        // The least-significant bit in the flag on the channel update tells us
3✔
2180
        // which edge is being updated.
3✔
2181
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2182

3✔
2183
        // Since we've deemed the update as not stale above, before marking it
3✔
2184
        // live, we'll make sure it has been signed by the correct party. If we
3✔
2185
        // have both pubkeys, either party can resurrect the channel. If we've
3✔
2186
        // already marked this with the stricter, single-sided resurrection we
3✔
2187
        // will only have the pubkey of the node with the oldest timestamp.
3✔
2188
        var pubKey *btcec.PublicKey
3✔
2189
        switch {
3✔
2190
        case isNode1 && chanInfo.NodeKey1Bytes != emptyPubkey:
×
2191
                pubKey, _ = chanInfo.NodeKey1()
×
2192
        case !isNode1 && chanInfo.NodeKey2Bytes != emptyPubkey:
2✔
2193
                pubKey, _ = chanInfo.NodeKey2()
2✔
2194
        }
2195
        if pubKey == nil {
4✔
2196
                return fmt.Errorf("incorrect pubkey to resurrect zombie "+
1✔
2197
                        "with chan_id=%v", msg.ShortChannelID)
1✔
2198
        }
1✔
2199

2200
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2201
        if err != nil {
3✔
2202
                return fmt.Errorf("unable to verify channel "+
1✔
2203
                        "update signature: %v", err)
1✔
2204
        }
1✔
2205

2206
        // With the signature valid, we'll proceed to mark the
2207
        // edge as live and wait for the channel announcement to
2208
        // come through again.
2209
        err = d.cfg.Graph.MarkEdgeLive(scid)
1✔
2210
        switch {
1✔
2211
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2212
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2213
                        "zombie index: %v", err)
×
2214

×
2215
                return nil
×
2216

2217
        case err != nil:
×
2218
                return fmt.Errorf("unable to remove edge with "+
×
2219
                        "chan_id=%v from zombie index: %v",
×
2220
                        msg.ShortChannelID, err)
×
2221

2222
        default:
1✔
2223
        }
2224

2225
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2226
                "index", msg.ShortChannelID)
1✔
2227

1✔
2228
        return nil
1✔
2229
}
2230

2231
// fetchNodeAnn fetches the latest signed node announcement from our point of
2232
// view for the node with the given public key. It also validates the node
2233
// announcement fields and returns an error if they are invalid to prevent
2234
// forwarding invalid node announcements to our peers.
2235
func (d *AuthenticatedGossiper) fetchNodeAnn(ctx context.Context,
2236
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
23✔
2237

23✔
2238
        node, err := d.cfg.Graph.FetchNode(ctx, pubKey)
23✔
2239
        if err != nil {
29✔
2240
                return nil, err
6✔
2241
        }
6✔
2242

2243
        nodeAnn, err := node.NodeAnnouncement(true)
17✔
2244
        if err != nil {
20✔
2245
                return nil, err
3✔
2246
        }
3✔
2247

2248
        return nodeAnn, netann.ValidateNodeAnnFields(nodeAnn)
17✔
2249
}
2250

2251
// isMsgStale determines whether a message retrieved from the backing
2252
// MessageStore is seen as stale by the current graph.
2253
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2254
        msg lnwire.Message) bool {
15✔
2255

15✔
2256
        switch msg := msg.(type) {
15✔
2257
        case *lnwire.AnnounceSignatures1:
5✔
2258
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
5✔
2259
                        msg.ShortChannelID,
5✔
2260
                )
5✔
2261

5✔
2262
                // If the channel cannot be found, it is most likely a leftover
5✔
2263
                // message for a channel that was closed, so we can consider it
5✔
2264
                // stale.
5✔
2265
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
8✔
2266
                        return true
3✔
2267
                }
3✔
2268
                if err != nil {
5✔
2269
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2270
                                "%v", msg.ShortChannelID, err)
×
2271
                        return false
×
2272
                }
×
2273

2274
                // If the proof exists in the graph, then we have successfully
2275
                // received the remote proof and assembled the full proof, so we
2276
                // can safely delete the local proof from the database.
2277
                return chanInfo.AuthProof != nil
5✔
2278

2279
        case *lnwire.ChannelUpdate1:
13✔
2280
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
13✔
2281

13✔
2282
                // If the channel cannot be found, it is most likely a leftover
13✔
2283
                // message for a channel that was closed, so we can consider it
13✔
2284
                // stale.
13✔
2285
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
16✔
2286
                        return true
3✔
2287
                }
3✔
2288
                if err != nil {
13✔
2289
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2290
                                "%v", msg.ShortChannelID, err)
×
2291
                        return false
×
2292
                }
×
2293

2294
                // Otherwise, we'll retrieve the correct policy that we
2295
                // currently have stored within our graph to check if this
2296
                // message is stale by comparing its timestamp.
2297
                var p *models.ChannelEdgePolicy
13✔
2298
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
26✔
2299
                        p = p1
13✔
2300
                } else {
16✔
2301
                        p = p2
3✔
2302
                }
3✔
2303

2304
                // If the policy is still unknown, then we can consider this
2305
                // policy fresh.
2306
                if p == nil {
13✔
2307
                        return false
×
2308
                }
×
2309

2310
                timestamp := time.Unix(int64(msg.Timestamp), 0)
13✔
2311
                return p.LastUpdate.After(timestamp)
13✔
2312

2313
        default:
×
2314
                // We'll make sure to not mark any unsupported messages as stale
×
2315
                // to ensure they are not removed.
×
2316
                return false
×
2317
        }
2318
}
2319

2320
// updateChannel creates a new fully signed update for the channel, and updates
2321
// the underlying graph with the new state.
2322
func (d *AuthenticatedGossiper) updateChannel(ctx context.Context,
2323
        info *models.ChannelEdgeInfo,
2324
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2325
        *lnwire.ChannelUpdate1, error) {
7✔
2326

7✔
2327
        // Parse the unsigned edge into a channel update.
7✔
2328
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
7✔
2329

7✔
2330
        // We'll generate a new signature over a digest of the channel
7✔
2331
        // announcement itself and update the timestamp to ensure it propagate.
7✔
2332
        err := netann.SignChannelUpdate(
7✔
2333
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
7✔
2334
                netann.ChanUpdSetTimestamp,
7✔
2335
        )
7✔
2336
        if err != nil {
7✔
2337
                return nil, nil, err
×
2338
        }
×
2339

2340
        // Next, we'll set the new signature in place, and update the reference
2341
        // in the backing slice.
2342
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
7✔
2343
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
7✔
2344

7✔
2345
        // To ensure that our signature is valid, we'll verify it ourself
7✔
2346
        // before committing it to the slice returned.
7✔
2347
        err = netann.ValidateChannelUpdateAnn(
7✔
2348
                d.selfKey, info.Capacity, chanUpdate,
7✔
2349
        )
7✔
2350
        if err != nil {
7✔
2351
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2352
                        "update sig: %v", err)
×
2353
        }
×
2354

2355
        // Finally, we'll write the new edge policy to disk.
2356
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
7✔
2357
                return nil, nil, err
×
2358
        }
×
2359

2360
        // We'll also create the original channel announcement so the two can
2361
        // be broadcast along side each other (if necessary), but only if we
2362
        // have a full channel announcement for this channel.
2363
        var chanAnn *lnwire.ChannelAnnouncement1
7✔
2364
        if info.AuthProof != nil {
13✔
2365
                chanID := lnwire.NewShortChanIDFromInt(info.ChannelID)
6✔
2366
                chanAnn = &lnwire.ChannelAnnouncement1{
6✔
2367
                        ShortChannelID:  chanID,
6✔
2368
                        NodeID1:         info.NodeKey1Bytes,
6✔
2369
                        NodeID2:         info.NodeKey2Bytes,
6✔
2370
                        ChainHash:       info.ChainHash,
6✔
2371
                        BitcoinKey1:     info.BitcoinKey1Bytes,
6✔
2372
                        Features:        lnwire.NewRawFeatureVector(),
6✔
2373
                        BitcoinKey2:     info.BitcoinKey2Bytes,
6✔
2374
                        ExtraOpaqueData: info.ExtraOpaqueData,
6✔
2375
                }
6✔
2376
                chanAnn.NodeSig1, err = lnwire.NewSigFromECDSARawSignature(
6✔
2377
                        info.AuthProof.NodeSig1Bytes,
6✔
2378
                )
6✔
2379
                if err != nil {
6✔
2380
                        return nil, nil, err
×
2381
                }
×
2382
                chanAnn.NodeSig2, err = lnwire.NewSigFromECDSARawSignature(
6✔
2383
                        info.AuthProof.NodeSig2Bytes,
6✔
2384
                )
6✔
2385
                if err != nil {
6✔
2386
                        return nil, nil, err
×
2387
                }
×
2388
                chanAnn.BitcoinSig1, err = lnwire.NewSigFromECDSARawSignature(
6✔
2389
                        info.AuthProof.BitcoinSig1Bytes,
6✔
2390
                )
6✔
2391
                if err != nil {
6✔
2392
                        return nil, nil, err
×
2393
                }
×
2394
                chanAnn.BitcoinSig2, err = lnwire.NewSigFromECDSARawSignature(
6✔
2395
                        info.AuthProof.BitcoinSig2Bytes,
6✔
2396
                )
6✔
2397
                if err != nil {
6✔
2398
                        return nil, nil, err
×
2399
                }
×
2400
        }
2401

2402
        return chanAnn, chanUpdate, err
7✔
2403
}
2404

2405
// SyncManager returns the gossiper's SyncManager instance.
2406
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2407
        return d.syncMgr
3✔
2408
}
3✔
2409

2410
// IsKeepAliveUpdate determines whether this channel update is considered a
2411
// keep-alive update based on the previous channel update processed for the same
2412
// direction.
2413
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2414
        prev *models.ChannelEdgePolicy) bool {
20✔
2415

20✔
2416
        // Both updates should be from the same direction.
20✔
2417
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
20✔
2418
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
20✔
2419

×
2420
                return false
×
2421
        }
×
2422

2423
        // The timestamp should always increase for a keep-alive update.
2424
        timestamp := time.Unix(int64(update.Timestamp), 0)
20✔
2425
        if !timestamp.After(prev.LastUpdate) {
20✔
2426
                return false
×
2427
        }
×
2428

2429
        // None of the remaining fields should change for a keep-alive update.
2430
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
23✔
2431
                return false
3✔
2432
        }
3✔
2433
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
38✔
2434
                return false
18✔
2435
        }
18✔
2436
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
8✔
2437
                return false
3✔
2438
        }
3✔
2439
        if update.TimeLockDelta != prev.TimeLockDelta {
5✔
2440
                return false
×
2441
        }
×
2442
        if update.HtlcMinimumMsat != prev.MinHTLC {
5✔
2443
                return false
×
2444
        }
×
2445
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
5✔
2446
                return false
×
2447
        }
×
2448
        if update.HtlcMaximumMsat != prev.MaxHTLC {
5✔
2449
                return false
×
2450
        }
×
2451
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
8✔
2452
                return false
3✔
2453
        }
3✔
2454
        return true
5✔
2455
}
2456

2457
// latestHeight returns the gossiper's latest height known of the chain.
2458
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2459
        d.Lock()
3✔
2460
        defer d.Unlock()
3✔
2461
        return d.bestHeight
3✔
2462
}
3✔
2463

2464
// handleNodeAnnouncement processes a new node announcement.
2465
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2466
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2467
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
27✔
2468

27✔
2469
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
27✔
2470

27✔
2471
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
27✔
2472
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
27✔
2473
                nMsg.source.SerializeCompressed())
27✔
2474

27✔
2475
        // We'll quickly ask the router if it already has a newer update for
27✔
2476
        // this node so we can skip validating signatures if not required.
27✔
2477
        if d.cfg.Graph.IsStaleNode(ctx, nodeAnn.NodeID, timestamp) {
38✔
2478
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
11✔
2479
                nMsg.err <- nil
11✔
2480
                return nil, true
11✔
2481
        }
11✔
2482

2483
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
22✔
2484
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2485
                        err)
3✔
2486

3✔
2487
                if !graph.IsError(
3✔
2488
                        err,
3✔
2489
                        graph.ErrOutdated,
3✔
2490
                        graph.ErrIgnored,
3✔
2491
                ) {
3✔
2492

×
2493
                        log.Error(err)
×
2494
                }
×
2495

2496
                nMsg.err <- err
3✔
2497
                return nil, false
3✔
2498
        }
2499

2500
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2501
        // quick check to ensure this node intends to publicly advertise itself
2502
        // to the network.
2503
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
19✔
2504
        if err != nil {
19✔
2505
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2506
                        nodeAnn.NodeID, err)
×
2507
                nMsg.err <- err
×
2508
                return nil, false
×
2509
        }
×
2510

2511
        var announcements []networkMsg
19✔
2512

19✔
2513
        // If it does, we'll add their announcement to our batch so that it can
19✔
2514
        // be broadcast to the rest of our peers.
19✔
2515
        if isPublic {
25✔
2516
                announcements = append(announcements, networkMsg{
6✔
2517
                        peer:     nMsg.peer,
6✔
2518
                        isRemote: nMsg.isRemote,
6✔
2519
                        source:   nMsg.source,
6✔
2520
                        msg:      nodeAnn,
6✔
2521
                })
6✔
2522
        } else {
22✔
2523
                log.Tracef("Skipping broadcasting node announcement for %x "+
16✔
2524
                        "due to being unadvertised", nodeAnn.NodeID)
16✔
2525
        }
16✔
2526

2527
        nMsg.err <- nil
19✔
2528
        // TODO(roasbeef): get rid of the above
19✔
2529

19✔
2530
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
19✔
2531
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
19✔
2532
                nMsg.source.SerializeCompressed())
19✔
2533

19✔
2534
        return announcements, true
19✔
2535
}
2536

2537
// handleChanAnnouncement processes a new channel announcement.
2538
//
2539
//nolint:funlen
2540
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2541
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2542
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
237✔
2543

237✔
2544
        scid := ann.ShortChannelID
237✔
2545

237✔
2546
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
237✔
2547
                nMsg.peer, scid.ToUint64())
237✔
2548

237✔
2549
        // We'll ignore any channel announcements that target any chain other
237✔
2550
        // than the set of chains we know of.
237✔
2551
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
237✔
2552
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2553
                        ", gossiper on chain=%v", ann.ChainHash,
×
2554
                        d.cfg.ChainHash)
×
2555
                log.Errorf(err.Error())
×
2556

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

×
2563
                nMsg.err <- err
×
2564
                return nil, false
×
2565
        }
×
2566

2567
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2568
        // reject the announcement. Since the router accepts alias SCIDs,
2569
        // not erroring out would be a DoS vector.
2570
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
237✔
2571
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2572
                log.Errorf(err.Error())
×
2573

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

×
2580
                nMsg.err <- err
×
2581
                return nil, false
×
2582
        }
×
2583

2584
        // If the advertised inclusionary block is beyond our knowledge of the
2585
        // chain tip, then we'll ignore it for now.
2586
        d.Lock()
237✔
2587
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
238✔
2588
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2589
                        "advertises height %v, only height %v is known",
1✔
2590
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2591
                d.Unlock()
1✔
2592
                nMsg.err <- nil
1✔
2593
                return nil, false
1✔
2594
        }
1✔
2595
        d.Unlock()
236✔
2596

236✔
2597
        // At this point, we'll now ask the router if this is a zombie/known
236✔
2598
        // edge. If so we can skip all the processing below.
236✔
2599
        if d.cfg.Graph.IsKnownEdge(scid) {
240✔
2600
                nMsg.err <- nil
4✔
2601
                return nil, true
4✔
2602
        }
4✔
2603

2604
        // Check if the channel is already closed in which case we can ignore
2605
        // it.
2606
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
235✔
2607
        if err != nil {
235✔
2608
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2609
                        err)
×
2610
                nMsg.err <- err
×
2611

×
2612
                return nil, false
×
2613
        }
×
2614

2615
        if closed {
236✔
2616
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2617

1✔
2618
                // If this is an announcement from us, we'll just ignore it.
1✔
2619
                if !nMsg.isRemote {
1✔
2620
                        nMsg.err <- err
×
2621
                        return nil, false
×
2622
                }
×
2623

2624
                log.Warnf("Increasing ban score for peer=%v due to outdated "+
1✔
2625
                        "channel announcement for channel %v", nMsg.peer, scid)
1✔
2626

1✔
2627
                // Increment the peer's ban score if they are sending closed
1✔
2628
                // channel announcements.
1✔
2629
                dcErr := d.handleBadPeer(nMsg.peer)
1✔
2630
                if dcErr != nil {
1✔
2631
                        err = dcErr
×
2632
                }
×
2633

2634
                nMsg.err <- err
1✔
2635

1✔
2636
                return nil, false
1✔
2637
        }
2638

2639
        // If this is a remote channel announcement, then we'll validate all
2640
        // the signatures within the proof as it should be well formed.
2641
        var proof *models.ChannelAuthProof
234✔
2642
        if nMsg.isRemote {
454✔
2643
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
220✔
2644
                if err != nil {
220✔
2645
                        err := fmt.Errorf("unable to validate announcement: "+
×
2646
                                "%v", err)
×
2647

×
2648
                        key := newRejectCacheKey(
×
2649
                                scid.ToUint64(),
×
2650
                                sourceToPub(nMsg.source),
×
2651
                        )
×
2652
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2653

×
2654
                        log.Error(err)
×
2655
                        nMsg.err <- err
×
2656
                        return nil, false
×
2657
                }
×
2658

2659
                // If the proof checks out, then we'll save the proof itself to
2660
                // the database so we can fetch it later when gossiping with
2661
                // other nodes.
2662
                proof = &models.ChannelAuthProof{
220✔
2663
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
220✔
2664
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
220✔
2665
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
220✔
2666
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
220✔
2667
                }
220✔
2668
        }
2669

2670
        // With the proof validated (if necessary), we can now store it within
2671
        // the database for our path finding and syncing needs.
2672
        edge := &models.ChannelEdgeInfo{
234✔
2673
                ChannelID:        scid.ToUint64(),
234✔
2674
                ChainHash:        ann.ChainHash,
234✔
2675
                NodeKey1Bytes:    ann.NodeID1,
234✔
2676
                NodeKey2Bytes:    ann.NodeID2,
234✔
2677
                BitcoinKey1Bytes: ann.BitcoinKey1,
234✔
2678
                BitcoinKey2Bytes: ann.BitcoinKey2,
234✔
2679
                AuthProof:        proof,
234✔
2680
                Features: lnwire.NewFeatureVector(
234✔
2681
                        ann.Features, lnwire.Features,
234✔
2682
                ),
234✔
2683
                ExtraOpaqueData: ann.ExtraOpaqueData,
234✔
2684
        }
234✔
2685

234✔
2686
        // If there were any optional message fields provided, we'll include
234✔
2687
        // them in its serialized disk representation now.
234✔
2688
        var tapscriptRoot fn.Option[chainhash.Hash]
234✔
2689
        if nMsg.optionalMsgFields != nil {
251✔
2690
                if nMsg.optionalMsgFields.capacity != nil {
21✔
2691
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
4✔
2692
                }
4✔
2693
                if nMsg.optionalMsgFields.channelPoint != nil {
24✔
2694
                        cp := *nMsg.optionalMsgFields.channelPoint
7✔
2695
                        edge.ChannelPoint = cp
7✔
2696
                }
7✔
2697

2698
                // Optional tapscript root for custom channels.
2699
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
17✔
2700
        }
2701

2702
        // Before we start validation or add the edge to the database, we obtain
2703
        // the mutex for this channel ID. We do this to ensure no other
2704
        // goroutine has read the database and is now making decisions based on
2705
        // this DB state, before it writes to the DB. It also ensures that we
2706
        // don't perform the expensive validation check on the same channel
2707
        // announcement at the same time.
2708
        d.channelMtx.Lock(scid.ToUint64())
234✔
2709

234✔
2710
        // If AssumeChannelValid is present, then we are unable to perform any
234✔
2711
        // of the expensive checks below, so we'll short-circuit our path
234✔
2712
        // straight to adding the edge to our graph. If the passed
234✔
2713
        // ShortChannelID is an alias, then we'll skip validation as it will
234✔
2714
        // not map to a legitimate tx. This is not a DoS vector as only we can
234✔
2715
        // add an alias ChannelAnnouncement from the gossiper.
234✔
2716
        if !(d.cfg.AssumeChannelValid || d.cfg.IsAlias(scid)) {
466✔
2717
                op, capacity, script, err := d.validateFundingTransaction(
232✔
2718
                        ctx, ann, tapscriptRoot,
232✔
2719
                )
232✔
2720
                if err != nil {
436✔
2721
                        defer d.channelMtx.Unlock(scid.ToUint64())
204✔
2722

204✔
2723
                        switch {
204✔
2724
                        case errors.Is(err, ErrNoFundingTransaction),
2725
                                errors.Is(err, ErrInvalidFundingOutput):
202✔
2726

202✔
2727
                                key := newRejectCacheKey(
202✔
2728
                                        scid.ToUint64(),
202✔
2729
                                        sourceToPub(nMsg.source),
202✔
2730
                                )
202✔
2731
                                _, _ = d.recentRejects.Put(
202✔
2732
                                        key, &cachedReject{},
202✔
2733
                                )
202✔
2734

2735
                        case errors.Is(err, ErrChannelSpent):
2✔
2736
                                key := newRejectCacheKey(
2✔
2737
                                        scid.ToUint64(),
2✔
2738
                                        sourceToPub(nMsg.source),
2✔
2739
                                )
2✔
2740
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
2✔
2741

2✔
2742
                                // Since this channel has already been closed,
2✔
2743
                                // we'll add it to the graph's closed channel
2✔
2744
                                // index such that we won't attempt to do
2✔
2745
                                // expensive validation checks on it again.
2✔
2746
                                // TODO: Populate the ScidCloser by using closed
2✔
2747
                                // channel notifications.
2✔
2748
                                dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
2✔
2749
                                if dbErr != nil {
2✔
2750
                                        log.Errorf("failed to mark scid(%v) "+
×
2751
                                                "as closed: %v", scid, dbErr)
×
2752

×
2753
                                        nMsg.err <- dbErr
×
2754

×
2755
                                        return nil, false
×
2756
                                }
×
2757

2758
                        default:
×
2759
                                // Otherwise, this is just a regular rejected
×
2760
                                // edge. We won't increase the ban score for the
×
2761
                                // remote peer.
×
2762
                                key := newRejectCacheKey(
×
2763
                                        scid.ToUint64(),
×
2764
                                        sourceToPub(nMsg.source),
×
2765
                                )
×
2766
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2767

×
2768
                                nMsg.err <- err
×
2769

×
2770
                                return nil, false
×
2771
                        }
2772

2773
                        if !nMsg.isRemote {
204✔
2774
                                log.Errorf("failed to add edge for local "+
×
2775
                                        "channel: %v", err)
×
2776
                                nMsg.err <- err
×
2777

×
2778
                                return nil, false
×
2779
                        }
×
2780

2781
                        log.Warnf("Increasing ban score for peer=%v due to "+
204✔
2782
                                "invalid channel announcement for channel %v",
204✔
2783
                                nMsg.peer, scid)
204✔
2784

204✔
2785
                        // Increment the peer's ban score if they are sending
204✔
2786
                        // us invalid channel announcements.
204✔
2787
                        dcErr := d.handleBadPeer(nMsg.peer)
204✔
2788
                        if dcErr != nil {
204✔
2789
                                err = dcErr
×
2790
                        }
×
2791

2792
                        nMsg.err <- err
204✔
2793

204✔
2794
                        return nil, false
204✔
2795
                }
2796

2797
                edge.FundingScript = fn.Some(script)
28✔
2798

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

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

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

4✔
2815
                defer d.channelMtx.Unlock(scid.ToUint64())
4✔
2816

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

×
2832
                                nMsg.err <- rErr
×
2833

×
2834
                                return nil, false
×
2835
                        }
×
2836

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

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

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

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

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

×
2863
                        return nil, false
×
2864
                }
×
2865

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

×
2872
                        return nil, false
×
2873
                }
×
2874

2875
                if shouldDc {
1✔
2876
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2877
                }
×
2878

2879
                nMsg.err <- err
1✔
2880

1✔
2881
                return nil, false
1✔
2882
        }
2883

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

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

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

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

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

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

5✔
2916
                d.wg.Add(1)
5✔
2917
                go func(updMsg *networkMsg) {
10✔
2918
                        defer d.wg.Done()
5✔
2919

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

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

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

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

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

2957
        nMsg.err <- nil
29✔
2958

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

29✔
2962
        return announcements, true
29✔
2963
}
2964

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

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

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

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

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

2992
        blockHeight := upd.ShortChannelID.BlockHeight
64✔
2993
        shortChanID := upd.ShortChannelID.ToUint64()
64✔
2994

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

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

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

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

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

64✔
3036
        if d.cfg.Graph.IsStaleEdgePolicy(
64✔
3037
                graphScid, timestamp, upd.ChannelFlags,
64✔
3038
        ) {
70✔
3039

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

6✔
3045
                nMsg.err <- nil
6✔
3046
                return nil, true
6✔
3047
        }
6✔
3048

3049
        // Check that the ChanUpdate is not too far into the future, this could
3050
        // reveal some faulty implementation therefore we log an error.
3051
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
61✔
3052
                err := fmt.Errorf("skewed timestamp of edge policy, "+
×
3053
                        "timestamp too far in the future: %v", timestamp.Unix())
×
3054

×
3055
                // If this is a channel_update from us, we'll just ignore it.
×
3056
                if !nMsg.isRemote {
×
3057
                        nMsg.err <- err
×
3058
                        return nil, false
×
3059
                }
×
3060

3061
                log.Errorf("Increasing ban score for peer=%v due to bad "+
×
3062
                        "channel_update with short_chan_id(%v): timestamp(%v) "+
×
3063
                        "too far in the future", nMsg.peer, shortChanID,
×
3064
                        timestamp.Unix())
×
3065

×
3066
                // Increment the peer's ban score if they are skewed channel
×
3067
                // updates.
×
3068
                dcErr := d.handleBadPeer(nMsg.peer)
×
3069
                if dcErr != nil {
×
3070
                        err = dcErr
×
3071
                }
×
3072

3073
                nMsg.err <- err
×
3074

×
3075
                return nil, false
×
3076
        }
3077

3078
        // Get the node pub key as far since we don't have it in the channel
3079
        // update announcement message. We'll need this to properly verify the
3080
        // message's signature.
3081
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
61✔
3082
        switch {
61✔
3083
        // No error, break.
3084
        case err == nil:
57✔
3085
                break
57✔
3086

3087
        case errors.Is(err, graphdb.ErrZombieEdge):
3✔
3088
                err = d.processZombieUpdate(ctx, chanInfo, graphScid, upd)
3✔
3089
                if err != nil {
5✔
3090
                        log.Debug(err)
2✔
3091
                        nMsg.err <- err
2✔
3092
                        return nil, false
2✔
3093
                }
2✔
3094

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

5✔
3124
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
5✔
3125
                switch {
5✔
3126
                // Nothing in the cache yet, we can just directly insert this
3127
                // element.
3128
                case err == cache.ErrElementNotFound:
5✔
3129
                        _, _ = d.prematureChannelUpdates.Put(
5✔
3130
                                shortChanID, &cachedNetworkMsg{
5✔
3131
                                        msgs: []*processedNetworkMsg{pMsg},
5✔
3132
                                })
5✔
3133

3134
                // There's already something in the cache, so we'll combine the
3135
                // set of messages into a single value.
3136
                default:
3✔
3137
                        msgs := earlyMsgs.msgs
3✔
3138
                        msgs = append(msgs, pMsg)
3✔
3139
                        _, _ = d.prematureChannelUpdates.Put(
3✔
3140
                                shortChanID, &cachedNetworkMsg{
3✔
3141
                                        msgs: msgs,
3✔
3142
                                })
3✔
3143
                }
3144

3145
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
5✔
3146
                        "(shortChanID=%v), saving for reprocessing later",
5✔
3147
                        shortChanID)
5✔
3148

5✔
3149
                // NOTE: We don't return anything on the error channel for this
5✔
3150
                // message, as we expect that will be done when this
5✔
3151
                // ChannelUpdate is later reprocessed. This might never happen
5✔
3152
                // if the corresponding ChannelAnnouncement is never received
5✔
3153
                // or the LRU cache is filled up and the entry is evicted.
5✔
3154
                return nil, false
5✔
3155

3156
        default:
×
3157
                err := fmt.Errorf("unable to validate channel update "+
×
3158
                        "short_chan_id=%v: %v", shortChanID, err)
×
3159
                log.Error(err)
×
3160
                nMsg.err <- err
×
3161

×
3162
                key := newRejectCacheKey(
×
3163
                        upd.ShortChannelID.ToUint64(),
×
3164
                        sourceToPub(nMsg.source),
×
3165
                )
×
3166
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3167

×
3168
                return nil, false
×
3169
        }
3170

3171
        // The least-significant bit in the flag on the channel update
3172
        // announcement tells us "which" side of the channels directed edge is
3173
        // being updated.
3174
        var (
57✔
3175
                pubKey       *btcec.PublicKey
57✔
3176
                edgeToUpdate *models.ChannelEdgePolicy
57✔
3177
        )
57✔
3178
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
57✔
3179
        switch direction {
57✔
3180
        case 0:
41✔
3181
                pubKey, _ = chanInfo.NodeKey1()
41✔
3182
                edgeToUpdate = e1
41✔
3183
        case 1:
19✔
3184
                pubKey, _ = chanInfo.NodeKey2()
19✔
3185
                edgeToUpdate = e2
19✔
3186
        }
3187

3188
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
57✔
3189
                "edge policy=%v", chanInfo.ChannelID,
57✔
3190
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
57✔
3191

57✔
3192
        // Validate the channel announcement with the expected public key and
57✔
3193
        // channel capacity. In the case of an invalid channel update, we'll
57✔
3194
        // return an error to the caller and exit early.
57✔
3195
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
57✔
3196
        if err != nil {
61✔
3197
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3198
                        "announcement for short_chan_id=%v: %v",
4✔
3199
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3200

4✔
3201
                log.Error(rErr)
4✔
3202
                nMsg.err <- rErr
4✔
3203
                return nil, false
4✔
3204
        }
4✔
3205

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

18✔
3248
                        if !rls[direction].Allow() {
27✔
3249
                                log.Debugf("Rate limiting update for channel "+
9✔
3250
                                        "%v from direction %x", shortChanID,
9✔
3251
                                        pubKey.SerializeCompressed())
9✔
3252
                                nMsg.err <- nil
9✔
3253
                                return nil, false
9✔
3254
                        }
9✔
3255
                }
3256
        }
3257

3258
        // We'll use chanInfo.ChannelID rather than the peer-supplied
3259
        // ShortChannelID in the ChannelUpdate to avoid the router having to
3260
        // lookup the stored SCID. If we're sending the update, we'll always
3261
        // use the SCID stored in the database rather than a potentially
3262
        // different alias. This might mean that SigBytes is incorrect as it
3263
        // signs a different SCID than the database SCID, but since there will
3264
        // only be a difference if AuthProof == nil, this is fine.
3265
        update := &models.ChannelEdgePolicy{
46✔
3266
                SigBytes:                  upd.Signature.ToSignatureBytes(),
46✔
3267
                ChannelID:                 chanInfo.ChannelID,
46✔
3268
                LastUpdate:                timestamp,
46✔
3269
                MessageFlags:              upd.MessageFlags,
46✔
3270
                ChannelFlags:              upd.ChannelFlags,
46✔
3271
                TimeLockDelta:             upd.TimeLockDelta,
46✔
3272
                MinHTLC:                   upd.HtlcMinimumMsat,
46✔
3273
                MaxHTLC:                   upd.HtlcMaximumMsat,
46✔
3274
                FeeBaseMSat:               lnwire.MilliSatoshi(upd.BaseFee),
46✔
3275
                FeeProportionalMillionths: lnwire.MilliSatoshi(upd.FeeRate),
46✔
3276
                InboundFee:                upd.InboundFee.ValOpt(),
46✔
3277
                ExtraOpaqueData:           upd.ExtraOpaqueData,
46✔
3278
        }
46✔
3279

46✔
3280
        if err := d.cfg.Graph.UpdateEdge(ctx, update, ops...); err != nil {
46✔
3281
                if graph.IsError(
×
3282
                        err, graph.ErrOutdated,
×
3283
                        graph.ErrIgnored,
×
3284
                ) {
×
3285

×
3286
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
×
3287
                                shortChanID, err)
×
3288
                } else {
×
3289
                        // Since we know the stored SCID in the graph, we'll
×
3290
                        // cache that SCID.
×
3291
                        key := newRejectCacheKey(
×
3292
                                chanInfo.ChannelID,
×
3293
                                sourceToPub(nMsg.source),
×
3294
                        )
×
3295
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3296

×
3297
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3298
                                shortChanID, err)
×
3299
                }
×
3300

3301
                nMsg.err <- err
×
3302
                return nil, false
×
3303
        }
3304

3305
        // If this is a local ChannelUpdate without an AuthProof, it means it
3306
        // is an update to a channel that is not (yet) supposed to be announced
3307
        // to the greater network. However, our channel counter party will need
3308
        // to be given the update, so we'll try sending the update directly to
3309
        // the remote peer.
3310
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
60✔
3311
                if nMsg.optionalMsgFields != nil {
28✔
3312
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
14✔
3313
                        if remoteAlias != nil {
17✔
3314
                                // The remoteAlias field was specified, meaning
3✔
3315
                                // that we should replace the SCID in the
3✔
3316
                                // update with the remote's alias. We'll also
3✔
3317
                                // need to re-sign the channel update. This is
3✔
3318
                                // required for option-scid-alias feature-bit
3✔
3319
                                // negotiated channels.
3✔
3320
                                upd.ShortChannelID = *remoteAlias
3✔
3321

3✔
3322
                                sig, err := d.cfg.SignAliasUpdate(upd)
3✔
3323
                                if err != nil {
3✔
3324
                                        log.Error(err)
×
3325
                                        nMsg.err <- err
×
3326
                                        return nil, false
×
3327
                                }
×
3328

3329
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
3330
                                if err != nil {
3✔
3331
                                        log.Error(err)
×
3332
                                        nMsg.err <- err
×
3333
                                        return nil, false
×
3334
                                }
×
3335

3336
                                upd.Signature = lnSig
3✔
3337
                        }
3338
                }
3339

3340
                // Get our peer's public key.
3341
                remotePubKey := remotePubFromChanInfo(
14✔
3342
                        chanInfo, upd.ChannelFlags,
14✔
3343
                )
14✔
3344

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

14✔
3348
                // Now we'll attempt to send the channel update message
14✔
3349
                // reliably to the remote peer in the background, so that we
14✔
3350
                // don't block if the peer happens to be offline at the moment.
14✔
3351
                err := d.reliableSender.sendMessage(ctx, upd, remotePubKey)
14✔
3352
                if err != nil {
14✔
3353
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3354
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3355
                                upd.ShortChannelID, remotePubKey, err)
×
3356
                        nMsg.err <- err
×
3357
                        return nil, false
×
3358
                }
×
3359
        }
3360

3361
        // Channel update announcement was successfully processed and now it
3362
        // can be broadcast to the rest of the network. However, we'll only
3363
        // broadcast the channel update announcement if it has an attached
3364
        // authentication proof. We also won't broadcast the update if it
3365
        // contains an alias because the network would reject this.
3366
        var announcements []networkMsg
46✔
3367
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
72✔
3368
                announcements = append(announcements, networkMsg{
26✔
3369
                        peer:     nMsg.peer,
26✔
3370
                        source:   nMsg.source,
26✔
3371
                        isRemote: nMsg.isRemote,
26✔
3372
                        msg:      upd,
26✔
3373
                })
26✔
3374
        }
26✔
3375

3376
        nMsg.err <- nil
46✔
3377

46✔
3378
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
46✔
3379
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
46✔
3380
                timestamp)
46✔
3381
        return announcements, true
46✔
3382
}
3383

3384
// handleAnnSig processes a new announcement signatures message.
3385
//
3386
//nolint:funlen
3387
func (d *AuthenticatedGossiper) handleAnnSig(ctx context.Context,
3388
        nMsg *networkMsg, ann *lnwire.AnnounceSignatures1) ([]networkMsg,
3389
        bool) {
24✔
3390

24✔
3391
        needBlockHeight := ann.ShortChannelID.BlockHeight +
24✔
3392
                d.cfg.ProofMatureDelta
24✔
3393
        shortChanID := ann.ShortChannelID.ToUint64()
24✔
3394

24✔
3395
        prefix := "local"
24✔
3396
        if nMsg.isRemote {
38✔
3397
                prefix = "remote"
14✔
3398
        }
14✔
3399

3400
        log.Infof("Received new %v announcement signature for %v", prefix,
24✔
3401
                ann.ShortChannelID)
24✔
3402

24✔
3403
        // By the specification, channel announcement proofs should be sent
24✔
3404
        // after some number of confirmations after channel was registered in
24✔
3405
        // bitcoin blockchain. Therefore, we check if the proof is mature.
24✔
3406
        d.Lock()
24✔
3407
        premature := d.isPremature(
24✔
3408
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
24✔
3409
        )
24✔
3410
        if premature {
27✔
3411
                log.Warnf("Premature proof announcement, current block height"+
3✔
3412
                        "lower than needed: %v < %v", d.bestHeight,
3✔
3413
                        needBlockHeight)
3✔
3414
                d.Unlock()
3✔
3415
                nMsg.err <- nil
3✔
3416
                return nil, false
3✔
3417
        }
3✔
3418
        d.Unlock()
24✔
3419

24✔
3420
        // Ensure that we know of a channel with the target channel ID before
24✔
3421
        // proceeding further.
24✔
3422
        //
24✔
3423
        // We must acquire the mutex for this channel ID before getting the
24✔
3424
        // channel from the database, to ensure what we read does not change
24✔
3425
        // before we call AddProof() later.
24✔
3426
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
24✔
3427
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
24✔
3428

24✔
3429
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
24✔
3430
                ann.ShortChannelID,
24✔
3431
        )
24✔
3432
        if err != nil {
28✔
3433
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
4✔
3434
                if err != nil {
7✔
3435
                        err := fmt.Errorf("unable to store the proof for "+
3✔
3436
                                "short_chan_id=%v: %v", shortChanID, err)
3✔
3437
                        log.Error(err)
3✔
3438
                        nMsg.err <- err
3✔
3439

3✔
3440
                        return nil, false
3✔
3441
                }
3✔
3442

3443
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
4✔
3444
                err := d.cfg.WaitingProofStore.Add(proof)
4✔
3445
                if err != nil {
4✔
3446
                        err := fmt.Errorf("unable to store the proof for "+
×
3447
                                "short_chan_id=%v: %v", shortChanID, err)
×
3448
                        log.Error(err)
×
3449
                        nMsg.err <- err
×
3450
                        return nil, false
×
3451
                }
×
3452

3453
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
4✔
3454
                        ", adding to waiting batch", prefix, shortChanID)
4✔
3455
                nMsg.err <- nil
4✔
3456
                return nil, false
4✔
3457
        }
3458

3459
        nodeID := nMsg.source.SerializeCompressed()
23✔
3460
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
23✔
3461
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
23✔
3462

23✔
3463
        // Ensure that channel that was retrieved belongs to the peer which
23✔
3464
        // sent the proof announcement.
23✔
3465
        if !(isFirstNode || isSecondNode) {
23✔
3466
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3467
                        "to the peer which sent the proof, short_chan_id=%v",
×
3468
                        shortChanID)
×
3469
                log.Error(err)
×
3470
                nMsg.err <- err
×
3471
                return nil, false
×
3472
        }
×
3473

3474
        // If proof was sent by a local sub-system, then we'll send the
3475
        // announcement signature to the remote node so they can also
3476
        // reconstruct the full channel announcement.
3477
        if !nMsg.isRemote {
36✔
3478
                var remotePubKey [33]byte
13✔
3479
                if isFirstNode {
26✔
3480
                        remotePubKey = chanInfo.NodeKey2Bytes
13✔
3481
                } else {
16✔
3482
                        remotePubKey = chanInfo.NodeKey1Bytes
3✔
3483
                }
3✔
3484

3485
                // Since the remote peer might not be online we'll call a
3486
                // method that will attempt to deliver the proof when it comes
3487
                // online.
3488
                err := d.reliableSender.sendMessage(ctx, ann, remotePubKey)
13✔
3489
                if err != nil {
13✔
3490
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3491
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3492
                                ann.ShortChannelID, remotePubKey, err)
×
3493
                        nMsg.err <- err
×
3494
                        return nil, false
×
3495
                }
×
3496
        }
3497

3498
        // Check if we already have the full proof for this channel.
3499
        if chanInfo.AuthProof != nil {
27✔
3500
                // If we already have the fully assembled proof, then the peer
4✔
3501
                // sending us their proof has probably not received our local
4✔
3502
                // proof yet. So be kind and send them the full proof.
4✔
3503
                if nMsg.isRemote {
8✔
3504
                        peerID := nMsg.source.SerializeCompressed()
4✔
3505
                        log.Debugf("Got AnnounceSignatures for channel with " +
4✔
3506
                                "full proof.")
4✔
3507

4✔
3508
                        d.wg.Add(1)
4✔
3509
                        go func() {
8✔
3510
                                defer d.wg.Done()
4✔
3511

4✔
3512
                                log.Debugf("Received half proof for channel "+
4✔
3513
                                        "%v with existing full proof. Sending"+
4✔
3514
                                        " full proof to peer=%x",
4✔
3515
                                        ann.ChannelID, peerID)
4✔
3516

4✔
3517
                                ca, _, _, err := netann.CreateChanAnnouncement(
4✔
3518
                                        chanInfo.AuthProof, chanInfo, e1, e2,
4✔
3519
                                )
4✔
3520
                                if err != nil {
4✔
3521
                                        log.Errorf("unable to gen ann: %v",
×
3522
                                                err)
×
3523
                                        return
×
3524
                                }
×
3525

3526
                                err = nMsg.peer.SendMessage(false, ca)
4✔
3527
                                if err != nil {
4✔
3528
                                        log.Errorf("Failed sending full proof"+
×
3529
                                                " to peer=%x: %v", peerID, err)
×
3530
                                        return
×
3531
                                }
×
3532

3533
                                log.Debugf("Full proof sent to peer=%x for "+
4✔
3534
                                        "chanID=%v", peerID, ann.ChannelID)
4✔
3535
                        }()
3536
                }
3537

3538
                log.Debugf("Already have proof for channel with chanID=%v",
4✔
3539
                        ann.ChannelID)
4✔
3540
                nMsg.err <- nil
4✔
3541
                return nil, true
4✔
3542
        }
3543

3544
        // Check that we received the opposite proof. If so, then we're now
3545
        // able to construct the full proof, and create the channel
3546
        // announcement. If we didn't receive the opposite half of the proof
3547
        // then we should store this one, and wait for the opposite to be
3548
        // received.
3549
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
22✔
3550
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
22✔
3551
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
22✔
3552
                err := fmt.Errorf("unable to get the opposite proof for "+
×
3553
                        "short_chan_id=%v: %v", shortChanID, err)
×
3554
                log.Error(err)
×
3555
                nMsg.err <- err
×
3556
                return nil, false
×
3557
        }
×
3558

3559
        if err == channeldb.ErrWaitingProofNotFound {
34✔
3560
                err := d.cfg.WaitingProofStore.Add(proof)
12✔
3561
                if err != nil {
12✔
3562
                        err := fmt.Errorf("unable to store the proof for "+
×
3563
                                "short_chan_id=%v: %v", shortChanID, err)
×
3564
                        log.Error(err)
×
3565
                        nMsg.err <- err
×
3566
                        return nil, false
×
3567
                }
×
3568

3569
                log.Infof("1/2 of channel ann proof received for "+
12✔
3570
                        "short_chan_id=%v, waiting for other half",
12✔
3571
                        shortChanID)
12✔
3572

12✔
3573
                nMsg.err <- nil
12✔
3574
                return nil, false
12✔
3575
        }
3576

3577
        // We now have both halves of the channel announcement proof, then
3578
        // we'll reconstruct the initial announcement so we can validate it
3579
        // shortly below.
3580
        var dbProof models.ChannelAuthProof
13✔
3581
        if isFirstNode {
17✔
3582
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
4✔
3583
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
4✔
3584
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
4✔
3585
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
4✔
3586
        } else {
16✔
3587
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
12✔
3588
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
12✔
3589
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
12✔
3590
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
12✔
3591
        }
12✔
3592

3593
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
13✔
3594
                &dbProof, chanInfo, e1, e2,
13✔
3595
        )
13✔
3596
        if err != nil {
13✔
3597
                log.Error(err)
×
3598
                nMsg.err <- err
×
3599
                return nil, false
×
3600
        }
×
3601

3602
        // With all the necessary components assembled validate the full
3603
        // channel announcement proof.
3604
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
13✔
3605
        if err != nil {
13✔
3606
                err := fmt.Errorf("channel announcement proof for "+
×
3607
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3608

×
3609
                log.Error(err)
×
3610
                nMsg.err <- err
×
3611
                return nil, false
×
3612
        }
×
3613

3614
        // If the channel was returned by the router it means that existence of
3615
        // funding point and inclusion of nodes bitcoin keys in it already
3616
        // checked by the router. In this stage we should check that node keys
3617
        // attest to the bitcoin keys by validating the signatures of
3618
        // announcement. If proof is valid then we'll populate the channel edge
3619
        // with it, so we can announce it on peer connect.
3620
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
13✔
3621
        if err != nil {
13✔
3622
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
3623
                        " %v", ann.ChannelID, err)
×
3624
                log.Error(err)
×
3625
                nMsg.err <- err
×
3626
                return nil, false
×
3627
        }
×
3628

3629
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
13✔
3630
        if err != nil {
13✔
3631
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3632
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3633
                log.Error(err)
×
3634
                nMsg.err <- err
×
3635
                return nil, false
×
3636
        }
×
3637

3638
        // Proof was successfully created and now can announce the channel to
3639
        // the remain network.
3640
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
13✔
3641
                ", adding to next ann batch", shortChanID)
13✔
3642

13✔
3643
        // Assemble the necessary announcements to add to the next broadcasting
13✔
3644
        // batch.
13✔
3645
        var announcements []networkMsg
13✔
3646
        announcements = append(announcements, networkMsg{
13✔
3647
                peer:   nMsg.peer,
13✔
3648
                source: nMsg.source,
13✔
3649
                msg:    chanAnn,
13✔
3650
        })
13✔
3651
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
25✔
3652
                announcements = append(announcements, networkMsg{
12✔
3653
                        peer:   nMsg.peer,
12✔
3654
                        source: src,
12✔
3655
                        msg:    e1Ann,
12✔
3656
                })
12✔
3657
        }
12✔
3658
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
24✔
3659
                announcements = append(announcements, networkMsg{
11✔
3660
                        peer:   nMsg.peer,
11✔
3661
                        source: src,
11✔
3662
                        msg:    e2Ann,
11✔
3663
                })
11✔
3664
        }
11✔
3665

3666
        // We'll also send along the node announcements for each channel
3667
        // participant if we know of them. To ensure our node announcement
3668
        // propagates to our channel counterparty, we'll set the source for
3669
        // each announcement to the node it belongs to, otherwise we won't send
3670
        // it since the source gets skipped. This isn't necessary for channel
3671
        // updates and announcement signatures since we send those directly to
3672
        // our channel counterparty through the gossiper's reliable sender.
3673
        node1Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey1Bytes)
13✔
3674
        if err != nil {
18✔
3675
                log.Debugf("Unable to fetch node announcement for %x: %v",
5✔
3676
                        chanInfo.NodeKey1Bytes, err)
5✔
3677
        } else {
16✔
3678
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
22✔
3679
                        announcements = append(announcements, networkMsg{
11✔
3680
                                peer:   nMsg.peer,
11✔
3681
                                source: nodeKey1,
11✔
3682
                                msg:    node1Ann,
11✔
3683
                        })
11✔
3684
                }
11✔
3685
        }
3686

3687
        node2Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey2Bytes)
13✔
3688
        if err != nil {
20✔
3689
                log.Debugf("Unable to fetch node announcement for %x: %v",
7✔
3690
                        chanInfo.NodeKey2Bytes, err)
7✔
3691
        } else {
16✔
3692
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
18✔
3693
                        announcements = append(announcements, networkMsg{
9✔
3694
                                peer:   nMsg.peer,
9✔
3695
                                source: nodeKey2,
9✔
3696
                                msg:    node2Ann,
9✔
3697
                        })
9✔
3698
                }
9✔
3699
        }
3700

3701
        nMsg.err <- nil
13✔
3702
        return announcements, true
13✔
3703
}
3704

3705
// isBanned returns true if the peer identified by pubkey is banned for sending
3706
// invalid channel announcements.
3707
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
211✔
3708
        return d.banman.isBanned(pubkey)
211✔
3709
}
211✔
3710

3711
// ShouldDisconnect returns true if we should disconnect the peer identified by
3712
// pubkey.
3713
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3714
        bool, error) {
209✔
3715

209✔
3716
        pubkeySer := pubkey.SerializeCompressed()
209✔
3717

209✔
3718
        var pubkeyBytes [33]byte
209✔
3719
        copy(pubkeyBytes[:], pubkeySer)
209✔
3720

209✔
3721
        // If the public key is banned, check whether or not this is a channel
209✔
3722
        // peer.
209✔
3723
        if d.isBanned(pubkeyBytes) {
211✔
3724
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3725
                if err != nil {
2✔
3726
                        return false, err
×
3727
                }
×
3728

3729
                // We should only disconnect non-channel peers.
3730
                if !isChanPeer {
3✔
3731
                        return true, nil
1✔
3732
                }
1✔
3733
        }
3734

3735
        return false, nil
208✔
3736
}
3737

3738
// validateFundingTransaction fetches the channel announcements claimed funding
3739
// transaction from chain to ensure that it exists, is not spent and matches
3740
// the channel announcement proof. The transaction's outpoint and value are
3741
// returned if we can glean them from the work done in this method.
3742
func (d *AuthenticatedGossiper) validateFundingTransaction(_ context.Context,
3743
        ann *lnwire.ChannelAnnouncement1,
3744
        tapscriptRoot fn.Option[chainhash.Hash]) (wire.OutPoint, btcutil.Amount,
3745
        []byte, error) {
232✔
3746

232✔
3747
        scid := ann.ShortChannelID
232✔
3748

232✔
3749
        // Before we can add the channel to the channel graph, we need to obtain
232✔
3750
        // the full funding outpoint that's encoded within the channel ID.
232✔
3751
        fundingTx, err := lnwallet.FetchFundingTxWrapper(
232✔
3752
                d.cfg.ChainIO, &scid, d.quit,
232✔
3753
        )
232✔
3754
        if err != nil {
233✔
3755
                //nolint:ll
1✔
3756
                //
1✔
3757
                // In order to ensure we don't erroneously mark a channel as a
1✔
3758
                // zombie due to an RPC failure, we'll attempt to string match
1✔
3759
                // for the relevant errors.
1✔
3760
                //
1✔
3761
                // * btcd:
1✔
3762
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
1✔
3763
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
1✔
3764
                // * bitcoind:
1✔
3765
                //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
1✔
3766
                //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
1✔
3767
                switch {
1✔
3768
                case strings.Contains(err.Error(), "not found"):
1✔
3769
                        fallthrough
1✔
3770

3771
                case strings.Contains(err.Error(), "out of range"):
1✔
3772
                        // If the funding transaction isn't found at all, then
1✔
3773
                        // we'll mark the edge itself as a zombie so we don't
1✔
3774
                        // continue to request it. We use the "zero key" for
1✔
3775
                        // both node pubkeys so this edge can't be resurrected.
1✔
3776
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
1✔
3777
                        if zErr != nil {
1✔
3778
                                return wire.OutPoint{}, 0, nil, zErr
×
3779
                        }
×
3780

3781
                default:
×
3782
                }
3783

3784
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
1✔
3785
                        ErrNoFundingTransaction, err)
1✔
3786
        }
3787

3788
        // Recreate witness output to be sure that declared in channel edge
3789
        // bitcoin keys and channel value corresponds to the reality.
3790
        fundingPkScript, err := makeFundingScript(
231✔
3791
                ann.BitcoinKey1[:], ann.BitcoinKey2[:], ann.Features,
231✔
3792
                tapscriptRoot,
231✔
3793
        )
231✔
3794
        if err != nil {
231✔
3795
                return wire.OutPoint{}, 0, nil, err
×
3796
        }
×
3797

3798
        // Next we'll validate that this channel is actually well formed. If
3799
        // this check fails, then this channel either doesn't exist, or isn't
3800
        // the one that was meant to be created according to the passed channel
3801
        // proofs.
3802
        fundingPoint, err := chanvalidate.Validate(
231✔
3803
                &chanvalidate.Context{
231✔
3804
                        Locator: &chanvalidate.ShortChanIDChanLocator{
231✔
3805
                                ID: scid,
231✔
3806
                        },
231✔
3807
                        MultiSigPkScript: fundingPkScript,
231✔
3808
                        FundingTx:        fundingTx,
231✔
3809
                },
231✔
3810
        )
231✔
3811
        if err != nil {
432✔
3812
                // Mark the edge as a zombie so we won't try to re-validate it
201✔
3813
                // on start up.
201✔
3814
                zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
201✔
3815
                if zErr != nil {
201✔
3816
                        return wire.OutPoint{}, 0, nil, zErr
×
3817
                }
×
3818

3819
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
201✔
3820
                        ErrInvalidFundingOutput, err)
201✔
3821
        }
3822

3823
        // Now that we have the funding outpoint of the channel, ensure
3824
        // that it hasn't yet been spent. If so, then this channel has
3825
        // been closed so we'll ignore it.
3826
        chanUtxo, err := d.cfg.ChainIO.GetUtxo(
30✔
3827
                fundingPoint, fundingPkScript, scid.BlockHeight, d.quit,
30✔
3828
        )
30✔
3829
        if err != nil {
32✔
3830
                if errors.Is(err, btcwallet.ErrOutputSpent) {
4✔
3831
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
2✔
3832
                        if zErr != nil {
2✔
3833
                                return wire.OutPoint{}, 0, nil, zErr
×
3834
                        }
×
3835
                }
3836

3837
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: unable to "+
2✔
3838
                        "fetch utxo for chan_id=%v, chan_point=%v: %w",
2✔
3839
                        ErrChannelSpent, scid.ToUint64(), fundingPoint, err)
2✔
3840
        }
3841

3842
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
28✔
3843
                nil
28✔
3844
}
3845

3846
// handleBadPeer takes a misbehaving peer and increases its ban score. Once
3847
// increased, it will disconnect the peer if its ban score has reached
3848
// `banThreshold` and it doesn't have a channel with us.
3849
func (d *AuthenticatedGossiper) handleBadPeer(peer lnpeer.Peer) error {
205✔
3850
        // Increment the peer's ban score for misbehavior.
205✔
3851
        d.banman.incrementBanScore(peer.PubKey())
205✔
3852

205✔
3853
        // If the peer is banned and not a channel peer, we'll disconnect them.
205✔
3854
        shouldDc, dcErr := d.ShouldDisconnect(peer.IdentityKey())
205✔
3855
        if dcErr != nil {
205✔
3856
                log.Errorf("failed to check if we should disconnect peer: %v",
×
3857
                        dcErr)
×
3858

×
3859
                return dcErr
×
3860
        }
×
3861

3862
        if shouldDc {
206✔
3863
                peer.Disconnect(ErrPeerBanned)
1✔
3864
        }
1✔
3865

3866
        return nil
205✔
3867
}
3868

3869
// makeFundingScript is used to make the funding script for both segwit v0 and
3870
// segwit v1 (taproot) channels.
3871
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3872
        features *lnwire.RawFeatureVector,
3873
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
231✔
3874

231✔
3875
        legacyFundingScript := func() ([]byte, error) {
462✔
3876
                witnessScript, err := input.GenMultiSigScript(
231✔
3877
                        bitcoinKey1, bitcoinKey2,
231✔
3878
                )
231✔
3879
                if err != nil {
231✔
3880
                        return nil, err
×
3881
                }
×
3882
                pkScript, err := input.WitnessScriptHash(witnessScript)
231✔
3883
                if err != nil {
231✔
3884
                        return nil, err
×
3885
                }
×
3886

3887
                return pkScript, nil
231✔
3888
        }
3889

3890
        if features.IsEmpty() {
462✔
3891
                return legacyFundingScript()
231✔
3892
        }
231✔
3893

3894
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
3✔
3895
        if chanFeatureBits.HasFeature(
3✔
3896
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
3897
        ) {
6✔
3898

3✔
3899
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
3900
                if err != nil {
3✔
3901
                        return nil, err
×
3902
                }
×
3903
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
3904
                if err != nil {
3✔
3905
                        return nil, err
×
3906
                }
×
3907

3908
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
3909
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
3910
                )
3✔
3911
                if err != nil {
3✔
3912
                        return nil, err
×
3913
                }
×
3914

3915
                // TODO(roasbeef): add tapscript root to gossip v1.5
3916

3917
                return fundingScript, nil
3✔
3918
        }
3919

3920
        return legacyFundingScript()
×
3921
}
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