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

lightningnetwork / lnd / 15856156912

24 Jun 2025 04:30PM UTC coverage: 58.181% (+0.008%) from 58.173%
15856156912

Pull #9978

github

web-flow
Merge a2aef8aae into 29ff13d83
Pull Request #9978: multi: fix deadlock in p2p race condition

54 of 59 new or added lines in 4 files covered. (91.53%)

54 existing lines in 10 files now uncovered.

98363 of 169063 relevant lines covered (58.18%)

1.81 hits per line

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

68.57
/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
        errChan := make(chan error, 1)
3✔
864

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

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

×
879
                        errChan <- ErrGossipSyncerNotFound
×
880
                        return errChan
×
881
                }
×
882

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

891
                errChan <- err
3✔
892
                return errChan
3✔
893

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

×
902
                        errChan <- ErrGossipSyncerNotFound
×
903
                        return errChan
×
904
                }
×
905

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

×
912
                        errChan <- err
×
913
                        return errChan
×
914
                }
×
915

916
                errChan <- nil
3✔
917
                return errChan
3✔
918

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

3✔
927
                if bytes.Equal(m.NodeID1[:], ownKey) ||
3✔
928
                        bytes.Equal(m.NodeID2[:], ownKey) {
6✔
929

3✔
930
                        log.Warn(ownErr)
3✔
931
                        errChan <- ownErr
3✔
932
                        return errChan
3✔
933
                }
3✔
934
        }
935

936
        nMsg := &networkMsg{
3✔
937
                msg:      msg,
3✔
938
                isRemote: true,
3✔
939
                peer:     peer,
3✔
940
                source:   peer.IdentityKey(),
3✔
941
                err:      errChan,
3✔
942
        }
3✔
943

3✔
944
        select {
3✔
945
        case d.networkMsgs <- nMsg:
3✔
946

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

959
        return nMsg.err
3✔
960
}
961

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

3✔
972
        optionalMsgFields := &optionalMsgFields{}
3✔
973
        optionalMsgFields.apply(optionalFields...)
3✔
974

3✔
975
        nMsg := &networkMsg{
3✔
976
                msg:               msg,
3✔
977
                optionalMsgFields: optionalMsgFields,
3✔
978
                isRemote:          false,
3✔
979
                source:            d.selfKey,
3✔
980
                err:               make(chan error, 1),
3✔
981
        }
3✔
982

3✔
983
        select {
3✔
984
        case d.networkMsgs <- nMsg:
3✔
985
        case <-d.quit:
×
986
                nMsg.err <- ErrGossiperShuttingDown
×
987
        }
988

989
        return nMsg.err
3✔
990
}
991

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

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

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

1014
        // isLocal is true if this was a message that originated locally. We'll
1015
        // use this to bypass our normal checks to ensure we prioritize sending
1016
        // out our own updates.
1017
        isLocal bool
1018

1019
        // sender is the set of peers that sent us this message.
1020
        senders map[route.Vertex]struct{}
1021
}
1022

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

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

1044
        // channelUpdates are identified by the channel update id field.
1045
        channelUpdates map[channelUpdateID]msgWithSenders
1046

1047
        // nodeAnnouncements are identified by the Vertex field.
1048
        nodeAnnouncements map[route.Vertex]msgWithSenders
1049

1050
        sync.Mutex
1051
}
1052

1053
// Reset operates on deDupedAnnouncements to reset the storage of
1054
// announcements.
1055
func (d *deDupedAnnouncements) Reset() {
3✔
1056
        d.Lock()
3✔
1057
        defer d.Unlock()
3✔
1058

3✔
1059
        d.reset()
3✔
1060
}
3✔
1061

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

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

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

1087
        // Channel announcements are identified by the short channel id field.
1088
        case *lnwire.ChannelAnnouncement1:
3✔
1089
                deDupKey := msg.ShortChannelID
3✔
1090
                sender := route.NewVertex(message.source)
3✔
1091

3✔
1092
                mws, ok := d.channelAnnouncements[deDupKey]
3✔
1093
                if !ok {
6✔
1094
                        mws = msgWithSenders{
3✔
1095
                                msg:     msg,
3✔
1096
                                isLocal: !message.isRemote,
3✔
1097
                                senders: make(map[route.Vertex]struct{}),
3✔
1098
                        }
3✔
1099
                        mws.senders[sender] = struct{}{}
3✔
1100

3✔
1101
                        d.channelAnnouncements[deDupKey] = mws
3✔
1102

3✔
1103
                        return
3✔
1104
                }
