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

lightningnetwork / lnd / 16569502135

28 Jul 2025 12:50PM UTC coverage: 67.251% (+0.02%) from 67.227%
16569502135

Pull #9455

github

web-flow
Merge b3899c4fd into 2e36f9b8b
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

179 of 208 new or added lines in 6 files covered. (86.06%)

105 existing lines in 23 files now uncovered.

135676 of 201746 relevant lines covered (67.25%)

21711.59 hits per line

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

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

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

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

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

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

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

475✔
443
        return k
475✔
444
}
475✔
445

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

454
// cachedReject is the empty value used to track the value for rejects.
455
type cachedReject struct {
456
}
457

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

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

478
        // bestHeight is the height of the block at the tip of the main chain
479
        // as we know it. Accesses *MUST* be done with the gossiper's lock
480
        // held.
481
        bestHeight uint32
482

483
        // cfg is a copy of the configuration struct that the gossiper service
484
        // was initialized with.
485
        cfg *Config
486

487
        // blockEpochs encapsulates a stream of block epochs that are sent at
488
        // every new block height.
489
        blockEpochs *chainntnfs.BlockEpochEvent
490

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

497
        // banman tracks our peer's ban status.
498
        banman *banman
499

500
        // networkMsgs is a channel that carries new network broadcasted
501
        // message from outside the gossiper service to be processed by the
502
        // networkHandler.
503
        networkMsgs chan *networkMsg
504

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

512
        // chanPolicyUpdates is a channel that requests to update the
513
        // forwarding policy of a set of channels is sent over.
514
        chanPolicyUpdates chan *chanPolicyUpdateRequest
515

516
        // selfKey is the identity public key of the backing Lightning node.
517
        selfKey *btcec.PublicKey
518

519
        // selfKeyLoc is the locator for the identity public key of the backing
520
        // Lightning node.
521
        selfKeyLoc keychain.KeyLocator
522

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

529
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
530

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

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

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

556
        // vb is used to enforce job dependency ordering of gossip messages.
557
        vb *ValidationBarrier
558

559
        sync.Mutex
560

561
        cancel fn.Option[context.CancelFunc]
562
        quit   chan struct{}
563
        wg     sync.WaitGroup
564
}
565

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

33✔
588
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
33✔
589

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

33✔
605
        gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
33✔
606
                NotifyWhenOnline:  cfg.NotifyWhenOnline,
33✔
607
                NotifyWhenOffline: cfg.NotifyWhenOffline,
33✔
608
                MessageStore:      cfg.MessageStore,
33✔
609
                IsMsgStale:        gossiper.isMsgStale,
33✔
610
        })
33✔
611

33✔
612
        return gossiper
33✔
613
}
33✔
614

615
// EdgeWithInfo contains the information that is required to update an edge.
616
type EdgeWithInfo struct {
617
        // Info describes the channel.
618
        Info *models.ChannelEdgeInfo
619

620
        // Edge describes the policy in one direction of the channel.
621
        Edge *models.ChannelEdgePolicy
622
}
623

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

4✔
633
        errChan := make(chan error, 1)
4✔
634
        policyUpdate := &chanPolicyUpdateRequest{
4✔
635
                edgesToUpdate: edgesToUpdate,
4✔
636
                errChan:       errChan,
4✔
637
        }
4✔
638

4✔
639
        select {
4✔
640
        case d.chanPolicyUpdates <- policyUpdate:
4✔
641
                err := <-errChan
4✔
642
                return err
4✔
643
        case <-d.quit:
×
644
                return fmt.Errorf("AuthenticatedGossiper shutting down")
×
645
        }
646
}
647

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

33✔
656
                log.Info("Authenticated Gossiper starting")
33✔
657
                err = d.start(ctx)
33✔
658
        })
33✔
659
        return err
33✔
660
}
661

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

33✔
672
        height, err := d.cfg.Graph.CurrentBlockHeight()
33✔
673
        if err != nil {
33✔
674
                return err
×
675
        }
×
676
        d.bestHeight = height
33✔
677

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

685
        d.syncMgr.Start()
33✔
686

33✔
687
        d.banman.start()
33✔
688

33✔
689
        // Start receiving blocks in its dedicated goroutine.
33✔
690
        d.wg.Add(2)
33✔
691
        go d.syncBlockHeight()
33✔
692
        go d.networkHandler(ctx)
33✔
693

33✔
694
        return nil
33✔
695
}
696

697
// syncBlockHeight syncs the best block height for the gossiper by reading
698
// blockEpochs.
699
//
700
// NOTE: must be run as a goroutine.
701
func (d *AuthenticatedGossiper) syncBlockHeight() {
33✔
702
        defer d.wg.Done()
33✔
703

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

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

3✔
722
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
3✔
723
                                newBlock.Hash)
3✔
724

3✔
725
                        // Resend future messages, if any.
3✔
726
                        d.resendFutureMessages(blockHeight)
3✔
727

728
                case <-d.quit:
30✔
729
                        return
30✔
730
                }
731
        }
732
}
733

734
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
735
// the unique ID when saving the message.
736
type futureMsgCache struct {
737
        *lru.Cache[uint64, *cachedFutureMsg]
738

739
        // msgID is a monotonically increased integer.
740
        msgID atomic.Uint64
741
}
742

743
// nextMsgID returns a unique message ID.
744
func (f *futureMsgCache) nextMsgID() uint64 {
6✔
745
        return f.msgID.Add(1)
6✔
746
}
6✔
747

748
// newFutureMsgCache creates a new future message cache with the underlying lru
749
// cache being initialized with the specified capacity.
750
func newFutureMsgCache(capacity uint64) *futureMsgCache {
34✔
751
        // Create a new cache.
34✔
752
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
34✔
753

34✔
754
        return &futureMsgCache{
34✔
755
                Cache: cache,
34✔
756
        }
34✔
757
}
34✔
758

759
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
760
type cachedFutureMsg struct {
761
        // msg is the network message.
762
        msg *networkMsg
763

764
        // height is the block height.
765
        height uint32
766
}
767

768
// Size returns the size of the message.
769
func (c *cachedFutureMsg) Size() (uint64, error) {
7✔
770
        // Return a constant 1.
7✔
771
        return 1, nil
7✔
772
}
7✔
773

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

3✔
782
                // keys are the target messages' caching keys.
3✔
783
                keys []uint64
3✔
784
        )
3✔
785

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

793
                return true
3✔
794
        }
795

796
        // Filter out the target messages.
797
        d.futureMsgs.Range(filterMsgs)
3✔
798

3✔
799
        // Return early if no messages found.
3✔
800
        if len(msgs) == 0 {
6✔
801
                return
3✔
802
        }
3✔
803

804
        // Remove the filtered messages.
805
        for _, key := range keys {
6✔
806
                d.futureMsgs.Delete(key)
3✔
807
        }
3✔
808

809
        log.Debugf("Resending %d network messages at height %d",
3✔
810
                len(msgs), height)
3✔
811

3✔
812
        for _, msg := range msgs {
6✔
813
                select {
3✔
814
                case d.networkMsgs <- msg:
3✔
815
                case <-d.quit:
×
816
                        msg.err <- ErrGossiperShuttingDown
×
817
                }
818
        }
819
}
820

821
// Stop signals any active goroutines for a graceful closure.
822
func (d *AuthenticatedGossiper) Stop() error {
34✔
823
        d.stopped.Do(func() {
67✔
824
                log.Info("Authenticated gossiper shutting down...")
33✔
825
                defer log.Debug("Authenticated gossiper shutdown complete")
33✔
826

33✔
827
                d.stop()
33✔
828
        })
33✔
829
        return nil
34✔
830
}
831

832
func (d *AuthenticatedGossiper) stop() {
33✔
833
        log.Debug("Authenticated Gossiper is stopping")
33✔
834
        defer log.Debug("Authenticated Gossiper stopped")
33✔
835

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

843
        d.syncMgr.Stop()
33✔
844

33✔
845
        d.banman.stop()
33✔
846

33✔
847
        d.cancel.WhenSome(func(fn context.CancelFunc) { fn() })
66✔
848
        close(d.quit)
33✔
849
        d.wg.Wait()
33✔
850

33✔
851
        // We'll stop our reliable sender after all of the gossiper's goroutines
33✔
852
        // have exited to ensure nothing can cause it to continue executing.
33✔
853
        d.reliableSender.Stop()
33✔
854
}
855

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

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

294✔
867
        errChan := make(chan error, 1)
294✔
868

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

3✔
878
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
3✔
879
                if !ok {
3✔
880
                        log.Warnf("Gossip syncer for peer=%x not found",
×
881
                                peer.PubKey())
×
882

×
883
                        errChan <- ErrGossipSyncerNotFound
×
884
                        return errChan
×
885
                }
×
886

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

895
                errChan <- err
3✔
896
                return errChan
3✔
897

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

×
906
                        errChan <- ErrGossipSyncerNotFound
×
907
                        return errChan
×
908
                }
×
909

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

×
916
                        errChan <- err
×
917
                        return errChan
×
918
                }
×
919

920
                errChan <- nil
3✔
921
                return errChan
3✔
922

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

223✔
931
                if bytes.Equal(m.NodeID1[:], ownKey) ||
223✔
932
                        bytes.Equal(m.NodeID2[:], ownKey) {
228✔
933

5✔
934
                        log.Warn(ownErr)
5✔
935
                        errChan <- ownErr
5✔
936
                        return errChan
5✔
937
                }
5✔
938
        }
939

