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

lightningnetwork / lnd / 16984045337

15 Aug 2025 05:53AM UTC coverage: 66.726% (-0.03%) from 66.758%
16984045337

Pull #9455

github

web-flow
Merge 6b38f8d9d into 3841d5554
Pull Request #9455: [1/2] discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

209 of 304 new or added lines in 8 files covered. (68.75%)

89 existing lines in 18 files now uncovered.

135980 of 203789 relevant lines covered (66.73%)

21467.08 hits per line

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

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

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

416
// cachedNetworkMsg is a wrapper around a network message that can be used with
417
// *lru.Cache.
418
//
419
// NOTE: This struct is not thread safe which means you need to assure no
420
// concurrent read write access to it and all its contents which are pointers
421
// as well.
422
type cachedNetworkMsg struct {
423
        msgs []*processedNetworkMsg
424
}
425

426
// Size returns the "size" of an entry. We return the number of items as we
427
// just want to limit the total amount of entries rather than do accurate size
428
// accounting.
429
func (c *cachedNetworkMsg) Size() (uint64, error) {
5✔
430
        return uint64(len(c.msgs)), nil
5✔
431
}
5✔
432

433
// rejectCacheKey is the cache key that we'll use to track announcements we've
434
// recently rejected.
435
type rejectCacheKey struct {
436
        pubkey [33]byte
437
        chanID uint64
438
}
439

440
// newRejectCacheKey returns a new cache key for the reject cache.
441
func newRejectCacheKey(cid uint64, pub [33]byte) rejectCacheKey {
475✔
442
        k := rejectCacheKey{
475✔
443
                chanID: cid,
475✔
444
                pubkey: pub,
475✔
445
        }
475✔
446

475✔
447
        return k
475✔
448
}
475✔
449

450
// sourceToPub returns a serialized-compressed public key for use in the reject
451
// cache.
452
func sourceToPub(pk *btcec.PublicKey) [33]byte {
489✔
453
        var pub [33]byte
489✔
454
        copy(pub[:], pk.SerializeCompressed())
489✔
455
        return pub
489✔
456
}
489✔
457

458
// cachedReject is the empty value used to track the value for rejects.
459
type cachedReject struct {
460
}
461

462
// Size returns the "size" of an entry. We return 1 as we just want to limit
463
// the total size.
464
func (c *cachedReject) Size() (uint64, error) {
206✔
465
        return 1, nil
206✔
466
}
206✔
467

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

482
        // bestHeight is the height of the block at the tip of the main chain
483
        // as we know it. Accesses *MUST* be done with the gossiper's lock
484
        // held.
485
        bestHeight uint32
486

487
        // cfg is a copy of the configuration struct that the gossiper service
488
        // was initialized with.
489
        cfg *Config
490

491
        // blockEpochs encapsulates a stream of block epochs that are sent at
492
        // every new block height.
493
        blockEpochs *chainntnfs.BlockEpochEvent
494

495
        // prematureChannelUpdates is a map of ChannelUpdates we have received
496
        // that wasn't associated with any channel we know about.  We store
497
        // them temporarily, such that we can reprocess them when a
498
        // ChannelAnnouncement for the channel is received.
499
        prematureChannelUpdates *lru.Cache[uint64, *cachedNetworkMsg]
500

501
        // banman tracks our peer's ban status.
502
        banman *banman
503

504
        // networkMsgs is a channel that carries new network broadcasted
505
        // message from outside the gossiper service to be processed by the
506
        // networkHandler.
507
        networkMsgs chan *networkMsg
508

509
        // futureMsgs is a list of premature network messages that have a block
510
        // height specified in the future. We will save them and resend it to
511
        // the chan networkMsgs once the block height has reached. The cached
512
        // map format is,
513
        //   {msgID1: msg1, msgID2: msg2, ...}
514
        futureMsgs *futureMsgCache
515

516
        // chanPolicyUpdates is a channel that requests to update the
517
        // forwarding policy of a set of channels is sent over.
518
        chanPolicyUpdates chan *chanPolicyUpdateRequest
519

520
        // selfKey is the identity public key of the backing Lightning node.
521
        selfKey *btcec.PublicKey
522

523
        // selfKeyLoc is the locator for the identity public key of the backing
524
        // Lightning node.
525
        selfKeyLoc keychain.KeyLocator
526

527
        // channelMtx is used to restrict the database access to one
528
        // goroutine per channel ID. This is done to ensure that when
529
        // the gossiper is handling an announcement, the db state stays
530
        // consistent between when the DB is first read until it's written.
531
        channelMtx *multimutex.Mutex[uint64]
532

533
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
534

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

544
        // reliableSender is a subsystem responsible for handling reliable
545
        // message send requests to peers. This should only be used for channels
546
        // that are unadvertised at the time of handling the message since if it
547
        // is advertised, then peers should be able to get the message from the
548
        // network.
549
        reliableSender *reliableSender
550

551
        // chanUpdateRateLimiter contains rate limiters for each direction of
552
        // a channel update we've processed. We'll use these to determine
553
        // whether we should accept a new update for a specific channel and
554
        // direction.
555
        //
556
        // NOTE: This map must be synchronized with the main
557
        // AuthenticatedGossiper lock.
558
        chanUpdateRateLimiter map[uint64][2]*rate.Limiter
559

560
        // vb is used to enforce job dependency ordering of gossip messages.
561
        vb *ValidationBarrier
562

563
        sync.Mutex
564

565
        cancel fn.Option[context.CancelFunc]
566
        quit   chan struct{}
567
        wg     sync.WaitGroup
568
}
569

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

33✔
592
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
33✔
593

33✔
594
        gossiper.syncMgr = newSyncManager(&SyncManagerCfg{
33✔
595
                ChainHash:                cfg.ChainHash,
33✔
596
                ChanSeries:               cfg.ChanSeries,
33✔
597
                RotateTicker:             cfg.RotateTicker,
33✔
598
                HistoricalSyncTicker:     cfg.HistoricalSyncTicker,
33✔
599
                NumActiveSyncers:         cfg.NumActiveSyncers,
33✔
600
                NoTimestampQueries:       cfg.NoTimestampQueries,
33✔
601
                IgnoreHistoricalFilters:  cfg.IgnoreHistoricalFilters,
33✔
602
                BestHeight:               gossiper.latestHeight,
33✔
603
                PinnedSyncers:            cfg.PinnedSyncers,
33✔
604
                IsStillZombieChannel:     cfg.IsStillZombieChannel,
33✔
605
                AllotedMsgBytesPerSecond: cfg.MsgRateBytes,
33✔
606
                AllotedMsgBytesBurst:     cfg.MsgBurstBytes,
33✔
607
                FilterConcurrency:        cfg.FilterConcurrency,
33✔
608
        })
33✔
609

33✔
610
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
33✔
611
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
33✔
612
                NotifyWhenOffline: cfg.NotifyWhenOffline,
33✔
613
                MessageStore:      cfg.MessageStore,
33✔
614
                IsMsgStale:        gossiper.isMsgStale,
33✔
615
        })
33✔
616

33✔
617
        return gossiper
33✔
618
}
33✔
619

620
// EdgeWithInfo contains the information that is required to update an edge.
621
type EdgeWithInfo struct {
622
        // Info describes the channel.
623
        Info *models.ChannelEdgeInfo
624

625
        // Edge describes the policy in one direction of the channel.
626
        Edge *models.ChannelEdgePolicy
627
}
628

629
// PropagateChanPolicyUpdate signals the AuthenticatedGossiper to perform the
630
// specified edge updates. Updates are done in two stages: first, the
631
// AuthenticatedGossiper ensures the update has been committed by dependent
632
// sub-systems, then it signs and broadcasts new updates to the network. A
633
// mapping between outpoints and updated channel policies is returned, which is
634
// used to update the forwarding policies of the underlying links.
635
func (d *AuthenticatedGossiper) PropagateChanPolicyUpdate(
636
        edgesToUpdate []EdgeWithInfo) error {
4✔
637

4✔
638
        errChan := make(chan error, 1)
4✔
639
        policyUpdate := &chanPolicyUpdateRequest{
4✔
640
                edgesToUpdate: edgesToUpdate,
4✔
641
                errChan:       errChan,
4✔
642
        }
4✔
643

4✔
644
        select {
4✔
645
        case d.chanPolicyUpdates <- policyUpdate:
4✔
646
                err := <-errChan
4✔
647
                return err
4✔
648
        case <-d.quit:
×
649
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
650
        }
651
}
652

653
// Start spawns network messages handler goroutine and registers on new block
654
// notifications in order to properly handle the premature announcements.
655
func (d *AuthenticatedGossiper) Start() error {
33✔
656
        var err error
33✔
657
        d.started.Do(func() {
66✔
658
                ctx, cancel := context.WithCancel(context.Background())
33✔
659
                d.cancel = fn.Some(cancel)
33✔
660

33✔
661
                log.Info("Authenticated Gossiper starting")
33✔
662
                err = d.start(ctx)
33✔
663
        })
33✔
664
        return err
33✔
665
}
666

667
func (d *AuthenticatedGossiper) start(ctx context.Context) error {
33✔
668
        // First we register for new notifications of newly discovered blocks.
33✔
669
        // We do this immediately so we'll later be able to consume any/all
33✔
670
        // blocks which were discovered.
33✔
671
        blockEpochs, err := d.cfg.Notifier.RegisterBlockEpochNtfn(nil)
33✔
672
        if err != nil {
33✔
673
                return err
×
674
        }
×
675
        d.blockEpochs = blockEpochs
33✔
676

33✔
677
        height, err := d.cfg.Graph.CurrentBlockHeight()
33✔
678
        if err != nil {
33✔
679
                return err
×
680
        }
×
681
        d.bestHeight = height
33✔
682

33✔
683
        // Start the reliable sender. In case we had any pending messages ready
33✔
684
        // to be sent when the gossiper was last shut down, we must continue on
33✔
685
        // our quest to deliver them to their respective peers.
33✔
686
        if err := d.reliableSender.Start(); err != nil {
33✔
687
                return err
×
688
        }
×
689

690
        d.syncMgr.Start()
33✔
691

33✔
692
        d.banman.start()
33✔
693

33✔
694
        // Start receiving blocks in its dedicated goroutine.
33✔
695
        d.wg.Add(2)
33✔
696
        go d.syncBlockHeight()
33✔
697
        go d.networkHandler(ctx)
33✔
698

33✔
699
        return nil
33✔
700
}
701

702
// syncBlockHeight syncs the best block height for the gossiper by reading
703
// blockEpochs.
704
//
705
// NOTE: must be run as a goroutine.
706
func (d *AuthenticatedGossiper) syncBlockHeight() {
33✔
707
        defer d.wg.Done()
33✔
708

33✔
709
        for {
66✔
710
                select {
33✔
711
                // A new block has arrived, so we can re-process the previously
712
                // premature announcements.
713
                case newBlock, ok := <-d.blockEpochs.Epochs:
3✔
714
                        // If the channel has been closed, then this indicates
3✔
715
                        // the daemon is shutting down, so we exit ourselves.
3✔
716
                        if !ok {
6✔
717
                                return
3✔
718
                        }
3✔
719

720
                        // Once a new block arrives, we update our running
721
                        // track of the height of the chain tip.
722
                        d.Lock()
3✔
723
                        blockHeight := uint32(newBlock.Height)
3✔
724
                        d.bestHeight = blockHeight
3✔
725
                        d.Unlock()
3✔
726

3✔
727
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
3✔
728
                                newBlock.Hash)
3✔
729

3✔
730
                        // Resend future messages, if any.
3✔
731
                        d.resendFutureMessages(blockHeight)
3✔
732

733
                case <-d.quit:
30✔
734
                        return
30✔
735
                }
736
        }
737
}
738

739
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
740
// the unique ID when saving the message.
741
type futureMsgCache struct {
742
        *lru.Cache[uint64, *cachedFutureMsg]
743

744
        // msgID is a monotonically increased integer.
745
        msgID atomic.Uint64
746
}
747