3✔
1105

1106
                mws.msg = msg
×
1107
                mws.senders[sender] = struct{}{}
×
1108
                d.channelAnnouncements[deDupKey] = mws
×
1109

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

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

×
1129
                                return
×
1130
                        }
×
1131

1132
                        oldTimestamp = update.Timestamp
×
1133
                }
1134

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

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

3✔
1153
                        // We'll mark the sender of the message in the
3✔
1154
                        // senders map.
3✔
1155
                        mws.senders[sender] = struct{}{}
3✔
1156

3✔
1157
                        d.channelUpdates[deDupKey] = mws
3✔
1158

3✔
1159
                        return
3✔
1160
                }
3✔
1161

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

1170
        // Node announcements are identified by the Vertex field.  Use the
1171
        // NodeID to create the corresponding Vertex.
1172
        case *lnwire.NodeAnnouncement:
3✔
1173
                sender := route.NewVertex(message.source)
3✔
1174
                deDupKey := route.Vertex(msg.NodeID)
3✔
1175

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

1184
                // Discard the message if it's old.
1185
                if oldTimestamp > msg.Timestamp {
6✔
1186
                        return
3✔
1187
                }
3✔
1188

1189
                // Replace if it's newer.
1190
                if oldTimestamp < msg.Timestamp {
6✔
1191
                        mws = msgWithSenders{
3✔
1192
                                msg:     msg,
3✔
1193
                                isLocal: !message.isRemote,
3✔
1194
                                senders: make(map[route.Vertex]struct{}),
3✔
1195
                        }
3✔
1196

3✔
1197
                        mws.senders[sender] = struct{}{}
3✔
1198

3✔
1199
                        d.nodeAnnouncements[deDupKey] = mws
3✔
1200

3✔
1201
                        return
3✔
1202
                }
3✔
1203

1204
                // Add to senders map if it's the same as we had.
1205
                mws.msg = msg
3✔
1206
                mws.senders[sender] = struct{}{}
3✔
1207
                d.nodeAnnouncements[deDupKey] = mws
3✔
1208
        }
1209
}
1210

1211
// AddMsgs is a helper method to add multiple messages to the announcement
1212
// batch.
1213
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
3✔
1214
        d.Lock()
3✔
1215
        defer d.Unlock()
3✔
1216

3✔
1217
        for _, msg := range msgs {
6✔
1218
                d.addMsg(msg)
3✔
1219
        }
3✔
1220
}
1221

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

1229
        // remoteMsgs is the set of messages that we received from a remote
1230
        // party.
1231
        remoteMsgs []msgWithSenders
1232
}
1233

1234
// addMsg adds a new message to the appropriate sub-slice.
1235
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
3✔
1236
        if msg.isLocal {
6✔
1237
                m.localMsgs = append(m.localMsgs, msg)
3✔
1238
        } else {
6✔
1239
                m.remoteMsgs = append(m.remoteMsgs, msg)
3✔
1240
        }
3✔
1241
}
1242

1243
// isEmpty returns true if the batch is empty.
1244
func (m *msgsToBroadcast) isEmpty() bool {
3✔
1245
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
3✔
1246
}
3✔
1247

1248
// length returns the length of the combined message set.
1249
func (m *msgsToBroadcast) length() int {
×
1250
        return len(m.localMsgs) + len(m.remoteMsgs)
×
1251
}
×
1252

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

3✔
1263
        // Get the total number of announcements.
3✔
1264
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
3✔
1265
                len(d.nodeAnnouncements)
3✔
1266

3✔
1267
        // Create an empty array of lnwire.Messages with a length equal to
3✔
1268
        // the total number of announcements.
3✔
1269
        msgs := msgsToBroadcast{
3✔
1270
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
3✔
1271
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
3✔
1272
        }
3✔
1273

3✔
1274
        // Add the channel announcements to the array first.
3✔
1275
        for _, message := range d.channelAnnouncements {
6✔
1276
                msgs.addMsg(message)
3✔
1277
        }
3✔
1278

1279
        // Then add the channel updates.
1280
        for _, message := range d.channelUpdates {
6✔
1281
                msgs.addMsg(message)
3✔
1282
        }