940
        nMsg := &networkMsg{
292✔
941
                msg:      msg,
292✔
942
                isRemote: true,
292✔
943
                peer:     peer,
292✔
944
                source:   peer.IdentityKey(),
292✔
945
                err:      errChan,
292✔
946
        }
292✔
947

292✔
948
        select {
292✔
949
        case d.networkMsgs <- nMsg:
292✔
950

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

963
        return nMsg.err
292✔
964
}
965

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

50✔
976
        optionalMsgFields := &optionalMsgFields{}
50✔
977
        optionalMsgFields.apply(optionalFields...)
50✔
978

50✔
979
        nMsg := &networkMsg{
50✔
980
                msg:               msg,
50✔
981
                optionalMsgFields: optionalMsgFields,
50✔
982
                isRemote:          false,
50✔
983
                source:            d.selfKey,
50✔
984
                err:               make(chan error, 1),
50✔
985
        }
50✔
986

50✔
987
        select {
50✔
988
        case d.networkMsgs <- nMsg:
50✔
989
        case <-d.quit:
×
990
                nMsg.err <- ErrGossiperShuttingDown
×
991
        }
992

993
        return nMsg.err
50✔
994
}
995

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

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

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

1018
        // isLocal is true if this was a message that originated locally. We'll
1019
        // use this to bypass our normal checks to ensure we prioritize sending
1020
        // out our own updates.
1021
        isLocal bool
1022

1023
        // sender is the set of peers that sent us this message.
1024
        senders map[route.Vertex]struct{}
1025
}
1026

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

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

1048
        // channelUpdates are identified by the channel update id field.
1049
        channelUpdates map[channelUpdateID]msgWithSenders
1050

1051
        // nodeAnnouncements are identified by the Vertex field.
1052
        nodeAnnouncements map[route.Vertex]msgWithSenders
1053

1054
        sync.Mutex
1055
}
1056

1057
// Reset operates on deDupedAnnouncements to reset the storage of
1058
// announcements.
1059
func (d *deDupedAnnouncements) Reset() {
35✔
1060
        d.Lock()
35✔
1061
        defer d.Unlock()
35✔
1062

35✔
1063
        d.reset()
35✔
1064
}
35✔
1065

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

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

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

1091
        // Channel announcements are identified by the short channel id field.
1092
        case *lnwire.ChannelAnnouncement1:
26✔
1093
                deDupKey := msg.ShortChannelID
26✔
1094
                sender := route.NewVertex(message.source)
26✔
1095

26✔
1096
                mws, ok := d.channelAnnouncements[deDupKey]
26✔
1097
                if !ok {
51✔
1098
                        mws = msgWithSenders{
25✔
1099
                                msg:     msg,
25✔
1100
                                isLocal: !message.isRemote,
25✔
1101
                                senders: make(map[route.Vertex]struct{}),
25✔
1102
                        }
25✔
1103
                        mws.senders[sender] = struct{}{}
25✔
1104

25✔
1105
                        d.channelAnnouncements[deDupKey] = mws
25✔
1106

25✔
1107
                        return
25✔
1108
                }
25✔
1109

1110
                mws.msg = msg
1✔
1111
                mws.senders[sender] = struct{}{}
1✔
1112
                d.channelAnnouncements[deDupKey] = mws
1✔
1113

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

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

×
1133
                                return
×
1134
                        }
×
1135

1136
                        oldTimestamp = update.Timestamp
3✔
1137
                }
1138

1139
                // If we already had this message with a strictly newer
1140
                // timestamp, then we'll just discard the message we got.
1141
                if oldTimestamp > msg.Timestamp {
50✔
1142
                        log.Debugf("Ignored outdated network message: "+
1✔
1143
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1144
                        return
1✔
1145
                }
1✔
1146

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

47✔
1157
                        // We'll mark the sender of the message in the
47✔
1158
                        // senders map.
47✔
1159
                        mws.senders[sender] = struct{}{}
47✔
1160

47✔
1161
                        d.channelUpdates[deDupKey] = mws
47✔
1162

47✔
1163
                        return
47✔
1164
                }
47✔
1165

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

1174
        // Node announcements are identified by the Vertex field.  Use the
1175
        // NodeID to create the corresponding Vertex.
1176
        case *lnwire.NodeAnnouncement:
25✔
1177
                sender := route.NewVertex(message.source)
25✔
1178
                deDupKey := route.Vertex(msg.NodeID)
25✔
1179

25✔
1180
                // We do the same for node announcements as we did for channel
25✔
1181
                // updates, as they also carry a timestamp.
25✔
1182
                oldTimestamp := uint32(0)
25✔
1183
                mws, ok := d.nodeAnnouncements[deDupKey]
25✔
1184
                if ok {
33✔
1185
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
8✔
1186
                }
8✔
1187

1188
                // Discard the message if it's old.
1189
                if oldTimestamp > msg.Timestamp {
28✔
1190
                        return
3✔
1191
                }
3✔
1192

1193
                // Replace if it's newer.
1194
                if oldTimestamp < msg.Timestamp {
46✔
1195
                        mws = msgWithSenders{
21✔
1196
                                msg:     msg,
21✔
1197
                                isLocal: !message.isRemote,
21✔
1198
                                senders: make(map[route.Vertex]struct{}),
21✔
1199
                        }
21✔
1200

21✔
1201
                        mws.senders[sender] = struct{}{}
21✔
1202

21✔
1203
                        d.nodeAnnouncements[deDupKey] = mws
21✔
1204

21✔
1205
                        return
21✔
1206
                }
21✔
1207

1208
                // Add to senders map if it's the same as we had.
1209
                mws.msg = msg
7✔
1210
                mws.senders[sender] = struct{}{}
7✔
1211
                d.nodeAnnouncements[deDupKey] = mws
7✔
1212
        }
1213
}
1214

1215
// AddMsgs is a helper method to add multiple messages to the announcement
1216
// batch.
1217
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
62✔
1218
        d.Lock()
62✔
1219
        defer d.Unlock()
62✔
1220

62✔
1221
        for _, msg := range msgs {
156✔
1222
                d.addMsg(msg)
94✔
1223
        }
94✔
1224
}
1225

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

1233
        // remoteMsgs is the set of messages that we received from a remote
1234
        // party.
1235
        remoteMsgs []msgWithSenders
1236
}
1237

1238
// addMsg adds a new message to the appropriate sub-slice.
1239
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
79✔
1240
        if msg.isLocal {
129✔
1241
                m.localMsgs = append(m.localMsgs, msg)
50✔
1242
        } else {
82✔
1243
                m.remoteMsgs = append(m.remoteMsgs, msg)
32✔
1244
        }
32✔
1245
}
1246

1247
// isEmpty returns true if the batch is empty.
1248
func (m *msgsToBroadcast) isEmpty() bool {
298✔
1249
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
298✔
1250
}
298✔
1251

1252
// length returns the length of the combined message set.
1253
func (m *msgsToBroadcast) length() int {
1✔
1254
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1255
}
1✔
1256

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

299✔
1267
        // Get the total number of announcements.
299✔
1268
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
299✔
1269
                len(d.nodeAnnouncements)
299✔
1270

299✔
1271
        // Create an empty array of lnwire.Messages with a length equal to
299✔
1272
        // the total number of announcements.
299✔
1273
        msgs := msgsToBroadcast{
299✔
1274
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
299✔
1275
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
299✔
1276
        }
299✔
1277

299✔
1278
        // Add the channel announcements to the array first.
299✔
1279
        for _, message := range d.channelAnnouncements {
321✔
1280
                msgs.addMsg(message)
22✔
1281
        }
22✔
1282

1283
        // Then add the channel updates.
1284
        for _, message := range d.channelUpdates {
342✔
1285
                msgs.addMsg(message)
43✔
1286
        }
43✔
1287

1288
        // Finally add the node announcements.
1289
        for _, message := range d.nodeAnnouncements {
319✔
1290
                msgs.addMsg(message)
20✔
1291
        }
20✔
1292

1293
        d.reset()
299✔
1294

299✔
1295
        // Return the array of lnwire.messages.
299✔
1296
        return msgs
299✔
1297
}
1298

1299
// calculateSubBatchSize is a helper function that calculates the size to break
1300
// down the batchSize into.
1301
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1302
        minimumBatchSize, batchSize int) int {
16✔
1303
        if subBatchDelay > totalDelay {
18✔
1304
                return batchSize
2✔
1305
        }
2✔
1306

1307
        subBatchSize := (batchSize*int(subBatchDelay) +
14✔
1308
                int(totalDelay) - 1) / int(totalDelay)
14✔
1309

14✔
1310
        if subBatchSize < minimumBatchSize {
18✔
1311
                return minimumBatchSize
4✔
1312
        }
4✔
1313

1314
        return subBatchSize
10✔
1315
}
1316

1317
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1318
// this variable so the function can be mocked in our test.
1319
var batchSizeCalculator = calculateSubBatchSize
1320

1321
// splitAnnouncementBatches takes an exiting list of announcements and
1322
// decomposes it into sub batches controlled by the `subBatchSize`.
1323
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1324
        announcementBatch []msgWithSenders) [][]msgWithSenders {
78✔
1325

78✔
1326
        subBatchSize := batchSizeCalculator(
78✔
1327
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
78✔
1328
                d.cfg.MinimumBatchSize, len(announcementBatch),
78✔
1329
        )
78✔
1330

78✔
1331
        var splitAnnouncementBatch [][]msgWithSenders
78✔
1332

78✔
1333
        for subBatchSize < len(announcementBatch) {
202✔
1334
                // For slicing with minimal allocation
124✔
1335
                // https://github.com/golang/go/wiki/SliceTricks
124✔
1336
                announcementBatch, splitAnnouncementBatch =
124✔
1337
                        announcementBatch[subBatchSize:],
124✔
1338
                        append(splitAnnouncementBatch,
124✔
1339
                                announcementBatch[0:subBatchSize:subBatchSize])
124✔
1340
        }
124✔
1341
        splitAnnouncementBatch = append(
78✔
1342
                splitAnnouncementBatch, announcementBatch,
78✔
1343
        )
78✔
1344

78✔
1345
        return splitAnnouncementBatch
78✔
1346
}
1347

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