748
// nextMsgID returns a unique message ID.
749
func (f *futureMsgCache) nextMsgID() uint64 {
6✔
750
        return f.msgID.Add(1)
6✔
751
}
6✔
752

753
// newFutureMsgCache creates a new future message cache with the underlying lru
754
// cache being initialized with the specified capacity.
755
func newFutureMsgCache(capacity uint64) *futureMsgCache {
34✔
756
        // Create a new cache.
34✔
757
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
34✔
758

34✔
759
        return &futureMsgCache{
34✔
760
                Cache: cache,
34✔
761
        }
34✔
762
}
34✔
763

764
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
765
type cachedFutureMsg struct {
766
        // msg is the network message.
767
        msg *networkMsg
768

769
        // height is the block height.
770
        height uint32
771
}
772

773
// Size returns the size of the message.
774
func (c *cachedFutureMsg) Size() (uint64, error) {
7✔
775
        // Return a constant 1.
7✔
776
        return 1, nil
7✔
777
}
7✔
778

779
// resendFutureMessages takes a block height, resends all the future messages
780
// found below and equal to that height and deletes those messages found in the
781
// gossiper's futureMsgs.
782
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
3✔
783
        var (
3✔
784
                // msgs are the target messages.
3✔
785
                msgs []*networkMsg
3✔
786

3✔
787
                // keys are the target messages' caching keys.
3✔
788
                keys []uint64
3✔
789
        )
3✔
790

3✔
791
        // filterMsgs is the visitor used when iterating the future cache.
3✔
792
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
6✔
793
                if cmsg.height <= height {
6✔
794
                        msgs = append(msgs, cmsg.msg)
3✔
795
                        keys = append(keys, k)
3✔
796
                }
3✔
797

798
                return true
3✔
799
        }
800

801
        // Filter out the target messages.
802
        d.futureMsgs.Range(filterMsgs)
3✔
803

3✔
804
        // Return early if no messages found.
3✔
805
        if len(msgs) == 0 {
6✔
806
                return
3✔
807
        }
3✔
808

809
        // Remove the filtered messages.
810
        for _, key := range keys {
6✔
811
                d.futureMsgs.Delete(key)
3✔
812
        }
3✔
813

814
        log.Debugf("Resending %d network messages at height %d",
3✔
815
                len(msgs), height)
3✔
816

3✔
817
        for _, msg := range msgs {
6✔
818
                select {
3✔
819
                case d.networkMsgs <- msg:
3✔
820
                case <-d.quit:
×
821
                        msg.err <- ErrGossiperShuttingDown
×
822
                }
823
        }
824
}
825

826
// Stop signals any active goroutines for a graceful closure.
827
func (d *AuthenticatedGossiper) Stop() error {
34✔
828
        d.stopped.Do(func() {
67✔
829
                log.Info("Authenticated gossiper shutting down...")
33✔
830
                defer log.Debug("Authenticated gossiper shutdown complete")
33✔
831

33✔
832
                d.stop()
33✔
833
        })
33✔
834
        return nil
34✔
835
}
836

837
func (d *AuthenticatedGossiper) stop() {
33✔
838
        log.Debug("Authenticated Gossiper is stopping")
33✔
839
        defer log.Debug("Authenticated Gossiper stopped")
33✔
840

33✔
841
        // `blockEpochs` is only initialized in the start routine so we make
33✔
842
        // sure we don't panic here in the case where the `Stop` method is
33✔
843
        // called when the `Start` method does not complete.
33✔
844
        if d.blockEpochs != nil {
66✔
845
                d.blockEpochs.Cancel()
33✔
846
        }
33✔
847

848
        d.syncMgr.Stop()
33✔
849

33✔
850
        d.banman.stop()
33✔
851

33✔
852
        d.cancel.WhenSome(func(fn context.CancelFunc) { fn() })
66✔
853
        close(d.quit)
33✔
854
        d.wg.Wait()
33✔
855

33✔
856
        // We'll stop our reliable sender after all of the gossiper's goroutines
33✔
857
        // have exited to ensure nothing can cause it to continue executing.
33✔
858
        d.reliableSender.Stop()
33✔
859
}
860

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

864
// ProcessRemoteAnnouncement sends a new remote announcement message along with
865
// the peer that sent the routing message. The announcement will be processed
866
// then added to a queue for batched trickled announcement to all connected
867
// peers.  Remote channel announcements should contain the announcement proof
868
// and be fully validated.
869
func (d *AuthenticatedGossiper) ProcessRemoteAnnouncement(ctx context.Context,
870
        msg lnwire.Message, peer lnpeer.Peer) chan error {
294✔
871

294✔
872
        errChan := make(chan error, 1)
294✔
873

294✔
874
        // For messages in the known set of channel series queries, we'll
294✔
875
        // dispatch the message directly to the GossipSyncer, and skip the main
294✔
876
        // processing loop.
294✔
877
        switch m := msg.(type) {
294✔
878
        case *lnwire.QueryShortChanIDs,
879
                *lnwire.QueryChannelRange,
880
                *lnwire.ReplyChannelRange,
881
                *lnwire.ReplyShortChanIDsEnd:
3✔
882

3✔
883
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
884
                if !ok {
3✔
885
                        log.Warnf("Gossip syncer for peer=%x not found",
×
886
                                peer.PubKey())
×
887

×
888
                        errChan <- ErrGossipSyncerNotFound
×
889
                        return errChan
×
890
                }
×
891

892
                // If we've found the message target, then we'll dispatch the
893
                // message directly to it.
894
                err := syncer.ProcessQueryMsg(m, peer.QuitSignal())
3✔
895
                if err != nil {
3✔
896
                        log.Errorf("Process query msg from peer %x got %v",
×
897
                                peer.PubKey(), err)
×
898
                }
×
899

900
                errChan <- err
3✔
901
                return errChan
3✔
902

903
        // If a peer is updating its current update horizon, then we'll dispatch
904
        // that directly to the proper GossipSyncer.
905
        case *lnwire.GossipTimestampRange:
3✔
906
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
907
                if !ok {
3✔
908
                        log.Warnf("Gossip syncer for peer=%x not found",
×
909
                                peer.PubKey())
×
910

×
911
                        errChan <- ErrGossipSyncerNotFound
×
912
                        return errChan
×
913
                }
×
914

915
                // Queue the message for asynchronous processing to prevent
916
                // blocking the gossiper when rate limiting is active.
917
                if !syncer.QueueTimestampRange(m) {
3✔
918
                        log.Warnf("Unable to queue gossip filter for peer=%x: "+
×
919
                                "queue full", peer.PubKey())
×
920

×
921
                        // Return nil to indicate we've handled the message,
×
922
                        // even though it was dropped. This prevents the peer
×
923
                        // from being disconnected.
×
924
                        errChan <- nil
×
925
                        return errChan
×
926
                }
×
927

928
                errChan <- nil
3✔
929
                return errChan
3✔
930

931
        // To avoid inserting edges in the graph for our own channels that we
932
        // have already closed, we ignore such channel announcements coming
933
        // from the remote.
934
        case *lnwire.ChannelAnnouncement1:
223✔
935
                ownKey := d.selfKey.SerializeCompressed()
223✔
936
                ownErr := fmt.Errorf("ignoring remote ChannelAnnouncement1 " +
223✔
937
                        "for own channel")
223✔
938

223✔
939
                if bytes.Equal(m.NodeID1[:], ownKey) ||
223✔
940
                        bytes.Equal(m.NodeID2[:], ownKey) {
228✔
941

5✔
942
                        log.Warn(ownErr)
5✔
943
                        errChan <- ownErr
5✔
944
                        return errChan
5✔
945
                }
5✔
946
        }
947

948
        nMsg := &networkMsg{
292✔
949
                msg:      msg,
292✔
950
                isRemote: true,
292✔
951
                peer:     peer,
292✔
952
                source:   peer.IdentityKey(),
292✔
953
                err:      errChan,
292✔
954
        }
292✔
955

292✔
956
        select {
292✔
957
        case d.networkMsgs <- nMsg:
292✔
958

959
        // If the peer that sent us this error is quitting, then we don't need
960
        // to send back an error and can return immediately.
961
        // TODO(elle): the peer should now just rely on canceling the passed
962
        //  context.
963
        case <-peer.QuitSignal():
×
964
                return nil
×
965
        case <-ctx.Done():
×
966
                return nil
×
967
        case <-d.quit:
×
968
                nMsg.err <- ErrGossiperShuttingDown
×
969
        }
970

971
        return nMsg.err
292✔
972
}
973

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

50✔
984
        optionalMsgFields := &optionalMsgFields{}
50✔
985
        optionalMsgFields.apply(optionalFields...)
50✔
986

50✔
987
        nMsg := &networkMsg{
50✔
988
                msg:               msg,
50✔
989
                optionalMsgFields: optionalMsgFields,
50✔
990
                isRemote:          false,
50✔
991
                source:            d.selfKey,
50✔
992
                err:               make(chan error, 1),
50✔
993
        }
50✔
994

50✔
995
        select {
50✔
996
        case d.networkMsgs <- nMsg:
50✔
997
        case <-d.quit:
×
998
                nMsg.err <- ErrGossiperShuttingDown
×
999
        }
1000

1001
        return nMsg.err
50✔
1002
}
1003

1004
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
1005
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
1006
// tuple.
1007
type channelUpdateID struct {
1008
        // channelID represents the set of data which is needed to
1009
        // retrieve all necessary data to validate the channel existence.
1010
        channelID lnwire.ShortChannelID
1011

1012
        // Flags least-significant bit must be set to 0 if the creating node
1013
        // corresponds to the first node in the previously sent channel
1014
        // announcement and 1 otherwise.
1015
        flags lnwire.ChanUpdateChanFlags
1016
}
1017

1018
// msgWithSenders is a wrapper struct around a message, and the set of peers
1019
// that originally sent us this message. Using this struct, we can ensure that
1020
// we don't re-send a message to the peer that sent it to us in the first
1021
// place.
1022
type msgWithSenders struct {
1023
        // msg is the wire message itself.
1024
        msg lnwire.Message
1025

1026
        // isLocal is true if this was a message that originated locally. We'll
1027
        // use this to bypass our normal checks to ensure we prioritize sending
1028
        // out our own updates.
1029
        isLocal bool
1030

1031
        // sender is the set of peers that sent us this message.
1032
        senders map[route.Vertex]struct{}
1033
}
1034

1035
// mergeSyncerMap is used to merge the set of senders of a particular message
1036
// with peers that we have an active GossipSyncer with. We do this to ensure
1037
// that we don't broadcast messages to any peers that we have active gossip
1038
// syncers for.
1039
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
32✔
1040
        for peerPub := range syncers {
35✔
1041
                m.senders[peerPub] = struct{}{}
3✔
1042
        }
3✔
1043
}
1044

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

1056
        // channelUpdates are identified by the channel update id field.
1057
        channelUpdates map[channelUpdateID]msgWithSenders
1058

1059
        // nodeAnnouncements are identified by the Vertex field.
1060
        nodeAnnouncements map[route.Vertex]msgWithSenders
1061

1062
        sync.Mutex
1063
}
1064

1065
// Reset operates on deDupedAnnouncements to reset the storage of
1066
// announcements.
1067
func (d *deDupedAnnouncements) Reset() {
35✔
1068
        d.Lock()
35✔
1069
        defer d.Unlock()
35✔
1070

35✔
1071
        d.reset()
35✔
1072
}
35✔
1073

1074
// reset is the private version of the Reset method. We have this so we can
1075
// call this method within method that are already holding the lock.
1076
func (d *deDupedAnnouncements) reset() {
332✔
1077
        // Storage of each type of announcement (channel announcements, channel
332✔
1078
        // updates, node announcements) is set to an empty map where the
332✔
1079
        // appropriate key points to the corresponding lnwire.Message.
332✔
1080
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
332✔
1081
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
332✔
1082
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
332✔
1083
}
332✔
1084

1085
// addMsg adds a new message to the current batch. If the message is already
1086
// present in the current batch, then this new instance replaces the latter,
1087
// and the set of senders is updated to reflect which node sent us this
1088
// message.
1089
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
94✔
1090
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
94✔
1091