3✔
1283

1284
        // Finally add the node announcements.
1285
        for _, message := range d.nodeAnnouncements {
6✔
1286
                msgs.addMsg(message)
3✔
1287
        }
3✔
1288

1289
        d.reset()
3✔
1290

3✔
1291
        // Return the array of lnwire.messages.
3✔
1292
        return msgs
3✔
1293
}
1294

1295
// calculateSubBatchSize is a helper function that calculates the size to break
1296
// down the batchSize into.
1297
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1298
        minimumBatchSize, batchSize int) int {
3✔
1299
        if subBatchDelay > totalDelay {
3✔
1300
                return batchSize
×
1301
        }
×
1302

1303
        subBatchSize := (batchSize*int(subBatchDelay) +
3✔
1304
                int(totalDelay) - 1) / int(totalDelay)
3✔
1305

3✔
1306
        if subBatchSize < minimumBatchSize {
6✔
1307
                return minimumBatchSize
3✔
1308
        }
3✔
1309

1310
        return subBatchSize
×
1311
}
1312

1313
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1314
// this variable so the function can be mocked in our test.
1315
var batchSizeCalculator = calculateSubBatchSize
1316

1317
// splitAnnouncementBatches takes an exiting list of announcements and
1318
// decomposes it into sub batches controlled by the `subBatchSize`.
1319
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1320
        announcementBatch []msgWithSenders) [][]msgWithSenders {
3✔
1321

3✔
1322
        subBatchSize := batchSizeCalculator(
3✔
1323
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
3✔
1324
                d.cfg.MinimumBatchSize, len(announcementBatch),
3✔
1325
        )
3✔
1326

3✔
1327
        var splitAnnouncementBatch [][]msgWithSenders
3✔
1328

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

3✔
1341
        return splitAnnouncementBatch
3✔
1342
}
1343

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

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

1361
        // Fetch the local and remote announcements.
1362
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
3✔
1363
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
3✔
1364

3✔
1365
        d.wg.Add(1)
3✔
1366
        go func() {
6✔
1367
                defer d.wg.Done()
3✔
1368

3✔
1369
                log.Debugf("Broadcasting %v new local announcements in %d "+
3✔
1370
                        "sub batches", len(annBatch.localMsgs),
3✔
1371
                        len(localBatches))
3✔
1372

3✔
1373
                // Send out the local announcements first.
3✔
1374
                for _, annBatch := range localBatches {
6✔
1375
                        d.sendLocalBatch(annBatch)
3✔
1376
                        delayNextBatch()
3✔
1377
                }
3✔
1378

1379
                log.Debugf("Broadcasting %v new remote announcements in %d "+
3✔
1380
                        "sub batches", len(annBatch.remoteMsgs),
3✔
1381
                        len(remoteBatches))
3✔
1382

3✔
1383
                // Now send the remote announcements.
3✔
1384
                for _, annBatch := range remoteBatches {
6✔
1385
                        d.sendRemoteBatch(ctx, annBatch)
3✔
1386
                        delayNextBatch()
3✔
1387
                }
3✔
1388
        }()
1389
}
1390

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

1401
        err := d.cfg.Broadcast(nil, msgsToSend...)
3✔
1402
        if err != nil {
3✔
1403
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1404
        }
×
1405
}
1406

1407
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1408
// peers.
1409
func (d *AuthenticatedGossiper) sendRemoteBatch(ctx context.Context,
1410
        annBatch []msgWithSenders) {
3✔
1411

3✔
1412
        syncerPeers := d.syncMgr.GossipSyncers()
3✔
1413

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

1421
        for _, msgChunk := range annBatch {
6✔
1422
                msgChunk := msgChunk
3✔
1423

3✔
1424
                // With the syncers taken care of, we'll merge the sender map
3✔
1425
                // with the set of syncers, so we don't send out duplicate
3✔
1426
                // messages.
3✔
1427
                msgChunk.mergeSyncerMap(syncerPeers)
3✔
1428

3✔
1429
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
3✔
1430
                if err != nil {
3✔
1431
                        log.Errorf("Unable to send batch "+
×
1432
                                "announcements: %v", err)
×
1433
                        continue
×
1434
                }
1435
        }
1436
}
1437

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

3✔
1447
        // Initialize empty deDupedAnnouncements to store announcement batch.