37✔
1355
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
37✔
1356
        // duration to delay the sending of next announcement batch.
37✔
1357
        delayNextBatch := func() {
108✔
1358
                select {
71✔
1359
                case <-time.After(d.cfg.SubBatchDelay):
54✔
1360
                case <-d.quit:
17✔
1361
                        return
17✔
1362
                }
1363
        }
1364

1365
        // Fetch the local and remote announcements.
1366
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
37✔
1367
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
37✔
1368

37✔
1369
        d.wg.Add(1)
37✔
1370
        go func() {
74✔
1371
                defer d.wg.Done()
37✔
1372

37✔
1373
                log.Debugf("Broadcasting %v new local announcements in %d "+
37✔
1374
                        "sub batches", len(annBatch.localMsgs),
37✔
1375
                        len(localBatches))
37✔
1376

37✔
1377
                // Send out the local announcements first.
37✔
1378
                for _, annBatch := range localBatches {
74✔
1379
                        d.sendLocalBatch(annBatch)
37✔
1380
                        delayNextBatch()
37✔
1381
                }
37✔
1382

1383
                log.Debugf("Broadcasting %v new remote announcements in %d "+
37✔
1384
                        "sub batches", len(annBatch.remoteMsgs),
37✔
1385
                        len(remoteBatches))
37✔
1386

37✔
1387
                // Now send the remote announcements.
37✔
1388
                for _, annBatch := range remoteBatches {
74✔
1389
                        d.sendRemoteBatch(ctx, annBatch)
37✔
1390
                        delayNextBatch()
37✔
1391
                }
37✔
1392
        }()
1393
}
1394

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

1405
        err := d.cfg.Broadcast(nil, msgsToSend...)
37✔
1406
        if err != nil {
37✔
1407
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1408
        }
×
1409
}
1410

1411
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1412
// peers.
1413
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1414
        annBatch []msgWithSenders) {
37✔
1415

37✔
1416
        syncerPeers := d.syncMgr.GossipSyncers()
37✔
1417

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

1425
        for _, msgChunk := range annBatch {
69✔
1426
                msgChunk := msgChunk
32✔
1427

32✔
1428
                // With the syncers taken care of, we'll merge the sender map
32✔
1429
                // with the set of syncers, so we don't send out duplicate
32✔
1430
                // messages.
32✔
1431
                msgChunk.mergeSyncerMap(syncerPeers)
32✔
1432

32✔
1433
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
32✔
1434
                if err != nil {
32✔
1435
                        log.Errorf("Unable to send batch "+
×
1436
                                "announcements: %v", err)
×
1437
                        continue
×
1438
                }
1439
        }
1440
}
1441

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

33✔
1451
        // Initialize empty deDupedAnnouncements to store announcement batch.
33✔
1452
        announcements := deDupedAnnouncements{}
33✔
1453
        announcements.Reset()
33✔
1454

33✔
1455
        d.cfg.RetransmitTicker.Resume()
33✔
1456
        defer d.cfg.RetransmitTicker.Stop()
33✔
1457

33✔
1458
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
33✔
1459
        defer trickleTimer.Stop()
33✔
1460

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

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

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

1489
                        // Finally, with the updates committed, we'll now add
1490
                        // them to the announcement batch to be flushed at the
1491
                        // start of the next epoch.
1492
                        announcements.AddMsgs(newChanUpdates...)
4✔
1493

1494
                case announcement := <-d.networkMsgs:
341✔
1495
                        log.Tracef("Received network message: "+
341✔
1496
                                "peer=%v, msg=%s, is_remote=%v",
341✔
1497
                                announcement.peer, announcement.msg.MsgType(),
341✔
1498
                                announcement.isRemote)
341✔
1499

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

24✔
1512
                                if emittedAnnouncements != nil {
37✔
1513
                                        announcements.AddMsgs(
13✔
1514
                                                emittedAnnouncements...,
13✔
1515
                                        )
13✔
1516
                                }
13✔
1517
                                continue
24✔
1518
                        }
1519

1520
                        // If this message was recently rejected, then we won't
1521
                        // attempt to re-process it.
1522
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
320✔
1523
                                announcement.msg,
320✔
1524
                                sourceToPub(announcement.source),
320✔
1525
                        ) {
321✔
1526

1✔
1527
                                announcement.err <- fmt.Errorf("recently " +
1✔
1528
                                        "rejected")
1✔
1529
                                continue
1✔
1530
                        }
1531

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

1543
                        d.wg.Add(1)
319✔
1544
                        go d.handleNetworkMessages(
319✔
1545
                                ctx, announcement, &announcements, annJobID,
319✔
1546
                        )
319✔
1547

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

298✔
1556
                        // If the current announcements batch is nil, then we
298✔
1557
                        // have no further work here.
298✔
1558
                        if announcementBatch.isEmpty() {
562✔
1559
                                continue
264✔
1560
                        }
1561

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

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

1582
                // The gossiper has been signalled to exit, to we exit our
1583
                // main loop so the wait group can be decremented.
1584
                case <-d.quit:
33✔
1585
                        return
33✔
1586
                }
1587
        }
1588
}
1589

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

319✔
1598
        defer d.wg.Done()
319✔
1599
        defer d.vb.CompleteJob()
319✔
1600

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

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

×
1612
                if errors.Is(err, ErrVBarrierShuttingDown) {
×
1613
                        log.Warnf("unexpected error during validation "+
×
1614
                                "barrier shutdown: %v", err)
×
1615
                }
×
1616
                nMsg.err <- err
×
1617

×
1618
                return
×
1619
        }
1620

1621
        // Process the network announcement to determine if this is either a
1622
        // new announcement from our PoV or an edges to a prior vertex/edge we
1623
        // previously proceeded.
1624
        newAnns, allow := d.processNetworkAnnouncement(ctx, nMsg)
319✔
1625

319✔
1626
        log.Tracef("Processed network message %s, returned "+
319✔
1627
                "len(announcements)=%v, allowDependents=%v",
319✔
1628
                nMsg.msg.MsgType(), len(newAnns), allow)
319✔
1629

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

×
1638
                nMsg.err <- err
×
1639

×
1640
                return
×
1641
        }
×
1642

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

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

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

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

1672
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1673
// false otherwise, This avoids expensive reprocessing of the message.
1674
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1675
        peerPub [33]byte) bool {
283✔
1676

283✔
1677
        var scid uint64
283✔
1678
        switch m := msg.(type) {
283✔
1679
        case *lnwire.ChannelUpdate1:
51✔
1680
                scid = m.ShortChannelID.ToUint64()
51✔
1681

1682
        case *lnwire.ChannelAnnouncement1:
221✔
1683
                scid = m.ShortChannelID.ToUint64()
221✔
1684

1685
        default:
17✔
1686
                return false
17✔
1687
        }
1688

1689
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
269✔
1690
        return err != cache.ErrElementNotFound
269✔
1691
}
1692

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

34✔
1701
        // Iterate over all of our channels and check if any of them fall
34✔
1702
        // within the prune interval or re-broadcast interval.
34✔
1703
        type updateTuple struct {
34✔
1704
                info *models.ChannelEdgeInfo
34✔
1705
                edge *models.ChannelEdgePolicy
34✔
1706
        }
34✔
1707

34✔
1708
        var (
34✔
1709
                havePublicChannels bool
34✔
1710
                edgesToUpdate      []updateTuple
34✔
1711
        )
34✔
1712
        err := d.cfg.Graph.ForAllOutgoingChannels(ctx, func(
34✔
1713
                info *models.ChannelEdgeInfo,
34✔
1714
                edge *models.ChannelEdgePolicy) error {
39✔
1715

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

1727
                // We make a note that we have at least one public channel. We
1728
                // use this to determine whether we should send a node
1729
                // announcement below.
1730
                havePublicChannels = true
4✔
1731

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

×
1741
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1742
                                info: info,
×
1743
                                edge: edge,
×
1744
                        })
×
1745
                        return nil
×
1746
                }
×
1747

1748
                timeElapsed := now.Sub(edge.LastUpdate)
4✔
1749

4✔
1750
                // If it's been longer than RebroadcastInterval since we've
4✔
1751
                // re-broadcasted the channel, add the channel to the set of
4✔
1752
                // edges we need to update.
4✔
1753
                if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1754
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1755
                                info: info,
1✔
1756
                                edge: edge,
1✔
1757
                        })
1✔
1758
                }
1✔
1759

1760
                return nil
4✔
1761
        }, func() {
3✔
1762
                havePublicChannels = false
3✔
1763
                edgesToUpdate = nil
3✔
1764
        })
3✔
1765
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
34✔
1766
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1767
                        err)
×
1768
        }
×
1769

1770
        var signedUpdates []lnwire.Message