94✔
1092
        // Depending on the message type (channel announcement, channel update,
94✔
1093
        // or node announcement), the message is added to the corresponding map
94✔
1094
        // in deDupedAnnouncements. Because each identifying key can have at
94✔
1095
        // most one value, the announcements are de-duplicated, with newer ones
94✔
1096
        // replacing older ones.
94✔
1097
        switch msg := message.msg.(type) {
94✔
1098

1099
        // Channel announcements are identified by the short channel id field.
1100
        case *lnwire.ChannelAnnouncement1:
26✔
1101
                deDupKey := msg.ShortChannelID
26✔
1102
                sender := route.NewVertex(message.source)
26✔
1103

26✔
1104
                mws, ok := d.channelAnnouncements[deDupKey]
26✔
1105
                if !ok {
51✔
1106
                        mws = msgWithSenders{
25✔
1107
                                msg:     msg,
25✔
1108
                                isLocal: !message.isRemote,
25✔
1109
                                senders: make(map[route.Vertex]struct{}),
25✔
1110
                        }
25✔
1111
                        mws.senders[sender] = struct{}{}
25✔
1112

25✔
1113
                        d.channelAnnouncements[deDupKey] = mws
25✔
1114

25✔
1115
                        return
25✔
1116
                }
25✔
1117

1118
                mws.msg = msg
1✔
1119
                mws.senders[sender] = struct{}{}
1✔
1120
                d.channelAnnouncements[deDupKey] = mws
1✔
1121

1122
        // Channel updates are identified by the (short channel id,
1123
        // channelflags) tuple.
1124
        case *lnwire.ChannelUpdate1:
49✔
1125
                sender := route.NewVertex(message.source)
49✔
1126
                deDupKey := channelUpdateID{
49✔
1127
                        msg.ShortChannelID,
49✔
1128
                        msg.ChannelFlags,
49✔
1129
                }
49✔
1130

49✔
1131
                oldTimestamp := uint32(0)
49✔
1132
                mws, ok := d.channelUpdates[deDupKey]
49✔
1133
                if ok {
52✔
1134
                        // If we already have seen this message, record its
3✔
1135
                        // timestamp.
3✔
1136
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1137
                        if !ok {
3✔
1138
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1139
                                        "got: %T", mws.msg)
×
1140

×
1141
                                return
×
1142
                        }
×
1143

1144
                        oldTimestamp = update.Timestamp
3✔
1145
                }
1146

1147
                // If we already had this message with a strictly newer
1148
                // timestamp, then we'll just discard the message we got.
1149
                if oldTimestamp > msg.Timestamp {
50✔
1150
                        log.Debugf("Ignored outdated network message: "+
1✔
1151
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1152
                        return
1✔
1153
                }
1✔
1154

1155
                // If the message we just got is newer than what we previously
1156
                // have seen, or this is the first time we see it, then we'll
1157
                // add it to our map of announcements.
1158
                if oldTimestamp < msg.Timestamp {
95✔
1159
                        mws = msgWithSenders{
47✔
1160
                                msg:     msg,
47✔
1161
                                isLocal: !message.isRemote,
47✔
1162
                                senders: make(map[route.Vertex]struct{}),
47✔
1163
                        }
47✔
1164

47✔
1165
                        // We'll mark the sender of the message in the
47✔
1166
                        // senders map.
47✔
1167
                        mws.senders[sender] = struct{}{}
47✔
1168

47✔
1169
                        d.channelUpdates[deDupKey] = mws
47✔
1170

47✔
1171
                        return
47✔
1172
                }
47✔
1173

1174
                // Lastly, if we had seen this exact message from before, with
1175
                // the same timestamp, we'll add the sender to the map of
1176
                // senders, such that we can skip sending this message back in
1177
                // the next batch.
1178
                mws.msg = msg
1✔
1179
                mws.senders[sender] = struct{}{}
1✔
1180
                d.channelUpdates[deDupKey] = mws
1✔
1181

1182
        // Node announcements are identified by the Vertex field.  Use the
1183
        // NodeID to create the corresponding Vertex.
1184
        case *lnwire.NodeAnnouncement:
25✔
1185
                sender := route.NewVertex(message.source)
25✔
1186
                deDupKey := route.Vertex(msg.NodeID)
25✔
1187

25✔
1188
                // We do the same for node announcements as we did for channel
25✔
1189
                // updates, as they also carry a timestamp.
25✔
1190
                oldTimestamp := uint32(0)
25✔
1191
                mws, ok := d.nodeAnnouncements[deDupKey]
25✔
1192
                if ok {
33✔
1193
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
8✔
1194
                }
8✔
1195

1196
                // Discard the message if it's old.
1197
                if oldTimestamp > msg.Timestamp {
28✔
1198
                        return
3✔
1199
                }
3✔
1200

1201
                // Replace if it's newer.
1202
                if oldTimestamp < msg.Timestamp {
46✔
1203
                        mws = msgWithSenders{
21✔
1204
                                msg:     msg,
21✔
1205
                                isLocal: !message.isRemote,
21✔
1206
                                senders: make(map[route.Vertex]struct{}),
21✔
1207
                        }
21✔
1208

21✔
1209
                        mws.senders[sender] = struct{}{}
21✔
1210

21✔
1211
                        d.nodeAnnouncements[deDupKey] = mws
21✔
1212

21✔
1213
                        return
21✔
1214
                }
21✔
1215

1216
                // Add to senders map if it's the same as we had.
1217
                mws.msg = msg
7✔
1218
                mws.senders[sender] = struct{}{}
7✔
1219
                d.nodeAnnouncements[deDupKey] = mws
7✔
1220
        }
1221
}
1222

1223
// AddMsgs is a helper method to add multiple messages to the announcement
1224
// batch.
1225
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
62✔
1226
        d.Lock()
62✔
1227
        defer d.Unlock()
62✔
1228

62✔
1229
        for _, msg := range msgs {
156✔
1230
                d.addMsg(msg)
94✔
1231
        }
94✔
1232
}
1233

1234
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1235
// to broadcast next into messages that are locally sourced and those that are
1236
// sourced remotely.
1237
type msgsToBroadcast struct {
1238
        // localMsgs is the set of messages we created locally.
1239
        localMsgs []msgWithSenders
1240

1241
        // remoteMsgs is the set of messages that we received from a remote
1242
        // party.
1243
        remoteMsgs []msgWithSenders
1244
}
1245

1246
// addMsg adds a new message to the appropriate sub-slice.
1247
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
79✔
1248
        if msg.isLocal {
129✔
1249
                m.localMsgs = append(m.localMsgs, msg)
50✔
1250
        } else {
82✔
1251
                m.remoteMsgs = append(m.remoteMsgs, msg)
32✔
1252
        }
32✔
1253
}
1254

1255
// isEmpty returns true if the batch is empty.
1256
func (m *msgsToBroadcast) isEmpty() bool {
299✔
1257
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
299✔
1258
}
299✔
1259

1260
// length returns the length of the combined message set.
1261
func (m *msgsToBroadcast) length() int {
1✔
1262
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1263
}
1✔
1264

1265
// Emit returns the set of de-duplicated announcements to be sent out during
1266
// the next announcement epoch, in the order of channel announcements, channel
1267
// updates, and node announcements. Each message emitted, contains the set of
1268
// peers that sent us the message. This way, we can ensure that we don't waste
1269
// bandwidth by re-sending a message to the peer that sent it to us in the
1270
// first place. Additionally, the set of stored messages are reset.
1271
func (d *deDupedAnnouncements) Emit() msgsToBroadcast {
300✔
1272
        d.Lock()
300✔
1273
        defer d.Unlock()
300✔
1274

300✔
1275
        // Get the total number of announcements.
300✔
1276
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
300✔
1277
                len(d.nodeAnnouncements)
300✔
1278

300✔
1279
        // Create an empty array of lnwire.Messages with a length equal to
300✔
1280
        // the total number of announcements.
300✔
1281
        msgs := msgsToBroadcast{
300✔
1282
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
300✔
1283
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
300✔
1284
        }
300✔
1285

300✔
1286
        // Add the channel announcements to the array first.
300✔
1287
        for _, message := range d.channelAnnouncements {
322✔
1288
                msgs.addMsg(message)
22✔
1289
        }
22✔
1290

1291
        // Then add the channel updates.
1292
        for _, message := range d.channelUpdates {
343✔
1293
                msgs.addMsg(message)
43✔
1294
        }
43✔
1295

1296
        // Finally add the node announcements.
1297
        for _, message := range d.nodeAnnouncements {
320✔
1298
                msgs.addMsg(message)
20✔
1299
        }
20✔
1300

1301
        d.reset()
300✔
1302

300✔
1303
        // Return the array of lnwire.messages.
300✔
1304
        return msgs
300✔
1305
}
1306

1307
// calculateSubBatchSize is a helper function that calculates the size to break
1308
// down the batchSize into.
1309
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1310
        minimumBatchSize, batchSize int) int {
16✔
1311
        if subBatchDelay > totalDelay {
18✔
1312
                return batchSize
2✔
1313
        }
2✔
1314

1315
        subBatchSize := (batchSize*int(subBatchDelay) +
14✔
1316
                int(totalDelay) - 1) / int(totalDelay)
14✔
1317

14✔
1318
        if subBatchSize < minimumBatchSize {
18✔
1319
                return minimumBatchSize
4✔
1320
        }
4✔
1321

1322
        return subBatchSize
10✔
1323
}
1324

1325
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1326
// this variable so the function can be mocked in our test.
1327
var batchSizeCalculator = calculateSubBatchSize
1328

1329
// splitAnnouncementBatches takes an exiting list of announcements and
1330
// decomposes it into sub batches controlled by the `subBatchSize`.
1331
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1332
        announcementBatch []msgWithSenders) [][]msgWithSenders {
78✔
1333

78✔
1334
        subBatchSize := batchSizeCalculator(
78✔
1335
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
78✔
1336
                d.cfg.MinimumBatchSize, len(announcementBatch),
78✔
1337
        )
78✔
1338

78✔
1339
        var splitAnnouncementBatch [][]msgWithSenders
78✔
1340

78✔
1341
        for subBatchSize < len(announcementBatch) {
202✔
1342
                // For slicing with minimal allocation
124✔
1343
                // https://github.com/golang/go/wiki/SliceTricks
124✔
1344
                announcementBatch, splitAnnouncementBatch =
124✔
1345
                        announcementBatch[subBatchSize:],
124✔
1346
                        append(splitAnnouncementBatch,
124✔
1347
                                announcementBatch[0:subBatchSize:subBatchSize])
124✔
1348
        }
124✔
1349
        splitAnnouncementBatch = append(
78✔
1350
                splitAnnouncementBatch, announcementBatch,
78✔
1351
        )
78✔
1352

78✔
1353
        return splitAnnouncementBatch
78✔
1354
}
1355

1356
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1357
// split size, and then sends out all items to the set of target peers. Locally
1358
// generated announcements are always sent before remotely generated
1359
// announcements.
1360
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(ctx context.Context,
1361
        annBatch msgsToBroadcast) {
37✔
1362

37✔
1363
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
37✔
1364
        // duration to delay the sending of next announcement batch.
37✔
1365
        delayNextBatch := func() {
108✔
1366
                select {
71✔
1367
                case <-time.After(d.cfg.SubBatchDelay):
54✔
1368
                case <-d.quit:
17✔
1369
                        return
17✔
1370
                }
1371
        }
1372

1373
        // Fetch the local and remote announcements.
1374
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
37✔
1375
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
37✔
1376

37✔
1377
        d.wg.Add(1)
37✔
1378
        go func() {
74✔
1379
                defer d.wg.Done()
37✔
1380

37✔
1381
                log.Debugf("Broadcasting %v new local announcements in %d "+
37✔
1382
                        "sub batches", len(annBatch.localMsgs),
37✔
1383
                        len(localBatches))
37✔
1384

37✔
1385
                // Send out the local announcements first.
37✔
1386
                for _, annBatch := range localBatches {
74✔
1387
                        d.sendLocalBatch(annBatch)
37✔
1388
                        delayNextBatch()
37✔
1389
                }
37✔
1390

1391
                log.Debugf("Broadcasting %v new remote announcements in %d "+
37✔
1392
                        "sub batches", len(annBatch.remoteMsgs),
37✔
1393
                        len(remoteBatches))
37✔
1394

37✔
1395
                // Now send the remote announcements.
37✔
1396
                for _, annBatch := range remoteBatches {
74✔
1397
                        d.sendRemoteBatch(ctx, annBatch)
37✔
1398
                        delayNextBatch()
37✔
1399
                }
37✔
1400
        }()
1401
}
1402

