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

lightningnetwork / lnd / 15296208252

28 May 2025 09:10AM UTC coverage: 58.328% (-0.03%) from 58.362%
15296208252

Pull #9875

github

web-flow
Merge 354ec40f9 into 8e96bd030
Pull Request #9875: discovery: make sure we do not block the read queue

4 of 7 new or added lines in 1 file covered. (57.14%)

110 existing lines in 13 files now uncovered.

97435 of 167047 relevant lines covered (58.33%)

1.81 hits per line

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

68.85
/discovery/gossiper.go
1
package discovery
2

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

13
        "github.com/btcsuite/btcd/btcec/v2"
14
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
15
        "github.com/btcsuite/btcd/btcutil"
16
        "github.com/btcsuite/btcd/chaincfg/chainhash"
17
        "github.com/btcsuite/btcd/wire"
18
        "github.com/davecgh/go-spew/spew"
19
        "github.com/lightninglabs/neutrino/cache"
20
        "github.com/lightninglabs/neutrino/cache/lru"
21
        "github.com/lightningnetwork/lnd/batch"
22
        "github.com/lightningnetwork/lnd/chainntnfs"
23
        "github.com/lightningnetwork/lnd/channeldb"
24
        "github.com/lightningnetwork/lnd/fn/v2"
25
        "github.com/lightningnetwork/lnd/graph"
26
        graphdb "github.com/lightningnetwork/lnd/graph/db"
27
        "github.com/lightningnetwork/lnd/graph/db/models"
28
        "github.com/lightningnetwork/lnd/input"
29
        "github.com/lightningnetwork/lnd/keychain"
30
        "github.com/lightningnetwork/lnd/lnpeer"
31
        "github.com/lightningnetwork/lnd/lnutils"
32
        "github.com/lightningnetwork/lnd/lnwallet"
33
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
34
        "github.com/lightningnetwork/lnd/lnwallet/chanvalidate"
35
        "github.com/lightningnetwork/lnd/lnwire"
36
        "github.com/lightningnetwork/lnd/multimutex"
37
        "github.com/lightningnetwork/lnd/netann"
38
        "github.com/lightningnetwork/lnd/routing/route"
39
        "github.com/lightningnetwork/lnd/ticker"
40
        "golang.org/x/time/rate"
41
)
42

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

175
        isRemote bool
176

177
        err chan error
178
}
179

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

555
        sync.Mutex
556

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

681
        d.syncMgr.Start()
3✔
682

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

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

3✔
690
        return nil
3✔
691
}
692

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

789
                return true
3✔
790
        }
791

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

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

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

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

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

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

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

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

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

839
        d.syncMgr.Stop()
3✔
840

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

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

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

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

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

3✔
863
        log.Debugf("Processing remote msg %T from peer=%x", msg, peer.PubKey())
3✔
864

3✔
865
        errChan := make(chan error, 1)
3✔
866

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

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

×
881
                        errChan <- ErrGossipSyncerNotFound
×
882
                        return errChan
×
883
                }
×
884

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

894
                        errChan <- err
3✔
895
                }()
896

897
                return errChan
3✔
898

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

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

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

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

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

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

3✔
932
                if bytes.Equal(m.NodeID1[:], ownKey) ||
3✔
933
                        bytes.Equal(m.NodeID2[:], ownKey) {
6✔
934

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

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

3✔
949
        select {
3✔
950
        case d.networkMsgs <- nMsg:
3✔
951

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

964
        return nMsg.err
3✔
965
}
966

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

3✔
977
        optionalMsgFields := &optionalMsgFields{}
3✔
978
        optionalMsgFields.apply(optionalFields...)
3✔
979

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

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

994
        return nMsg.err
3✔
995
}
996

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

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

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

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

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

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

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

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

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

1055
        sync.Mutex
1056
}
1057

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

3✔
1064
        d.reset()
3✔
1065
}
3✔
1066

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

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

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

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

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

3✔
1106
                        d.channelAnnouncements[deDupKey] = mws
3✔
1107

3✔
1108
                        return
3✔
1109
                }
3✔
1110

1111
                mws.msg = msg
×
1112
                mws.senders[sender] = struct{}{}
×
1113
                d.channelAnnouncements[deDupKey] = mws
×
1114

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

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

×
1134
                                return
×
1135
                        }
×
1136

1137
                        oldTimestamp = update.Timestamp
×
1138
                }
1139

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

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

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

3✔
1162
                        d.channelUpdates[deDupKey] = mws
3✔
1163

3✔
1164
                        return
3✔
1165
                }