34✔
1771
        for _, chanToUpdate := range edgesToUpdate {
35✔
1772
                // Re-sign and update the channel on disk and retrieve our
1✔
1773
                // ChannelUpdate to broadcast.
1✔
1774
                chanAnn, chanUpdate, err := d.updateChannel(
1✔
1775
                        ctx, chanToUpdate.info, chanToUpdate.edge,
1✔
1776
                )
1✔
1777
                if err != nil {
1✔
1778
                        return fmt.Errorf("unable to update channel: %w", err)
×
1779
                }
×
1780

1781
                // If we have a valid announcement to transmit, then we'll send
1782
                // that along with the update.
1783
                if chanAnn != nil {
2✔
1784
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1785
                }
1✔
1786

1787
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1788
        }
1789

1790
        // If we don't have any public channels, we return as we don't want to
1791
        // broadcast anything that would reveal our existence.
1792
        if !havePublicChannels {
67✔
1793
                return nil
33✔
1794
        }
33✔
1795

1796
        // We'll also check that our NodeAnnouncement is not too old.
1797
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
4✔
1798
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
4✔
1799
        timeElapsed := now.Sub(timestamp)
4✔
1800

4✔
1801
        // If it's been a full day since we've re-broadcasted the
4✔
1802
        // node announcement, refresh it and resend it.
4✔
1803
        nodeAnnStr := ""
4✔
1804
        if timeElapsed >= d.cfg.RebroadcastInterval {
5✔
1805
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
1✔
1806
                if err != nil {
1✔
1807
                        return fmt.Errorf("unable to get refreshed node "+
×
1808
                                "announcement: %v", err)
×
1809
                }
×
1810

1811
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1812
                nodeAnnStr = " and our refreshed node announcement"
1✔
1813

1✔
1814
                // Before broadcasting the refreshed node announcement, add it
1✔
1815
                // to our own graph.
1✔
1816
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
2✔
1817
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1818
                                "to graph: %v", err)
1✔
1819
                }
1✔
1820
        }
1821

1822
        // If we don't have any updates to re-broadcast, then we'll exit
1823
        // early.
1824
        if len(signedUpdates) == 0 {
7✔
1825
                return nil
3✔
1826
        }
3✔
1827

1828
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1829
                len(edgesToUpdate), nodeAnnStr)
1✔
1830

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

1837
        return nil
1✔
1838
}
1839

1840
// processChanPolicyUpdate generates a new set of channel updates for the
1841
// provided list of edges and updates the backing ChannelGraphSource.
1842
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1843
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
4✔
1844

4✔
1845
        var chanUpdates []networkMsg
4✔
1846
        for _, edgeInfo := range edgesToUpdate {
10✔
1847
                // Now that we've collected all the channels we need to update,
6✔
1848
                // we'll re-sign and update the backing ChannelGraphSource, and
6✔
1849
                // retrieve our ChannelUpdate to broadcast.
6✔
1850
                _, chanUpdate, err := d.updateChannel(
6✔
1851
                        ctx, edgeInfo.Info, edgeInfo.Edge,
6✔
1852
                )
6✔
1853
                if err != nil {
6✔
1854
                        return nil, err
×
1855
                }
×
1856

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

4✔
1871
                        var defaultAlias lnwire.ShortChannelID
4✔
1872
                        foundAlias, _ := d.cfg.GetAlias(chanID)
4✔
1873
                        if foundAlias != defaultAlias {
7✔
1874
                                chanUpdate.ShortChannelID = foundAlias
3✔
1875

3✔
1876
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
3✔
1877
                                if err != nil {
3✔
1878
                                        log.Errorf("Unable to sign alias "+
×
1879
                                                "update: %v", err)
×
1880
                                        continue
×
1881
                                }
1882

1883
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1884
                                if err != nil {
3✔
1885
                                        log.Errorf("Unable to create sig: %v",
×
1886
                                                err)
×
1887
                                        continue
×
1888
                                }
1889

1890
                                chanUpdate.Signature = lnSig
3✔
1891
                        }
1892

1893
                        remotePubKey := remotePubFromChanInfo(
4✔
1894
                                edgeInfo.Info, chanUpdate.ChannelFlags,
4✔
1895
                        )
4✔
1896
                        err := d.reliableSender.sendMessage(
4✔
1897
                                ctx, chanUpdate, remotePubKey,
4✔
1898
                        )
4✔
1899
                        if err != nil {
4✔
1900
                                log.Errorf("Unable to reliably send %v for "+
×
1901
                                        "channel=%v to peer=%x: %v",
×
1902
                                        chanUpdate.MsgType(),
×
1903
                                        chanUpdate.ShortChannelID,
×
1904
                                        remotePubKey, err)
×
1905
                        }
×
1906
                        continue
4✔
1907
                }
1908

1909
                // We set ourselves as the source of this message to indicate
1910
                // that we shouldn't skip any peers when sending this message.
1911
                chanUpdates = append(chanUpdates, networkMsg{
5✔
1912
                        source:   d.selfKey,
5✔
1913
                        isRemote: false,
5✔
1914
                        msg:      chanUpdate,
5✔
1915
                })
5✔
1916
        }
1917

1918
        return chanUpdates, nil
4✔
1919
}
1920

1921
// remotePubFromChanInfo returns the public key of the remote peer given a
1922
// ChannelEdgeInfo that describe a channel we have with them.
1923
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1924
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
15✔
1925

15✔
1926
        var remotePubKey [33]byte
15✔
1927
        switch {
15✔
1928
        case chanFlags&lnwire.ChanUpdateDirection == 0:
15✔
1929
                remotePubKey = chanInfo.NodeKey2Bytes
15✔
1930
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1931
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1932
        }
1933

1934
        return remotePubKey
15✔
1935
}
1936

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

3✔
1948
        // First, we'll fetch the state of the channel as we know if from the
3✔
1949
        // database.
3✔
1950
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
3✔
1951
                chanAnnMsg.ShortChannelID,
3✔
1952
        )
3✔
1953
        if err != nil {
3✔
1954
                return nil, err
×
1955
        }
×
1956

1957
        // The edge is in the graph, and has a proof attached, then we'll just
1958
        // reject it as normal.
1959
        if chanInfo.AuthProof != nil {
6✔
1960
                return nil, nil
3✔
1961
        }
3✔
1962

1963
        // Otherwise, this means that the edge is within the graph, but it
1964
        // doesn't yet have a proper proof attached. If we did not receive
1965
        // the proof such that we now can add it, there's nothing more we
1966
        // can do.
1967
        if proof == nil {
×
1968
                return nil, nil
×
1969
        }
×
1970

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

1988
        // If everything checks out, then we'll add the fully assembled proof
1989
        // to the database.
1990
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
1991
        if err != nil {
×
1992
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
1993
                        chanAnnMsg.ShortChannelID, err)
×
1994
                log.Error(err)
×
1995
                return nil, err
×
1996
        }
×
1997

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

×
2018
        }
×
2019

2020
        return announcements, nil
×
2021
}
2022

2023
// fetchPKScript fetches the output script for the given SCID.
2024
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2025
        []byte, error) {
×
2026

×
2027
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2028
}
×
2029

2030
// addNode processes the given node announcement, and adds it to our channel
2031
// graph.
2032
func (d *AuthenticatedGossiper) addNode(ctx context.Context,
2033
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
20✔
2034

20✔
2035
        if err := netann.ValidateNodeAnn(msg); err != nil {
21✔
2036
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
2037
                        err)
1✔
2038
        }
1✔
2039

2040
        return d.cfg.Graph.AddNode(
19✔
2041
                ctx, models.NodeFromWireAnnouncement(msg), op...,
19✔
2042
        )
19✔
2043
}
2044

2045
// isPremature decides whether a given network message has a block height+delta
2046
// value specified in the future. If so, the message will be added to the
2047
// future message map and be processed when the block height as reached.
2048
//
2049
// NOTE: must be used inside a lock.
2050
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2051
        delta uint32, msg *networkMsg) bool {
292✔
2052

292✔
2053
        // The channel is already confirmed at chanID.BlockHeight so we minus
292✔
2054
        // one block. For instance, if the required confirmation for this
292✔
2055
        // channel announcement is 6, we then only need to wait for 5 more
292✔
2056
        // blocks once the funding tx is confirmed.
292✔
2057
        if delta > 0 {
295✔
2058
                delta--
3✔
2059
        }
3✔
2060

2061
        msgHeight := chanID.BlockHeight + delta
292✔
2062

292✔
2063
        // The message height is smaller or equal to our best known height,
292✔
2064
        // thus the message is mature.
292✔
2065
        if msgHeight <= d.bestHeight {
583✔
2066
                return false
291✔
2067
        }
291✔
2068

2069
        // Add the premature message to our future messages which will be
2070
        // resent once the block height has reached.
2071
        //
2072
        // Copy the networkMsgs since the old message's err chan will be
2073
        // consumed.
2074
        copied := &networkMsg{
4✔
2075
                peer:              msg.peer,
4✔
2076
                source:            msg.source,
4✔
2077
                msg:               msg.msg,
4✔
2078
                optionalMsgFields: msg.optionalMsgFields,
4✔
2079
                isRemote:          msg.isRemote,
4✔
2080
                err:               make(chan error, 1),
4✔
2081
        }
4✔
2082

4✔
2083
        // Create the cached message.
4✔
2084
        cachedMsg := &cachedFutureMsg{
4✔
2085
                msg:    copied,
4✔
2086
                height: msgHeight,
4✔
2087
        }
4✔
2088

4✔
2089
        // Increment the msg ID and add it to the cache.
4✔
2090
        nextMsgID := d.futureMsgs.nextMsgID()
4✔
2091
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
4✔
2092
        if err != nil {
4✔
2093
                log.Errorf("Adding future message got error: %v", err)
×
2094
        }
×
2095

2096
        log.Debugf("Network message: %v added to future messages for "+
4✔
2097
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
4✔
2098
                msgHeight, d.bestHeight)
4✔
2099

4✔
2100
        return true
4✔
2101
}
2102

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