1403
// sendLocalBatch broadcasts a list of locally generated announcements to our
1404
// peers. For local announcements, we skip the filter and dedup logic and just
1405
// send the announcements out to all our coonnected peers.
1406
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
37✔
1407
        msgsToSend := lnutils.Map(
37✔
1408
                annBatch, func(m msgWithSenders) lnwire.Message {
83✔
1409
                        return m.msg
46✔
1410
                },
46✔
1411
        )
1412

1413
        err := d.cfg.Broadcast(nil, msgsToSend...)
37✔
1414
        if err != nil {
37✔
1415
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1416
        }
×
1417
}
1418

1419
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1420
// peers.
1421
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1422
        annBatch []msgWithSenders) {
37✔
1423

37✔
1424
        syncerPeers := d.syncMgr.GossipSyncers()
37✔
1425

37✔
1426
        // We'll first attempt to filter out this new message for all peers
37✔
1427
        // that have active gossip syncers active.
37✔
1428
        for pub, syncer := range syncerPeers {
40✔
1429
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
3✔
1430
                syncer.FilterGossipMsgs(ctx, annBatch...)
3✔
1431
        }
3✔
1432

1433
        for _, msgChunk := range annBatch {
69✔
1434
                msgChunk := msgChunk
32✔
1435

32✔
1436
                // With the syncers taken care of, we'll merge the sender map
32✔
1437
                // with the set of syncers, so we don't send out duplicate
32✔
1438
                // messages.
32✔
1439
                msgChunk.mergeSyncerMap(syncerPeers)
32✔
1440

32✔
1441
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
32✔
1442
                if err != nil {
32✔
1443
                        log.Errorf("Unable to send batch "+
×
1444
                                "announcements: %v", err)
×
1445
                        continue
×
1446
                }
1447
        }
1448
}
1449

1450
// networkHandler is the primary goroutine that drives this service. The roles
1451
// of this goroutine includes answering queries related to the state of the
1452
// network, syncing up newly connected peers, and also periodically
1453
// broadcasting our latest topology state to all connected peers.
1454
//
1455
// NOTE: This MUST be run as a goroutine.
1456
func (d *AuthenticatedGossiper) networkHandler(ctx context.Context) {
33✔
1457
        defer d.wg.Done()
33✔
1458

33✔
1459
        // Initialize empty deDupedAnnouncements to store announcement batch.
33✔
1460
        announcements := deDupedAnnouncements{}
33✔
1461
        announcements.Reset()
33✔
1462

33✔
1463
        d.cfg.RetransmitTicker.Resume()
33✔
1464
        defer d.cfg.RetransmitTicker.Stop()
33✔
1465

33✔
1466
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
33✔
1467
        defer trickleTimer.Stop()
33✔
1468

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

1475
        for {
702✔
1476
                select {
669✔
1477
                // A new policy update has arrived. We'll commit it to the
1478
                // sub-systems below us, then craft, sign, and broadcast a new
1479
                // ChannelUpdate for the set of affected clients.
1480
                case policyUpdate := <-d.chanPolicyUpdates:
4✔
1481
                        log.Tracef("Received channel %d policy update requests",
4✔
1482
                                len(policyUpdate.edgesToUpdate))
4✔
1483

4✔
1484
                        // First, we'll now create new fully signed updates for
4✔
1485
                        // the affected channels and also update the underlying
4✔
1486
                        // graph with the new state.
4✔
1487
                        newChanUpdates, err := d.processChanPolicyUpdate(
4✔
1488
                                ctx, policyUpdate.edgesToUpdate,
4✔
1489
                        )
4✔
1490
                        policyUpdate.errChan <- err
4✔
1491
                        if err != nil {
4✔
1492
                                log.Errorf("Unable to craft policy updates: %v",
×
1493
                                        err)
×
1494
                                continue
×
1495
                        }
1496

1497
                        // Finally, with the updates committed, we'll now add
1498
                        // them to the announcement batch to be flushed at the
1499
                        // start of the next epoch.
1500
                        announcements.AddMsgs(newChanUpdates...)
4✔
1501

1502
                case announcement := <-d.networkMsgs:
341✔
1503
                        log.Tracef("Received network message: "+
341✔
1504
                                "peer=%v, msg=%s, is_remote=%v",
341✔
1505
                                announcement.peer, announcement.msg.MsgType(),
341✔
1506
                                announcement.isRemote)
341✔
1507

341✔
1508
                        switch announcement.msg.(type) {
341✔
1509
                        // Channel announcement signatures are amongst the only
1510
                        // messages that we'll process serially.
1511
                        case *lnwire.AnnounceSignatures1:
24✔
1512
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
24✔
1513
                                        ctx, announcement,
24✔
1514
                                )
24✔
1515
                                log.Debugf("Processed network message %s, "+
24✔
1516
                                        "returned len(announcements)=%v",
24✔
1517
                                        announcement.msg.MsgType(),
24✔
1518
                                        len(emittedAnnouncements))
24✔
1519

24✔
1520
                                if emittedAnnouncements != nil {
37✔
1521
                                        announcements.AddMsgs(
13✔
1522
                                                emittedAnnouncements...,
13✔
1523
                                        )
13✔
1524
                                }
13✔
1525
                                continue
24✔
1526
                        }
1527

1528
                        // If this message was recently rejected, then we won't
1529
                        // attempt to re-process it.
1530
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
320✔
1531
                                announcement.msg,
320✔
1532
                                sourceToPub(announcement.source),
320✔
1533
                        ) {
321✔
1534

1✔
1535
                                announcement.err <- fmt.Errorf("recently " +
1✔
1536
                                        "rejected")
1✔
1537
                                continue
1✔
1538
                        }
1539

1540
                        // We'll set up any dependent, and wait until a free
1541
                        // slot for this job opens up, this allow us to not
1542
                        // have thousands of goroutines active.
1543
                        annJobID, err := d.vb.InitJobDependencies(
319✔
1544
                                announcement.msg,
319✔
1545
                        )
319✔
1546
                        if err != nil {
319✔
1547
                                announcement.err <- err
×
1548
                                continue
×
1549
                        }
1550

1551
                        d.wg.Add(1)
319✔
1552
                        go d.handleNetworkMessages(
319✔
1553
                                ctx, announcement, &announcements, annJobID,
319✔
1554
                        )
319✔
1555

1556
                // The trickle timer has ticked, which indicates we should
1557
                // flush to the network the pending batch of new announcements
1558
                // we've received since the last trickle tick.
1559
                case <-trickleTimer.C:
299✔
1560
                        // Emit the current batch of announcements from
299✔
1561
                        // deDupedAnnouncements.
299✔
1562
                        announcementBatch := announcements.Emit()
299✔
1563

299✔
1564
                        // If the current announcements batch is nil, then we
299✔
1565
                        // have no further work here.
299✔
1566
                        if announcementBatch.isEmpty() {
564✔
1567
                                continue
265✔
1568
                        }
1569

1570
                        // At this point, we have the set of local and remote
1571
                        // announcements we want to send out. We'll do the
1572
                        // batching as normal for both, but for local
1573
                        // announcements, we'll blast them out w/o regard for
1574
                        // our peer's policies so we ensure they propagate
1575
                        // properly.
1576
                        d.splitAndSendAnnBatch(ctx, announcementBatch)
37✔
1577

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

1590
                // The gossiper has been signalled to exit, to we exit our
1591
                // main loop so the wait group can be decremented.
1592
                case <-d.quit:
33✔
1593
                        return
33✔
1594
                }
1595
        }
1596
}
1597

1598
// handleNetworkMessages is responsible for waiting for dependencies for a
1599
// given network message and processing the message. Once processed, it will
1600
// signal its dependants and add the new announcements to the announce batch.
1601
//
1602
// NOTE: must be run as a goroutine.
1603
func (d *AuthenticatedGossiper) handleNetworkMessages(ctx context.Context,
1604
        nMsg *networkMsg, deDuped *deDupedAnnouncements, jobID JobID) {
319✔
1605

319✔
1606
        defer d.wg.Done()
319✔
1607
        defer d.vb.CompleteJob()
319✔
1608

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

319✔
1613
        // If this message has an existing dependency, then we'll wait until
319✔
1614
        // that has been fully validated before we proceed.
319✔
1615
        err := d.vb.WaitForParents(jobID, nMsg.msg)
319✔
1616
        if err != nil {
319✔
1617
                log.Debugf("Validating network message %s got err: %v",
×
1618
                        nMsg.msg.MsgType(), err)
×
1619

×
1620
                if errors.Is(err, ErrVBarrierShuttingDown) {
×
1621
                        log.Warnf("unexpected error during validation "+
×
1622
                                "barrier shutdown: %v", err)
×
1623
                }
×
1624
                nMsg.err <- err
×
1625

×
1626
                return
×
1627
        }
1628

1629
        // Process the network announcement to determine if this is either a
1630
        // new announcement from our PoV or an edges to a prior vertex/edge we
1631
        // previously proceeded.
1632
        newAnns, allow := d.processNetworkAnnouncement(ctx, nMsg)
319✔
1633

319✔
1634
        log.Tracef("Processed network message %s, returned "+
319✔
1635
                "len(announcements)=%v, allowDependents=%v",
319✔
1636
                nMsg.msg.MsgType(), len(newAnns), allow)
319✔
1637

319✔
1638
        // If this message had any dependencies, then we can now signal them to
319✔
1639
        // continue.
319✔
1640
        err = d.vb.SignalDependents(nMsg.msg, jobID)
319✔
1641
        if err != nil {
319✔
1642
                // Something is wrong if SignalDependents returns an error.
×
1643
                log.Errorf("SignalDependents returned error for msg=%v with "+
×
1644
                        "JobID=%v", spew.Sdump(nMsg.msg), jobID)
×
1645

×
1646
                nMsg.err <- err
×
1647

×
1648
                return
×
1649
        }
×
1650

1651
        // If the announcement was accepted, then add the emitted announcements
1652
        // to our announce batch to be broadcast once the trickle timer ticks
1653
        // gain.
1654
        if newAnns != nil && shouldBroadcast {
359✔
1655
                // TODO(roasbeef): exclude peer that sent.
40✔
1656
                deDuped.AddMsgs(newAnns...)
40✔
1657
        } else if newAnns != nil {
326✔
1658
                log.Trace("Skipping broadcast of announcements received " +
4✔
1659
                        "during initial graph sync")
4✔
1660
        }
4✔
1661
}
1662

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

1665
// InitSyncState is called by outside sub-systems when a connection is
1666
// established to a new peer that understands how to perform channel range
1667
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1668
// needed to handle new queries.
1669
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
3✔
1670
        d.syncMgr.InitSyncState(syncPeer)
3✔
1671
}
3✔
1672

1673
// PruneSyncState is called by outside sub-systems once a peer that we were
1674
// previously connected to has been disconnected. In this case we can stop the
1675
// existing GossipSyncer assigned to the peer and free up resources.
1676
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
3✔
1677
        d.syncMgr.PruneSyncState(peer)
3✔
1678
}
3✔
1679

1680
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1681
// false otherwise, This avoids expensive reprocessing of the message.
1682
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1683
        peerPub [33]byte) bool {
283✔
1684

283✔
1685
        var scid uint64
283✔
1686
        switch m := msg.(type) {
283✔
1687
        case *lnwire.ChannelUpdate1:
51✔
1688
                scid = m.ShortChannelID.ToUint64()
51✔
1689

1690
        case *lnwire.ChannelAnnouncement1:
221✔
1691
                scid = m.ShortChannelID.ToUint64()
221✔
1692

1693
        default:
17✔
1694
                return false
17✔
1695
        }
1696

1697
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
269✔
1698
        return err != cache.ErrElementNotFound
269✔
1699
}
1700