3✔
1166

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

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

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

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

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

3✔
1202
                        mws.senders[sender] = struct{}{}
3✔
1203

3✔
1204
                        d.nodeAnnouncements[deDupKey] = mws
3✔
1205

3✔
1206
                        return
3✔
1207
                }
3✔
1208

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

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

3✔
1222
        for _, msg := range msgs {
6✔
1223
                d.addMsg(msg)
3✔
1224
        }
3✔
1225
}
1226

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

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

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

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

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

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

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

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

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

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

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

1294
        d.reset()
3✔
1295

3✔
1296
        // Return the array of lnwire.messages.
3✔
1297
        return msgs
3✔
1298
}
1299

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

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

3✔
1311
        if subBatchSize < minimumBatchSize {
6✔
1312
                return minimumBatchSize
3✔
1313
        }
3✔
1314

1315
        return subBatchSize
×
1316
}
1317

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

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

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

3✔
1332
        var splitAnnouncementBatch [][]msgWithSenders
3✔
1333

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

3✔
1346
        return splitAnnouncementBatch
3✔
1347
}
1348

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

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

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

3✔
1370
        d.wg.Add(1)
3✔
1371
        go func() {
6✔
1372
                defer d.wg.Done()
3✔
1373

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

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

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

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

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

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

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

3✔
1417
        syncerPeers := d.syncMgr.GossipSyncers()
3✔
1418

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

1426
        for _, msgChunk := range annBatch {
6✔
1427
                msgChunk := msgChunk
3✔
1428

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

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

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

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

3✔
1456
        d.cfg.RetransmitTicker.Resume()
3✔
1457
        defer d.cfg.RetransmitTicker.Stop()
3✔
1458

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

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

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

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

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

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

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

3✔
1513
                                if emittedAnnouncements != nil {
6✔
1514
                                        announcements.AddMsgs(
3✔
1515
                                                emittedAnnouncements...,
3✔
1516
                                        )
3✔
1517
                                }
3✔
1518
                                continue
3✔
1519
                        }
1520

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

×
1528
                                announcement.err <- fmt.Errorf("recently " +
×
1529
                                        "rejected")
×
1530
                                continue
×
1531
                        }
1532

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

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

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

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

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

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

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

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

3✔
1599
        defer d.wg.Done()
3✔
1600
        defer d.vb.CompleteJob()
3✔
1601

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

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

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

×
1619
                return
×
1620
        }
1621

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

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

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

×
1639
                nMsg.err <- err
×
1640

×
1641
                return
×
1642
        }
×
1643

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

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

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

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

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

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

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

1686
        default:
3✔
1687
                return false
3✔
1688
        }
1689

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

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

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

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

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

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

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

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

1749
                timeElapsed := now.Sub(edge.LastUpdate)
3✔
1750

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

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

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

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

1785
                signedUpdates = append(signedUpdates, chanUpdate)
×
1786
        }
1787

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

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

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

1809
                signedUpdates = append(signedUpdates, &newNodeAnn)
×
1810
                nodeAnnStr = " and our refreshed node announcement"
×
1811

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

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

1826
        log.Infof("Retransmitting %v outgoing channels%v",
×
1827
                len(edgesToUpdate), nodeAnnStr)
×
1828

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

1835
        return nil
×
1836
}
1837

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

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

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

3✔
1869
                        var defaultAlias lnwire.ShortChannelID
3✔
1870
                        foundAlias, _ := d.cfg.GetAlias(chanID)
3✔
1871
                        if foundAlias != defaultAlias {
6✔
1872
                                chanUpdate.ShortChannelID = foundAlias
3✔
1873

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

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

1888
                                chanUpdate.Signature = lnSig
3✔
1889
                        }
1890

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

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

1916
        return chanUpdates, nil
3✔
1917
}
1918

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

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

1932
        return remotePubKey
3✔
1933
}
1934

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

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

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

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

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

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

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

×
2016
        }
×
2017

2018
        return announcements, nil
×
2019
}
2020

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

×
2025
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2026
}
×
2027

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

3✔
2033
        if err := netann.ValidateNodeAnn(msg); err != nil {
3✔
2034
                return fmt.Errorf("unable to validate node announcement: %w",
×
2035
                        err)
×
2036
        }
×
2037

2038
        return d.cfg.Graph.AddNode(models.NodeFromWireAnnouncement(msg), op...)
3✔
2039
}
2040

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

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

2057
        msgHeight := chanID.BlockHeight + delta
3✔
2058

3✔
2059
        // The message height is smaller or equal to our best known height,