340✔
2113
        // If this is a remote update, we set the scheduler option to lazily
340✔
2114
        // add it to the graph.
340✔
2115
        var schedulerOp []batch.SchedulerOption
340✔
2116
        if nMsg.isRemote {
633✔
2117
                schedulerOp = append(schedulerOp, batch.LazyAdd())
293✔
2118
        }
293✔
2119

2120
        switch msg := nMsg.msg.(type) {
340✔
2121
        // A new node announcement has arrived which either presents new
2122
        // information about a node in one of the channels we know about, or a
2123
        // updating previously advertised information.
2124
        case *lnwire.NodeAnnouncement:
27✔
2125
                return d.handleNodeAnnouncement(ctx, nMsg, msg, schedulerOp)
27✔
2126

2127
        // A new channel announcement has arrived, this indicates the
2128
        // *creation* of a new channel within the network. This only advertises
2129
        // the existence of a channel and not yet the routing policies in
2130
        // either direction of the channel.
2131
        case *lnwire.ChannelAnnouncement1:
234✔
2132
                return d.handleChanAnnouncement(ctx, nMsg, msg, schedulerOp...)
234✔
2133

2134
        // A new authenticated channel edge update has arrived. This indicates
2135
        // that the directional information for an already known channel has
2136
        // been updated.
2137
        case *lnwire.ChannelUpdate1:
64✔
2138
                return d.handleChanUpdate(ctx, nMsg, msg, schedulerOp)
64✔
2139

2140
        // A new signature announcement has been received. This indicates
2141
        // willingness of nodes involved in the funding of a channel to
2142
        // announce this new channel to the rest of the world.
2143
        case *lnwire.AnnounceSignatures1:
24✔
2144
                return d.handleAnnSig(ctx, nMsg, msg)
24✔
2145

2146
        default:
×
2147
                err := errors.New("wrong type of the announcement")
×
2148
                nMsg.err <- err
×
2149
                return nil, false
×
2150
        }
2151
}
2152

2153
// processZombieUpdate determines whether the provided channel update should
2154
// resurrect a given zombie edge.
2155
//
2156
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2157
// should be inspected.
2158
func (d *AuthenticatedGossiper) processZombieUpdate(_ context.Context,
2159
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2160
        msg *lnwire.ChannelUpdate1) error {
3✔
2161

3✔
2162
        // The least-significant bit in the flag on the channel update tells us
3✔
2163
        // which edge is being updated.
3✔
2164
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2165

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

2183
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2184
        if err != nil {
3✔
2185
                return fmt.Errorf("unable to verify channel "+
1✔
2186
                        "update signature: %v", err)
1✔
2187
        }
1✔
2188

2189
        // With the signature valid, we'll proceed to mark the
2190
        // edge as live and wait for the channel announcement to
2191
        // come through again.
2192
        err = d.cfg.Graph.MarkEdgeLive(scid)
1✔
2193
        switch {
1✔
2194
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2195
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2196
                        "zombie index: %v", err)
×
2197

×
2198
                return nil
×
2199

2200
        case err != nil:
×
2201
                return fmt.Errorf("unable to remove edge with "+
×
2202
                        "chan_id=%v from zombie index: %v",
×
2203
                        msg.ShortChannelID, err)
×
2204

2205
        default:
1✔
2206
        }
2207

2208
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2209
                "index", msg.ShortChannelID)
1✔
2210

1✔
2211
        return nil
1✔
2212
}
2213

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

23✔
2219
        node, err := d.cfg.Graph.FetchLightningNode(ctx, pubKey)
23✔
2220
        if err != nil {
29✔
2221
                return nil, err
6✔
2222
        }
6✔
2223

2224
        return node.NodeAnnouncement(true)
17✔
2225
}
2226

2227
// isMsgStale determines whether a message retrieved from the backing
2228
// MessageStore is seen as stale by the current graph.
2229
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2230
        msg lnwire.Message) bool {
15✔
2231

15✔
2232
        switch msg := msg.(type) {
15✔
2233
        case *lnwire.AnnounceSignatures1:
5✔
2234
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
5✔
2235
                        msg.ShortChannelID,
5✔
2236
                )
5✔
2237

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

2250
                // If the proof exists in the graph, then we have successfully
2251
                // received the remote proof and assembled the full proof, so we
2252
                // can safely delete the local proof from the database.
2253
                return chanInfo.AuthProof != nil
5✔
2254

2255
        case *lnwire.ChannelUpdate1:
13✔
2256
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
13✔
2257

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

2270
                // Otherwise, we'll retrieve the correct policy that we
2271
                // currently have stored within our graph to check if this
2272
                // message is stale by comparing its timestamp.
2273
                var p *models.ChannelEdgePolicy
13✔
2274
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
26✔
2275
                        p = p1
13✔
2276
                } else {
16✔
2277
                        p = p2
3✔
2278
                }
3✔
2279

2280
                // If the policy is still unknown, then we can consider this
2281
                // policy fresh.
2282
                if p == nil {
13✔
2283
                        return false
×
2284
                }
×
2285

2286
                timestamp := time.Unix(int64(msg.Timestamp), 0)
13✔
2287
                return p.LastUpdate.After(timestamp)
13✔
2288

2289
        default:
×
2290
                // We'll make sure to not mark any unsupported messages as stale
×
2291
                // to ensure they are not removed.
×
2292
                return false
×
2293
        }
2294
}
2295

2296
// updateChannel creates a new fully signed update for the channel, and updates
2297
// the underlying graph with the new state.
2298
func (d *AuthenticatedGossiper) updateChannel(ctx context.Context,
2299
        info *models.ChannelEdgeInfo,
2300
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2301
        *lnwire.ChannelUpdate1, error) {
7✔
2302

7✔
2303
        // Parse the unsigned edge into a channel update.
7✔
2304
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
7✔
2305

7✔
2306
        // We'll generate a new signature over a digest of the channel
7✔
2307
        // announcement itself and update the timestamp to ensure it propagate.
7✔
2308
        err := netann.SignChannelUpdate(
7✔
2309
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
7✔
2310
                netann.ChanUpdSetTimestamp,
7✔
2311
        )
7✔
2312
        if err != nil {
7✔
2313
                return nil, nil, err
×
2314
        }
×
2315

2316
        // Next, we'll set the new signature in place, and update the reference
2317
        // in the backing slice.
2318
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
7✔
2319
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
7✔
2320

7✔
2321
        // To ensure that our signature is valid, we'll verify it ourself
7✔
2322
        // before committing it to the slice returned.
7✔
2323
        err = netann.ValidateChannelUpdateAnn(
7✔
2324
                d.selfKey, info.Capacity, chanUpdate,
7✔
2325
        )
7✔
2326
        if err != nil {
7✔
2327
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2328
                        "update sig: %v", err)
×
2329
        }
×
2330

2331
        // Finally, we'll write the new edge policy to disk.
2332
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
7✔
2333
                return nil, nil, err
×
2334
        }
×
2335

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

2378
        return chanAnn, chanUpdate, err
7✔
2379
}
2380

2381
// SyncManager returns the gossiper's SyncManager instance.
2382
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2383
        return d.syncMgr
3✔
2384
}
3✔
2385

2386
// IsKeepAliveUpdate determines whether this channel update is considered a
2387
// keep-alive update based on the previous channel update processed for the same
2388
// direction.
2389
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2390
        prev *models.ChannelEdgePolicy) bool {
20✔
2391

20✔
2392
        // Both updates should be from the same direction.
20✔
2393
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
20✔
2394
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
20✔
2395

×
2396
                return false
×
2397
        }
×
2398

2399
        // The timestamp should always increase for a keep-alive update.
2400
        timestamp := time.Unix(int64(update.Timestamp), 0)
20✔
2401
        if !timestamp.After(prev.LastUpdate) {
20✔
2402
                return false
×
2403
        }
×
2404

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

2433
// latestHeight returns the gossiper's latest height known of the chain.
2434
func (d *AuthenticatedGossiper) latestHeight() uint32 {
3✔
2435
        d.Lock()
3✔
2436
        defer d.Unlock()
3✔
2437
        return d.bestHeight
3✔
2438
}
3✔
2439

2440
// handleNodeAnnouncement processes a new node announcement.
2441
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2442
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2443
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
27✔
2444

27✔
2445
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
27✔
2446

27✔
2447
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
27✔
2448
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
27✔
2449
                nMsg.source.SerializeCompressed())
27✔
2450

27✔
2451
        // We'll quickly ask the router if it already has a newer update for
27✔
2452
        // this node so we can skip validating signatures if not required.
27✔
2453
        if d.cfg.Graph.IsStaleNode(ctx, nodeAnn.NodeID, timestamp) {
38✔
2454
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
11✔
2455
                nMsg.err <- nil
11✔
2456
                return nil, true
11✔
2457
        }
11✔
2458

2459
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
22✔
2460
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2461
                        err)
3✔
2462

3✔
2463
                if !graph.IsError(
3✔
2464
                        err,
3✔
2465
                        graph.ErrOutdated,
3✔
2466
                        graph.ErrIgnored,
3✔
2467
                ) {
3✔
2468

×
2469
                        log.Error(err)
×
2470
                }
×
2471

2472
                nMsg.err <- err
3✔
2473
                return nil, false
3✔
2474
        }
2475

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

2487
        var announcements []networkMsg
19✔
2488

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

2503
        nMsg.err <- nil
19✔
2504
        // TODO(roasbeef): get rid of the above