1701
// retransmitStaleAnns examines all outgoing channels that the source node is
1702
// known to maintain to check to see if any of them are "stale". A channel is
1703
// stale iff, the last timestamp of its rebroadcast is older than the
1704
// RebroadcastInterval. We also check if a refreshed node announcement should
1705
// be resent.
1706
func (d *AuthenticatedGossiper) retransmitStaleAnns(ctx context.Context,
1707
        now time.Time) error {
34✔
1708

34✔
1709
        // Iterate over all of our channels and check if any of them fall
34✔
1710
        // within the prune interval or re-broadcast interval.
34✔
1711
        type updateTuple struct {
34✔
1712
                info *models.ChannelEdgeInfo
34✔
1713
                edge *models.ChannelEdgePolicy
34✔
1714
        }
34✔
1715

34✔
1716
        var (
34✔
1717
                havePublicChannels bool
34✔
1718
                edgesToUpdate      []updateTuple
34✔
1719
        )
34✔
1720
        err := d.cfg.Graph.ForAllOutgoingChannels(ctx, func(
34✔
1721
                info *models.ChannelEdgeInfo,
34✔
1722
                edge *models.ChannelEdgePolicy) error {
39✔
1723

5✔
1724
                // If there's no auth proof attached to this edge, it means
5✔
1725
                // that it is a private channel not meant to be announced to
5✔
1726
                // the greater network, so avoid sending channel updates for
5✔
1727
                // this channel to not leak its
5✔
1728
                // existence.
5✔
1729
                if info.AuthProof == nil {
9✔
1730
                        log.Debugf("Skipping retransmission of channel "+
4✔
1731
                                "without AuthProof: %v", info.ChannelID)
4✔
1732
                        return nil
4✔
1733
                }
4✔
1734

1735
                // We make a note that we have at least one public channel. We
1736
                // use this to determine whether we should send a node
1737
                // announcement below.
1738
                havePublicChannels = true
4✔
1739

4✔
1740
                // If this edge has a ChannelUpdate that was created before the
4✔
1741
                // introduction of the MaxHTLC field, then we'll update this
4✔
1742
                // edge to propagate this information in the network.
4✔
1743
                if !edge.MessageFlags.HasMaxHtlc() {
4✔
1744
                        // We'll make sure we support the new max_htlc field if
×
1745
                        // not already present.
×
1746
                        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
×
1747
                        edge.MaxHTLC = lnwire.NewMSatFromSatoshis(info.Capacity)
×
1748

×
1749
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1750
                                info: info,
×
1751
                                edge: edge,
×
1752
                        })
×
1753
                        return nil
×
1754
                }
×
1755

1756
                timeElapsed := now.Sub(edge.LastUpdate)
4✔
1757

4✔
1758
                // If it's been longer than RebroadcastInterval since we've
4✔
1759
                // re-broadcasted the channel, add the channel to the set of
4✔
1760
                // edges we need to update.
4✔
1761
                if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1762
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1763
                                info: info,
1✔
1764
                                edge: edge,
1✔
1765
                        })
1✔
1766
                }
1✔
1767

1768
                return nil
4✔
1769
        }, func() {
3✔
1770
                havePublicChannels = false
3✔
1771
                edgesToUpdate = nil
3✔
1772
        })
3✔
1773
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
34✔
1774
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1775
                        err)
×
1776
        }
×
1777

1778
        var signedUpdates []lnwire.Message
34✔
1779
        for _, chanToUpdate := range edgesToUpdate {
35✔
1780
                // Re-sign and update the channel on disk and retrieve our
1✔
1781
                // ChannelUpdate to broadcast.
1✔
1782
                chanAnn, chanUpdate, err := d.updateChannel(
1✔
1783
                        ctx, chanToUpdate.info, chanToUpdate.edge,
1✔
1784
                )
1✔
1785
                if err != nil {
1✔
1786
                        return fmt.Errorf("unable to update channel: %w", err)
×
1787
                }
×
1788

1789
                // If we have a valid announcement to transmit, then we'll send
1790
                // that along with the update.
1791
                if chanAnn != nil {
2✔
1792
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1793
                }
1✔
1794

1795
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1796
        }
1797

1798
        // If we don't have any public channels, we return as we don't want to
1799
        // broadcast anything that would reveal our existence.
1800
        if !havePublicChannels {
67✔
1801
                return nil
33✔
1802
        }
33✔
1803

1804
        // We'll also check that our NodeAnnouncement is not too old.
1805
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
4✔
1806
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
4✔
1807
        timeElapsed := now.Sub(timestamp)
4✔
1808

4✔
1809
        // If it's been a full day since we've re-broadcasted the
4✔
1810
        // node announcement, refresh it and resend it.
4✔
1811
        nodeAnnStr := ""
4✔
1812
        if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1813
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
1✔
1814
                if err != nil {
1✔
1815
                        return fmt.Errorf("unable to get refreshed node "+
×
1816
                                "announcement: %v", err)
×
1817
                }
×
1818

1819
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1820
                nodeAnnStr = " and our refreshed node announcement"
1✔
1821

1✔
1822
                // Before broadcasting the refreshed node announcement, add it
1✔
1823
                // to our own graph.
1✔
1824
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
2✔
1825
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1826
                                "to graph: %v", err)
1✔
1827
                }
1✔
1828
        }
1829

1830
        // If we don't have any updates to re-broadcast, then we'll exit
1831
        // early.
1832
        if len(signedUpdates) == 0 {
7✔
1833
                return nil
3✔
1834
        }
3✔
1835

1836
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1837
                len(edgesToUpdate), nodeAnnStr)
1✔
1838

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

1845
        return nil
1✔
1846
}
1847

1848
// processChanPolicyUpdate generates a new set of channel updates for the
1849
// provided list of edges and updates the backing ChannelGraphSource.
1850
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1851
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
4✔
1852

4✔
1853
        var chanUpdates []networkMsg
4✔
1854
        for _, edgeInfo := range edgesToUpdate {
10✔
1855
                // Now that we've collected all the channels we need to update,
6✔
1856
                // we'll re-sign and update the backing ChannelGraphSource, and
6✔
1857
                // retrieve our ChannelUpdate to broadcast.
6✔
1858
                _, chanUpdate, err := d.updateChannel(
6✔
1859
                        ctx, edgeInfo.Info, edgeInfo.Edge,
6✔
1860
                )
6✔
1861
                if err != nil {
6✔
1862
                        return nil, err
×
1863
                }
×
1864

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

4✔
1879
                        var defaultAlias lnwire.ShortChannelID
4✔
1880
                        foundAlias, _ := d.cfg.GetAlias(chanID)
4✔
1881
                        if foundAlias != defaultAlias {
7✔
1882
                                chanUpdate.ShortChannelID = foundAlias
3✔
1883

3✔
1884
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
3✔
1885
                                if err != nil {
3✔
1886
                                        log.Errorf("Unable to sign alias "+
×
1887
                                                "update: %v", err)
×
1888
                                        continue
×
1889
                                }
1890

1891
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1892
                                if err != nil {
3✔
1893
                                        log.Errorf("Unable to create sig: %v",
×
1894
                                                err)
×
1895
                                        continue
×
1896
                                }
1897

1898
                                chanUpdate.Signature = lnSig
3✔
1899
                        }
1900

1901
                        remotePubKey := remotePubFromChanInfo(
4✔
1902
                                edgeInfo.Info, chanUpdate.ChannelFlags,
4✔
1903
                        )
4✔
1904
                        err := d.reliableSender.sendMessage(
4✔
1905
                                ctx, chanUpdate, remotePubKey,
4✔
1906
                        )
4✔
1907
                        if err != nil {
4✔
1908
                                log.Errorf("Unable to reliably send %v for "+
×
1909
                                        "channel=%v to peer=%x: %v",
×
1910
                                        chanUpdate.MsgType(),
×
1911
                                        chanUpdate.ShortChannelID,
×
1912
                                        remotePubKey, err)
×
1913
                        }
×
1914
                        continue
4✔
1915
                }
1916

1917
                // We set ourselves as the source of this message to indicate
1918
                // that we shouldn't skip any peers when sending this message.
1919
                chanUpdates = append(chanUpdates, networkMsg{
5✔
1920
                        source:   d.selfKey,
5✔
1921
                        isRemote: false,
5✔
1922
                        msg:      chanUpdate,
5✔
1923
                })
5✔
1924
        }
1925

1926
        return chanUpdates, nil
4✔
1927
}
1928

1929
// remotePubFromChanInfo returns the public key of the remote peer given a
1930
// ChannelEdgeInfo that describe a channel we have with them.
1931
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1932
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
15✔
1933

15✔
1934
        var remotePubKey [33]byte
15✔
1935
        switch {
15✔
1936
        case chanFlags&lnwire.ChanUpdateDirection == 0:
15✔
1937
                remotePubKey = chanInfo.NodeKey2Bytes
15✔
1938
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1939
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1940
        }
1941

1942
        return remotePubKey
15✔
1943
}
1944

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

3✔
1956
        // First, we'll fetch the state of the channel as we know if from the
3✔
1957
        // database.
3✔
1958
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
1959
                chanAnnMsg.ShortChannelID,
3✔
1960
        )
3✔
1961
        if err != nil {
3✔
1962
                return nil, err
×
1963
        }
×
1964

1965
        // The edge is in the graph, and has a proof attached, then we'll just
1966
        // reject it as normal.
1967
        if chanInfo.AuthProof != nil {
6✔
1968
                return nil, nil
3✔
1969
        }
3✔
1970

1971
        // Otherwise, this means that the edge is within the graph, but it
1972
        // doesn't yet have a proper proof attached. If we did not receive
1973
        // the proof such that we now can add it, there's nothing more we
1974
        // can do.
1975
        if proof == nil {
×
1976
                return nil, nil
×
1977
        }
×
1978

1979
        // We'll then create then validate the new fully assembled
1980
        // announcement.
1981
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
×
1982
                proof, chanInfo, e1, e2,
×
1983
        )
×
1984
        if err != nil {
×
1985
                return nil, err
×
1986
        }
×
1987
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
×
1988
        if err != nil {
×
1989
                err := fmt.Errorf("assembled channel announcement proof "+
×
1990
                        "for shortChanID=%v isn't valid: %v",
×
1991
                        chanAnnMsg.ShortChannelID, err)
×
1992
                log.Error(err)
×
1993
                return nil, err
×
1994
        }
×
1995

1996
        // If everything checks out, then we'll add the fully assembled proof
1997
        // to the database.
1998
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
1999
        if err != nil {
×
2000
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
2001
                        chanAnnMsg.ShortChannelID, err)
×
2002
                log.Error(err)
×
2003
                return nil, err
×
2004
        }
×
2005

2006
        // As we now have a complete channel announcement for this channel,
2007
        // we'll construct the announcement so they can be broadcast out to all
2008
        // our peers.
2009
        announcements := make([]networkMsg, 0, 3)
×
2010
        announcements = append(announcements, networkMsg{
×
2011
                source: d.selfKey,
×
2012
                msg:    chanAnn,
×
2013
        })
×
2014
        if e1Ann != nil {
×
2015
                announcements = append(announcements, networkMsg{
×
2016
                        source: d.selfKey,
×
2017
                        msg:    e1Ann,
×
2018
                })
×
2019
        }
×
2020
        if e2Ann != nil {
×
2021
                announcements = append(announcements, networkMsg{
×
2022
                        source: d.selfKey,
×
2023
                        msg:    e2Ann,
×
2024
                })
×
2025

×
2026
        }
×
2027

2028
        return announcements, nil
×
2029
}
2030

2031
// fetchPKScript fetches the output script for the given SCID.
2032
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2033
        []byte, error) {
×
2034

×
2035
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2036
}
×
2037