3✔
2060
        // thus the message is mature.
3✔
2061
        if msgHeight <= d.bestHeight {
6✔
2062
                return false
3✔
2063
        }
3✔
2064

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

3✔
2079
        // Create the cached message.
3✔
2080
        cachedMsg := &cachedFutureMsg{
3✔
2081
                msg:    copied,
3✔
2082
                height: msgHeight,
3✔
2083
        }
3✔
2084

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

2092
        log.Debugf("Network message: %v added to future messages for "+
3✔
2093
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
3✔
2094
                msgHeight, d.bestHeight)
3✔
2095

3✔
2096
        return true
3✔
2097
}
2098

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

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

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

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

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

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

2142
        default:
×
2143
                err := errors.New("wrong type of the announcement")
×
2144
                nMsg.err <- err
×
2145
                return nil, false
×
2146
        }
2147
}
2148

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

×
2158
        // The least-significant bit in the flag on the channel update tells us
×
2159
        // which edge is being updated.
×
2160
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
×
2161

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

2179
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
×
2180
        if err != nil {
×
2181
                return fmt.Errorf("unable to verify channel "+
×
2182
                        "update signature: %v", err)
×
2183
        }
×
2184

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

×
2194
                return nil
×
2195

2196
        case err != nil:
×
2197
                return fmt.Errorf("unable to remove edge with "+
×
2198
                        "chan_id=%v from zombie index: %v",
×
2199
                        msg.ShortChannelID, err)
×
2200

2201
        default:
×
2202
        }
2203

2204
        log.Debugf("Removed edge with chan_id=%v from zombie "+
×
2205
                "index", msg.ShortChannelID)
×
2206

×
2207
        return nil
×
2208
}
2209

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

3✔
2215
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
3✔
2216
        if err != nil {
3✔
2217
                return nil, err
×
2218
        }
×
2219

2220
        return node.NodeAnnouncement(true)
3✔
2221
}
2222

2223
// isMsgStale determines whether a message retrieved from the backing
2224
// MessageStore is seen as stale by the current graph.
2225
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2226
        msg lnwire.Message) bool {
3✔
2227

3✔
2228
        switch msg := msg.(type) {
3✔
2229
        case *lnwire.AnnounceSignatures1:
3✔
2230
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
3✔
2231
                        msg.ShortChannelID,
3✔
2232
                )
3✔
2233

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

2246
                // If the proof exists in the graph, then we have successfully
2247
                // received the remote proof and assembled the full proof, so we
2248
                // can safely delete the local proof from the database.
2249
                return chanInfo.AuthProof != nil
3✔
2250

2251
        case *lnwire.ChannelUpdate1:
3✔
2252
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
3✔
2253

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

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

2276
                // If the policy is still unknown, then we can consider this
2277
                // policy fresh.
2278
                if p == nil {
3✔
2279
                        return false
×
2280
                }
×
2281

2282
                timestamp := time.Unix(int64(msg.Timestamp), 0)
3✔
2283
                return p.LastUpdate.After(timestamp)
3✔
2284

2285
        default:
×
2286
                // We'll make sure to not mark any unsupported messages as stale
×
2287
                // to ensure they are not removed.
×
2288
                return false
×
2289
        }
2290
}
2291

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

3✔
2299
        // Parse the unsigned edge into a channel update.
3✔
2300
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
3✔
2301

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

2312
        // Next, we'll set the new signature in place, and update the reference
2313
        // in the backing slice.
2314
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
3✔
2315
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
3✔
2316

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

2327
        // Finally, we'll write the new edge policy to disk.
2328
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
3✔
2329
                return nil, nil, err
×
2330
        }
×
2331

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

2374
        return chanAnn, chanUpdate, err
3✔
2375
}
2376

2377
// SyncManager returns the gossiper's SyncManager instance.
2378
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2379
        return d.syncMgr
3✔
2380
}
3✔
2381

2382
// IsKeepAliveUpdate determines whether this channel update is considered a
2383
// keep-alive update based on the previous channel update processed for the same
2384
// direction.
2385
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2386
        prev *models.ChannelEdgePolicy) bool {
3✔
2387

3✔
2388
        // Both updates should be from the same direction.
3✔
2389
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
3✔
2390
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
3✔
2391

×
2392
                return false
×
2393
        }
×
2394

2395
        // The timestamp should always increase for a keep-alive update.
2396
        timestamp := time.Unix(int64(update.Timestamp), 0)
3✔
2397
        if !timestamp.After(prev.LastUpdate) {
3✔
2398
                return false
×
2399
        }
