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

lightningnetwork / lnd / 16937581283

13 Aug 2025 12:43PM UTC coverage: 66.901% (-0.03%) from 66.929%
16937581283

Pull #10148

github

web-flow
Merge b1deddec4 into c6a9116e3
Pull Request #10148: graph/db+sqldb: different defaults for SQLite and Postgres query options

11 of 81 new or added lines in 7 files covered. (13.58%)

88 existing lines in 25 files now uncovered.

135834 of 203036 relevant lines covered (66.9%)

21598.84 hits per line

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

78.99
/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() {
329✔
1077
        // Storage of each type of announcement (channel announcements, channel
329✔
1078
        // updates, node announcements) is set to an empty map where the
329✔
1079
        // appropriate key points to the corresponding lnwire.Message.
329✔
1080
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
329✔
1081
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
329✔
1082
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
329✔
1083
}
329✔
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 {
296✔
1257
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
296✔
1258
}
296✔
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 {
297✔
1272
        d.Lock()
297✔
1273
        defer d.Unlock()
297✔
1274

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

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

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

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

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

1301
        d.reset()
297✔
1302

297✔
1303
        // Return the array of lnwire.messages.
297✔
1304
        return msgs
297✔
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 {
699✔
1476
                select {
666✔
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:
296✔
1560
                        // Emit the current batch of announcements from
296✔
1561
                        // deDupedAnnouncements.
296✔
1562
                        announcementBatch := announcements.Emit()
296✔
1563

296✔
1564
                        // If the current announcements batch is nil, then we
296✔
1565
                        // have no further work here.
296✔
1566
                        if announcementBatch.isEmpty() {
558✔
1567
                                continue
262✔
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
        return node.NodeAnnouncement(true)
17✔
2233
}
2234

2235
// isMsgStale determines whether a message retrieved from the backing
2236
// MessageStore is seen as stale by the current graph.
2237
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2238
        msg lnwire.Message) bool {
15✔
2239

15✔
2240
        switch msg := msg.(type) {
15✔
2241
        case *lnwire.AnnounceSignatures1:
5✔
2242
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
5✔
2243
                        msg.ShortChannelID,
5✔
2244
                )
5✔
2245

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

2258
                // If the proof exists in the graph, then we have successfully
2259
                // received the remote proof and assembled the full proof, so we
2260
                // can safely delete the local proof from the database.
2261
                return chanInfo.AuthProof != nil
5✔
2262

2263
        case *lnwire.ChannelUpdate1:
13✔
2264
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
13✔
2265

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

2278
                // Otherwise, we'll retrieve the correct policy that we
2279
                // currently have stored within our graph to check if this
2280
                // message is stale by comparing its timestamp.
2281
                var p *models.ChannelEdgePolicy
13✔
2282
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
26✔
2283
                        p = p1
13✔
2284
                } else {
16✔
2285
                        p = p2
3✔
2286
                }
3✔
2287

2288
                // If the policy is still unknown, then we can consider this
2289
                // policy fresh.
2290
                if p == nil {
13✔
2291
                        return false
×
2292
                }
×
2293

2294
                timestamp := time.Unix(int64(msg.Timestamp), 0)
13✔
2295
                return p.LastUpdate.After(timestamp)
13✔
2296

2297
        default:
×
2298
                // We'll make sure to not mark any unsupported messages as stale
×
2299
                // to ensure they are not removed.
×
2300
                return false
×
2301
        }
2302
}
2303

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

7✔
2311
        // Parse the unsigned edge into a channel update.
7✔
2312
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
7✔
2313

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

2324
        // Next, we'll set the new signature in place, and update the reference
2325
        // in the backing slice.
2326
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
7✔
2327
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
7✔
2328

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

2339
        // Finally, we'll write the new edge policy to disk.
2340
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
7✔
2341
                return nil, nil, err
×
2342
        }
×
2343

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

2386
        return chanAnn, chanUpdate, err
7✔
2387
}
2388

2389
// SyncManager returns the gossiper's SyncManager instance.
2390
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2391
        return d.syncMgr
3✔
2392
}
3✔
2393

2394
// IsKeepAliveUpdate determines whether this channel update is considered a
2395
// keep-alive update based on the previous channel update processed for the same
2396
// direction.
2397
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2398
        prev *models.ChannelEdgePolicy) bool {
20✔
2399

20✔
2400
        // Both updates should be from the same direction.
20✔
2401
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
20✔
2402
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
20✔
2403

×
2404
                return false
×
2405
        }
×
2406