2038
// addNode processes the given node announcement, and adds it to our channel
2039
// graph.
2040
func (d *AuthenticatedGossiper) addNode(ctx context.Context,
2041
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
20✔
2042

20✔
2043
        if err := netann.ValidateNodeAnn(msg); err != nil {
21✔
2044
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
2045
                        err)
1✔
2046
        }
1✔
2047

2048
        return d.cfg.Graph.AddNode(
19✔
2049
                ctx, models.NodeFromWireAnnouncement(msg), op...,
19✔
2050
        )
19✔
2051
}
2052

2053
// isPremature decides whether a given network message has a block height+delta
2054
// value specified in the future. If so, the message will be added to the
2055
// future message map and be processed when the block height as reached.
2056
//
2057
// NOTE: must be used inside a lock.
2058
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2059
        delta uint32, msg *networkMsg) bool {
292✔
2060

292✔
2061
        // The channel is already confirmed at chanID.BlockHeight so we minus
292✔
2062
        // one block. For instance, if the required confirmation for this
292✔
2063
        // channel announcement is 6, we then only need to wait for 5 more
292✔
2064
        // blocks once the funding tx is confirmed.
292✔
2065
        if delta > 0 {
295✔
2066
                delta--
3✔
2067
        }
3✔
2068

2069
        msgHeight := chanID.BlockHeight + delta
292✔
2070

292✔
2071
        // The message height is smaller or equal to our best known height,
292✔
2072
        // thus the message is mature.
292✔
2073
        if msgHeight <= d.bestHeight {
583✔
2074
                return false
291✔
2075
        }
291✔
2076

2077
        // Add the premature message to our future messages which will be
2078
        // resent once the block height has reached.
2079
        //
2080
        // Copy the networkMsgs since the old message's err chan will be
2081
        // consumed.
2082
        copied := &networkMsg{
4✔
2083
                peer:              msg.peer,
4✔
2084
                source:            msg.source,
4✔
2085
                msg:               msg.msg,
4✔
2086
                optionalMsgFields: msg.optionalMsgFields,
4✔
2087
                isRemote:          msg.isRemote,
4✔
2088
                err:               make(chan error, 1),
4✔
2089
        }
4✔
2090

4✔
2091
        // Create the cached message.
4✔
2092
        cachedMsg := &cachedFutureMsg{
4✔
2093
                msg:    copied,
4✔
2094
                height: msgHeight,
4✔
2095
        }
4✔
2096

4✔
2097
        // Increment the msg ID and add it to the cache.
4✔
2098
        nextMsgID := d.futureMsgs.nextMsgID()
4✔
2099
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
4✔
2100
        if err != nil {
4✔
2101
                log.Errorf("Adding future message got error: %v", err)
×
2102
        }
×
2103

2104
        log.Debugf("Network message: %v added to future messages for "+
4✔
2105
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
4✔
2106
                msgHeight, d.bestHeight)
4✔
2107

4✔
2108
        return true
4✔
2109
}
2110

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

340✔
2121
        // If this is a remote update, we set the scheduler option to lazily
340✔
2122
        // add it to the graph.
340✔
2123
        var schedulerOp []batch.SchedulerOption
340✔
2124
        if nMsg.isRemote {
633✔
2125
                schedulerOp = append(schedulerOp, batch.LazyAdd())
293✔
2126
        }
293✔
2127

2128
        switch msg := nMsg.msg.(type) {
340✔
2129
        // A new node announcement has arrived which either presents new
2130
        // information about a node in one of the channels we know about, or a
2131
        // updating previously advertised information.
2132
        case *lnwire.NodeAnnouncement:
27✔
2133
                return d.handleNodeAnnouncement(ctx, nMsg, msg, schedulerOp)
27✔
2134

2135
        // A new channel announcement has arrived, this indicates the
2136
        // *creation* of a new channel within the network. This only advertises
2137
        // the existence of a channel and not yet the routing policies in
2138
        // either direction of the channel.
2139
        case *lnwire.ChannelAnnouncement1:
234✔
2140
                return d.handleChanAnnouncement(ctx, nMsg, msg, schedulerOp...)
234✔
2141

2142
        // A new authenticated channel edge update has arrived. This indicates
2143
        // that the directional information for an already known channel has
2144
        // been updated.
2145
        case *lnwire.ChannelUpdate1:
64✔
2146
                return d.handleChanUpdate(ctx, nMsg, msg, schedulerOp)
64✔
2147

2148
        // A new signature announcement has been received. This indicates
2149
        // willingness of nodes involved in the funding of a channel to
2150
        // announce this new channel to the rest of the world.
2151
        case *lnwire.AnnounceSignatures1:
24✔
2152
                return d.handleAnnSig(ctx, nMsg, msg)
24✔
2153

2154
        default:
×
2155
                err := errors.New("wrong type of the announcement")
×
2156
                nMsg.err <- err
×
2157
                return nil, false
×
2158
        }
2159
}
2160

2161
// processZombieUpdate determines whether the provided channel update should
2162
// resurrect a given zombie edge.
2163
//
2164
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2165
// should be inspected.
2166
func (d *AuthenticatedGossiper) processZombieUpdate(_ context.Context,
2167
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2168
        msg *lnwire.ChannelUpdate1) error {
3✔
2169

3✔
2170
        // The least-significant bit in the flag on the channel update tells us
3✔
2171
        // which edge is being updated.
3✔
2172
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2173

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

2191
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2192
        if err != nil {
3✔
2193
                return fmt.Errorf("unable to verify channel "+
1✔
2194
                        "update signature: %v", err)
1✔
2195
        }
1✔
2196

2197
        // With the signature valid, we'll proceed to mark the
2198
        // edge as live and wait for the channel announcement to
2199
        // come through again.
2200
        err = d.cfg.Graph.MarkEdgeLive(scid)
1✔
2201
        switch {
1✔
2202
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2203
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2204
                        "zombie index: %v", err)
×
2205

×
2206
                return nil
×
2207

2208
        case err != nil:
×
2209
                return fmt.Errorf("unable to remove edge with "+
×
2210
                        "chan_id=%v from zombie index: %v",
×
2211
                        msg.ShortChannelID, err)
×
2212

2213
        default:
1✔
2214
        }
2215

2216
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2217
                "index", msg.ShortChannelID)
1✔
2218

1✔
2219
        return nil
1✔
2220
}
2221

2222
// fetchNodeAnn fetches the latest signed node announcement from our point of
2223
// view for the node with the given public key.
2224
func (d *AuthenticatedGossiper) fetchNodeAnn(ctx context.Context,
2225
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
23✔
2226

23✔
2227
        node, err := d.cfg.Graph.FetchLightningNode(ctx, pubKey)
23✔
2228
        if err != nil {
29✔
2229
                return nil, err
6✔
2230
        }
6✔
2231

2232
        nodeAnn, err := node.NodeAnnouncement(true)
17✔
2233
        if err != nil {
20✔
2234
                return nil, err
3✔
2235
        }
3✔
2236

2237
        return nodeAnn, netann.ValidateNodeAnnFields(nodeAnn)
17✔
2238
}
2239

2240
// isMsgStale determines whether a message retrieved from the backing
2241
// MessageStore is seen as stale by the current graph.
2242
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2243
        msg lnwire.Message) bool {
16✔
2244

16✔
2245
        switch msg := msg.(type) {
16✔
2246
        case *lnwire.AnnounceSignatures1:
5✔
2247
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
5✔
2248
                        msg.ShortChannelID,
5✔
2249
                )
5✔
2250

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

2263
                // If the proof exists in the graph, then we have successfully
2264
                // received the remote proof and assembled the full proof, so we
2265
                // can safely delete the local proof from the database.
2266
                return chanInfo.AuthProof != nil
5✔
2267

2268
        case *lnwire.ChannelUpdate1:
14✔
2269
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
14✔
2270

14✔
2271
                // If the channel cannot be found, it is most likely a leftover
14✔
2272
                // message for a channel that was closed, so we can consider it
14✔
2273
                // stale.
14✔
2274
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
17✔
2275
                        return true
3✔
2276
                }
3✔
2277
                if err != nil {
14✔
2278
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2279
                                "%v", msg.ShortChannelID, err)
×
2280
                        return false
×
2281
                }
×
2282

2283
                // Otherwise, we'll retrieve the correct policy that we
2284
                // currently have stored within our graph to check if this
2285
                // message is stale by comparing its timestamp.
2286
                var p *models.ChannelEdgePolicy
14✔
2287
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
28✔
2288
                        p = p1
14✔
2289
                } else {
17✔
2290
                        p = p2
3✔
2291
                }
3✔
2292

2293
                // If the policy is still unknown, then we can consider this
2294
                // policy fresh.
2295
                if p == nil {
14✔
2296
                        return false
×
2297
                }
×
2298

2299
                timestamp := time.Unix(int64(msg.Timestamp), 0)
14✔
2300
                return p.LastUpdate.After(timestamp)
14✔
2301

2302
        default:
×
2303
                // We'll make sure to not mark any unsupported messages as stale
×
2304
                // to ensure they are not removed.
×
2305
                return false
×
2306
        }
2307
}
2308

2309
// updateChannel creates a new fully signed update for the channel, and updates
2310
// the underlying graph with the new state.
2311
func (d *AuthenticatedGossiper) updateChannel(ctx context.Context,
2312
        info *models.ChannelEdgeInfo,
2313
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2314
        *lnwire.ChannelUpdate1, error) {
7✔
2315

7✔
2316
        // Parse the unsigned edge into a channel update.
7✔
2317
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
7✔
2318

7✔
2319
        // We'll generate a new signature over a digest of the channel
7✔
2320
        // announcement itself and update the timestamp to ensure it propagate.
7✔
2321
        err := netann.SignChannelUpdate(
7✔
2322
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
7✔
2323
                netann.ChanUpdSetTimestamp,
7✔
2324
        )
7✔
2325
        if err != nil {
7✔
2326
                return nil, nil, err
×
2327
        }
×
2328

2329
        // Next, we'll set the new signature in place, and update the reference
2330
        // in the backing slice.
2331
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
7✔
2332
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
7✔
2333

7✔
2334
        // To ensure that our signature is valid, we'll verify it ourself
7✔
2335
        // before committing it to the slice returned.
7✔
2336
        err = netann.ValidateChannelUpdateAnn(
7✔
2337
                d.selfKey, info.Capacity, chanUpdate,
7✔
2338
        )
7✔
2339
        if err != nil {
7✔
2340
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2341
                        "update sig: %v", err)
×
2342
        }
×
2343

2344
        // Finally, we'll write the new edge policy to disk.
2345
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
7✔
2346
                return nil, nil, err
×
2347
        }
×
2348

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

2391
        return chanAnn, chanUpdate, err
7✔
2392
}
2393

2394
// SyncManager returns the gossiper's SyncManager instance.
2395
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2396
        return d.syncMgr
3✔
2397
}
3✔
2398

2399
// IsKeepAliveUpdate determines whether this channel update is considered a
2400
// keep-alive update based on the previous channel update processed for the same
2401
// direction.
2402
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2403
        prev *models.ChannelEdgePolicy) bool {
20✔
2404

20✔
2405
        // Both updates should be from the same direction.
20✔
2406
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
20✔
2407
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
20✔
2408

×
2409
                return false
×
2410
        }
×
2411

2412
        // The timestamp should always increase for a keep-alive update.
2413
        timestamp := time.Unix(int64(update.Timestamp), 0)
20✔
2414
        if !timestamp.After(prev.LastUpdate) {
20✔
2415
                return false
×
2416
        }
×
2417

2418
        // None of the remaining fields should change for a keep-alive update.
2419
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
23✔
2420
                return false
3✔
2421
        }
3✔
2422
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
38✔
2423
                return false
18✔
2424
        }
18✔
2425
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
8✔
2426
                return false
3✔
2427
        }
3✔
2428
        if update.TimeLockDelta != prev.TimeLockDelta {
5✔
2429
                return false
×
2430
        }
×
2431
        if update.HtlcMinimumMsat != prev.MinHTLC {
5✔
2432
                return false
×
2433
        }