3✔
1448
        announcements := deDupedAnnouncements{}
3✔
1449
        announcements.Reset()
3✔
1450

3✔
1451
        d.cfg.RetransmitTicker.Resume()
3✔
1452
        defer d.cfg.RetransmitTicker.Stop()
3✔
1453

3✔
1454
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
3✔
1455
        defer trickleTimer.Stop()
3✔
1456

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

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

3✔
1472
                        // Process policy updates asynchronously to avoid
3✔
1473
                        // blocking the main network handler loop because the
3✔
1474
                        // graph db has to be updated here which might be slow
3✔
1475
                        // to acquire the db lock.
3✔
1476
                        d.wg.Add(1)
3✔
1477
                        go func(update *chanPolicyUpdateRequest) {
6✔
1478
                                defer d.wg.Done()
3✔
1479

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

×
NEW
1492
                                        return
×
NEW
1493
                                }
×
1494

1495
                                // Finally, with the updates committed, we'll
1496
                                // now add them to the announcement batch to be
1497
                                // flushed at the start of the next epoch.
1498
                                announcements.AddMsgs(chanUpdates...)
3✔
1499
                        }(policyUpdate)
1500

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

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

3✔
1519
                                if emittedAnnouncements != nil {
6✔
1520
                                        announcements.AddMsgs(
3✔
1521
                                                emittedAnnouncements...,
3✔
1522
                                        )
3✔
1523
                                }
3✔
1524
                                continue
3✔
1525
                        }
1526

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

×
1534
                                announcement.err <- fmt.Errorf("recently " +
×
1535
                                        "rejected")
×
1536
                                continue
×
1537
                        }
1538

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

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

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

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

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

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

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

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

3✔
1605
        defer d.wg.Done()
3✔
1606
        defer d.vb.CompleteJob()
3✔
1607

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

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

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

×
1625
                return
×
1626
        }
1627

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

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

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

×
1645
                nMsg.err <- err
×
1646

×
1647
                return
×
1648
        }
×
1649

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

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

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

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

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

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

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

1692
        default:
3✔
1693
                return false
3✔
1694
        }
1695

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

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

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

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

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

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

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

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

1755
                timeElapsed := now.Sub(edge.LastUpdate)
3✔
1756

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

1767
                return nil
3✔
1768
        })
1769
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
1770
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1771
                        err)
×
1772
        }
×
1773

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

1785
                // If we have a valid announcement to transmit, then we'll send
1786
                // that along with the update.
1787
                if chanAnn != nil {
×
1788
                        signedUpdates = append(signedUpdates, chanAnn)
×
1789
                }
×
1790

1791
                signedUpdates = append(signedUpdates, chanUpdate)
×
1792
        }
1793

1794
        // If we don't have any public channels, we return as we don't want to
1795
        // broadcast anything that would reveal our existence.
1796
        if !havePublicChannels {
6✔
1797
                return nil
3✔
1798
        }
3✔
1799

1800
        // We'll also check that our NodeAnnouncement is not too old.
1801
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
3✔
1802
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
3✔
1803
        timeElapsed := now.Sub(timestamp)
3✔
1804

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

1815
                signedUpdates = append(signedUpdates, &newNodeAnn)
×
1816
                nodeAnnStr = " and our refreshed node announcement"
×
1817

×
1818
                // Before broadcasting the refreshed node announcement, add it
×
1819
                // to our own graph.
×
1820
                if err := d.addNode(ctx, &newNodeAnn); err != nil {
×
1821
                        log.Errorf("Unable to add refreshed node announcement "+
×
1822
                                "to graph: %v", err)
×
1823
                }
×
1824
        }
1825

1826
        // If we don't have any updates to re-broadcast, then we'll exit
1827
        // early.
1828
        if len(signedUpdates) == 0 {
6✔
1829
                return nil
3✔
1830
        }
3✔
1831

1832
        log.Infof("Retransmitting %v outgoing channels%v",
×
1833
                len(edgesToUpdate), nodeAnnStr)
×
1834

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

1841
        return nil
×
1842
}
1843