2407
        // The timestamp should always increase for a keep-alive update.
2408
        timestamp := time.Unix(int64(update.Timestamp), 0)
20✔
2409
        if !timestamp.After(prev.LastUpdate) {
20✔
2410
                return false
×
2411
        }
×
2412

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

2441
// latestHeight returns the gossiper's latest height known of the chain.
2442
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2443
        d.Lock()
3✔
2444
        defer d.Unlock()
3✔
2445
        return d.bestHeight
3✔
2446
}
3✔
2447

2448
// handleNodeAnnouncement processes a new node announcement.
2449
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2450
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2451
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
27✔
2452

27✔
2453
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
27✔
2454

27✔
2455
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
27✔
2456
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
27✔
2457
                nMsg.source.SerializeCompressed())
27✔
2458

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

2467
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
22✔
2468
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2469
                        err)
3✔
2470

3✔
2471
                if !graph.IsError(
3✔
2472
                        err,
3✔
2473
                        graph.ErrOutdated,
3✔
2474
                        graph.ErrIgnored,
3✔
2475
                ) {
3✔
2476

×
2477
                        log.Error(err)
×
2478
                }
×
2479

2480
                nMsg.err <- err
3✔
2481
                return nil, false
3✔
2482
        }
2483

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

2495
        var announcements []networkMsg
19✔
2496

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

2511
        nMsg.err <- nil
19✔
2512
        // TODO(roasbeef): get rid of the above
19✔
2513

19✔
2514
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
19✔
2515
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
19✔
2516
                nMsg.source.SerializeCompressed())
19✔
2517

19✔
2518
        return announcements, true
19✔
2519
}
2520

2521
// handleChanAnnouncement processes a new channel announcement.
2522
//
2523
//nolint:funlen
2524
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2525
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2526
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
237✔
2527

237✔
2528
        scid := ann.ShortChannelID
237✔
2529

237✔
2530
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
237✔
2531
                nMsg.peer, scid.ToUint64())
237✔
2532

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

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

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

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

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

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

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

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

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

×
2596
                return nil, false
×
2597
        }
×
2598

2599
        if closed {
236✔
2600
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2601
                log.Error(err)
1✔
2602

1✔
2603
                // If this is an announcement from us, we'll just ignore it.
1✔
2604
                if !nMsg.isRemote {
1✔
2605
                        nMsg.err <- err
×
2606
                        return nil, false
×
2607
                }
×
2608

2609
                // Increment the peer's ban score if they are sending closed
2610
                // channel announcements.
2611
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2612

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

×
2621
                        return nil, false
×
2622
                }
×
2623

2624
                if shouldDc {
1✔
2625
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2626
                }
×
2627

2628
                nMsg.err <- err
1✔
2629

1✔
2630
                return nil, false
1✔
2631
        }
2632

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

×
2642
                        key := newRejectCacheKey(
×
2643
                                scid.ToUint64(),
×
2644
                                sourceToPub(nMsg.source),
×
2645
                        )
×
2646
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2647

×
2648
                        log.Error(err)
×
2649
                        nMsg.err <- err
×
2650
                        return nil, false
×
2651
                }
×
2652

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

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

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

2692
                // Optional tapscript root for custom channels.
2693
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
17✔
2694
        }
2695

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

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

204✔
2717
                        switch {
204✔
2718
                        case errors.Is(err, ErrNoFundingTransaction),
2719
                                errors.Is(err, ErrInvalidFundingOutput):
202✔
2720

202✔
2721
                                key := newRejectCacheKey(
202✔
2722
                                        scid.ToUint64(),
202✔
2723
                                        sourceToPub(nMsg.source),
202✔
2724
                                )
202✔
2725
                                _, _ = d.recentRejects.Put(
202✔
2726
                                        key, &cachedReject{},
202✔
2727
                                )
202✔
2728

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

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

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

×
2756
                                        nMsg.err <- dbErr
×
2757

×
2758
                                        return nil, false
×
2759
                                }
×
2760

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

2770
                        default:
×
2771
                                // Otherwise, this is just a regular rejected
×
2772
                                // edge.
×
2773
                                key := newRejectCacheKey(
×
2774
                                        scid.ToUint64(),
×
2775
                                        sourceToPub(nMsg.source),
×
2776
                                )
×
2777
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2778
                        }
2779

2780
                        if !nMsg.isRemote {
204✔
2781
                                log.Errorf("failed to add edge for local "+
×
2782
                                        "channel: %v", err)
×
2783
                                nMsg.err <- err
×
2784

×
2785
                                return nil, false
×
2786
                        }