19✔
2505

19✔
2506
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
19✔
2507
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
19✔
2508
                nMsg.source.SerializeCompressed())
19✔
2509

19✔
2510
        return announcements, true
19✔
2511
}
2512

2513
// handleChanAnnouncement processes a new channel announcement.
2514
//
2515
//nolint:funlen
2516
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2517
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2518
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
237✔
2519

237✔
2520
        scid := ann.ShortChannelID
237✔
2521

237✔
2522
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
237✔
2523
                nMsg.peer, scid.ToUint64())
237✔
2524

237✔
2525
        // We'll ignore any channel announcements that target any chain other
237✔
2526
        // than the set of chains we know of.
237✔
2527
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
237✔
2528
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2529
                        ", gossiper on chain=%v", ann.ChainHash,
×
2530
                        d.cfg.ChainHash)
×
2531
                log.Errorf(err.Error())
×
2532

×
2533
                key := newRejectCacheKey(
×
2534
                        scid.ToUint64(),
×
2535
                        sourceToPub(nMsg.source),
×
2536
                )
×
2537
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2538

×
2539
                nMsg.err <- err
×
2540
                return nil, false
×
2541
        }
×
2542

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

×
2550
                key := newRejectCacheKey(
×
2551
                        scid.ToUint64(),
×
2552
                        sourceToPub(nMsg.source),
×
2553
                )
×
2554
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2555

×
2556
                nMsg.err <- err
×
2557
                return nil, false
×
2558
        }
×
2559

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

236✔
2573
        // At this point, we'll now ask the router if this is a zombie/known
236✔
2574
        // edge. If so we can skip all the processing below.
236✔
2575
        if d.cfg.Graph.IsKnownEdge(scid) {
240✔
2576
                nMsg.err <- nil
4✔
2577
                return nil, true
4✔
2578
        }
4✔
2579

2580
        // Check if the channel is already closed in which case we can ignore
2581
        // it.
2582
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
235✔
2583
        if err != nil {
235✔
2584
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2585
                        err)
×
2586
                nMsg.err <- err
×
2587

×
2588
                return nil, false
×
2589
        }
×
2590

2591
        if closed {
236✔
2592
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2593
                log.Error(err)
1✔
2594

1✔
2595
                // If this is an announcement from us, we'll just ignore it.
1✔
2596
                if !nMsg.isRemote {
1✔
2597
                        nMsg.err <- err
×
2598
                        return nil, false
×
2599
                }
×
2600

2601
                // Increment the peer's ban score if they are sending closed
2602
                // channel announcements.
2603
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2604

1✔
2605
                // If the peer is banned and not a channel peer, we'll
1✔
2606
                // disconnect them.
1✔
2607
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2608
                if dcErr != nil {
1✔
2609
                        log.Errorf("failed to check if we should disconnect "+
×
2610
                                "peer: %v", dcErr)
×
2611
                        nMsg.err <- dcErr
×
2612

×
2613
                        return nil, false
×
2614
                }
×
2615

2616
                if shouldDc {
1✔
2617
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2618
                }
×
2619

2620
                nMsg.err <- err
1✔
2621

1✔
2622
                return nil, false
1✔
2623
        }
2624

2625
        // If this is a remote channel announcement, then we'll validate all
2626
        // the signatures within the proof as it should be well formed.
2627
        var proof *models.ChannelAuthProof
234✔
2628
        if nMsg.isRemote {
454✔
2629
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
220✔
2630
                if err != nil {
220✔
2631
                        err := fmt.Errorf("unable to validate announcement: "+
×
2632
                                "%v", err)
×
2633

×
2634
                        key := newRejectCacheKey(
×
2635
                                scid.ToUint64(),
×
2636
                                sourceToPub(nMsg.source),
×
2637
                        )
×
2638
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2639

×
2640
                        log.Error(err)
×
2641
                        nMsg.err <- err
×
2642
                        return nil, false
×
2643
                }
×
2644

2645
                // If the proof checks out, then we'll save the proof itself to
2646
                // the database so we can fetch it later when gossiping with
2647
                // other nodes.
2648
                proof = &models.ChannelAuthProof{
220✔
2649
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
220✔
2650
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
220✔
2651
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
220✔
2652
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
220✔
2653
                }
220✔
2654
        }
2655

2656
        // With the proof validated (if necessary), we can now store it within
2657
        // the database for our path finding and syncing needs.
2658
        edge := &models.ChannelEdgeInfo{
234✔
2659
                ChannelID:        scid.ToUint64(),
234✔
2660
                ChainHash:        ann.ChainHash,
234✔
2661
                NodeKey1Bytes:    ann.NodeID1,
234✔
2662
                NodeKey2Bytes:    ann.NodeID2,
234✔
2663
                BitcoinKey1Bytes: ann.BitcoinKey1,
234✔
2664
                BitcoinKey2Bytes: ann.BitcoinKey2,
234✔
2665
                AuthProof:        proof,
234✔
2666
                Features: lnwire.NewFeatureVector(
234✔
2667
                        ann.Features, lnwire.Features,
234✔
2668
                ),
234✔
2669
                ExtraOpaqueData: ann.ExtraOpaqueData,
234✔
2670
        }
234✔
2671

234✔
2672
        // If there were any optional message fields provided, we'll include
234✔
2673
        // them in its serialized disk representation now.
234✔
2674
        var tapscriptRoot fn.Option[chainhash.Hash]
234✔
2675
        if nMsg.optionalMsgFields != nil {
251✔
2676
                if nMsg.optionalMsgFields.capacity != nil {
21✔
2677
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
4✔
2678
                }
4✔
2679
                if nMsg.optionalMsgFields.channelPoint != nil {
24✔
2680
                        cp := *nMsg.optionalMsgFields.channelPoint
7✔
2681
                        edge.ChannelPoint = cp
7✔
2682
                }
7✔
2683

2684
                // Optional tapscript root for custom channels.
2685
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
17✔
2686
        }
2687

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

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

204✔
2709
                        switch {
204✔
2710
                        case errors.Is(err, ErrNoFundingTransaction),
2711
                                errors.Is(err, ErrInvalidFundingOutput):
202✔
2712

202✔
2713
                                key := newRejectCacheKey(
202✔
2714
                                        scid.ToUint64(),
202✔
2715
                                        sourceToPub(nMsg.source),
202✔
2716
                                )
202✔
2717
                                _, _ = d.recentRejects.Put(
202✔
2718
                                        key, &cachedReject{},
202✔
2719
                                )
202✔
2720

202✔
2721
                                // Increment the peer's ban score. We check
202✔
2722
                                // isRemote so we don't actually ban the peer in
202✔
2723
                                // case of a local bug.
202✔
2724
                                if nMsg.isRemote {
404✔
2725
                                        d.banman.incrementBanScore(
202✔
2726
                                                nMsg.peer.PubKey(),
202✔
2727
                                        )
202✔
2728
                                }
202✔
2729

2730
                        case errors.Is(err, ErrChannelSpent):
2✔
2731
                                key := newRejectCacheKey(
2✔
2732
                                        scid.ToUint64(),
2✔
2733
                                        sourceToPub(nMsg.source),
2✔
2734
                                )
2✔
2735
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
2✔
2736

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

×
2748
                                        nMsg.err <- dbErr
×
2749

×
2750
                                        return nil, false
×
2751
                                }
×
2752

2753
                                // Increment the peer's ban score. We check
2754
                                // isRemote so we don't accidentally ban
2755
                                // ourselves in case of a bug.
2756
                                if nMsg.isRemote {
4✔
2757
                                        d.banman.incrementBanScore(
2✔
2758
                                                nMsg.peer.PubKey(),
2✔
2759
                                        )
2✔
2760
                                }
2✔
2761

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

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

×
2777
                                return nil, false
×
2778
                        }
×
2779

2780
                        shouldDc, dcErr := d.ShouldDisconnect(
204✔
2781
                                nMsg.peer.IdentityKey(),
204✔
2782
                        )
204✔
2783
                        if dcErr != nil {
204✔
2784
                                log.Errorf("failed to check if we should "+
×
2785
                                        "disconnect peer: %v", dcErr)
×
2786
                                nMsg.err <- dcErr
×
2787

×
2788
                                return nil, false
×
2789
                        }
×
2790

2791
                        if shouldDc {
205✔
2792
                                nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2793
                        }
1✔
2794

2795
                        nMsg.err <- err
204✔
2796

204✔
2797
                        return nil, false
204✔
2798
                }
2799

2800
                edge.FundingScript = fn.Some(script)
28✔
2801

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

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

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

4✔
2818
                defer d.channelMtx.Unlock(scid.ToUint64())
4✔
2819

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

×
2835
                                nMsg.err <- rErr
×
2836

×
2837
                                return nil, false
×
2838
                        }
×
2839

2840
                        log.Debugf("Extracted %v announcements from rejected "+
3✔
2841
                                "msgs", len(anns))
3✔
2842

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

3✔
2851
                        return anns, true
3✔
2852
                }
2853

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

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

×
2866
                        return nil, false
×
2867
                }
×
2868

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

×
2875
                        return nil, false
×
2876
                }
×
2877

2878
                if shouldDc {
1✔
2879
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2880
                }
×
2881

2882
                nMsg.err <- err
1✔
2883

1✔
2884
                return nil, false
1✔
2885
        }
2886

2887
        // If err is nil, release the lock immediately.
2888
        d.channelMtx.Unlock(scid.ToUint64())
29✔
2889

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

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

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

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

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

5✔
2919
                d.wg.Add(1)