1844
// processChanPolicyUpdate generates a new set of channel updates for the
1845
// provided list of edges and updates the backing ChannelGraphSource.
1846
func (d *AuthenticatedGossiper) processChanPolicyUpdate(ctx context.Context,
1847
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
3✔
1848

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

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

3✔
1875
                        var defaultAlias lnwire.ShortChannelID
3✔
1876
                        foundAlias, _ := d.cfg.GetAlias(chanID)
3✔
1877
                        if foundAlias != defaultAlias {
6✔
1878
                                chanUpdate.ShortChannelID = foundAlias
3✔
1879

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

1887
                                lnSig, err := lnwire.NewSigFromSignature(sig)
3✔
1888
                                if err != nil {
3✔
1889
                                        log.Errorf("Unable to create sig: %v",
×
1890
                                                err)
×
1891
                                        continue
×
1892
                                }
1893

1894
                                chanUpdate.Signature = lnSig
3✔
1895
                        }
1896

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

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

1922
        return chanUpdates, nil
3✔
1923
}
1924

1925
// remotePubFromChanInfo returns the public key of the remote peer given a
1926
// ChannelEdgeInfo that describe a channel we have with them.
1927
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1928
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
3✔
1929

3✔
1930
        var remotePubKey [33]byte
3✔
1931
        switch {
3✔
1932
        case chanFlags&lnwire.ChanUpdateDirection == 0:
3✔
1933
                remotePubKey = chanInfo.NodeKey2Bytes
3✔
1934
        case chanFlags&lnwire.ChanUpdateDirection == 1:
3✔
1935
                remotePubKey = chanInfo.NodeKey1Bytes
3✔
1936
        }
1937

1938
        return remotePubKey
3✔
1939
}
1940

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

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

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

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

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

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

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

×
2022
        }
×
2023

2024
        return announcements, nil
×
2025
}
2026

2027
// fetchPKScript fetches the output script for the given SCID.
2028
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2029
        []byte, error) {
×
2030

×
2031
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2032
}
×
2033

2034
// addNode processes the given node announcement, and adds it to our channel
2035
// graph.
2036
func (d *AuthenticatedGossiper) addNode(ctx context.Context,
2037
        msg *lnwire.NodeAnnouncement, op ...batch.SchedulerOption) error {
3✔
2038

3✔
2039
        if err := netann.ValidateNodeAnn(msg); err != nil {
3✔
2040
                return fmt.Errorf("unable to validate node announcement: %w",
×
2041
                        err)
×
2042
        }
×
2043

2044
        return d.cfg.Graph.AddNode(
3✔
2045
                ctx, models.NodeFromWireAnnouncement(msg), op...,
3✔
2046
        )
3✔
2047
}
2048

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

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

2065
        msgHeight := chanID.BlockHeight + delta
3✔
2066

3✔
2067
        // The message height is smaller or equal to our best known height,
3✔
2068
        // thus the message is mature.
3✔
2069
        if msgHeight <= d.bestHeight {
6✔
2070
                return false
3✔
2071
        }
3✔
2072

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

3✔
2087
        // Create the cached message.
3✔
2088
        cachedMsg := &cachedFutureMsg{
3✔
2089
                msg:    copied,
3✔
2090
                height: msgHeight,
3✔
2091
        }
3✔
2092

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

2100
        log.Debugf("Network message: %v added to future messages for "+
3✔
2101
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
3✔
2102
                msgHeight, d.bestHeight)
3✔
2103

3✔
2104
        return true
3✔
2105
}
2106

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

3✔
2117
        // If this is a remote update, we set the scheduler option to lazily
3✔
2118
        // add it to the graph.
3✔
2119
        var schedulerOp []batch.SchedulerOption
3✔
2120
        if nMsg.isRemote {
6✔
2121
                schedulerOp = append(schedulerOp, batch.LazyAdd())
3✔
2122
        }
3✔
2123

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

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

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

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

2150
        default:
×
2151
                err := errors.New("wrong type of the announcement")
×
2152
                nMsg.err <- err
×
2153
                return nil, false
×
2154
        }
2155
}
2156

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

×
2166
        // The least-significant bit in the flag on the channel update tells us
×
2167
        // which edge is being updated.
×
2168
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
×
2169

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

2187
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
×
2188
        if err != nil {
×
2189
                return fmt.Errorf("unable to verify channel "+
×
2190
                        "update signature: %v", err)
×
2191
        }
×
2192

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

×
2202
                return nil
×
2203

2204
        case err != nil:
×
2205
                return fmt.Errorf("unable to remove edge with "+
×
2206
                        "chan_id=%v from zombie index: %v",
×
2207
                        msg.ShortChannelID, err)