×
2787

2788
                        shouldDc, dcErr := d.ShouldDisconnect(
204✔
2789
                                nMsg.peer.IdentityKey(),
204✔
2790
                        )
204✔
2791
                        if dcErr != nil {
204✔
2792
                                log.Errorf("failed to check if we should "+
×
2793
                                        "disconnect peer: %v", dcErr)
×
2794
                                nMsg.err <- dcErr
×
2795

×
2796
                                return nil, false
×
2797
                        }
×
2798

2799
                        if shouldDc {
205✔
2800
                                nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2801
                        }
1✔
2802

2803
                        nMsg.err <- err
204✔
2804

204✔
2805
                        return nil, false
204✔
2806
                }
2807

2808
                edge.FundingScript = fn.Some(script)
28✔
2809

28✔
2810
                // TODO(roasbeef): this is a hack, needs to be removed after
28✔
2811
                //  commitment fees are dynamic.
28✔
2812
                edge.Capacity = capacity
28✔
2813
                edge.ChannelPoint = op
28✔
2814
        }
2815

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

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

4✔
2826
                defer d.channelMtx.Unlock(scid.ToUint64())
4✔
2827

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

×
2843
                                nMsg.err <- rErr
×
2844

×
2845
                                return nil, false
×
2846
                        }
×
2847

2848
                        log.Debugf("Extracted %v announcements from rejected "+
3✔
2849
                                "msgs", len(anns))
3✔
2850

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

3✔
2859
                        return anns, true
3✔
2860
                }
2861

2862
                // Otherwise, this is just a regular rejected edge.
2863
                key := newRejectCacheKey(
1✔
2864
                        scid.ToUint64(),
1✔
2865
                        sourceToPub(nMsg.source),
1✔
2866
                )
1✔
2867
                _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2868

1✔
2869
                if !nMsg.isRemote {
1✔
2870
                        log.Errorf("failed to add edge for local channel: %v",
×
2871
                                err)
×
2872
                        nMsg.err <- err
×
2873

×
2874
                        return nil, false
×
2875
                }
×
2876

2877
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2878
                if dcErr != nil {
1✔
2879
                        log.Errorf("failed to check if we should disconnect "+
×
2880
                                "peer: %v", dcErr)
×
2881
                        nMsg.err <- dcErr
×
2882

×
2883
                        return nil, false
×
2884
                }
×
2885

2886
                if shouldDc {
1✔
2887
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2888
                }
×
2889

2890
                nMsg.err <- err
1✔
2891

1✔
2892
                return nil, false
1✔
2893
        }
2894

2895
        // If err is nil, release the lock immediately.
2896
        d.channelMtx.Unlock(scid.ToUint64())
29✔
2897

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

29✔
2900
        // If we earlier received any ChannelUpdates for this channel, we can
29✔
2901
        // now process them, as the channel is added to the graph.
29✔
2902
        var channelUpdates []*processedNetworkMsg
29✔
2903

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

2913
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2914
        // ensure we don't block here, as we can handle only one announcement
2915
        // at a time.
2916
        for _, cu := range channelUpdates {
34✔
2917
                // Skip if already processed.
5✔
2918
                if cu.processed {
8✔
2919
                        continue
3✔
2920
                }
2921

2922
                // Mark the ChannelUpdate as processed. This ensures that a
2923
                // subsequent announcement in the option-scid-alias case does
2924
                // not re-use an old ChannelUpdate.
2925
                cu.processed = true
5✔
2926

5✔
2927
                d.wg.Add(1)
5✔
2928
                go func(updMsg *networkMsg) {
10✔
2929
                        defer d.wg.Done()
5✔
2930

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

5✔
2939
                                select {
5✔
2940
                                case d.networkMsgs <- updMsg:
5✔
2941
                                case <-d.quit:
×
2942
                                        updMsg.err <- ErrGossiperShuttingDown
×
2943
                                }
2944

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

2954
        // Channel announcement was successfully processed and now it might be
2955
        // broadcast to other connected nodes if it was an announcement with
2956
        // proof (remote).
2957
        var announcements []networkMsg
29✔
2958

29✔
2959
        if proof != nil {
44✔
2960
                announcements = append(announcements, networkMsg{
15✔
2961
                        peer:     nMsg.peer,
15✔
2962
                        isRemote: nMsg.isRemote,
15✔
2963
                        source:   nMsg.source,
15✔
2964
                        msg:      ann,
15✔
2965
                })
15✔
2966
        }
15✔
2967

2968
        nMsg.err <- nil
29✔
2969

29✔
2970
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
29✔
2971
                nMsg.peer, scid.ToUint64())
29✔
2972

29✔
2973
        return announcements, true
29✔
2974
}
2975