×
2434
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
5✔
2435
                return false
×
2436
        }
×
2437
        if update.HtlcMaximumMsat != prev.MaxHTLC {
5✔
2438
                return false
×
2439
        }
×
2440
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
8✔
2441
                return false
3✔
2442
        }
3✔
2443
        return true
5✔
2444
}
2445

2446
// latestHeight returns the gossiper's latest height known of the chain.
2447
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2448
        d.Lock()
3✔
2449
        defer d.Unlock()
3✔
2450
        return d.bestHeight
3✔
2451
}
3✔
2452

2453
// handleNodeAnnouncement processes a new node announcement.
2454
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2455
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2456
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
27✔
2457

27✔
2458
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
27✔
2459

27✔
2460
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
27✔
2461
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
27✔
2462
                nMsg.source.SerializeCompressed())
27✔
2463

27✔
2464
        // We'll quickly ask the router if it already has a newer update for
27✔
2465
        // this node so we can skip validating signatures if not required.
27✔
2466
        if d.cfg.Graph.IsStaleNode(ctx, nodeAnn.NodeID, timestamp) {
38✔
2467
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
11✔
2468
                nMsg.err <- nil
11✔
2469
                return nil, true
11✔
2470
        }
11✔
2471

2472
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
22✔
2473
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2474
                        err)
3✔
2475

3✔
2476
                if !graph.IsError(
3✔
2477
                        err,
3✔
2478
                        graph.ErrOutdated,
3✔
2479
                        graph.ErrIgnored,
3✔
2480
                ) {
3✔
2481

×
2482
                        log.Error(err)
×
2483
                }
×
2484

2485
                nMsg.err <- err
3✔
2486
                return nil, false
3✔
2487
        }
2488

2489
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2490
        // quick check to ensure this node intends to publicly advertise itself
2491
        // to the network.
2492
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
19✔
2493
        if err != nil {
19✔
2494
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2495
                        nodeAnn.NodeID, err)
×
2496
                nMsg.err <- err
×
2497
                return nil, false
×
2498
        }
×
2499

2500
        var announcements []networkMsg
19✔
2501

19✔
2502
        // If it does, we'll add their announcement to our batch so that it can
19✔
2503
        // be broadcast to the rest of our peers.
19✔
2504
        if isPublic {
25✔
2505
                announcements = append(announcements, networkMsg{
6✔
2506
                        peer:     nMsg.peer,
6✔
2507
                        isRemote: nMsg.isRemote,
6✔
2508
                        source:   nMsg.source,
6✔
2509
                        msg:      nodeAnn,
6✔
2510
                })
6✔
2511
        } else {
22✔
2512
                log.Tracef("Skipping broadcasting node announcement for %x "+
16✔
2513
                        "due to being unadvertised", nodeAnn.NodeID)
16✔
2514
        }
16✔
2515

2516
        nMsg.err <- nil
19✔
2517
        // TODO(roasbeef): get rid of the above
19✔
2518

19✔
2519
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
19✔
2520
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
19✔
2521
                nMsg.source.SerializeCompressed())
19✔
2522

19✔
2523
        return announcements, true
19✔
2524
}
2525

2526
// handleChanAnnouncement processes a new channel announcement.
2527
//
2528
//nolint:funlen
2529
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2530
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2531
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
237✔
2532

237✔
2533
        scid := ann.ShortChannelID
237✔
2534

237✔
2535
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
237✔
2536
                nMsg.peer, scid.ToUint64())
237✔
2537

237✔
2538
        // We'll ignore any channel announcements that target any chain other
237✔
2539
        // than the set of chains we know of.
237✔
2540
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
237✔
2541
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2542
                        ", gossiper on chain=%v", ann.ChainHash,
×
2543
                        d.cfg.ChainHash)
×
2544
                log.Errorf(err.Error())
×
2545

×
2546
                key := newRejectCacheKey(
×
2547
                        scid.ToUint64(),
×
2548
                        sourceToPub(nMsg.source),
×
2549
                )
×
2550
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2551

×
2552
                nMsg.err <- err
×
2553
                return nil, false
×
2554
        }
×
2555

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

×
2563
                key := newRejectCacheKey(
×
2564
                        scid.ToUint64(),
×
2565
                        sourceToPub(nMsg.source),
×
2566
                )
×
2567
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2568

×
2569
                nMsg.err <- err
×
2570
                return nil, false
×
2571
        }
×
2572

2573
        // If the advertised inclusionary block is beyond our knowledge of the
2574
        // chain tip, then we'll ignore it for now.
2575
        d.Lock()
237✔
2576
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
238✔
2577
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2578
                        "advertises height %v, only height %v is known",
1✔
2579
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2580
                d.Unlock()
1✔
2581
                nMsg.err <- nil
1✔
2582
                return nil, false
1✔
2583
        }
1✔
2584
        d.Unlock()
236✔
2585

236✔
2586
        // At this point, we'll now ask the router if this is a zombie/known
236✔
2587
        // edge. If so we can skip all the processing below.
236✔
2588
        if d.cfg.Graph.IsKnownEdge(scid) {
240✔
2589
                nMsg.err <- nil
4✔
2590
                return nil, true
4✔
2591
        }
4✔
2592

2593
        // Check if the channel is already closed in which case we can ignore
2594
        // it.
2595
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
235✔
2596
        if err != nil {
235✔
2597
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2598
                        err)
×
2599
                nMsg.err <- err
×
2600

×
2601
                return nil, false
×
2602
        }
×
2603

2604
        if closed {
236✔
2605
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2606
                log.Error(err)
1✔
2607

1✔
2608
                // If this is an announcement from us, we'll just ignore it.
1✔
2609
                if !nMsg.isRemote {
1✔
2610
                        nMsg.err <- err
×
2611
                        return nil, false
×
2612
                }
×
2613

2614
                // Increment the peer's ban score if they are sending closed
2615
                // channel announcements.
2616
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2617

1✔
2618
                // If the peer is banned and not a channel peer, we'll
1✔
2619
                // disconnect them.
1✔
2620
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2621
                if dcErr != nil {
1✔
2622
                        log.Errorf("failed to check if we should disconnect "+
×
2623
                                "peer: %v", dcErr)
×
2624
                        nMsg.err <- dcErr
×
2625

×
2626
                        return nil, false
×
2627
                }
×
2628

2629
                if shouldDc {
1✔
2630
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2631
                }
×
2632

2633
                nMsg.err <- err
1✔
2634

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

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

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

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

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

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

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

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

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

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

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

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

202✔
2734
                                // Increment the peer's ban score. We check
202✔
2735
                                // isRemote so we don't actually ban the peer in
202✔
2736
                                // case of a local bug.
202✔
2737
                                if nMsg.isRemote {
404✔
2738
                                        d.banman.incrementBanScore(
202✔
2739
                                                nMsg.peer.PubKey(),
202✔
2740
                                        )
202✔
2741
                                }
202✔
2742

2743
                        case errors.Is(err, ErrChannelSpent):
2✔
2744
                                key := newRejectCacheKey(
2✔
2745
                                        scid.ToUint64(),
2✔
2746
                                        sourceToPub(nMsg.source),
2✔
2747
                                )
2✔
2748
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
2✔
2749

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

×
2761
                                        nMsg.err <- dbErr
×
2762

×
2763
                                        return nil, false
×
2764
                                }
×
2765

2766
                                // Increment the peer's ban score. We check
2767
                                // isRemote so we don't accidentally ban
2768
                                // ourselves in case of a bug.
2769
                                if nMsg.isRemote {
4✔
2770
                                        d.banman.incrementBanScore(
2✔
2771
                                                nMsg.peer.PubKey(),
2✔
2772
                                        )
2✔
2773
                                }
2✔
2774

2775
                        default:
×
2776
                                // Otherwise, this is just a regular rejected
×
2777
                                // edge.
×
2778
                                key := newRejectCacheKey(
×
2779
                                        scid.ToUint64(),
×
2780
                                        sourceToPub(nMsg.source),
×
2781
                                )
×
2782
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2783
                        }
2784

2785
                        if !nMsg.isRemote {
204✔
2786
                                log.Errorf("failed to add edge for local "+
×
2787
                                        "channel: %v", err)
×
2788
                                nMsg.err <- err
×
2789

×
2790
                                return nil, false
×
2791
                        }
×
2792

2793
                        shouldDc, dcErr := d.ShouldDisconnect(
204✔
2794
                                nMsg.peer.IdentityKey(),
204✔
2795
                        )
204✔
2796
                        if dcErr != nil {
204✔
2797
                                log.Errorf("failed to check if we should "+
×
2798
                                        "disconnect peer: %v", dcErr)
×
2799
                                nMsg.err <- dcErr
×
2800

×
2801
                                return nil, false
×
2802
                        }
×
2803

2804
                        if shouldDc {
205✔
2805
                                nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2806
                        }
1✔
2807

2808
                        nMsg.err <- err
204✔
2809

204✔
2810
                        return nil, false
204✔
2811
                }
2812

2813
                edge.FundingScript = fn.Some(script)
28✔
2814

28✔
2815
                // TODO(roasbeef): this is a hack, needs to be removed after
28✔
2816
                //  commitment fees are dynamic.
28✔
2817
                edge.Capacity = capacity
28✔
2818
                edge.ChannelPoint = op
28✔
2819
        }
2820

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

30✔
2823
        // We will add the edge to the channel router. If the nodes present in
30✔
2824
        // this channel are not present in the database, a partial node will be
30✔
2825
        // added to represent each node while we wait for a node announcement.
30✔
2826
        err = d.cfg.Graph.AddEdge(ctx, edge, ops...)
30✔
2827
        if err != nil {
34✔
2828
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
4✔
2829
                        scid.ToUint64(), err)
4✔
2830

4✔
2831
                defer d.channelMtx.Unlock(scid.ToUint64())
4✔
2832

4✔
2833
                // If the edge was rejected due to already being known, then it
4✔
2834
                // may be the case that this new message has a fresh channel
4✔
2835
                // proof, so we'll check.
4✔
2836
                if graph.IsError(err, graph.ErrIgnored) {
7✔
2837
                        // Attempt to process the rejected message to see if we
3✔
2838
                        // get any new announcements.
3✔
2839
                        anns, rErr := d.processRejectedEdge(ctx, ann, proof)
3✔
2840
                        if rErr != nil {
3✔
2841
                                key := newRejectCacheKey(
×
2842
                                        scid.ToUint64(),
×
2843
                                        sourceToPub(nMsg.source),
×
2844
                                )
×
2845
                                cr := &cachedReject{}
×
2846
                                _, _ = d.recentRejects.Put(key, cr)
×
2847

×
2848
                                nMsg.err <- rErr
×
2849

×
2850
                                return nil, false
×
2851
                        }
×
2852

2853
                        log.Debugf("Extracted %v announcements from rejected "+
3✔
2854
                                "msgs", len(anns))
3✔
2855

3✔
2856
                        // If while processing this rejected edge, we realized
3✔
2857
                        // there's a set of announcements we could extract,
3✔
2858
                        // then we'll return those directly.
3✔
2859
                        //
3✔
2860
                        // NOTE: since this is an ErrIgnored, we can return
3✔
2861
                        // true here to signal "allow" to its dependants.
3✔
2862
                        nMsg.err <- nil
3✔
2863

3✔
2864
                        return anns, true
3✔
2865
                }
2866

2867
                // Otherwise, this is just a regular rejected edge.
2868
                key := newRejectCacheKey(
1✔
2869
                        scid.ToUint64(),
1✔
2870
                        sourceToPub(nMsg.source),
1✔
2871
                )
1✔
2872
                _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2873

1✔
2874
                if !nMsg.isRemote {
1✔
2875
                        log.Errorf("failed to add edge for local channel: %v",
×
2876
                                err)
×
2877
                        nMsg.err <- err
×
2878

×
2879
                        return nil, false
×
2880
                }
×
2881

2882
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2883
                if dcErr != nil {
1✔
2884
                        log.Errorf("failed to check if we should disconnect "+
×
2885
                                "peer: %v", dcErr)
×
2886
                        nMsg.err <- dcErr
×
2887

×
2888
                        return nil, false
×
2889
                }