×
2208

2209
        default:
×
2210
        }
2211

2212
        log.Debugf("Removed edge with chan_id=%v from zombie "+
×
2213
                "index", msg.ShortChannelID)
×
2214

×
2215
        return nil
×
2216
}
2217

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

3✔
2223
        node, err := d.cfg.Graph.FetchLightningNode(ctx, pubKey)
3✔
2224
        if err != nil {
3✔
2225
                return nil, err
×
2226
        }
×
2227

2228
        return node.NodeAnnouncement(true)
3✔
2229
}
2230

2231
// isMsgStale determines whether a message retrieved from the backing
2232
// MessageStore is seen as stale by the current graph.
2233
func (d *AuthenticatedGossiper) isMsgStale(_ context.Context,
2234
        msg lnwire.Message) bool {
3✔
2235

3✔
2236
        switch msg := msg.(type) {
3✔
2237
        case *lnwire.AnnounceSignatures1:
3✔
2238
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
3✔
2239
                        msg.ShortChannelID,
3✔
2240
                )
3✔
2241

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

2254
                // If the proof exists in the graph, then we have successfully
2255
                // received the remote proof and assembled the full proof, so we
2256
                // can safely delete the local proof from the database.
2257
                return chanInfo.AuthProof != nil
3✔
2258

2259
        case *lnwire.ChannelUpdate1:
3✔
2260
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
3✔
2261

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

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

2284
                // If the policy is still unknown, then we can consider this
2285
                // policy fresh.
2286
                if p == nil {
3✔
2287
                        return false
×
2288
                }
×
2289

2290
                timestamp := time.Unix(int64(msg.Timestamp), 0)
3✔
2291
                return p.LastUpdate.After(timestamp)
3✔
2292

2293
        default:
×
2294
                // We'll make sure to not mark any unsupported messages as stale
×
2295
                // to ensure they are not removed.
×
2296
                return false
×
2297
        }
2298
}
2299

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

3✔
2307
        // Parse the unsigned edge into a channel update.
3✔
2308
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
3✔
2309

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

2320
        // Next, we'll set the new signature in place, and update the reference
2321
        // in the backing slice.
2322
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
3✔
2323
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
3✔
2324

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

2335
        // Finally, we'll write the new edge policy to disk.
2336
        if err := d.cfg.Graph.UpdateEdge(ctx, edge); err != nil {
3✔
2337
                return nil, nil, err
×
2338
        }
×
2339

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

2382
        return chanAnn, chanUpdate, err
3✔
2383
}
2384

2385
// SyncManager returns the gossiper's SyncManager instance.
2386
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
3✔
2387
        return d.syncMgr
3✔
2388
}
3✔
2389

2390
// IsKeepAliveUpdate determines whether this channel update is considered a
2391
// keep-alive update based on the previous channel update processed for the same
2392
// direction.
2393
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2394
        prev *models.ChannelEdgePolicy) bool {
3✔
2395

3✔
2396
        // Both updates should be from the same direction.
3✔
2397
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
3✔
2398
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
3✔
2399

×
2400
                return false
×
2401
        }
×
2402

2403
        // The timestamp should always increase for a keep-alive update.
2404
        timestamp := time.Unix(int64(update.Timestamp), 0)
3✔
2405
        if !timestamp.After(prev.LastUpdate) {
3✔
2406
                return false
×
2407
        }
×
2408

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

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

2444
// handleNodeAnnouncement processes a new node announcement.
2445
func (d *AuthenticatedGossiper) handleNodeAnnouncement(ctx context.Context,
2446
        nMsg *networkMsg, nodeAnn *lnwire.NodeAnnouncement,
2447
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2448

3✔
2449
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
3✔
2450

3✔
2451
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
3✔
2452
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
3✔
2453
                nMsg.source.SerializeCompressed())
3✔
2454

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

2463
        if err := d.addNode(ctx, nodeAnn, ops...); err != nil {
6✔
2464
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
3✔
2465
                        err)
3✔
2466

3✔
2467
                if !graph.IsError(
3✔
2468
                        err,
3✔
2469
                        graph.ErrOutdated,
3✔
2470
                        graph.ErrIgnored,
3✔
2471
                ) {
3✔
2472

×
2473
                        log.Error(err)
×
2474
                }