5✔
2920
                go func(updMsg *networkMsg) {
10✔
2921
                        defer d.wg.Done()
5✔
2922

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

5✔
2931
                                select {
5✔
2932
                                case d.networkMsgs <- updMsg:
5✔
2933
                                case <-d.quit:
×
2934
                                        updMsg.err <- ErrGossiperShuttingDown
×
2935
                                }
2936

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

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

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

2960
        nMsg.err <- nil
29✔
2961

29✔
2962
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
29✔
2963
                nMsg.peer, scid.ToUint64())
29✔
2964

29✔
2965
        return announcements, true
29✔
2966
}
2967

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

64✔
2975
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
64✔
2976
                nMsg.peer, upd.ShortChannelID.ToUint64())
64✔
2977

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

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

×
2991
                nMsg.err <- err
×
2992
                return nil, false
×
2993
        }
×
2994

2995
        blockHeight := upd.ShortChannelID.BlockHeight
64✔
2996
        shortChanID := upd.ShortChannelID.ToUint64()
64✔
2997

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

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

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

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

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

64✔
3039
        if d.cfg.Graph.IsStaleEdgePolicy(
64✔
3040
                graphScid, timestamp, upd.ChannelFlags,
64✔
3041
        ) {
70✔
3042

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

6✔
3048
                nMsg.err <- nil
6✔
3049
                return nil, true
6✔
3050
        }
6✔
3051

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

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

×
3065
                return nil, false
×
3066
        }
×
3067

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

3077
        case errors.Is(err, graphdb.ErrZombieEdge):
3✔
3078
                err = d.processZombieUpdate(ctx, chanInfo, graphScid, upd)
3✔
3079
                if err != nil {
5✔
3080
                        log.Debug(err)
2✔
3081
                        nMsg.err <- err
2✔
3082
                        return nil, false
2✔
3083
                }
2✔
3084

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

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

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

3135
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
5✔
3136
                        "(shortChanID=%v), saving for reprocessing later",
5✔
3137
                        shortChanID)
5✔
3138

5✔
3139
                // NOTE: We don't return anything on the error channel for this
5✔
3140
                // message, as we expect that will be done when this
5✔
3141
                // ChannelUpdate is later reprocessed. This might never happen
5✔
3142
                // if the corresponding ChannelAnnouncement is never received
5✔
3143
                // or the LRU cache is filled up and the entry is evicted.
5✔
3144
                return nil, false
5✔
3145

3146
        default:
×
3147
                err := fmt.Errorf("unable to validate channel update "+
×
3148
                        "short_chan_id=%v: %v", shortChanID, err)
×
3149
                log.Error(err)
×
3150
                nMsg.err <- err
×
3151

×
3152
                key := newRejectCacheKey(
×
3153
                        upd.ShortChannelID.ToUint64(),
×
3154
                        sourceToPub(nMsg.source),
×
3155
                )
×
3156
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3157

×
3158
                return nil, false
×
3159
        }
3160

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

3178
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
57✔
3179
                "edge policy=%v", chanInfo.ChannelID,
57✔
3180
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
57✔
3181

57✔
3182
        // Validate the channel announcement with the expected public key and
57✔
3183
        // channel capacity. In the case of an invalid channel update, we'll
57✔
3184
        // return an error to the caller and exit early.
57✔
3185
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
57✔
3186
        if err != nil {
61✔
3187
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3188
                        "announcement for short_chan_id=%v: %v",
4✔
3189
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3190

4✔
3191
                log.Error(rErr)
4✔
3192
                nMsg.err <- rErr
4✔
3193
                return nil, false
4✔
3194
        }
4✔
3195

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

18✔
3238
                        if !rls[direction].Allow() {
27✔
3239
                                log.Debugf("Rate limiting update for channel "+
9✔
3240
                                        "%v from direction %x", shortChanID,
9✔
3241
                                        pubKey.SerializeCompressed())
9✔
3242
                                nMsg.err <- nil
9✔
3243
                                return nil, false
9✔
3244
                        }
9✔
3245
                }
3246
        }
3247

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

46✔
3270
        if err := d.cfg.Graph.UpdateEdge(ctx, update, ops...); err != nil {
46✔
3271
                if graph.IsError(
×
3272
                        err, graph.ErrOutdated,
×
3273
                        graph.ErrIgnored,
×
3274
                ) {
×
3275

×
3276
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
×
3277
                                shortChanID, err)
×
3278
                } else {
×
3279
                        // Since we know the stored SCID in the graph, we'll
×
3280
                        // cache that SCID.
×
3281
                        key := newRejectCacheKey(
×
3282
                                chanInfo.ChannelID,
×
3283
                                sourceToPub(nMsg.source),
×
3284
                        )
×
3285
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3286

×
3287
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3288
                                shortChanID, err)
×
3289
                }
×
3290

3291
                nMsg.err <- err
×
3292
                return nil, false
×
3293
        }
3294

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

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

3319
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
3320
                                if err != nil {
3✔
3321
                                        log.Error(err)
×
3322
                                        nMsg.err <- err
×
3323
                                        return nil, false
×
3324
                                }
×
3325

3326
                                upd.Signature = lnSig
3✔
3327
                        }
3328
                }
3329

3330
                // Get our peer's public key.
3331
                remotePubKey := remotePubFromChanInfo(
14✔
3332
                        chanInfo, upd.ChannelFlags,
14✔
3333
                )
14✔
3334

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

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

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

3366
        nMsg.err <- nil
46✔
3367

46✔
3368
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
46✔
3369
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
46✔
3370
                timestamp)
46✔
3371
        return announcements, true
46✔
3372
}
3373

3374
// handleAnnSig processes a new announcement signatures message.
3375
//
3376
//nolint:funlen
3377
func (d *AuthenticatedGossiper) handleAnnSig(ctx context.Context,
3378
        nMsg *networkMsg, ann *lnwire.AnnounceSignatures1) ([]networkMsg,
3379
        bool) {
24✔
3380

24✔
3381
        needBlockHeight := ann.ShortChannelID.BlockHeight +
24✔
3382
                d.cfg.ProofMatureDelta
24✔
3383
        shortChanID := ann.ShortChannelID.ToUint64()
24✔
3384

24✔
3385
        prefix := "local"
24✔
3386
        if nMsg.isRemote {
38✔
3387
                prefix = "remote"
14✔
3388
        }
14✔
3389

3390
        log.Infof("Received new %v announcement signature for %v", prefix,
24✔
3391
                ann.ShortChannelID)
24✔
3392

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

24✔
3410
        // Ensure that we know of a channel with the target channel ID before
24✔
3411
        // proceeding further.
24✔
3412
        //
24✔
3413
        // We must acquire the mutex for this channel ID before getting the
24✔
3414
        // channel from the database, to ensure what we read does not change
24✔
3415
        // before we call AddProof() later.
24✔
3416
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
24✔
3417
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
24✔
3418

24✔
3419
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
24✔
3420
                ann.ShortChannelID,
24✔
3421
        )
24✔
3422
        if err != nil {
28✔
3423
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
4✔
3424
                if err != nil {
7✔
3425
                        err := fmt.Errorf("unable to store the proof for "+
3✔
3426
                                "short_chan_id=%v: %v", shortChanID, err)
3✔
3427
                        log.Error(err)
3✔
3428
                        nMsg.err <- err
3✔
3429

3✔
3430
                        return nil, false
3✔
3431
                }
3✔
3432

3433
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
4✔
3434
                err := d.cfg.WaitingProofStore.Add(proof)
4✔
3435
                if err != nil {
4✔
3436
                        err := fmt.Errorf("unable to store the proof for "+
×
3437
                                "short_chan_id=%v: %v", shortChanID, err)
×
3438
                        log.Error(err)
×
3439
                        nMsg.err <- err
×
3440
                        return nil, false
×
3441
                }
×
3442

3443
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
4✔
3444
                        ", adding to waiting batch", prefix, shortChanID)
4✔
3445
                nMsg.err <- nil
4✔
3446
                return nil, false
4✔
3447
        }
3448

3449
        nodeID := nMsg.source.SerializeCompressed()
23✔
3450
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
23✔
3451
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
23✔
3452

23✔
3453
        // Ensure that channel that was retrieved belongs to the peer which
23✔
3454
        // sent the proof announcement.
23✔
3455
        if !(isFirstNode || isSecondNode) {
23✔
3456
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3457
                        "to the peer which sent the proof, short_chan_id=%v",
×
3458
                        shortChanID)
×
3459
                log.Error(err)
×
3460
                nMsg.err <- err
×
3461
                return nil, false
×
3462
        }
×
3463

3464
        // If proof was sent by a local sub-system, then we'll send the
3465
        // announcement signature to the remote node so they can also
3466
        // reconstruct the full channel announcement.