×
2400

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

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

2436
// handleNodeAnnouncement processes a new node announcement.
2437
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2438
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2439
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2440

3✔
2441
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
3✔
2442

3✔
2443
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
3✔
2444
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
3✔
2445
                nMsg.source.SerializeCompressed())
3✔
2446

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

2455
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
6✔
2456
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2457
                        err)
3✔
2458

3✔
2459
                if !graph.IsError(
3✔
2460
                        err,
3✔
2461
                        graph.ErrOutdated,
3✔
2462
                        graph.ErrIgnored,
3✔
2463
                ) {
3✔
2464

×
2465
                        log.Error(err)
×
2466
                }
×
2467

2468
                nMsg.err <- err
3✔
2469
                return nil, false
3✔
2470
        }
2471

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

2483
        var announcements []networkMsg
3✔
2484

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

2499
        nMsg.err <- nil
3✔
2500
        // TODO(roasbeef): get rid of the above
3✔
2501

3✔
2502
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
3✔
2503
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
3✔
2504
                nMsg.source.SerializeCompressed())
3✔
2505

3✔
2506
        return announcements, true
3✔
2507
}
2508

2509
// handleChanAnnouncement processes a new channel announcement.
2510
//
2511
//nolint:funlen
2512
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2513
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2514
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2515

3✔
2516
        scid := ann.ShortChannelID
3✔
2517

3✔
2518
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
3✔
2519
                nMsg.peer, scid.ToUint64())
3✔
2520

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

×
2529
                key := newRejectCacheKey(
×
2530
                        scid.ToUint64(),
×
2531
                        sourceToPub(nMsg.source),
×
2532
                )
×
2533
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2534

×
2535
                nMsg.err <- err
×
2536
                return nil, false
×
2537
        }
×
2538

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

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

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

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

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

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

×
2584
                return nil, false
×
2585
        }
×
2586

2587
        if closed {
3✔
2588
                err = fmt.Errorf("ignoring closed channel %v", scid)
×
2589
                log.Error(err)
×
2590

×
2591
                // If this is an announcement from us, we'll just ignore it.
×
2592
                if !nMsg.isRemote {
×
2593
                        nMsg.err <- err
×
2594
                        return nil, false
×
2595
                }
×
2596

2597
                // Increment the peer's ban score if they are sending closed
2598
                // channel announcements.
2599
                d.banman.incrementBanScore(nMsg.peer.PubKey())
×
2600

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

×
2609
                        return nil, false
×
2610
                }
×
2611

2612
                if shouldDc {
×
2613
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2614
                }
×
2615

2616
                nMsg.err <- err
×
2617

×
2618
                return nil, false
×
2619
        }
2620

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

×
2630
                        key := newRejectCacheKey(
×
2631
                                scid.ToUint64(),
×
2632
                                sourceToPub(nMsg.source),
×
2633
                        )
×
2634
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2635

×
2636
                        log.Error(err)
×
2637
                        nMsg.err <- err
×
2638
                        return nil, false
×
2639
                }
×
2640

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

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

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

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

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

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

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

×
2710
                        switch {
×
2711
                        case errors.Is(err, ErrNoFundingTransaction),
2712
                                errors.Is(err, ErrInvalidFundingOutput):
×
2713

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

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

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

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

×
2749
                                        nMsg.err <- dbErr
×
2750

×
2751
                                        return nil, false
×
2752
                                }
×
2753

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

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

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

×
2778
                                return nil, false
×
2779
                        }
×
2780

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

×
2789
                                return nil, false
×
2790
                        }
×
2791

2792
                        if shouldDc {
×
2793
                                nMsg.peer.Disconnect(ErrPeerBanned)
×
2794
                        }
×
2795

2796
                        nMsg.err <- err
×
2797

×
2798
                        return nil, false
×
2799
                }
2800

2801
                edge.FundingScript = fn.Some(script)
3✔
2802

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

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

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

3✔
2819
                defer d.channelMtx.Unlock(scid.ToUint64())
3✔
2820

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

×
2836
                                nMsg.err <- rErr
×
2837

×
2838
                                return nil, false
×
2839
                        }
×
2840

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

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

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

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

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

×
2867
                        return nil, false
×
2868
                }
×
2869

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

×
2876
                        return nil, false
×
2877
                }
×
2878

2879
                if shouldDc {
×
2880
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2881
                }
×
2882

2883
                nMsg.err <- err
×
2884

×
2885
                return nil, false
×
2886
        }
2887

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

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

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

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

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

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

3✔
2920
                d.wg.Add(1)