×
2475

2476
                nMsg.err <- err
3✔
2477
                return nil, false
3✔
2478
        }
2479

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

2491
        var announcements []networkMsg
3✔
2492

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

2507
        nMsg.err <- nil
3✔
2508
        // TODO(roasbeef): get rid of the above
3✔
2509

3✔
2510
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
3✔
2511
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
3✔
2512
                nMsg.source.SerializeCompressed())
3✔
2513

3✔
2514
        return announcements, true
3✔
2515
}
2516

2517
// handleChanAnnouncement processes a new channel announcement.
2518
//
2519
//nolint:funlen
2520
func (d *AuthenticatedGossiper) handleChanAnnouncement(ctx context.Context,
2521
        nMsg *networkMsg, ann *lnwire.ChannelAnnouncement1,
2522
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
3✔
2523

3✔
2524
        scid := ann.ShortChannelID
3✔
2525

3✔
2526
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
3✔
2527
                nMsg.peer, scid.ToUint64())
3✔
2528

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

×
2537
                key := newRejectCacheKey(
×
2538
                        scid.ToUint64(),
×
2539
                        sourceToPub(nMsg.source),
×
2540
                )
×
2541
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2542

×
2543
                nMsg.err <- err
×
2544
                return nil, false
×
2545
        }
×
2546

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

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

×
2560
                nMsg.err <- err
×
2561
                return nil, false
×
2562
        }
×
2563

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

3✔
2577
        // At this point, we'll now ask the router if this is a zombie/known
3✔
2578
        // edge. If so we can skip all the processing below.
3✔
2579
        if d.cfg.Graph.IsKnownEdge(scid) {
6✔
2580
                nMsg.err <- nil
3✔
2581
                return nil, true
3✔
2582
        }
3✔
2583

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

×
2592
                return nil, false
×
2593
        }
×
2594

2595
        if closed {
3✔
2596
                err = fmt.Errorf("ignoring closed channel %v", scid)
×
2597
                log.Error(err)
×
2598

×
2599
                // If this is an announcement from us, we'll just ignore it.
×
2600
                if !nMsg.isRemote {
×
2601
                        nMsg.err <- err
×
2602
                        return nil, false
×
2603
                }
×
2604

2605
                // Increment the peer's ban score if they are sending closed
2606
                // channel announcements.
2607
                d.banman.incrementBanScore(nMsg.peer.PubKey())
×
2608

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

×
2617
                        return nil, false
×
2618
                }
×
2619

2620
                if shouldDc {
×
2621
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2622
                }
×
2623

2624
                nMsg.err <- err
×
2625

×
2626
                return nil, false
×
2627
        }
2628

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

×
2638
                        key := newRejectCacheKey(
×
2639
                                scid.ToUint64(),
×
2640
                                sourceToPub(nMsg.source),
×
2641
                        )
×
2642
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2643

×
2644
                        log.Error(err)
×
2645
                        nMsg.err <- err
×
2646
                        return nil, false
×
2647
                }
×
2648

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

2660
        // With the proof validated (if necessary), we can now store it within
2661
        // the database for our path finding and syncing needs.
2662
        var featureBuf bytes.Buffer
3✔
2663
        if err := ann.Features.Encode(&featureBuf); err != nil {
3✔
2664
                log.Errorf("unable to encode features: %v", err)
×
2665
                nMsg.err <- err
×
2666
                return nil, false
×
2667
        }
×
2668

2669
        edge := &models.ChannelEdgeInfo{
3✔
2670
                ChannelID:        scid.ToUint64(),
3✔
2671
                ChainHash:        ann.ChainHash,
3✔
2672
                NodeKey1Bytes:    ann.NodeID1,
3✔
2673
                NodeKey2Bytes:    ann.NodeID2,
3✔
2674
                BitcoinKey1Bytes: ann.BitcoinKey1,
3✔
2675
                BitcoinKey2Bytes: ann.BitcoinKey2,
3✔
2676
                AuthProof:        proof,
3✔
2677
                Features:         featureBuf.Bytes(),
3✔
2678
                ExtraOpaqueData:  ann.ExtraOpaqueData,
3✔
2679
        }
3✔
2680

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

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

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

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