3467
        if !nMsg.isRemote {
36✔
3468
                var remotePubKey [33]byte
13✔
3469
                if isFirstNode {
26✔
3470
                        remotePubKey = chanInfo.NodeKey2Bytes
13✔
3471
                } else {
16✔
3472
                        remotePubKey = chanInfo.NodeKey1Bytes
3✔
3473
                }
3✔
3474

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

3488
        // Check if we already have the full proof for this channel.
3489
        if chanInfo.AuthProof != nil {
27✔
3490
                // If we already have the fully assembled proof, then the peer
4✔
3491
                // sending us their proof has probably not received our local
4✔
3492
                // proof yet. So be kind and send them the full proof.
4✔
3493
                if nMsg.isRemote {
8✔
3494
                        peerID := nMsg.source.SerializeCompressed()
4✔
3495
                        log.Debugf("Got AnnounceSignatures for channel with " +
4✔
3496
                                "full proof.")
4✔
3497

4✔
3498
                        d.wg.Add(1)
4✔
3499
                        go func() {
8✔
3500
                                defer d.wg.Done()
4✔
3501

4✔
3502
                                log.Debugf("Received half proof for channel "+
4✔
3503
                                        "%v with existing full proof. Sending"+
4✔
3504
                                        " full proof to peer=%x",
4✔
3505
                                        ann.ChannelID, peerID)
4✔
3506

4✔
3507
                                ca, _, _, err := netann.CreateChanAnnouncement(
4✔
3508
                                        chanInfo.AuthProof, chanInfo, e1, e2,
4✔
3509
                                )
4✔
3510
                                if err != nil {
4✔
3511
                                        log.Errorf("unable to gen ann: %v",
×
3512
                                                err)
×
3513
                                        return
×
3514
                                }
×
3515

3516
                                err = nMsg.peer.SendMessage(false, ca)
4✔
3517
                                if err != nil {
4✔
3518
                                        log.Errorf("Failed sending full proof"+
×
3519
                                                " to peer=%x: %v", peerID, err)
×
3520
                                        return
×
3521
                                }
×
3522

3523
                                log.Debugf("Full proof sent to peer=%x for "+
4✔
3524
                                        "chanID=%v", peerID, ann.ChannelID)
4✔
3525
                        }()
3526
                }
3527

3528
                log.Debugf("Already have proof for channel with chanID=%v",
4✔
3529
                        ann.ChannelID)
4✔
3530
                nMsg.err <- nil
4✔
3531
                return nil, true
4✔
3532
        }
3533

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

3549
        if err == channeldb.ErrWaitingProofNotFound {
34✔
3550
                err := d.cfg.WaitingProofStore.Add(proof)
12✔
3551
                if err != nil {
12✔
3552
                        err := fmt.Errorf("unable to store the proof for "+
×
3553
                                "short_chan_id=%v: %v", shortChanID, err)
×
3554
                        log.Error(err)
×
3555
                        nMsg.err <- err
×
3556
                        return nil, false
×
3557
                }
×
3558

3559
                log.Infof("1/2 of channel ann proof received for "+
12✔
3560
                        "short_chan_id=%v, waiting for other half",
12✔
3561
                        shortChanID)
12✔
3562

12✔
3563
                nMsg.err <- nil
12✔
3564
                return nil, false
12✔
3565
        }
3566

3567
        // We now have both halves of the channel announcement proof, then
3568
        // we'll reconstruct the initial announcement so we can validate it
3569
        // shortly below.
3570
        var dbProof models.ChannelAuthProof
13✔
3571
        if isFirstNode {
17✔
3572
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
4✔
3573
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
4✔
3574
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
4✔
3575
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
4✔
3576
        } else {
16✔
3577
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
12✔
3578
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
12✔
3579
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
12✔
3580
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
12✔
3581
        }
12✔
3582

3583
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
13✔
3584
                &dbProof, chanInfo, e1, e2,
13✔
3585
        )
13✔
3586
        if err != nil {
13✔
3587
                log.Error(err)
×
3588
                nMsg.err <- err
×
3589
                return nil, false
×
3590
        }
×
3591

3592
        // With all the necessary components assembled validate the full
3593
        // channel announcement proof.
3594
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
13✔
3595
        if err != nil {
13✔
3596
                err := fmt.Errorf("channel announcement proof for "+
×
3597
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3598

×
3599
                log.Error(err)
×
3600
                nMsg.err <- err
×
3601
                return nil, false
×
3602
        }
×
3603

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

3619
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
13✔
3620
        if err != nil {
13✔
3621
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3622
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3623
                log.Error(err)
×
3624
                nMsg.err <- err
×
3625
                return nil, false
×
3626
        }
×
3627

3628
        // Proof was successfully created and now can announce the channel to
3629
        // the remain network.
3630
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
13✔
3631
                ", adding to next ann batch", shortChanID)
13✔
3632

13✔
3633
        // Assemble the necessary announcements to add to the next broadcasting
13✔
3634
        // batch.
13✔
3635
        var announcements []networkMsg
13✔
3636
        announcements = append(announcements, networkMsg{
13✔
3637
                peer:   nMsg.peer,
13✔
3638
                source: nMsg.source,
13✔
3639
                msg:    chanAnn,
13✔
3640
        })
13✔
3641
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
25✔
3642
                announcements = append(announcements, networkMsg{
12✔
3643
                        peer:   nMsg.peer,
12✔
3644
                        source: src,
12✔
3645
                        msg:    e1Ann,
12✔
3646
                })
12✔
3647
        }
12✔
3648
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
24✔
3649
                announcements = append(announcements, networkMsg{
11✔
3650
                        peer:   nMsg.peer,
11✔
3651
                        source: src,
11✔
3652
                        msg:    e2Ann,
11✔
3653
                })
11✔
3654
        }
11✔
3655

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

3677
        node2Ann, err := d.fetchNodeAnn(ctx, chanInfo.NodeKey2Bytes)
13✔
3678
        if err != nil {
20✔
3679
                log.Debugf("Unable to fetch node announcement for %x: %v",
7✔
3680
                        chanInfo.NodeKey2Bytes, err)
7✔
3681
        } else {
16✔
3682
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
18✔
3683
                        announcements = append(announcements, networkMsg{
9✔
3684
                                peer:   nMsg.peer,
9✔
3685
                                source: nodeKey2,
9✔
3686
                                msg:    node2Ann,
9✔
3687
                        })
9✔
3688
                }
9✔
3689
        }
3690

3691
        nMsg.err <- nil
13✔
3692
        return announcements, true
13✔
3693
}
3694

3695
// isBanned returns true if the peer identified by pubkey is banned for sending
3696
// invalid channel announcements.
3697
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
211✔
3698
        return d.banman.isBanned(pubkey)
211✔
3699
}
211✔
3700

3701
// ShouldDisconnect returns true if we should disconnect the peer identified by
3702
// pubkey.
3703
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3704
        bool, error) {
209✔
3705

209✔
3706
        pubkeySer := pubkey.SerializeCompressed()
209✔
3707

209✔
3708
        var pubkeyBytes [33]byte
209✔
3709
        copy(pubkeyBytes[:], pubkeySer)
209✔
3710

209✔
3711
        // If the public key is banned, check whether or not this is a channel
209✔
3712
        // peer.
209✔
3713
        if d.isBanned(pubkeyBytes) {
211✔
3714
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3715
                if err != nil {
2✔
3716
                        return false, err
×
3717
                }
×
3718

3719
                // We should only disconnect non-channel peers.
3720
                if !isChanPeer {
3✔
3721
                        return true, nil
1✔
3722
                }
1✔
3723
        }
3724

3725
        return false, nil
208✔
3726
}
3727

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

232✔
3737
        scid := ann.ShortChannelID
232✔
3738

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

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

3771
                default:
×
3772
                }
3773

3774
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
1✔
3775
                        ErrNoFundingTransaction, err)
1✔
3776
        }
3777

3778
        // Recreate witness output to be sure that declared in channel edge
3779
        // bitcoin keys and channel value corresponds to the reality.
3780
        fundingPkScript, err := makeFundingScript(
231✔
3781
                ann.BitcoinKey1[:], ann.BitcoinKey2[:], ann.Features,
231✔
3782
                tapscriptRoot,
231✔
3783
        )
231✔
3784
        if err != nil {
231✔
3785
                return wire.OutPoint{}, 0, nil, err
×
3786
        }
×
3787

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

3809
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
201✔
3810
                        ErrInvalidFundingOutput, err)
201✔
3811
        }
3812

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

3827
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: unable to "+
2✔
3828
                        "fetch utxo for chan_id=%v, chan_point=%v: %w",
2✔
3829
                        ErrChannelSpent, scid.ToUint64(), fundingPoint, err)
2✔
3830
        }
3831

3832
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
28✔
3833
                nil
28✔
3834
}
3835

3836
// makeFundingScript is used to make the funding script for both segwit v0 and
3837
// segwit v1 (taproot) channels.
3838
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3839
        features *lnwire.RawFeatureVector,
3840
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
231✔
3841

231✔
3842
        legacyFundingScript := func() ([]byte, error) {
462✔
3843
                witnessScript, err := input.GenMultiSigScript(
231✔
3844
                        bitcoinKey1, bitcoinKey2,
231✔
3845
                )
231✔
3846
                if err != nil {
231✔
3847
                        return nil, err
×
3848
                }
×
3849
                pkScript, err := input.WitnessScriptHash(witnessScript)
231✔
3850
                if err != nil {
231✔
3851
                        return nil, err
×
3852
                }
×
3853

3854
                return pkScript, nil
231✔
3855
        }
3856

3857
        if features.IsEmpty() {
462✔
3858
                return legacyFundingScript()
231✔
3859
        }
231✔
3860

3861
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
3✔
3862
        if chanFeatureBits.HasFeature(
3✔
3863
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
3864
        ) {
6✔
3865

3✔
3866
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
3867
                if err != nil {
3✔
3868
                        return nil, err
×
3869
                }
×
3870
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
3871
                if err != nil {
3✔
3872
                        return nil, err
×
3873
                }
×
3874

3875
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
3876
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
3877
                )
3✔
3878
                if err != nil {
3✔
3879
                        return nil, err
×
3880
                }
×
3881

3882
                // TODO(roasbeef): add tapscript root to gossip v1.5
3883

3884
                return fundingScript, nil
3✔
3885
        }
3886

3887
        return legacyFundingScript()
×
3888
}
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