2976
// handleChanUpdate processes a new channel update.
2977
//
2978
//nolint:funlen
2979
func (d *AuthenticatedGossiper) handleChanUpdate(ctx context.Context,
2980
        nMsg *networkMsg, upd *lnwire.ChannelUpdate1,
2981
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
64✔
2982

64✔
2983
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
64✔
2984
                nMsg.peer, upd.ShortChannelID.ToUint64())
64✔
2985

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

×
2993
                key := newRejectCacheKey(
×
2994
                        upd.ShortChannelID.ToUint64(),
×
2995
                        sourceToPub(nMsg.source),
×
2996
                )
×
2997
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2998

×
2999
                nMsg.err <- err
×
3000
                return nil, false
×
3001
        }
×
3002

3003
        blockHeight := upd.ShortChannelID.BlockHeight
64✔
3004
        shortChanID := upd.ShortChannelID.ToUint64()
64✔
3005

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

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

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

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

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

64✔
3047
        if d.cfg.Graph.IsStaleEdgePolicy(
64✔
3048
                graphScid, timestamp, upd.ChannelFlags,
64✔
3049
        ) {
70✔
3050

6✔
3051
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
6✔
3052
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
6✔
3053
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
6✔
3054
                )
6✔
3055

6✔
3056
                nMsg.err <- nil
6✔
3057
                return nil, true
6✔
3058
        }
6✔
3059

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

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

×
3073
                return nil, false
×
3074
        }
×
3075

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

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

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

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

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

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

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

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

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

×
3166
                return nil, false
×
3167
        }
3168

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

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

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

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

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

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

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

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

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

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

3299
                nMsg.err <- err
×
3300
                return nil, false
×
3301
        }
3302

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

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

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

3334
                                upd.Signature = lnSig
3✔
3335
                        }
3336
                }
3337

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

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

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

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

3374
        nMsg.err <- nil
46✔
3375

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

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

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

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

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

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

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

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

3✔
3438
                        return nil, false
3✔
3439
                }
3✔
3440

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12✔
3571
                nMsg.err <- nil
12✔
3572
                return nil, false
12✔
3573
        }
3574

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

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

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

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

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

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

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

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

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

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

3699
        nMsg.err <- nil
13✔
3700
        return announcements, true
13✔
3701
}
3702

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

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

209✔
3714
        pubkeySer := pubkey.SerializeCompressed()
209✔
3715

209✔
3716
        var pubkeyBytes [33]byte
209✔
3717
        copy(pubkeyBytes[:], pubkeySer)
209✔
3718

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

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

3733
        return false, nil
208✔
3734
}
3735

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

232✔
3745
        scid := ann.ShortChannelID
232✔
3746

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

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

3779
                default:
×
3780
                }
3781

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

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

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

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

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

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

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

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

231✔
3850
        legacyFundingScript := func() ([]byte, error) {
462✔
3851
                witnessScript, err := input.GenMultiSigScript(
231✔
3852
                        bitcoinKey1, bitcoinKey2,
231✔
3853
                )
231✔
3854
                if err != nil {
231✔
3855
                        return nil, err
×
3856
                }
×
3857
                pkScript, err := input.WitnessScriptHash(witnessScript)
231✔
3858
                if err != nil {
231✔
3859
                        return nil, err
×
3860
                }
×
3861

3862
                return pkScript, nil
231✔
3863
        }
3864

3865
        if features.IsEmpty() {
462✔
3866
                return legacyFundingScript()
231✔
3867
        }
231✔
3868

3869
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
3✔
3870
        if chanFeatureBits.HasFeature(
3✔
3871
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
3872
        ) {
6✔
3873

3✔
3874
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
3875
                if err != nil {
3✔
3876
                        return nil, err
×
3877
                }
×
3878
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
3879
                if err != nil {
3✔
3880
                        return nil, err
×
3881
                }
×
3882

3883
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
3884
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
3885
                )
3✔
3886
                if err != nil {
3✔
3887
                        return nil, err
×
3888
                }
×
3889

3890
                // TODO(roasbeef): add tapscript root to gossip v1.5
3891

3892
                return fundingScript, nil
3✔
3893
        }
3894

3895
        return legacyFundingScript()
×
3896
}
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