×
2718
                        switch {
×
2719
                        case errors.Is(err, ErrNoFundingTransaction),
2720
                                errors.Is(err, ErrInvalidFundingOutput):
×
2721

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

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

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

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

×
2757
                                        nMsg.err <- dbErr
×
2758

×
2759
                                        return nil, false
×
2760
                                }
×
2761

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

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

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

×
2786
                                return nil, false
×
2787
                        }
×
2788

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

×
2797
                                return nil, false
×
2798
                        }
×
2799

2800
                        if shouldDc {
×
2801
                                nMsg.peer.Disconnect(ErrPeerBanned)
×
2802
                        }
×
2803

2804
                        nMsg.err <- err
×
2805

×
2806
                        return nil, false
×
2807
                }
2808

2809
                edge.FundingScript = fn.Some(script)
3✔
2810

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

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

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

3✔
2827
                defer d.channelMtx.Unlock(scid.ToUint64())
3✔
2828

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

×
2844
                                nMsg.err <- rErr
×
2845

×
2846
                                return nil, false
×
2847
                        }
×
2848

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

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

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

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

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

×
2875
                        return nil, false
×
2876
                }
×
2877

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

×
2884
                        return nil, false
×
2885
                }
×
2886

2887
                if shouldDc {
×
2888
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2889
                }
×
2890

2891
                nMsg.err <- err
×
2892

×
2893
                return nil, false
×
2894
        }
2895

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

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

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

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

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

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

3✔
2928
                d.wg.Add(1)
3✔
2929
                go func(updMsg *networkMsg) {
6✔
2930
                        defer d.wg.Done()
3✔
2931

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

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

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

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

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

2969
        nMsg.err <- nil
3✔
2970

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

3✔
2974
        return announcements, true
3✔
2975
}
2976

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

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

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

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

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

3004
        blockHeight := upd.ShortChannelID.BlockHeight
3✔
3005
        shortChanID := upd.ShortChannelID.ToUint64()
3✔
3006

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

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

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

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

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

3✔
3048
        if d.cfg.Graph.IsStaleEdgePolicy(
3✔
3049
                graphScid, timestamp, upd.ChannelFlags,
3✔
3050
        ) {
6✔
3051

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

3✔
3057
                nMsg.err <- nil
3✔
3058
                return nil, true
3✔
3059
        }
3✔
3060

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

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

×
3074
                return nil, false
×
3075
        }
×
3076

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

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

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

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

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

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

3✔
3148
                // NOTE: We don't return anything on the error channel for this
3✔
3149
                // message, as we expect that will be done when this
3✔
3150
                // ChannelUpdate is later reprocessed.
3✔
3151
                return nil, false
3✔
3152

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

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

×
3165
                return nil, false
×
3166
        }
3167

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

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

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

×
3198
                log.Error(rErr)
×
3199
                nMsg.err <- rErr
×
3200
                return nil, false
×
3201
        }
×
3202

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3373
        nMsg.err <- nil
3✔
3374

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

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

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

3✔
3392
        prefix := "local"
3✔
3393
        if nMsg.isRemote {
6✔
3394
                prefix = "remote"
3✔
3395
        }
3✔
3396

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

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

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

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

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

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

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

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

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

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

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

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

3✔
3505
                        d.wg.Add(1)
3✔
3506
                        go func() {
6✔
3507
                                defer d.wg.Done()
3✔
3508

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

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

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

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

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

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

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

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

3✔
3570
                nMsg.err <- nil
3✔
3571
                return nil, false
3✔
3572
        }
3573

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

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

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

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

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

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

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

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

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

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

3698
        nMsg.err <- nil
3✔
3699
        return announcements, true
3✔
3700
}
3701

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

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

3✔
3713
        pubkeySer := pubkey.SerializeCompressed()
3✔
3714

3✔
3715
        var pubkeyBytes [33]byte
3✔
3716
        copy(pubkeyBytes[:], pubkeySer)
3✔
3717

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

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

3732
        return false, nil
3✔
3733
}
3734

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

3✔
3744
        scid := ann.ShortChannelID
3✔
3745

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

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

3778
                default:
×
3779
                }
3780

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

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

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

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

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

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

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

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

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

3861
                return pkScript, nil
3✔
3862
        }
3863

3864
        if features.IsEmpty() {
6✔
3865
                return legacyFundingScript()
3✔
3866
        }
3✔
3867

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

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

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

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

3891
                return fundingScript, nil
3✔
3892
        }
3893

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