×
2890

2891
                if shouldDc {
1✔
2892
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2893
                }
×
2894

2895
                nMsg.err <- err
1✔
2896

1✔
2897
                return nil, false
1✔
2898
        }
2899

2900
        // If err is nil, release the lock immediately.
2901
        d.channelMtx.Unlock(scid.ToUint64())
29✔
2902

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

29✔
2905
        // If we earlier received any ChannelUpdates for this channel, we can
29✔
2906
        // now process them, as the channel is added to the graph.
29✔
2907
        var channelUpdates []*processedNetworkMsg
29✔
2908

29✔
2909
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
29✔
2910
        if err == nil {
34✔
2911
                // There was actually an entry in the map, so we'll accumulate
5✔
2912
                // it. We don't worry about deletion, since it'll eventually
5✔
2913
                // fall out anyway.
5✔
2914
                chanMsgs := earlyChanUpdates
5✔
2915
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
5✔
2916
        }
5✔
2917

2918
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2919
        // ensure we don't block here, as we can handle only one announcement
2920
        // at a time.
2921
        for _, cu := range channelUpdates {
34✔
2922
                // Skip if already processed.
5✔
2923
                if cu.processed {
7✔
2924
                        continue
2✔
2925
                }
2926

2927
                // Mark the ChannelUpdate as processed. This ensures that a
2928
                // subsequent announcement in the option-scid-alias case does
2929
                // not re-use an old ChannelUpdate.
2930
                cu.processed = true
5✔
2931

5✔
2932
                d.wg.Add(1)
5✔
2933
                go func(updMsg *networkMsg) {
10✔
2934
                        defer d.wg.Done()
5✔
2935

5✔
2936
                        switch msg := updMsg.msg.(type) {
5✔
2937
                        // Reprocess the message, making sure we return an
2938
                        // error to the original caller in case the gossiper
2939
                        // shuts down.
2940
                        case *lnwire.ChannelUpdate1:
5✔
2941
                                log.Debugf("Reprocessing ChannelUpdate for "+
5✔
2942
                                        "shortChanID=%v", scid.ToUint64())
5✔
2943

5✔
2944
                                select {
5✔
2945
                                case d.networkMsgs <- updMsg:
5✔
2946
                                case <-d.quit:
×
2947
                                        updMsg.err <- ErrGossiperShuttingDown
×
2948
                                }
2949

2950
                        // We don't expect any other message type than
2951
                        // ChannelUpdate to be in this cache.
2952
                        default:
×
2953
                                log.Errorf("Unsupported message type found "+
×
2954
                                        "among ChannelUpdates: %T", msg)
×
2955
                        }
2956
                }(cu.msg)
2957
        }
2958

2959
        // Channel announcement was successfully processed and now it might be
2960
        // broadcast to other connected nodes if it was an announcement with
2961
        // proof (remote).
2962
        var announcements []networkMsg
29✔
2963

29✔
2964
        if proof != nil {
44✔
2965
                announcements = append(announcements, networkMsg{
15✔
2966
                        peer:     nMsg.peer,
15✔
2967
                        isRemote: nMsg.isRemote,
15✔
2968
                        source:   nMsg.source,
15✔
2969
                        msg:      ann,
15✔
2970
                })
15✔
2971
        }
15✔
2972

2973
        nMsg.err <- nil
29✔
2974

29✔
2975
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
29✔
2976
                nMsg.peer, scid.ToUint64())
29✔
2977

29✔
2978
        return announcements, true
29✔
2979
}
2980

2981
// handleChanUpdate processes a new channel update.
2982
//
2983
//nolint:funlen
2984
func (d *AuthenticatedGossiper) handleChanUpdate(ctx context.Context,
2985
        nMsg *networkMsg, upd *lnwire.ChannelUpdate1,
2986
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
64✔
2987

64✔
2988
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
64✔
2989
                nMsg.peer, upd.ShortChannelID.ToUint64())
64✔
2990

64✔
2991
        // We'll ignore any channel updates that target any chain other than
64✔
2992
        // the set of chains we know of.
64✔
2993
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
64✔
2994
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2995
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2996
                log.Errorf(err.Error())
×
2997

×
2998
                key := newRejectCacheKey(
×
2999
                        upd.ShortChannelID.ToUint64(),
×
3000
                        sourceToPub(nMsg.source),
×
3001
                )
×
3002
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3003

×
3004
                nMsg.err <- err
×
3005
                return nil, false
×
3006
        }
×
3007

3008
        blockHeight := upd.ShortChannelID.BlockHeight
64✔
3009
        shortChanID := upd.ShortChannelID.ToUint64()
64✔
3010

64✔
3011
        // If the advertised inclusionary block is beyond our knowledge of the
64✔
3012
        // chain tip, then we'll put the announcement in limbo to be fully
64✔
3013
        // verified once we advance forward in the chain. If the update has an
64✔
3014
        // alias SCID, we'll skip the isPremature check. This is necessary
64✔
3015
        // since aliases start at block height 16_000_000.
64✔
3016
        d.Lock()
64✔
3017
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
64✔
3018
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
64✔
UNCOV
3019

×
UNCOV
3020
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
UNCOV
3021
                        "premature: advertises height %v, only height %v is "+
×
UNCOV
3022
                        "known", shortChanID, blockHeight, d.bestHeight)
×
UNCOV
3023
                d.Unlock()
×
UNCOV
3024
                nMsg.err <- nil
×
UNCOV
3025
                return nil, false
×
UNCOV
3026
        }
×
3027
        d.Unlock()
64✔
3028

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

64✔
3034
        // Fetch the SCID we should be using to lock the channelMtx and make
64✔
3035
        // graph queries with.
64✔
3036
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
64✔
3037
        if err != nil {
128✔
3038
                // Fallback and set the graphScid to the peer-provided SCID.
64✔
3039
                // This will occur for non-option-scid-alias channels and for
64✔
3040
                // public option-scid-alias channels after 6 confirmations.
64✔
3041
                // Once public option-scid-alias channels have 6 confs, we'll
64✔
3042
                // ignore ChannelUpdates with one of their aliases.
64✔
3043
                graphScid = upd.ShortChannelID
64✔
3044
        }
64✔
3045

3046
        // We make sure to obtain the mutex for this channel ID before we access
3047
        // the database. This ensures the state we read from the database has
3048
        // not changed between this point and when we call UpdateEdge() later.
3049
        d.channelMtx.Lock(graphScid.ToUint64())
64✔
3050
        defer d.channelMtx.Unlock(graphScid.ToUint64())
64✔
3051

64✔
3052
        if d.cfg.Graph.IsStaleEdgePolicy(
64✔
3053
                graphScid, timestamp, upd.ChannelFlags,
64✔
3054
        ) {
70✔
3055

6✔
3056
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
6✔
3057
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
6✔
3058
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
6✔
3059
                )
6✔
3060

6✔
3061
                nMsg.err <- nil
6✔
3062
                return nil, true
6✔
3063
        }
6✔
3064

3065
        // Check that the ChanUpdate is not too far into the future, this could
3066
        // reveal some faulty implementation therefore we log an error.
3067
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
61✔
3068
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
3069
                        "short_chan_id(%v), timestamp too far in the future: "+
×
3070
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
3071
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
3072
                        nMsg.isRemote,
×
3073
                )
×
3074

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

×
3078
                return nil, false
×
3079
        }
×
3080

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

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

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

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

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

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

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

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

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

×
3171
                return nil, false
×
3172
        }
3173

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

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

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

4✔
3204
                log.Error(rErr)
4✔
3205
                nMsg.err <- rErr
4✔
3206
                return nil, false
4✔
3207
        }
4✔
3208

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

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

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

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

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

×
3300
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3301
                                shortChanID, err)
×
3302
                }
×
3303

3304
                nMsg.err <- err
×
3305
                return nil, false
×
3306
        }
3307

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

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

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

3339
                                upd.Signature = lnSig
3✔
3340
                        }
3341
                }
3342

3343
                // Get our peer's public key.
3344
                remotePubKey := remotePubFromChanInfo(
14✔
3345
                        chanInfo, upd.ChannelFlags,
14✔
3346
                )
14✔
3347

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

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

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

3379
        nMsg.err <- nil
46✔
3380

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

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

24✔
3394
        needBlockHeight := ann.ShortChannelID.BlockHeight +
24✔
3395
                d.cfg.ProofMatureDelta
24✔
3396
        shortChanID := ann.ShortChannelID.ToUint64()
24✔
3397

24✔
3398
        prefix := "local"
24✔
3399
        if nMsg.isRemote {
38✔
3400
                prefix = "remote"
14✔
3401
        }
14✔
3402

3403
        log.Infof("Received new %v announcement signature for %v", prefix,
24✔
3404
                ann.ShortChannelID)
24✔
3405

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

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

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

3✔
3443
                        return nil, false
3✔
3444
                }
3✔
3445

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

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

3462
        nodeID := nMsg.source.SerializeCompressed()
23✔
3463
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
23✔
3464
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
23✔
3465

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

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

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

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

4✔
3511
                        d.wg.Add(1)
4✔
3512
                        go func() {
8✔
3513
                                defer d.wg.Done()
4✔
3514

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

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

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

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

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

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

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

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

12✔
3576
                nMsg.err <- nil
12✔
3577
                return nil, false
12✔
3578
        }
3579

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

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

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

×
3612
                log.Error(err)
×
3613
                nMsg.err <- err
×
3614
                return nil, false
×
3615
        }
×
3616

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

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

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

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

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

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

3704
        nMsg.err <- nil
13✔
3705
        return announcements, true
13✔
3706
}
3707

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

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

209✔
3719
        pubkeySer := pubkey.SerializeCompressed()
209✔
3720

209✔
3721
        var pubkeyBytes [33]byte
209✔
3722
        copy(pubkeyBytes[:], pubkeySer)
209✔
3723

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

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

3738
        return false, nil
208✔
3739
}
3740

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

232✔
3750
        scid := ann.ShortChannelID
232✔
3751

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

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

3784
                default:
×
3785
                }
3786

3787
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
1✔
3788
                        ErrNoFundingTransaction, err)
1✔
3789
        }
3790

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

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

3822
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
201✔
3823
                        ErrInvalidFundingOutput, err)
201✔
3824
        }
3825

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

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

3845
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
28✔
3846
                nil
28✔
3847
}
3848

3849
// makeFundingScript is used to make the funding script for both segwit v0 and
3850
// segwit v1 (taproot) channels.
3851
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3852
        features *lnwire.RawFeatureVector,
3853
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
231✔
3854

231✔
3855
        legacyFundingScript := func() ([]byte, error) {
462✔
3856
                witnessScript, err := input.GenMultiSigScript(
231✔
3857
                        bitcoinKey1, bitcoinKey2,
231✔
3858
                )
231✔
3859
                if err != nil {
231✔
3860
                        return nil, err
×
3861
                }
×
3862
                pkScript, err := input.WitnessScriptHash(witnessScript)
231✔
3863
                if err != nil {
231✔
3864
                        return nil, err
×
3865
                }
×
3866

3867
                return pkScript, nil
231✔
3868
        }
3869

3870
        if features.IsEmpty() {
462✔
3871
                return legacyFundingScript()
231✔
3872
        }
231✔
3873

3874
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
3✔
3875
        if chanFeatureBits.HasFeature(
3✔
3876
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
3877
        ) {
6✔
3878

3✔
3879
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
3880
                if err != nil {
3✔
3881
                        return nil, err
×
3882
                }
×
3883
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
3884
                if err != nil {
3✔
3885
                        return nil, err
×
3886
                }
×
3887

3888
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
3889
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
3890
                )
3✔
3891
                if err != nil {
3✔
3892
                        return nil, err
×
3893
                }
×
3894

3895
                // TODO(roasbeef): add tapscript root to gossip v1.5
3896

3897
                return fundingScript, nil
3✔
3898
        }
3899

3900
        return legacyFundingScript()
×
3901
}
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