3✔
2921
                go func(updMsg *networkMsg) {
6✔
2922
                        defer d.wg.Done()
3✔
2923

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

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

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

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

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

2961
        nMsg.err <- nil
3✔
2962

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

3✔
2966
        return announcements, true
3✔
2967
}
2968

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

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

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

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

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

2996
        blockHeight := upd.ShortChannelID.BlockHeight
3✔
2997
        shortChanID := upd.ShortChannelID.ToUint64()
3✔
2998

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

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

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

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

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

3✔
3040
        if d.cfg.Graph.IsStaleEdgePolicy(
3✔
3041
                graphScid, timestamp, upd.ChannelFlags,
3✔
3042
        ) {
6✔
3043

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

3✔
3049
                nMsg.err <- nil
3✔
3050
                return nil, true
3✔
3051
        }
3✔
3052

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

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

×
3066
                return nil, false
×
3067
        }
×
3068

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

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

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

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

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

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

3✔
3140
                // NOTE: We don't return anything on the error channel for this
3✔
3141
                // message, as we expect that will be done when this
3✔
3142
                // ChannelUpdate is later reprocessed.
3✔
3143
                return nil, false
3✔
3144

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

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

×
3157
                return nil, false
×
3158
        }
3159

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

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

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

×
3190
                log.Error(rErr)
×
3191
                nMsg.err <- rErr
×
3192
                return nil, false
×
3193
        }
×
3194

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

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

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

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

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

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

3289
                nMsg.err <- err
×
3290
                return nil, false
×
3291
        }
3292

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

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

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

3324
                                upd.Signature = lnSig
3✔
3325
                        }
3326
                }
3327

3328
                // Get our peer's public key.
3329
                remotePubKey := remotePubFromChanInfo(
3✔
3330
                        chanInfo, upd.ChannelFlags,
3✔
3331
                )
3✔
3332

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

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

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

3364
        nMsg.err <- nil
3✔
3365

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

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

3✔
3379
        needBlockHeight := ann.ShortChannelID.BlockHeight +
3✔
3380
                d.cfg.ProofMatureDelta
3✔
3381
        shortChanID := ann.ShortChannelID.ToUint64()
3✔
3382

3✔
3383
        prefix := "local"
3✔
3384
        if nMsg.isRemote {
6✔
3385
                prefix = "remote"
3✔
3386
        }
3✔
3387

3388
        log.Infof("Received new %v announcement signature for %v", prefix,
3✔
3389
                ann.ShortChannelID)
3✔
3390

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

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

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

3✔
3428
                        return nil, false
3✔
3429
                }
3✔
3430

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

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

3447
        nodeID := nMsg.source.SerializeCompressed()
3✔
3448
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
3✔
3449
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
3✔
3450

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

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

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

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

3✔
3496
                        d.wg.Add(1)
3✔
3497
                        go func() {
6✔
3498
                                defer d.wg.Done()
3✔
3499

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

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

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

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

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

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

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

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

3✔
3561
                nMsg.err <- nil
3✔
3562
                return nil, false
3✔
3563
        }
3564

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

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

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

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

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

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

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

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

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

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

3689
        nMsg.err <- nil
3✔
3690
        return announcements, true
3✔
3691
}
3692

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

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

3✔
3704
        pubkeySer := pubkey.SerializeCompressed()
3✔
3705

3✔
3706
        var pubkeyBytes [33]byte
3✔
3707
        copy(pubkeyBytes[:], pubkeySer)
3✔
3708

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

3717
                // We should only disconnect non-channel peers.
3718
                if !isChanPeer {
×
3719
                        return true, nil
×
3720
                }
×
3721
        }
3722

3723
        return false, nil
3✔
3724
}
3725

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

3✔
3735
        scid := ann.ShortChannelID
3✔
3736

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

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

3769
                default:
×
3770
                }
3771

3772
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
×
3773
                        ErrNoFundingTransaction, err)
×
3774
        }
3775

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

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

3807
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
×
3808
                        ErrInvalidFundingOutput, err)
×
3809
        }
3810

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

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

3830
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
3✔
3831
                nil
3✔
3832
}
3833

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

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

3852
                return pkScript, nil
3✔
3853
        }
3854

3855
        if features.IsEmpty() {
6✔
3856
                return legacyFundingScript()
3✔
3857
        }
3✔
3858

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

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

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

3880
                // TODO(roasbeef): add tapscript root to gossip v1.5
3881

3882
                return fundingScript, nil
3✔
3883
        }
3884

3885
        return legacyFundingScript()
×
3886
}
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