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

lightningnetwork / lnd / 14358372723

09 Apr 2025 01:26PM UTC coverage: 56.696% (-12.3%) from 69.037%
14358372723

Pull #9696

github

web-flow
Merge e2837e400 into 867d27d68
Pull Request #9696: Add `development_guidelines.md` for both human and machine

107055 of 188823 relevant lines covered (56.7%)

22721.56 hits per line

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

70.63
/discovery/gossiper.go
1
package discovery
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

174
        isRemote bool
175

176
        err chan error
177
}
178

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

472✔
438
        return k
472✔
439
}
472✔
440

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

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

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

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

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

478
        quit chan struct{}
479
        wg   sync.WaitGroup
480

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

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

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

495
        // banman tracks our peer's ban status.
496
        banman *banman
497

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

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

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

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

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

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

527
        recentRejects *lru.Cache[rejectCacheKey, *cachedReject]
528

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

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

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

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

557
        sync.Mutex
558
}
559

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

30✔
582
        gossiper.vb = NewValidationBarrier(1000, gossiper.quit)
30✔
583

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

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

30✔
606
        return gossiper
30✔
607
}
30✔
608

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

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

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

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

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

642
// Start spawns network messages handler goroutine and registers on new block
643
// notifications in order to properly handle the premature announcements.
644
func (d *AuthenticatedGossiper) Start() error {
30✔
645
        var err error
30✔
646
        d.started.Do(func() {
60✔
647
                log.Info("Authenticated Gossiper starting")
30✔
648
                err = d.start()
30✔
649
        })
30✔
650
        return err
30✔
651
}
652

653
func (d *AuthenticatedGossiper) start() error {
30✔
654
        // First we register for new notifications of newly discovered blocks.
30✔
655
        // We do this immediately so we'll later be able to consume any/all
30✔
656
        // blocks which were discovered.
30✔
657
        blockEpochs, err := d.cfg.Notifier.RegisterBlockEpochNtfn(nil)
30✔
658
        if err != nil {
30✔
659
                return err
×
660
        }
×
661
        d.blockEpochs = blockEpochs
30✔
662

30✔
663
        height, err := d.cfg.Graph.CurrentBlockHeight()
30✔
664
        if err != nil {
30✔
665
                return err
×
666
        }
×
667
        d.bestHeight = height
30✔
668

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

676
        d.syncMgr.Start()
30✔
677

30✔
678
        d.banman.start()
30✔
679

30✔
680
        // Start receiving blocks in its dedicated goroutine.
30✔
681
        d.wg.Add(2)
30✔
682
        go d.syncBlockHeight()
30✔
683
        go d.networkHandler()
30✔
684

30✔
685
        return nil
30✔
686
}
687

688
// syncBlockHeight syncs the best block height for the gossiper by reading
689
// blockEpochs.
690
//
691
// NOTE: must be run as a goroutine.
692
func (d *AuthenticatedGossiper) syncBlockHeight() {
30✔
693
        defer d.wg.Done()
30✔
694

30✔
695
        for {
60✔
696
                select {
30✔
697
                // A new block has arrived, so we can re-process the previously
698
                // premature announcements.
699
                case newBlock, ok := <-d.blockEpochs.Epochs:
×
700
                        // If the channel has been closed, then this indicates
×
701
                        // the daemon is shutting down, so we exit ourselves.
×
702
                        if !ok {
×
703
                                return
×
704
                        }
×
705

706
                        // Once a new block arrives, we update our running
707
                        // track of the height of the chain tip.
708
                        d.Lock()
×
709
                        blockHeight := uint32(newBlock.Height)
×
710
                        d.bestHeight = blockHeight
×
711
                        d.Unlock()
×
712

×
713
                        log.Debugf("New block: height=%d, hash=%s", blockHeight,
×
714
                                newBlock.Hash)
×
715

×
716
                        // Resend future messages, if any.
×
717
                        d.resendFutureMessages(blockHeight)
×
718

719
                case <-d.quit:
30✔
720
                        return
30✔
721
                }
722
        }
723
}
724

725
// futureMsgCache embeds a `lru.Cache` with a message counter that's served as
726
// the unique ID when saving the message.
727
type futureMsgCache struct {
728
        *lru.Cache[uint64, *cachedFutureMsg]
729

730
        // msgID is a monotonically increased integer.
731
        msgID atomic.Uint64
732
}
733

734
// nextMsgID returns a unique message ID.
735
func (f *futureMsgCache) nextMsgID() uint64 {
3✔
736
        return f.msgID.Add(1)
3✔
737
}
3✔
738

739
// newFutureMsgCache creates a new future message cache with the underlying lru
740
// cache being initialized with the specified capacity.
741
func newFutureMsgCache(capacity uint64) *futureMsgCache {
31✔
742
        // Create a new cache.
31✔
743
        cache := lru.NewCache[uint64, *cachedFutureMsg](capacity)
31✔
744

31✔
745
        return &futureMsgCache{
31✔
746
                Cache: cache,
31✔
747
        }
31✔
748
}
31✔
749

750
// cachedFutureMsg is a future message that's saved to the `futureMsgCache`.
751
type cachedFutureMsg struct {
752
        // msg is the network message.
753
        msg *networkMsg
754

755
        // height is the block height.
756
        height uint32
757
}
758

759
// Size returns the size of the message.
760
func (c *cachedFutureMsg) Size() (uint64, error) {
4✔
761
        // Return a constant 1.
4✔
762
        return 1, nil
4✔
763
}
4✔
764

765
// resendFutureMessages takes a block height, resends all the future messages
766
// found below and equal to that height and deletes those messages found in the
767
// gossiper's futureMsgs.
768
func (d *AuthenticatedGossiper) resendFutureMessages(height uint32) {
×
769
        var (
×
770
                // msgs are the target messages.
×
771
                msgs []*networkMsg
×
772

×
773
                // keys are the target messages' caching keys.
×
774
                keys []uint64
×
775
        )
×
776

×
777
        // filterMsgs is the visitor used when iterating the future cache.
×
778
        filterMsgs := func(k uint64, cmsg *cachedFutureMsg) bool {
×
779
                if cmsg.height <= height {
×
780
                        msgs = append(msgs, cmsg.msg)
×
781
                        keys = append(keys, k)
×
782
                }
×
783

784
                return true
×
785
        }
786

787
        // Filter out the target messages.
788
        d.futureMsgs.Range(filterMsgs)
×
789

×
790
        // Return early if no messages found.
×
791
        if len(msgs) == 0 {
×
792
                return
×
793
        }
×
794

795
        // Remove the filtered messages.
796
        for _, key := range keys {
×
797
                d.futureMsgs.Delete(key)
×
798
        }
×
799

800
        log.Debugf("Resending %d network messages at height %d",
×
801
                len(msgs), height)
×
802

×
803
        for _, msg := range msgs {
×
804
                select {
×
805
                case d.networkMsgs <- msg:
×
806
                case <-d.quit:
×
807
                        msg.err <- ErrGossiperShuttingDown
×
808
                }
809
        }
810
}
811

812
// Stop signals any active goroutines for a graceful closure.
813
func (d *AuthenticatedGossiper) Stop() error {
31✔
814
        d.stopped.Do(func() {
61✔
815
                log.Info("Authenticated gossiper shutting down...")
30✔
816
                defer log.Debug("Authenticated gossiper shutdown complete")
30✔
817

30✔
818
                d.stop()
30✔
819
        })
30✔
820
        return nil
31✔
821
}
822

823
func (d *AuthenticatedGossiper) stop() {
30✔
824
        log.Debug("Authenticated Gossiper is stopping")
30✔
825
        defer log.Debug("Authenticated Gossiper stopped")
30✔
826

30✔
827
        // `blockEpochs` is only initialized in the start routine so we make
30✔
828
        // sure we don't panic here in the case where the `Stop` method is
30✔
829
        // called when the `Start` method does not complete.
30✔
830
        if d.blockEpochs != nil {
60✔
831
                d.blockEpochs.Cancel()
30✔
832
        }
30✔
833

834
        d.syncMgr.Stop()
30✔
835

30✔
836
        d.banman.stop()
30✔
837

30✔
838
        close(d.quit)
30✔
839
        d.wg.Wait()
30✔
840

30✔
841
        // We'll stop our reliable sender after all of the gossiper's goroutines
30✔
842
        // have exited to ensure nothing can cause it to continue executing.
30✔
843
        d.reliableSender.Stop()
30✔
844
}
845

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

849
// ProcessRemoteAnnouncement sends a new remote announcement message along with
850
// the peer that sent the routing message. The announcement will be processed
851
// then added to a queue for batched trickled announcement to all connected
852
// peers.  Remote channel announcements should contain the announcement proof
853
// and be fully validated.
854
func (d *AuthenticatedGossiper) ProcessRemoteAnnouncement(msg lnwire.Message,
855
        peer lnpeer.Peer) chan error {
291✔
856

291✔
857
        log.Debugf("Processing remote msg %T from peer=%x", msg, peer.PubKey())
291✔
858

291✔
859
        errChan := make(chan error, 1)
291✔
860

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

×
870
                syncer, ok := d.syncMgr.GossipSyncer(peer.PubKey())
×
871
                if !ok {
×
872
                        log.Warnf("Gossip syncer for peer=%x not found",
×
873
                                peer.PubKey())
×
874

×
875
                        errChan <- ErrGossipSyncerNotFound
×
876
                        return errChan
×
877
                }
×
878

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

887
                errChan <- err
×
888
                return errChan
×
889

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

×
898
                        errChan <- ErrGossipSyncerNotFound
×
899
                        return errChan
×
900
                }
×
901

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

×
908
                        errChan <- err
×
909
                        return errChan
×
910
                }
×
911

912
                errChan <- nil
×
913
                return errChan
×
914

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

220✔
923
                if bytes.Equal(m.NodeID1[:], ownKey) ||
220✔
924
                        bytes.Equal(m.NodeID2[:], ownKey) {
222✔
925

2✔
926
                        log.Warn(ownErr)
2✔
927
                        errChan <- ownErr
2✔
928
                        return errChan
2✔
929
                }
2✔
930
        }
931

932
        nMsg := &networkMsg{
289✔
933
                msg:      msg,
289✔
934
                isRemote: true,
289✔
935
                peer:     peer,
289✔
936
                source:   peer.IdentityKey(),
289✔
937
                err:      errChan,
289✔
938
        }
289✔
939

289✔
940
        select {
289✔
941
        case d.networkMsgs <- nMsg:
289✔
942

943
        // If the peer that sent us this error is quitting, then we don't need
944
        // to send back an error and can return immediately.
945
        case <-peer.QuitSignal():
×
946
                return nil
×
947
        case <-d.quit:
×
948
                nMsg.err <- ErrGossiperShuttingDown
×
949
        }
950

951
        return nMsg.err
289✔
952
}
953

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

47✔
964
        optionalMsgFields := &optionalMsgFields{}
47✔
965
        optionalMsgFields.apply(optionalFields...)
47✔
966

47✔
967
        nMsg := &networkMsg{
47✔
968
                msg:               msg,
47✔
969
                optionalMsgFields: optionalMsgFields,
47✔
970
                isRemote:          false,
47✔
971
                source:            d.selfKey,
47✔
972
                err:               make(chan error, 1),
47✔
973
        }
47✔
974

47✔
975
        select {
47✔
976
        case d.networkMsgs <- nMsg:
47✔
977
        case <-d.quit:
×
978
                nMsg.err <- ErrGossiperShuttingDown
×
979
        }
980

981
        return nMsg.err
47✔
982
}
983

984
// channelUpdateID is a unique identifier for ChannelUpdate messages, as
985
// channel updates can be identified by the (ShortChannelID, ChannelFlags)
986
// tuple.
987
type channelUpdateID struct {
988
        // channelID represents the set of data which is needed to
989
        // retrieve all necessary data to validate the channel existence.
990
        channelID lnwire.ShortChannelID
991

992
        // Flags least-significant bit must be set to 0 if the creating node
993
        // corresponds to the first node in the previously sent channel
994
        // announcement and 1 otherwise.
995
        flags lnwire.ChanUpdateChanFlags
996
}
997

998
// msgWithSenders is a wrapper struct around a message, and the set of peers
999
// that originally sent us this message. Using this struct, we can ensure that
1000
// we don't re-send a message to the peer that sent it to us in the first
1001
// place.
1002
type msgWithSenders struct {
1003
        // msg is the wire message itself.
1004
        msg lnwire.Message
1005

1006
        // isLocal is true if this was a message that originated locally. We'll
1007
        // use this to bypass our normal checks to ensure we prioritize sending
1008
        // out our own updates.
1009
        isLocal bool
1010

1011
        // sender is the set of peers that sent us this message.
1012
        senders map[route.Vertex]struct{}
1013
}
1014

1015
// mergeSyncerMap is used to merge the set of senders of a particular message
1016
// with peers that we have an active GossipSyncer with. We do this to ensure
1017
// that we don't broadcast messages to any peers that we have active gossip
1018
// syncers for.
1019
func (m *msgWithSenders) mergeSyncerMap(syncers map[route.Vertex]*GossipSyncer) {
29✔
1020
        for peerPub := range syncers {
29✔
1021
                m.senders[peerPub] = struct{}{}
×
1022
        }
×
1023
}
1024

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

1036
        // channelUpdates are identified by the channel update id field.
1037
        channelUpdates map[channelUpdateID]msgWithSenders
1038

1039
        // nodeAnnouncements are identified by the Vertex field.
1040
        nodeAnnouncements map[route.Vertex]msgWithSenders
1041

1042
        sync.Mutex
1043
}
1044

1045
// Reset operates on deDupedAnnouncements to reset the storage of
1046
// announcements.
1047
func (d *deDupedAnnouncements) Reset() {
32✔
1048
        d.Lock()
32✔
1049
        defer d.Unlock()
32✔
1050

32✔
1051
        d.reset()
32✔
1052
}
32✔
1053

1054
// reset is the private version of the Reset method. We have this so we can
1055
// call this method within method that are already holding the lock.
1056
func (d *deDupedAnnouncements) reset() {
327✔
1057
        // Storage of each type of announcement (channel announcements, channel
327✔
1058
        // updates, node announcements) is set to an empty map where the
327✔
1059
        // appropriate key points to the corresponding lnwire.Message.
327✔
1060
        d.channelAnnouncements = make(map[lnwire.ShortChannelID]msgWithSenders)
327✔
1061
        d.channelUpdates = make(map[channelUpdateID]msgWithSenders)
327✔
1062
        d.nodeAnnouncements = make(map[route.Vertex]msgWithSenders)
327✔
1063
}
327✔
1064

1065
// addMsg adds a new message to the current batch. If the message is already
1066
// present in the current batch, then this new instance replaces the latter,
1067
// and the set of senders is updated to reflect which node sent us this
1068
// message.
1069
func (d *deDupedAnnouncements) addMsg(message networkMsg) {
91✔
1070
        log.Tracef("Adding network message: %v to batch", message.msg.MsgType())
91✔
1071

91✔
1072
        // Depending on the message type (channel announcement, channel update,
91✔
1073
        // or node announcement), the message is added to the corresponding map
91✔
1074
        // in deDupedAnnouncements. Because each identifying key can have at
91✔
1075
        // most one value, the announcements are de-duplicated, with newer ones
91✔
1076
        // replacing older ones.
91✔
1077
        switch msg := message.msg.(type) {
91✔
1078

1079
        // Channel announcements are identified by the short channel id field.
1080
        case *lnwire.ChannelAnnouncement1:
23✔
1081
                deDupKey := msg.ShortChannelID
23✔
1082
                sender := route.NewVertex(message.source)
23✔
1083

23✔
1084
                mws, ok := d.channelAnnouncements[deDupKey]
23✔
1085
                if !ok {
45✔
1086
                        mws = msgWithSenders{
22✔
1087
                                msg:     msg,
22✔
1088
                                isLocal: !message.isRemote,
22✔
1089
                                senders: make(map[route.Vertex]struct{}),
22✔
1090
                        }
22✔
1091
                        mws.senders[sender] = struct{}{}
22✔
1092

22✔
1093
                        d.channelAnnouncements[deDupKey] = mws
22✔
1094

22✔
1095
                        return
22✔
1096
                }
22✔
1097

1098
                mws.msg = msg
1✔
1099
                mws.senders[sender] = struct{}{}
1✔
1100
                d.channelAnnouncements[deDupKey] = mws
1✔
1101

1102
        // Channel updates are identified by the (short channel id,
1103
        // channelflags) tuple.
1104
        case *lnwire.ChannelUpdate1:
46✔
1105
                sender := route.NewVertex(message.source)
46✔
1106
                deDupKey := channelUpdateID{
46✔
1107
                        msg.ShortChannelID,
46✔
1108
                        msg.ChannelFlags,
46✔
1109
                }
46✔
1110

46✔
1111
                oldTimestamp := uint32(0)
46✔
1112
                mws, ok := d.channelUpdates[deDupKey]
46✔
1113
                if ok {
49✔
1114
                        // If we already have seen this message, record its
3✔
1115
                        // timestamp.
3✔
1116
                        update, ok := mws.msg.(*lnwire.ChannelUpdate1)
3✔
1117
                        if !ok {
3✔
1118
                                log.Errorf("Expected *lnwire.ChannelUpdate1, "+
×
1119
                                        "got: %T", mws.msg)
×
1120

×
1121
                                return
×
1122
                        }
×
1123

1124
                        oldTimestamp = update.Timestamp
3✔
1125
                }
1126

1127
                // If we already had this message with a strictly newer
1128
                // timestamp, then we'll just discard the message we got.
1129
                if oldTimestamp > msg.Timestamp {
47✔
1130
                        log.Debugf("Ignored outdated network message: "+
1✔
1131
                                "peer=%v, msg=%s", message.peer, msg.MsgType())
1✔
1132
                        return
1✔
1133
                }
1✔
1134

1135
                // If the message we just got is newer than what we previously
1136
                // have seen, or this is the first time we see it, then we'll
1137
                // add it to our map of announcements.
1138
                if oldTimestamp < msg.Timestamp {
89✔
1139
                        mws = msgWithSenders{
44✔
1140
                                msg:     msg,
44✔
1141
                                isLocal: !message.isRemote,
44✔
1142
                                senders: make(map[route.Vertex]struct{}),
44✔
1143
                        }
44✔
1144

44✔
1145
                        // We'll mark the sender of the message in the
44✔
1146
                        // senders map.
44✔
1147
                        mws.senders[sender] = struct{}{}
44✔
1148

44✔
1149
                        d.channelUpdates[deDupKey] = mws
44✔
1150

44✔
1151
                        return
44✔
1152
                }
44✔
1153

1154
                // Lastly, if we had seen this exact message from before, with
1155
                // the same timestamp, we'll add the sender to the map of
1156
                // senders, such that we can skip sending this message back in
1157
                // the next batch.
1158
                mws.msg = msg
1✔
1159
                mws.senders[sender] = struct{}{}
1✔
1160
                d.channelUpdates[deDupKey] = mws
1✔
1161

1162
        // Node announcements are identified by the Vertex field.  Use the
1163
        // NodeID to create the corresponding Vertex.
1164
        case *lnwire.NodeAnnouncement:
22✔
1165
                sender := route.NewVertex(message.source)
22✔
1166
                deDupKey := route.Vertex(msg.NodeID)
22✔
1167

22✔
1168
                // We do the same for node announcements as we did for channel
22✔
1169
                // updates, as they also carry a timestamp.
22✔
1170
                oldTimestamp := uint32(0)
22✔
1171
                mws, ok := d.nodeAnnouncements[deDupKey]
22✔
1172
                if ok {
27✔
1173
                        oldTimestamp = mws.msg.(*lnwire.NodeAnnouncement).Timestamp
5✔
1174
                }
5✔
1175

1176
                // Discard the message if it's old.
1177
                if oldTimestamp > msg.Timestamp {
22✔
1178
                        return
×
1179
                }
×
1180

1181
                // Replace if it's newer.
1182
                if oldTimestamp < msg.Timestamp {
40✔
1183
                        mws = msgWithSenders{
18✔
1184
                                msg:     msg,
18✔
1185
                                isLocal: !message.isRemote,
18✔
1186
                                senders: make(map[route.Vertex]struct{}),
18✔
1187
                        }
18✔
1188

18✔
1189
                        mws.senders[sender] = struct{}{}
18✔
1190

18✔
1191
                        d.nodeAnnouncements[deDupKey] = mws
18✔
1192

18✔
1193
                        return
18✔
1194
                }
18✔
1195

1196
                // Add to senders map if it's the same as we had.
1197
                mws.msg = msg
4✔
1198
                mws.senders[sender] = struct{}{}
4✔
1199
                d.nodeAnnouncements[deDupKey] = mws
4✔
1200
        }
1201
}
1202

1203
// AddMsgs is a helper method to add multiple messages to the announcement
1204
// batch.
1205
func (d *deDupedAnnouncements) AddMsgs(msgs ...networkMsg) {
59✔
1206
        d.Lock()
59✔
1207
        defer d.Unlock()
59✔
1208

59✔
1209
        for _, msg := range msgs {
150✔
1210
                d.addMsg(msg)
91✔
1211
        }
91✔
1212
}
1213

1214
// msgsToBroadcast is returned by Emit() and partitions the messages we'd like
1215
// to broadcast next into messages that are locally sourced and those that are
1216
// sourced remotely.
1217
type msgsToBroadcast struct {
1218
        // localMsgs is the set of messages we created locally.
1219
        localMsgs []msgWithSenders
1220

1221
        // remoteMsgs is the set of messages that we received from a remote
1222
        // party.
1223
        remoteMsgs []msgWithSenders
1224
}
1225

1226
// addMsg adds a new message to the appropriate sub-slice.
1227
func (m *msgsToBroadcast) addMsg(msg msgWithSenders) {
76✔
1228
        if msg.isLocal {
123✔
1229
                m.localMsgs = append(m.localMsgs, msg)
47✔
1230
        } else {
76✔
1231
                m.remoteMsgs = append(m.remoteMsgs, msg)
29✔
1232
        }
29✔
1233
}
1234

1235
// isEmpty returns true if the batch is empty.
1236
func (m *msgsToBroadcast) isEmpty() bool {
294✔
1237
        return len(m.localMsgs) == 0 && len(m.remoteMsgs) == 0
294✔
1238
}
294✔
1239

1240
// length returns the length of the combined message set.
1241
func (m *msgsToBroadcast) length() int {
1✔
1242
        return len(m.localMsgs) + len(m.remoteMsgs)
1✔
1243
}
1✔
1244

1245
// Emit returns the set of de-duplicated announcements to be sent out during
1246
// the next announcement epoch, in the order of channel announcements, channel
1247
// updates, and node announcements. Each message emitted, contains the set of
1248
// peers that sent us the message. This way, we can ensure that we don't waste
1249
// bandwidth by re-sending a message to the peer that sent it to us in the
1250
// first place. Additionally, the set of stored messages are reset.
1251
func (d *deDupedAnnouncements) Emit() msgsToBroadcast {
295✔
1252
        d.Lock()
295✔
1253
        defer d.Unlock()
295✔
1254

295✔
1255
        // Get the total number of announcements.
295✔
1256
        numAnnouncements := len(d.channelAnnouncements) + len(d.channelUpdates) +
295✔
1257
                len(d.nodeAnnouncements)
295✔
1258

295✔
1259
        // Create an empty array of lnwire.Messages with a length equal to
295✔
1260
        // the total number of announcements.
295✔
1261
        msgs := msgsToBroadcast{
295✔
1262
                localMsgs:  make([]msgWithSenders, 0, numAnnouncements),
295✔
1263
                remoteMsgs: make([]msgWithSenders, 0, numAnnouncements),
295✔
1264
        }
295✔
1265

295✔
1266
        // Add the channel announcements to the array first.
295✔
1267
        for _, message := range d.channelAnnouncements {
314✔
1268
                msgs.addMsg(message)
19✔
1269
        }
19✔
1270

1271
        // Then add the channel updates.
1272
        for _, message := range d.channelUpdates {
335✔
1273
                msgs.addMsg(message)
40✔
1274
        }
40✔
1275

1276
        // Finally add the node announcements.
1277
        for _, message := range d.nodeAnnouncements {
312✔
1278
                msgs.addMsg(message)
17✔
1279
        }
17✔
1280

1281
        d.reset()
295✔
1282

295✔
1283
        // Return the array of lnwire.messages.
295✔
1284
        return msgs
295✔
1285
}
1286

1287
// calculateSubBatchSize is a helper function that calculates the size to break
1288
// down the batchSize into.
1289
func calculateSubBatchSize(totalDelay, subBatchDelay time.Duration,
1290
        minimumBatchSize, batchSize int) int {
13✔
1291
        if subBatchDelay > totalDelay {
15✔
1292
                return batchSize
2✔
1293
        }
2✔
1294

1295
        subBatchSize := (batchSize*int(subBatchDelay) +
11✔
1296
                int(totalDelay) - 1) / int(totalDelay)
11✔
1297

11✔
1298
        if subBatchSize < minimumBatchSize {
12✔
1299
                return minimumBatchSize
1✔
1300
        }
1✔
1301

1302
        return subBatchSize
10✔
1303
}
1304

1305
// batchSizeCalculator maps to the function `calculateSubBatchSize`. We create
1306
// this variable so the function can be mocked in our test.
1307
var batchSizeCalculator = calculateSubBatchSize
1308

1309
// splitAnnouncementBatches takes an exiting list of announcements and
1310
// decomposes it into sub batches controlled by the `subBatchSize`.
1311
func (d *AuthenticatedGossiper) splitAnnouncementBatches(
1312
        announcementBatch []msgWithSenders) [][]msgWithSenders {
75✔
1313

75✔
1314
        subBatchSize := batchSizeCalculator(
75✔
1315
                d.cfg.TrickleDelay, d.cfg.SubBatchDelay,
75✔
1316
                d.cfg.MinimumBatchSize, len(announcementBatch),
75✔
1317
        )
75✔
1318

75✔
1319
        var splitAnnouncementBatch [][]msgWithSenders
75✔
1320

75✔
1321
        for subBatchSize < len(announcementBatch) {
196✔
1322
                // For slicing with minimal allocation
121✔
1323
                // https://github.com/golang/go/wiki/SliceTricks
121✔
1324
                announcementBatch, splitAnnouncementBatch =
121✔
1325
                        announcementBatch[subBatchSize:],
121✔
1326
                        append(splitAnnouncementBatch,
121✔
1327
                                announcementBatch[0:subBatchSize:subBatchSize])
121✔
1328
        }
121✔
1329
        splitAnnouncementBatch = append(
75✔
1330
                splitAnnouncementBatch, announcementBatch,
75✔
1331
        )
75✔
1332

75✔
1333
        return splitAnnouncementBatch
75✔
1334
}
1335

1336
// splitAndSendAnnBatch takes a batch of messages, computes the proper batch
1337
// split size, and then sends out all items to the set of target peers. Locally
1338
// generated announcements are always sent before remotely generated
1339
// announcements.
1340
func (d *AuthenticatedGossiper) splitAndSendAnnBatch(
1341
        annBatch msgsToBroadcast) {
34✔
1342

34✔
1343
        // delayNextBatch is a helper closure that blocks for `SubBatchDelay`
34✔
1344
        // duration to delay the sending of next announcement batch.
34✔
1345
        delayNextBatch := func() {
102✔
1346
                select {
68✔
1347
                case <-time.After(d.cfg.SubBatchDelay):
51✔
1348
                case <-d.quit:
17✔
1349
                        return
17✔
1350
                }
1351
        }
1352

1353
        // Fetch the local and remote announcements.
1354
        localBatches := d.splitAnnouncementBatches(annBatch.localMsgs)
34✔
1355
        remoteBatches := d.splitAnnouncementBatches(annBatch.remoteMsgs)
34✔
1356

34✔
1357
        d.wg.Add(1)
34✔
1358
        go func() {
68✔
1359
                defer d.wg.Done()
34✔
1360

34✔
1361
                log.Debugf("Broadcasting %v new local announcements in %d "+
34✔
1362
                        "sub batches", len(annBatch.localMsgs),
34✔
1363
                        len(localBatches))
34✔
1364

34✔
1365
                // Send out the local announcements first.
34✔
1366
                for _, annBatch := range localBatches {
68✔
1367
                        d.sendLocalBatch(annBatch)
34✔
1368
                        delayNextBatch()
34✔
1369
                }
34✔
1370

1371
                log.Debugf("Broadcasting %v new remote announcements in %d "+
34✔
1372
                        "sub batches", len(annBatch.remoteMsgs),
34✔
1373
                        len(remoteBatches))
34✔
1374

34✔
1375
                // Now send the remote announcements.
34✔
1376
                for _, annBatch := range remoteBatches {
68✔
1377
                        d.sendRemoteBatch(annBatch)
34✔
1378
                        delayNextBatch()
34✔
1379
                }
34✔
1380
        }()
1381
}
1382

1383
// sendLocalBatch broadcasts a list of locally generated announcements to our
1384
// peers. For local announcements, we skip the filter and dedup logic and just
1385
// send the announcements out to all our coonnected peers.
1386
func (d *AuthenticatedGossiper) sendLocalBatch(annBatch []msgWithSenders) {
34✔
1387
        msgsToSend := lnutils.Map(
34✔
1388
                annBatch, func(m msgWithSenders) lnwire.Message {
77✔
1389
                        return m.msg
43✔
1390
                },
43✔
1391
        )
1392

1393
        err := d.cfg.Broadcast(nil, msgsToSend...)
34✔
1394
        if err != nil {
34✔
1395
                log.Errorf("Unable to send local batch announcements: %v", err)
×
1396
        }
×
1397
}
1398

1399
// sendRemoteBatch broadcasts a list of remotely generated announcements to our
1400
// peers.
1401
func (d *AuthenticatedGossiper) sendRemoteBatch(annBatch []msgWithSenders) {
34✔
1402
        syncerPeers := d.syncMgr.GossipSyncers()
34✔
1403

34✔
1404
        // We'll first attempt to filter out this new message for all peers
34✔
1405
        // that have active gossip syncers active.
34✔
1406
        for pub, syncer := range syncerPeers {
34✔
1407
                log.Tracef("Sending messages batch to GossipSyncer(%s)", pub)
×
1408
                syncer.FilterGossipMsgs(annBatch...)
×
1409
        }
×
1410

1411
        for _, msgChunk := range annBatch {
63✔
1412
                msgChunk := msgChunk
29✔
1413

29✔
1414
                // With the syncers taken care of, we'll merge the sender map
29✔
1415
                // with the set of syncers, so we don't send out duplicate
29✔
1416
                // messages.
29✔
1417
                msgChunk.mergeSyncerMap(syncerPeers)
29✔
1418

29✔
1419
                err := d.cfg.Broadcast(msgChunk.senders, msgChunk.msg)
29✔
1420
                if err != nil {
29✔
1421
                        log.Errorf("Unable to send batch "+
×
1422
                                "announcements: %v", err)
×
1423
                        continue
×
1424
                }
1425
        }
1426
}
1427

1428
// networkHandler is the primary goroutine that drives this service. The roles
1429
// of this goroutine includes answering queries related to the state of the
1430
// network, syncing up newly connected peers, and also periodically
1431
// broadcasting our latest topology state to all connected peers.
1432
//
1433
// NOTE: This MUST be run as a goroutine.
1434
func (d *AuthenticatedGossiper) networkHandler() {
30✔
1435
        defer d.wg.Done()
30✔
1436

30✔
1437
        // Initialize empty deDupedAnnouncements to store announcement batch.
30✔
1438
        announcements := deDupedAnnouncements{}
30✔
1439
        announcements.Reset()
30✔
1440

30✔
1441
        d.cfg.RetransmitTicker.Resume()
30✔
1442
        defer d.cfg.RetransmitTicker.Stop()
30✔
1443

30✔
1444
        trickleTimer := time.NewTicker(d.cfg.TrickleDelay)
30✔
1445
        defer trickleTimer.Stop()
30✔
1446

30✔
1447
        // To start, we'll first check to see if there are any stale channel or
30✔
1448
        // node announcements that we need to re-transmit.
30✔
1449
        if err := d.retransmitStaleAnns(time.Now()); err != nil {
30✔
1450
                log.Errorf("Unable to rebroadcast stale announcements: %v", err)
×
1451
        }
×
1452

1453
        for {
694✔
1454
                select {
664✔
1455
                // A new policy update has arrived. We'll commit it to the
1456
                // sub-systems below us, then craft, sign, and broadcast a new
1457
                // ChannelUpdate for the set of affected clients.
1458
                case policyUpdate := <-d.chanPolicyUpdates:
1✔
1459
                        log.Tracef("Received channel %d policy update requests",
1✔
1460
                                len(policyUpdate.edgesToUpdate))
1✔
1461

1✔
1462
                        // First, we'll now create new fully signed updates for
1✔
1463
                        // the affected channels and also update the underlying
1✔
1464
                        // graph with the new state.
1✔
1465
                        newChanUpdates, err := d.processChanPolicyUpdate(
1✔
1466
                                policyUpdate.edgesToUpdate,
1✔
1467
                        )
1✔
1468
                        policyUpdate.errChan <- err
1✔
1469
                        if err != nil {
1✔
1470
                                log.Errorf("Unable to craft policy updates: %v",
×
1471
                                        err)
×
1472
                                continue
×
1473
                        }
1474

1475
                        // Finally, with the updates committed, we'll now add
1476
                        // them to the announcement batch to be flushed at the
1477
                        // start of the next epoch.
1478
                        announcements.AddMsgs(newChanUpdates...)
1✔
1479

1480
                case announcement := <-d.networkMsgs:
338✔
1481
                        log.Tracef("Received network message: "+
338✔
1482
                                "peer=%v, msg=%s, is_remote=%v",
338✔
1483
                                announcement.peer, announcement.msg.MsgType(),
338✔
1484
                                announcement.isRemote)
338✔
1485

338✔
1486
                        switch announcement.msg.(type) {
338✔
1487
                        // Channel announcement signatures are amongst the only
1488
                        // messages that we'll process serially.
1489
                        case *lnwire.AnnounceSignatures1:
21✔
1490
                                emittedAnnouncements, _ := d.processNetworkAnnouncement(
21✔
1491
                                        announcement,
21✔
1492
                                )
21✔
1493
                                log.Debugf("Processed network message %s, "+
21✔
1494
                                        "returned len(announcements)=%v",
21✔
1495
                                        announcement.msg.MsgType(),
21✔
1496
                                        len(emittedAnnouncements))
21✔
1497

21✔
1498
                                if emittedAnnouncements != nil {
31✔
1499
                                        announcements.AddMsgs(
10✔
1500
                                                emittedAnnouncements...,
10✔
1501
                                        )
10✔
1502
                                }
10✔
1503
                                continue
21✔
1504
                        }
1505

1506
                        // If this message was recently rejected, then we won't
1507
                        // attempt to re-process it.
1508
                        if announcement.isRemote && d.isRecentlyRejectedMsg(
317✔
1509
                                announcement.msg,
317✔
1510
                                sourceToPub(announcement.source),
317✔
1511
                        ) {
318✔
1512

1✔
1513
                                announcement.err <- fmt.Errorf("recently " +
1✔
1514
                                        "rejected")
1✔
1515
                                continue
1✔
1516
                        }
1517

1518
                        // We'll set up any dependent, and wait until a free
1519
                        // slot for this job opens up, this allow us to not
1520
                        // have thousands of goroutines active.
1521
                        annJobID, err := d.vb.InitJobDependencies(
316✔
1522
                                announcement.msg,
316✔
1523
                        )
316✔
1524
                        if err != nil {
316✔
1525
                                announcement.err <- err
×
1526
                                continue
×
1527
                        }
1528

1529
                        d.wg.Add(1)
316✔
1530
                        go d.handleNetworkMessages(
316✔
1531
                                announcement, &announcements, annJobID,
316✔
1532
                        )
316✔
1533

1534
                // The trickle timer has ticked, which indicates we should
1535
                // flush to the network the pending batch of new announcements
1536
                // we've received since the last trickle tick.
1537
                case <-trickleTimer.C:
294✔
1538
                        // Emit the current batch of announcements from
294✔
1539
                        // deDupedAnnouncements.
294✔
1540
                        announcementBatch := announcements.Emit()
294✔
1541

294✔
1542
                        // If the current announcements batch is nil, then we
294✔
1543
                        // have no further work here.
294✔
1544
                        if announcementBatch.isEmpty() {
554✔
1545
                                continue
260✔
1546
                        }
1547

1548
                        // At this point, we have the set of local and remote
1549
                        // announcements we want to send out. We'll do the
1550
                        // batching as normal for both, but for local
1551
                        // announcements, we'll blast them out w/o regard for
1552
                        // our peer's policies so we ensure they propagate
1553
                        // properly.
1554
                        d.splitAndSendAnnBatch(announcementBatch)
34✔
1555

1556
                // The retransmission timer has ticked which indicates that we
1557
                // should check if we need to prune or re-broadcast any of our
1558
                // personal channels or node announcement. This addresses the
1559
                // case of "zombie" channels and channel advertisements that
1560
                // have been dropped, or not properly propagated through the
1561
                // network.
1562
                case tick := <-d.cfg.RetransmitTicker.Ticks():
1✔
1563
                        if err := d.retransmitStaleAnns(tick); err != nil {
1✔
1564
                                log.Errorf("unable to rebroadcast stale "+
×
1565
                                        "announcements: %v", err)
×
1566
                        }
×
1567

1568
                // The gossiper has been signalled to exit, to we exit our
1569
                // main loop so the wait group can be decremented.
1570
                case <-d.quit:
30✔
1571
                        return
30✔
1572
                }
1573
        }
1574
}
1575

1576
// handleNetworkMessages is responsible for waiting for dependencies for a
1577
// given network message and processing the message. Once processed, it will
1578
// signal its dependants and add the new announcements to the announce batch.
1579
//
1580
// NOTE: must be run as a goroutine.
1581
func (d *AuthenticatedGossiper) handleNetworkMessages(nMsg *networkMsg,
1582
        deDuped *deDupedAnnouncements, jobID JobID) {
316✔
1583

316✔
1584
        defer d.wg.Done()
316✔
1585
        defer d.vb.CompleteJob()
316✔
1586

316✔
1587
        // We should only broadcast this message forward if it originated from
316✔
1588
        // us or it wasn't received as part of our initial historical sync.
316✔
1589
        shouldBroadcast := !nMsg.isRemote || d.syncMgr.IsGraphSynced()
316✔
1590

316✔
1591
        // If this message has an existing dependency, then we'll wait until
316✔
1592
        // that has been fully validated before we proceed.
316✔
1593
        err := d.vb.WaitForParents(jobID, nMsg.msg)
316✔
1594
        if err != nil {
316✔
1595
                log.Debugf("Validating network message %s got err: %v",
×
1596
                        nMsg.msg.MsgType(), err)
×
1597

×
1598
                if errors.Is(err, ErrVBarrierShuttingDown) {
×
1599
                        log.Warnf("unexpected error during validation "+
×
1600
                                "barrier shutdown: %v", err)
×
1601
                }
×
1602
                nMsg.err <- err
×
1603

×
1604
                return
×
1605
        }
1606

1607
        // Process the network announcement to determine if this is either a
1608
        // new announcement from our PoV or an edges to a prior vertex/edge we
1609
        // previously proceeded.
1610
        newAnns, allow := d.processNetworkAnnouncement(nMsg)
316✔
1611

316✔
1612
        log.Tracef("Processed network message %s, returned "+
316✔
1613
                "len(announcements)=%v, allowDependents=%v",
316✔
1614
                nMsg.msg.MsgType(), len(newAnns), allow)
316✔
1615

316✔
1616
        // If this message had any dependencies, then we can now signal them to
316✔
1617
        // continue.
316✔
1618
        err = d.vb.SignalDependents(nMsg.msg, jobID)
316✔
1619
        if err != nil {
316✔
1620
                // Something is wrong if SignalDependents returns an error.
×
1621
                log.Errorf("SignalDependents returned error for msg=%v with "+
×
1622
                        "JobID=%v", spew.Sdump(nMsg.msg), jobID)
×
1623

×
1624
                nMsg.err <- err
×
1625

×
1626
                return
×
1627
        }
×
1628

1629
        // If the announcement was accepted, then add the emitted announcements
1630
        // to our announce batch to be broadcast once the trickle timer ticks
1631
        // gain.
1632
        if newAnns != nil && shouldBroadcast {
353✔
1633
                // TODO(roasbeef): exclude peer that sent.
37✔
1634
                deDuped.AddMsgs(newAnns...)
37✔
1635
        } else if newAnns != nil {
317✔
1636
                log.Trace("Skipping broadcast of announcements received " +
1✔
1637
                        "during initial graph sync")
1✔
1638
        }
1✔
1639
}
1640

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

1643
// InitSyncState is called by outside sub-systems when a connection is
1644
// established to a new peer that understands how to perform channel range
1645
// queries. We'll allocate a new gossip syncer for it, and start any goroutines
1646
// needed to handle new queries.
1647
func (d *AuthenticatedGossiper) InitSyncState(syncPeer lnpeer.Peer) {
×
1648
        d.syncMgr.InitSyncState(syncPeer)
×
1649
}
×
1650

1651
// PruneSyncState is called by outside sub-systems once a peer that we were
1652
// previously connected to has been disconnected. In this case we can stop the
1653
// existing GossipSyncer assigned to the peer and free up resources.
1654
func (d *AuthenticatedGossiper) PruneSyncState(peer route.Vertex) {
×
1655
        d.syncMgr.PruneSyncState(peer)
×
1656
}
×
1657

1658
// isRecentlyRejectedMsg returns true if we recently rejected a message, and
1659
// false otherwise, This avoids expensive reprocessing of the message.
1660
func (d *AuthenticatedGossiper) isRecentlyRejectedMsg(msg lnwire.Message,
1661
        peerPub [33]byte) bool {
280✔
1662

280✔
1663
        var scid uint64
280✔
1664
        switch m := msg.(type) {
280✔
1665
        case *lnwire.ChannelUpdate1:
48✔
1666
                scid = m.ShortChannelID.ToUint64()
48✔
1667

1668
        case *lnwire.ChannelAnnouncement1:
218✔
1669
                scid = m.ShortChannelID.ToUint64()
218✔
1670

1671
        default:
14✔
1672
                return false
14✔
1673
        }
1674

1675
        _, err := d.recentRejects.Get(newRejectCacheKey(scid, peerPub))
266✔
1676
        return err != cache.ErrElementNotFound
266✔
1677
}
1678

1679
// retransmitStaleAnns examines all outgoing channels that the source node is
1680
// known to maintain to check to see if any of them are "stale". A channel is
1681
// stale iff, the last timestamp of its rebroadcast is older than the
1682
// RebroadcastInterval. We also check if a refreshed node announcement should
1683
// be resent.
1684
func (d *AuthenticatedGossiper) retransmitStaleAnns(now time.Time) error {
31✔
1685
        // Iterate over all of our channels and check if any of them fall
31✔
1686
        // within the prune interval or re-broadcast interval.
31✔
1687
        type updateTuple struct {
31✔
1688
                info *models.ChannelEdgeInfo
31✔
1689
                edge *models.ChannelEdgePolicy
31✔
1690
        }
31✔
1691

31✔
1692
        var (
31✔
1693
                havePublicChannels bool
31✔
1694
                edgesToUpdate      []updateTuple
31✔
1695
        )
31✔
1696
        err := d.cfg.Graph.ForAllOutgoingChannels(func(
31✔
1697
                info *models.ChannelEdgeInfo,
31✔
1698
                edge *models.ChannelEdgePolicy) error {
33✔
1699

2✔
1700
                // If there's no auth proof attached to this edge, it means
2✔
1701
                // that it is a private channel not meant to be announced to
2✔
1702
                // the greater network, so avoid sending channel updates for
2✔
1703
                // this channel to not leak its
2✔
1704
                // existence.
2✔
1705
                if info.AuthProof == nil {
3✔
1706
                        log.Debugf("Skipping retransmission of channel "+
1✔
1707
                                "without AuthProof: %v", info.ChannelID)
1✔
1708
                        return nil
1✔
1709
                }
1✔
1710

1711
                // We make a note that we have at least one public channel. We
1712
                // use this to determine whether we should send a node
1713
                // announcement below.
1714
                havePublicChannels = true
1✔
1715

1✔
1716
                // If this edge has a ChannelUpdate that was created before the
1✔
1717
                // introduction of the MaxHTLC field, then we'll update this
1✔
1718
                // edge to propagate this information in the network.
1✔
1719
                if !edge.MessageFlags.HasMaxHtlc() {
1✔
1720
                        // We'll make sure we support the new max_htlc field if
×
1721
                        // not already present.
×
1722
                        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
×
1723
                        edge.MaxHTLC = lnwire.NewMSatFromSatoshis(info.Capacity)
×
1724

×
1725
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
×
1726
                                info: info,
×
1727
                                edge: edge,
×
1728
                        })
×
1729
                        return nil
×
1730
                }
×
1731

1732
                timeElapsed := now.Sub(edge.LastUpdate)
1✔
1733

1✔
1734
                // If it's been longer than RebroadcastInterval since we've
1✔
1735
                // re-broadcasted the channel, add the channel to the set of
1✔
1736
                // edges we need to update.
1✔
1737
                if timeElapsed >= d.cfg.RebroadcastInterval {
2✔
1738
                        edgesToUpdate = append(edgesToUpdate, updateTuple{
1✔
1739
                                info: info,
1✔
1740
                                edge: edge,
1✔
1741
                        })
1✔
1742
                }
1✔
1743

1744
                return nil
1✔
1745
        })
1746
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
31✔
1747
                return fmt.Errorf("unable to retrieve outgoing channels: %w",
×
1748
                        err)
×
1749
        }
×
1750

1751
        var signedUpdates []lnwire.Message
31✔
1752
        for _, chanToUpdate := range edgesToUpdate {
32✔
1753
                // Re-sign and update the channel on disk and retrieve our
1✔
1754
                // ChannelUpdate to broadcast.
1✔
1755
                chanAnn, chanUpdate, err := d.updateChannel(
1✔
1756
                        chanToUpdate.info, chanToUpdate.edge,
1✔
1757
                )
1✔
1758
                if err != nil {
1✔
1759
                        return fmt.Errorf("unable to update channel: %w", err)
×
1760
                }
×
1761

1762
                // If we have a valid announcement to transmit, then we'll send
1763
                // that along with the update.
1764
                if chanAnn != nil {
2✔
1765
                        signedUpdates = append(signedUpdates, chanAnn)
1✔
1766
                }
1✔
1767

1768
                signedUpdates = append(signedUpdates, chanUpdate)
1✔
1769
        }
1770

1771
        // If we don't have any public channels, we return as we don't want to
1772
        // broadcast anything that would reveal our existence.
1773
        if !havePublicChannels {
61✔
1774
                return nil
30✔
1775
        }
30✔
1776

1777
        // We'll also check that our NodeAnnouncement is not too old.
1778
        currentNodeAnn := d.cfg.FetchSelfAnnouncement()
1✔
1779
        timestamp := time.Unix(int64(currentNodeAnn.Timestamp), 0)
1✔
1780
        timeElapsed := now.Sub(timestamp)
1✔
1781

1✔
1782
        // If it's been a full day since we've re-broadcasted the
1✔
1783
        // node announcement, refresh it and resend it.
1✔
1784
        nodeAnnStr := ""
1✔
1785
        if timeElapsed >= d.cfg.RebroadcastInterval {
2✔
1786
                newNodeAnn, err := d.cfg.UpdateSelfAnnouncement()
1✔
1787
                if err != nil {
1✔
1788
                        return fmt.Errorf("unable to get refreshed node "+
×
1789
                                "announcement: %v", err)
×
1790
                }
×
1791

1792
                signedUpdates = append(signedUpdates, &newNodeAnn)
1✔
1793
                nodeAnnStr = " and our refreshed node announcement"
1✔
1794

1✔
1795
                // Before broadcasting the refreshed node announcement, add it
1✔
1796
                // to our own graph.
1✔
1797
                if err := d.addNode(&newNodeAnn); err != nil {
2✔
1798
                        log.Errorf("Unable to add refreshed node announcement "+
1✔
1799
                                "to graph: %v", err)
1✔
1800
                }
1✔
1801
        }
1802

1803
        // If we don't have any updates to re-broadcast, then we'll exit
1804
        // early.
1805
        if len(signedUpdates) == 0 {
1✔
1806
                return nil
×
1807
        }
×
1808

1809
        log.Infof("Retransmitting %v outgoing channels%v",
1✔
1810
                len(edgesToUpdate), nodeAnnStr)
1✔
1811

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

1818
        return nil
1✔
1819
}
1820

1821
// processChanPolicyUpdate generates a new set of channel updates for the
1822
// provided list of edges and updates the backing ChannelGraphSource.
1823
func (d *AuthenticatedGossiper) processChanPolicyUpdate(
1824
        edgesToUpdate []EdgeWithInfo) ([]networkMsg, error) {
1✔
1825

1✔
1826
        var chanUpdates []networkMsg
1✔
1827
        for _, edgeInfo := range edgesToUpdate {
4✔
1828
                // Now that we've collected all the channels we need to update,
3✔
1829
                // we'll re-sign and update the backing ChannelGraphSource, and
3✔
1830
                // retrieve our ChannelUpdate to broadcast.
3✔
1831
                _, chanUpdate, err := d.updateChannel(
3✔
1832
                        edgeInfo.Info, edgeInfo.Edge,
3✔
1833
                )
3✔
1834
                if err != nil {
3✔
1835
                        return nil, err
×
1836
                }
×
1837

1838
                // We'll avoid broadcasting any updates for private channels to
1839
                // avoid directly giving away their existence. Instead, we'll
1840
                // send the update directly to the remote party.
1841
                if edgeInfo.Info.AuthProof == nil {
4✔
1842
                        // If AuthProof is nil and an alias was found for this
1✔
1843
                        // ChannelID (meaning the option-scid-alias feature was
1✔
1844
                        // negotiated), we'll replace the ShortChannelID in the
1✔
1845
                        // update with the peer's alias. We do this after
1✔
1846
                        // updateChannel so that the alias isn't persisted to
1✔
1847
                        // the database.
1✔
1848
                        chanID := lnwire.NewChanIDFromOutPoint(
1✔
1849
                                edgeInfo.Info.ChannelPoint,
1✔
1850
                        )
1✔
1851

1✔
1852
                        var defaultAlias lnwire.ShortChannelID
1✔
1853
                        foundAlias, _ := d.cfg.GetAlias(chanID)
1✔
1854
                        if foundAlias != defaultAlias {
1✔
1855
                                chanUpdate.ShortChannelID = foundAlias
×
1856

×
1857
                                sig, err := d.cfg.SignAliasUpdate(chanUpdate)
×
1858
                                if err != nil {
×
1859
                                        log.Errorf("Unable to sign alias "+
×
1860
                                                "update: %v", err)
×
1861
                                        continue
×
1862
                                }
1863

1864
                                lnSig, err := lnwire.NewSigFromSignature(sig)
×
1865
                                if err != nil {
×
1866
                                        log.Errorf("Unable to create sig: %v",
×
1867
                                                err)
×
1868
                                        continue
×
1869
                                }
1870

1871
                                chanUpdate.Signature = lnSig
×
1872
                        }
1873

1874
                        remotePubKey := remotePubFromChanInfo(
1✔
1875
                                edgeInfo.Info, chanUpdate.ChannelFlags,
1✔
1876
                        )
1✔
1877
                        err := d.reliableSender.sendMessage(
1✔
1878
                                chanUpdate, remotePubKey,
1✔
1879
                        )
1✔
1880
                        if err != nil {
1✔
1881
                                log.Errorf("Unable to reliably send %v for "+
×
1882
                                        "channel=%v to peer=%x: %v",
×
1883
                                        chanUpdate.MsgType(),
×
1884
                                        chanUpdate.ShortChannelID,
×
1885
                                        remotePubKey, err)
×
1886
                        }
×
1887
                        continue
1✔
1888
                }
1889

1890
                // We set ourselves as the source of this message to indicate
1891
                // that we shouldn't skip any peers when sending this message.
1892
                chanUpdates = append(chanUpdates, networkMsg{
2✔
1893
                        source:   d.selfKey,
2✔
1894
                        isRemote: false,
2✔
1895
                        msg:      chanUpdate,
2✔
1896
                })
2✔
1897
        }
1898

1899
        return chanUpdates, nil
1✔
1900
}
1901

1902
// remotePubFromChanInfo returns the public key of the remote peer given a
1903
// ChannelEdgeInfo that describe a channel we have with them.
1904
func remotePubFromChanInfo(chanInfo *models.ChannelEdgeInfo,
1905
        chanFlags lnwire.ChanUpdateChanFlags) [33]byte {
12✔
1906

12✔
1907
        var remotePubKey [33]byte
12✔
1908
        switch {
12✔
1909
        case chanFlags&lnwire.ChanUpdateDirection == 0:
12✔
1910
                remotePubKey = chanInfo.NodeKey2Bytes
12✔
1911
        case chanFlags&lnwire.ChanUpdateDirection == 1:
×
1912
                remotePubKey = chanInfo.NodeKey1Bytes
×
1913
        }
1914

1915
        return remotePubKey
12✔
1916
}
1917

1918
// processRejectedEdge examines a rejected edge to see if we can extract any
1919
// new announcements from it.  An edge will get rejected if we already added
1920
// the same edge without AuthProof to the graph. If the received announcement
1921
// contains a proof, we can add this proof to our edge.  We can end up in this
1922
// situation in the case where we create a channel, but for some reason fail
1923
// to receive the remote peer's proof, while the remote peer is able to fully
1924
// assemble the proof and craft the ChannelAnnouncement.
1925
func (d *AuthenticatedGossiper) processRejectedEdge(
1926
        chanAnnMsg *lnwire.ChannelAnnouncement1,
1927
        proof *models.ChannelAuthProof) ([]networkMsg, error) {
×
1928

×
1929
        // First, we'll fetch the state of the channel as we know if from the
×
1930
        // database.
×
1931
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
×
1932
                chanAnnMsg.ShortChannelID,
×
1933
        )
×
1934
        if err != nil {
×
1935
                return nil, err
×
1936
        }
×
1937

1938
        // The edge is in the graph, and has a proof attached, then we'll just
1939
        // reject it as normal.
1940
        if chanInfo.AuthProof != nil {
×
1941
                return nil, nil
×
1942
        }
×
1943

1944
        // Otherwise, this means that the edge is within the graph, but it
1945
        // doesn't yet have a proper proof attached. If we did not receive
1946
        // the proof such that we now can add it, there's nothing more we
1947
        // can do.
1948
        if proof == nil {
×
1949
                return nil, nil
×
1950
        }
×
1951

1952
        // We'll then create then validate the new fully assembled
1953
        // announcement.
1954
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
×
1955
                proof, chanInfo, e1, e2,
×
1956
        )
×
1957
        if err != nil {
×
1958
                return nil, err
×
1959
        }
×
1960
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
×
1961
        if err != nil {
×
1962
                err := fmt.Errorf("assembled channel announcement proof "+
×
1963
                        "for shortChanID=%v isn't valid: %v",
×
1964
                        chanAnnMsg.ShortChannelID, err)
×
1965
                log.Error(err)
×
1966
                return nil, err
×
1967
        }
×
1968

1969
        // If everything checks out, then we'll add the fully assembled proof
1970
        // to the database.
1971
        err = d.cfg.Graph.AddProof(chanAnnMsg.ShortChannelID, proof)
×
1972
        if err != nil {
×
1973
                err := fmt.Errorf("unable add proof to shortChanID=%v: %w",
×
1974
                        chanAnnMsg.ShortChannelID, err)
×
1975
                log.Error(err)
×
1976
                return nil, err
×
1977
        }
×
1978

1979
        // As we now have a complete channel announcement for this channel,
1980
        // we'll construct the announcement so they can be broadcast out to all
1981
        // our peers.
1982
        announcements := make([]networkMsg, 0, 3)
×
1983
        announcements = append(announcements, networkMsg{
×
1984
                source: d.selfKey,
×
1985
                msg:    chanAnn,
×
1986
        })
×
1987
        if e1Ann != nil {
×
1988
                announcements = append(announcements, networkMsg{
×
1989
                        source: d.selfKey,
×
1990
                        msg:    e1Ann,
×
1991
                })
×
1992
        }
×
1993
        if e2Ann != nil {
×
1994
                announcements = append(announcements, networkMsg{
×
1995
                        source: d.selfKey,
×
1996
                        msg:    e2Ann,
×
1997
                })
×
1998

×
1999
        }
×
2000

2001
        return announcements, nil
×
2002
}
2003

2004
// fetchPKScript fetches the output script for the given SCID.
2005
func (d *AuthenticatedGossiper) fetchPKScript(chanID *lnwire.ShortChannelID) (
2006
        []byte, error) {
×
2007

×
2008
        return lnwallet.FetchPKScriptWithQuit(d.cfg.ChainIO, chanID, d.quit)
×
2009
}
×
2010

2011
// addNode processes the given node announcement, and adds it to our channel
2012
// graph.
2013
func (d *AuthenticatedGossiper) addNode(msg *lnwire.NodeAnnouncement,
2014
        op ...batch.SchedulerOption) error {
17✔
2015

17✔
2016
        if err := netann.ValidateNodeAnn(msg); err != nil {
18✔
2017
                return fmt.Errorf("unable to validate node announcement: %w",
1✔
2018
                        err)
1✔
2019
        }
1✔
2020

2021
        return d.cfg.Graph.AddNode(models.NodeFromWireAnnouncement(msg), op...)
16✔
2022
}
2023

2024
// isPremature decides whether a given network message has a block height+delta
2025
// value specified in the future. If so, the message will be added to the
2026
// future message map and be processed when the block height as reached.
2027
//
2028
// NOTE: must be used inside a lock.
2029
func (d *AuthenticatedGossiper) isPremature(chanID lnwire.ShortChannelID,
2030
        delta uint32, msg *networkMsg) bool {
289✔
2031

289✔
2032
        // The channel is already confirmed at chanID.BlockHeight so we minus
289✔
2033
        // one block. For instance, if the required confirmation for this
289✔
2034
        // channel announcement is 6, we then only need to wait for 5 more
289✔
2035
        // blocks once the funding tx is confirmed.
289✔
2036
        if delta > 0 {
289✔
2037
                delta--
×
2038
        }
×
2039

2040
        msgHeight := chanID.BlockHeight + delta
289✔
2041

289✔
2042
        // The message height is smaller or equal to our best known height,
289✔
2043
        // thus the message is mature.
289✔
2044
        if msgHeight <= d.bestHeight {
577✔
2045
                return false
288✔
2046
        }
288✔
2047

2048
        // Add the premature message to our future messages which will be
2049
        // resent once the block height has reached.
2050
        //
2051
        // Copy the networkMsgs since the old message's err chan will be
2052
        // consumed.
2053
        copied := &networkMsg{
1✔
2054
                peer:              msg.peer,
1✔
2055
                source:            msg.source,
1✔
2056
                msg:               msg.msg,
1✔
2057
                optionalMsgFields: msg.optionalMsgFields,
1✔
2058
                isRemote:          msg.isRemote,
1✔
2059
                err:               make(chan error, 1),
1✔
2060
        }
1✔
2061

1✔
2062
        // Create the cached message.
1✔
2063
        cachedMsg := &cachedFutureMsg{
1✔
2064
                msg:    copied,
1✔
2065
                height: msgHeight,
1✔
2066
        }
1✔
2067

1✔
2068
        // Increment the msg ID and add it to the cache.
1✔
2069
        nextMsgID := d.futureMsgs.nextMsgID()
1✔
2070
        _, err := d.futureMsgs.Put(nextMsgID, cachedMsg)
1✔
2071
        if err != nil {
1✔
2072
                log.Errorf("Adding future message got error: %v", err)
×
2073
        }
×
2074

2075
        log.Debugf("Network message: %v added to future messages for "+
1✔
2076
                "msgHeight=%d, bestHeight=%d", msg.msg.MsgType(),
1✔
2077
                msgHeight, d.bestHeight)
1✔
2078

1✔
2079
        return true
1✔
2080
}
2081

2082
// processNetworkAnnouncement processes a new network relate authenticated
2083
// channel or node announcement or announcements proofs. If the announcement
2084
// didn't affect the internal state due to either being out of date, invalid,
2085
// or redundant, then nil is returned. Otherwise, the set of announcements will
2086
// be returned which should be broadcasted to the rest of the network. The
2087
// boolean returned indicates whether any dependents of the announcement should
2088
// attempt to be processed as well.
2089
func (d *AuthenticatedGossiper) processNetworkAnnouncement(
2090
        nMsg *networkMsg) ([]networkMsg, bool) {
337✔
2091

337✔
2092
        // If this is a remote update, we set the scheduler option to lazily
337✔
2093
        // add it to the graph.
337✔
2094
        var schedulerOp []batch.SchedulerOption
337✔
2095
        if nMsg.isRemote {
627✔
2096
                schedulerOp = append(schedulerOp, batch.LazyAdd())
290✔
2097
        }
290✔
2098

2099
        switch msg := nMsg.msg.(type) {
337✔
2100
        // A new node announcement has arrived which either presents new
2101
        // information about a node in one of the channels we know about, or a
2102
        // updating previously advertised information.
2103
        case *lnwire.NodeAnnouncement:
24✔
2104
                return d.handleNodeAnnouncement(nMsg, msg, schedulerOp)
24✔
2105

2106
        // A new channel announcement has arrived, this indicates the
2107
        // *creation* of a new channel within the network. This only advertises
2108
        // the existence of a channel and not yet the routing policies in
2109
        // either direction of the channel.
2110
        case *lnwire.ChannelAnnouncement1:
231✔
2111
                return d.handleChanAnnouncement(nMsg, msg, schedulerOp...)
231✔
2112

2113
        // A new authenticated channel edge update has arrived. This indicates
2114
        // that the directional information for an already known channel has
2115
        // been updated.
2116
        case *lnwire.ChannelUpdate1:
61✔
2117
                return d.handleChanUpdate(nMsg, msg, schedulerOp)
61✔
2118

2119
        // A new signature announcement has been received. This indicates
2120
        // willingness of nodes involved in the funding of a channel to
2121
        // announce this new channel to the rest of the world.
2122
        case *lnwire.AnnounceSignatures1:
21✔
2123
                return d.handleAnnSig(nMsg, msg)
21✔
2124

2125
        default:
×
2126
                err := errors.New("wrong type of the announcement")
×
2127
                nMsg.err <- err
×
2128
                return nil, false
×
2129
        }
2130
}
2131

2132
// processZombieUpdate determines whether the provided channel update should
2133
// resurrect a given zombie edge.
2134
//
2135
// NOTE: only the NodeKey1Bytes and NodeKey2Bytes members of the ChannelEdgeInfo
2136
// should be inspected.
2137
func (d *AuthenticatedGossiper) processZombieUpdate(
2138
        chanInfo *models.ChannelEdgeInfo, scid lnwire.ShortChannelID,
2139
        msg *lnwire.ChannelUpdate1) error {
3✔
2140

3✔
2141
        // The least-significant bit in the flag on the channel update tells us
3✔
2142
        // which edge is being updated.
3✔
2143
        isNode1 := msg.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
2144

3✔
2145
        // Since we've deemed the update as not stale above, before marking it
3✔
2146
        // live, we'll make sure it has been signed by the correct party. If we
3✔
2147
        // have both pubkeys, either party can resurrect the channel. If we've
3✔
2148
        // already marked this with the stricter, single-sided resurrection we
3✔
2149
        // will only have the pubkey of the node with the oldest timestamp.
3✔
2150
        var pubKey *btcec.PublicKey
3✔
2151
        switch {
3✔
2152
        case isNode1 && chanInfo.NodeKey1Bytes != emptyPubkey:
×
2153
                pubKey, _ = chanInfo.NodeKey1()
×
2154
        case !isNode1 && chanInfo.NodeKey2Bytes != emptyPubkey:
2✔
2155
                pubKey, _ = chanInfo.NodeKey2()
2✔
2156
        }
2157
        if pubKey == nil {
4✔
2158
                return fmt.Errorf("incorrect pubkey to resurrect zombie "+
1✔
2159
                        "with chan_id=%v", msg.ShortChannelID)
1✔
2160
        }
1✔
2161

2162
        err := netann.VerifyChannelUpdateSignature(msg, pubKey)
2✔
2163
        if err != nil {
3✔
2164
                return fmt.Errorf("unable to verify channel "+
1✔
2165
                        "update signature: %v", err)
1✔
2166
        }
1✔
2167

2168
        // With the signature valid, we'll proceed to mark the
2169
        // edge as live and wait for the channel announcement to
2170
        // come through again.
2171
        err = d.cfg.Graph.MarkEdgeLive(scid)
1✔
2172
        switch {
1✔
2173
        case errors.Is(err, graphdb.ErrZombieEdgeNotFound):
×
2174
                log.Errorf("edge with chan_id=%v was not found in the "+
×
2175
                        "zombie index: %v", err)
×
2176

×
2177
                return nil
×
2178

2179
        case err != nil:
×
2180
                return fmt.Errorf("unable to remove edge with "+
×
2181
                        "chan_id=%v from zombie index: %v",
×
2182
                        msg.ShortChannelID, err)
×
2183

2184
        default:
1✔
2185
        }
2186

2187
        log.Debugf("Removed edge with chan_id=%v from zombie "+
1✔
2188
                "index", msg.ShortChannelID)
1✔
2189

1✔
2190
        return nil
1✔
2191
}
2192

2193
// fetchNodeAnn fetches the latest signed node announcement from our point of
2194
// view for the node with the given public key.
2195
func (d *AuthenticatedGossiper) fetchNodeAnn(
2196
        pubKey [33]byte) (*lnwire.NodeAnnouncement, error) {
20✔
2197

20✔
2198
        node, err := d.cfg.Graph.FetchLightningNode(pubKey)
20✔
2199
        if err != nil {
26✔
2200
                return nil, err
6✔
2201
        }
6✔
2202

2203
        return node.NodeAnnouncement(true)
14✔
2204
}
2205

2206
// isMsgStale determines whether a message retrieved from the backing
2207
// MessageStore is seen as stale by the current graph.
2208
func (d *AuthenticatedGossiper) isMsgStale(msg lnwire.Message) bool {
12✔
2209
        switch msg := msg.(type) {
12✔
2210
        case *lnwire.AnnounceSignatures1:
2✔
2211
                chanInfo, _, _, err := d.cfg.Graph.GetChannelByID(
2✔
2212
                        msg.ShortChannelID,
2✔
2213
                )
2✔
2214

2✔
2215
                // If the channel cannot be found, it is most likely a leftover
2✔
2216
                // message for a channel that was closed, so we can consider it
2✔
2217
                // stale.
2✔
2218
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
2✔
2219
                        return true
×
2220
                }
×
2221
                if err != nil {
2✔
2222
                        log.Debugf("Unable to retrieve channel=%v from graph: "+
×
2223
                                "%v", chanInfo.ChannelID, err)
×
2224
                        return false
×
2225
                }
×
2226

2227
                // If the proof exists in the graph, then we have successfully
2228
                // received the remote proof and assembled the full proof, so we
2229
                // can safely delete the local proof from the database.
2230
                return chanInfo.AuthProof != nil
2✔
2231

2232
        case *lnwire.ChannelUpdate1:
10✔
2233
                _, p1, p2, err := d.cfg.Graph.GetChannelByID(msg.ShortChannelID)
10✔
2234

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

2247
                // Otherwise, we'll retrieve the correct policy that we
2248
                // currently have stored within our graph to check if this
2249
                // message is stale by comparing its timestamp.
2250
                var p *models.ChannelEdgePolicy
10✔
2251
                if msg.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
20✔
2252
                        p = p1
10✔
2253
                } else {
10✔
2254
                        p = p2
×
2255
                }
×
2256

2257
                // If the policy is still unknown, then we can consider this
2258
                // policy fresh.
2259
                if p == nil {
10✔
2260
                        return false
×
2261
                }
×
2262

2263
                timestamp := time.Unix(int64(msg.Timestamp), 0)
10✔
2264
                return p.LastUpdate.After(timestamp)
10✔
2265

2266
        default:
×
2267
                // We'll make sure to not mark any unsupported messages as stale
×
2268
                // to ensure they are not removed.
×
2269
                return false
×
2270
        }
2271
}
2272

2273
// updateChannel creates a new fully signed update for the channel, and updates
2274
// the underlying graph with the new state.
2275
func (d *AuthenticatedGossiper) updateChannel(info *models.ChannelEdgeInfo,
2276
        edge *models.ChannelEdgePolicy) (*lnwire.ChannelAnnouncement1,
2277
        *lnwire.ChannelUpdate1, error) {
4✔
2278

4✔
2279
        // Parse the unsigned edge into a channel update.
4✔
2280
        chanUpdate := netann.UnsignedChannelUpdateFromEdge(info, edge)
4✔
2281

4✔
2282
        // We'll generate a new signature over a digest of the channel
4✔
2283
        // announcement itself and update the timestamp to ensure it propagate.
4✔
2284
        err := netann.SignChannelUpdate(
4✔
2285
                d.cfg.AnnSigner, d.selfKeyLoc, chanUpdate,
4✔
2286
                netann.ChanUpdSetTimestamp,
4✔
2287
        )
4✔
2288
        if err != nil {
4✔
2289
                return nil, nil, err
×
2290
        }
×
2291

2292
        // Next, we'll set the new signature in place, and update the reference
2293
        // in the backing slice.
2294
        edge.LastUpdate = time.Unix(int64(chanUpdate.Timestamp), 0)
4✔
2295
        edge.SigBytes = chanUpdate.Signature.ToSignatureBytes()
4✔
2296

4✔
2297
        // To ensure that our signature is valid, we'll verify it ourself
4✔
2298
        // before committing it to the slice returned.
4✔
2299
        err = netann.ValidateChannelUpdateAnn(
4✔
2300
                d.selfKey, info.Capacity, chanUpdate,
4✔
2301
        )
4✔
2302
        if err != nil {
4✔
2303
                return nil, nil, fmt.Errorf("generated invalid channel "+
×
2304
                        "update sig: %v", err)
×
2305
        }
×
2306

2307
        // Finally, we'll write the new edge policy to disk.
2308
        if err := d.cfg.Graph.UpdateEdge(edge); err != nil {
4✔
2309
                return nil, nil, err
×
2310
        }
×
2311

2312
        // We'll also create the original channel announcement so the two can
2313
        // be broadcast along side each other (if necessary), but only if we
2314
        // have a full channel announcement for this channel.
2315
        var chanAnn *lnwire.ChannelAnnouncement1
4✔
2316
        if info.AuthProof != nil {
7✔
2317
                chanID := lnwire.NewShortChanIDFromInt(info.ChannelID)
3✔
2318
                chanAnn = &lnwire.ChannelAnnouncement1{
3✔
2319
                        ShortChannelID:  chanID,
3✔
2320
                        NodeID1:         info.NodeKey1Bytes,
3✔
2321
                        NodeID2:         info.NodeKey2Bytes,
3✔
2322
                        ChainHash:       info.ChainHash,
3✔
2323
                        BitcoinKey1:     info.BitcoinKey1Bytes,
3✔
2324
                        Features:        lnwire.NewRawFeatureVector(),
3✔
2325
                        BitcoinKey2:     info.BitcoinKey2Bytes,
3✔
2326
                        ExtraOpaqueData: info.ExtraOpaqueData,
3✔
2327
                }
3✔
2328
                chanAnn.NodeSig1, err = lnwire.NewSigFromECDSARawSignature(
3✔
2329
                        info.AuthProof.NodeSig1Bytes,
3✔
2330
                )
3✔
2331
                if err != nil {
3✔
2332
                        return nil, nil, err
×
2333
                }
×
2334
                chanAnn.NodeSig2, err = lnwire.NewSigFromECDSARawSignature(
3✔
2335
                        info.AuthProof.NodeSig2Bytes,
3✔
2336
                )
3✔
2337
                if err != nil {
3✔
2338
                        return nil, nil, err
×
2339
                }
×
2340
                chanAnn.BitcoinSig1, err = lnwire.NewSigFromECDSARawSignature(
3✔
2341
                        info.AuthProof.BitcoinSig1Bytes,
3✔
2342
                )
3✔
2343
                if err != nil {
3✔
2344
                        return nil, nil, err
×
2345
                }
×
2346
                chanAnn.BitcoinSig2, err = lnwire.NewSigFromECDSARawSignature(
3✔
2347
                        info.AuthProof.BitcoinSig2Bytes,
3✔
2348
                )
3✔
2349
                if err != nil {
3✔
2350
                        return nil, nil, err
×
2351
                }
×
2352
        }
2353

2354
        return chanAnn, chanUpdate, err
4✔
2355
}
2356

2357
// SyncManager returns the gossiper's SyncManager instance.
2358
func (d *AuthenticatedGossiper) SyncManager() *SyncManager {
×
2359
        return d.syncMgr
×
2360
}
×
2361

2362
// IsKeepAliveUpdate determines whether this channel update is considered a
2363
// keep-alive update based on the previous channel update processed for the same
2364
// direction.
2365
func IsKeepAliveUpdate(update *lnwire.ChannelUpdate1,
2366
        prev *models.ChannelEdgePolicy) bool {
17✔
2367

17✔
2368
        // Both updates should be from the same direction.
17✔
2369
        if update.ChannelFlags&lnwire.ChanUpdateDirection !=
17✔
2370
                prev.ChannelFlags&lnwire.ChanUpdateDirection {
17✔
2371

×
2372
                return false
×
2373
        }
×
2374

2375
        // The timestamp should always increase for a keep-alive update.
2376
        timestamp := time.Unix(int64(update.Timestamp), 0)
17✔
2377
        if !timestamp.After(prev.LastUpdate) {
17✔
2378
                return false
×
2379
        }
×
2380

2381
        // None of the remaining fields should change for a keep-alive update.
2382
        if update.ChannelFlags.IsDisabled() != prev.ChannelFlags.IsDisabled() {
17✔
2383
                return false
×
2384
        }
×
2385
        if lnwire.MilliSatoshi(update.BaseFee) != prev.FeeBaseMSat {
32✔
2386
                return false
15✔
2387
        }
15✔
2388
        if lnwire.MilliSatoshi(update.FeeRate) != prev.FeeProportionalMillionths {
2✔
2389
                return false
×
2390
        }
×
2391
        if update.TimeLockDelta != prev.TimeLockDelta {
2✔
2392
                return false
×
2393
        }
×
2394
        if update.HtlcMinimumMsat != prev.MinHTLC {
2✔
2395
                return false
×
2396
        }
×
2397
        if update.MessageFlags.HasMaxHtlc() && !prev.MessageFlags.HasMaxHtlc() {
2✔
2398
                return false
×
2399
        }
×
2400
        if update.HtlcMaximumMsat != prev.MaxHTLC {
2✔
2401
                return false
×
2402
        }
×
2403
        if !bytes.Equal(update.ExtraOpaqueData, prev.ExtraOpaqueData) {
2✔
2404
                return false
×
2405
        }
×
2406
        return true
2✔
2407
}
2408

2409
// latestHeight returns the gossiper's latest height known of the chain.
2410
func (d *AuthenticatedGossiper) latestHeight() uint32 {
×
2411
        d.Lock()
×
2412
        defer d.Unlock()
×
2413
        return d.bestHeight
×
2414
}
×
2415

2416
// handleNodeAnnouncement processes a new node announcement.
2417
func (d *AuthenticatedGossiper) handleNodeAnnouncement(nMsg *networkMsg,
2418
        nodeAnn *lnwire.NodeAnnouncement,
2419
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
24✔
2420

24✔
2421
        timestamp := time.Unix(int64(nodeAnn.Timestamp), 0)
24✔
2422

24✔
2423
        log.Debugf("Processing NodeAnnouncement: peer=%v, timestamp=%v, "+
24✔
2424
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
24✔
2425
                nMsg.source.SerializeCompressed())
24✔
2426

24✔
2427
        // We'll quickly ask the router if it already has a newer update for
24✔
2428
        // this node so we can skip validating signatures if not required.
24✔
2429
        if d.cfg.Graph.IsStaleNode(nodeAnn.NodeID, timestamp) {
32✔
2430
                log.Debugf("Skipped processing stale node: %x", nodeAnn.NodeID)
8✔
2431
                nMsg.err <- nil
8✔
2432
                return nil, true
8✔
2433
        }
8✔
2434

2435
        if err := d.addNode(nodeAnn, ops...); err != nil {
16✔
2436
                log.Debugf("Adding node: %x got error: %v", nodeAnn.NodeID,
×
2437
                        err)
×
2438

×
2439
                if !graph.IsError(
×
2440
                        err,
×
2441
                        graph.ErrOutdated,
×
2442
                        graph.ErrIgnored,
×
2443
                ) {
×
2444

×
2445
                        log.Error(err)
×
2446
                }
×
2447

2448
                nMsg.err <- err
×
2449
                return nil, false
×
2450
        }
2451

2452
        // In order to ensure we don't leak unadvertised nodes, we'll make a
2453
        // quick check to ensure this node intends to publicly advertise itself
2454
        // to the network.
2455
        isPublic, err := d.cfg.Graph.IsPublicNode(nodeAnn.NodeID)
16✔
2456
        if err != nil {
16✔
2457
                log.Errorf("Unable to determine if node %x is advertised: %v",
×
2458
                        nodeAnn.NodeID, err)
×
2459
                nMsg.err <- err
×
2460
                return nil, false
×
2461
        }
×
2462

2463
        var announcements []networkMsg
16✔
2464

16✔
2465
        // If it does, we'll add their announcement to our batch so that it can
16✔
2466
        // be broadcast to the rest of our peers.
16✔
2467
        if isPublic {
19✔
2468
                announcements = append(announcements, networkMsg{
3✔
2469
                        peer:     nMsg.peer,
3✔
2470
                        isRemote: nMsg.isRemote,
3✔
2471
                        source:   nMsg.source,
3✔
2472
                        msg:      nodeAnn,
3✔
2473
                })
3✔
2474
        } else {
16✔
2475
                log.Tracef("Skipping broadcasting node announcement for %x "+
13✔
2476
                        "due to being unadvertised", nodeAnn.NodeID)
13✔
2477
        }
13✔
2478

2479
        nMsg.err <- nil
16✔
2480
        // TODO(roasbeef): get rid of the above
16✔
2481

16✔
2482
        log.Debugf("Processed NodeAnnouncement: peer=%v, timestamp=%v, "+
16✔
2483
                "node=%x, source=%x", nMsg.peer, timestamp, nodeAnn.NodeID,
16✔
2484
                nMsg.source.SerializeCompressed())
16✔
2485

16✔
2486
        return announcements, true
16✔
2487
}
2488

2489
// handleChanAnnouncement processes a new channel announcement.
2490
func (d *AuthenticatedGossiper) handleChanAnnouncement(nMsg *networkMsg,
2491
        ann *lnwire.ChannelAnnouncement1,
2492
        ops ...batch.SchedulerOption) ([]networkMsg, bool) {
234✔
2493

234✔
2494
        scid := ann.ShortChannelID
234✔
2495

234✔
2496
        log.Debugf("Processing ChannelAnnouncement1: peer=%v, short_chan_id=%v",
234✔
2497
                nMsg.peer, scid.ToUint64())
234✔
2498

234✔
2499
        // We'll ignore any channel announcements that target any chain other
234✔
2500
        // than the set of chains we know of.
234✔
2501
        if !bytes.Equal(ann.ChainHash[:], d.cfg.ChainHash[:]) {
234✔
2502
                err := fmt.Errorf("ignoring ChannelAnnouncement1 from chain=%v"+
×
2503
                        ", gossiper on chain=%v", ann.ChainHash,
×
2504
                        d.cfg.ChainHash)
×
2505
                log.Errorf(err.Error())
×
2506

×
2507
                key := newRejectCacheKey(
×
2508
                        scid.ToUint64(),
×
2509
                        sourceToPub(nMsg.source),
×
2510
                )
×
2511
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2512

×
2513
                nMsg.err <- err
×
2514
                return nil, false
×
2515
        }
×
2516

2517
        // If this is a remote ChannelAnnouncement with an alias SCID, we'll
2518
        // reject the announcement. Since the router accepts alias SCIDs,
2519
        // not erroring out would be a DoS vector.
2520
        if nMsg.isRemote && d.cfg.IsAlias(scid) {
234✔
2521
                err := fmt.Errorf("ignoring remote alias channel=%v", scid)
×
2522
                log.Errorf(err.Error())
×
2523

×
2524
                key := newRejectCacheKey(
×
2525
                        scid.ToUint64(),
×
2526
                        sourceToPub(nMsg.source),
×
2527
                )
×
2528
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2529

×
2530
                nMsg.err <- err
×
2531
                return nil, false
×
2532
        }
×
2533

2534
        // If the advertised inclusionary block is beyond our knowledge of the
2535
        // chain tip, then we'll ignore it for now.
2536
        d.Lock()
234✔
2537
        if nMsg.isRemote && d.isPremature(scid, 0, nMsg) {
235✔
2538
                log.Warnf("Announcement for chan_id=(%v), is premature: "+
1✔
2539
                        "advertises height %v, only height %v is known",
1✔
2540
                        scid.ToUint64(), scid.BlockHeight, d.bestHeight)
1✔
2541
                d.Unlock()
1✔
2542
                nMsg.err <- nil
1✔
2543
                return nil, false
1✔
2544
        }
1✔
2545
        d.Unlock()
233✔
2546

233✔
2547
        // At this point, we'll now ask the router if this is a zombie/known
233✔
2548
        // edge. If so we can skip all the processing below.
233✔
2549
        if d.cfg.Graph.IsKnownEdge(scid) {
234✔
2550
                nMsg.err <- nil
1✔
2551
                return nil, true
1✔
2552
        }
1✔
2553

2554
        // Check if the channel is already closed in which case we can ignore
2555
        // it.
2556
        closed, err := d.cfg.ScidCloser.IsClosedScid(scid)
232✔
2557
        if err != nil {
232✔
2558
                log.Errorf("failed to check if scid %v is closed: %v", scid,
×
2559
                        err)
×
2560
                nMsg.err <- err
×
2561

×
2562
                return nil, false
×
2563
        }
×
2564

2565
        if closed {
233✔
2566
                err = fmt.Errorf("ignoring closed channel %v", scid)
1✔
2567
                log.Error(err)
1✔
2568

1✔
2569
                // If this is an announcement from us, we'll just ignore it.
1✔
2570
                if !nMsg.isRemote {
1✔
2571
                        nMsg.err <- err
×
2572
                        return nil, false
×
2573
                }
×
2574

2575
                // Increment the peer's ban score if they are sending closed
2576
                // channel announcements.
2577
                d.banman.incrementBanScore(nMsg.peer.PubKey())
1✔
2578

1✔
2579
                // If the peer is banned and not a channel peer, we'll
1✔
2580
                // disconnect them.
1✔
2581
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2582
                if dcErr != nil {
1✔
2583
                        log.Errorf("failed to check if we should disconnect "+
×
2584
                                "peer: %v", dcErr)
×
2585
                        nMsg.err <- dcErr
×
2586

×
2587
                        return nil, false
×
2588
                }
×
2589

2590
                if shouldDc {
1✔
2591
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2592
                }
×
2593

2594
                nMsg.err <- err
1✔
2595

1✔
2596
                return nil, false
1✔
2597
        }
2598

2599
        // If this is a remote channel announcement, then we'll validate all
2600
        // the signatures within the proof as it should be well formed.
2601
        var proof *models.ChannelAuthProof
231✔
2602
        if nMsg.isRemote {
448✔
2603
                err := netann.ValidateChannelAnn(ann, d.fetchPKScript)
217✔
2604
                if err != nil {
217✔
2605
                        err := fmt.Errorf("unable to validate announcement: "+
×
2606
                                "%v", err)
×
2607

×
2608
                        key := newRejectCacheKey(
×
2609
                                scid.ToUint64(),
×
2610
                                sourceToPub(nMsg.source),
×
2611
                        )
×
2612
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2613

×
2614
                        log.Error(err)
×
2615
                        nMsg.err <- err
×
2616
                        return nil, false
×
2617
                }
×
2618

2619
                // If the proof checks out, then we'll save the proof itself to
2620
                // the database so we can fetch it later when gossiping with
2621
                // other nodes.
2622
                proof = &models.ChannelAuthProof{
217✔
2623
                        NodeSig1Bytes:    ann.NodeSig1.ToSignatureBytes(),
217✔
2624
                        NodeSig2Bytes:    ann.NodeSig2.ToSignatureBytes(),
217✔
2625
                        BitcoinSig1Bytes: ann.BitcoinSig1.ToSignatureBytes(),
217✔
2626
                        BitcoinSig2Bytes: ann.BitcoinSig2.ToSignatureBytes(),
217✔
2627
                }
217✔
2628
        }
2629

2630
        // With the proof validated (if necessary), we can now store it within
2631
        // the database for our path finding and syncing needs.
2632
        var featureBuf bytes.Buffer
231✔
2633
        if err := ann.Features.Encode(&featureBuf); err != nil {
231✔
2634
                log.Errorf("unable to encode features: %v", err)
×
2635
                nMsg.err <- err
×
2636
                return nil, false
×
2637
        }
×
2638

2639
        edge := &models.ChannelEdgeInfo{
231✔
2640
                ChannelID:        scid.ToUint64(),
231✔
2641
                ChainHash:        ann.ChainHash,
231✔
2642
                NodeKey1Bytes:    ann.NodeID1,
231✔
2643
                NodeKey2Bytes:    ann.NodeID2,
231✔
2644
                BitcoinKey1Bytes: ann.BitcoinKey1,
231✔
2645
                BitcoinKey2Bytes: ann.BitcoinKey2,
231✔
2646
                AuthProof:        proof,
231✔
2647
                Features:         featureBuf.Bytes(),
231✔
2648
                ExtraOpaqueData:  ann.ExtraOpaqueData,
231✔
2649
        }
231✔
2650

231✔
2651
        // If there were any optional message fields provided, we'll include
231✔
2652
        // them in its serialized disk representation now.
231✔
2653
        var tapscriptRoot fn.Option[chainhash.Hash]
231✔
2654
        if nMsg.optionalMsgFields != nil {
245✔
2655
                if nMsg.optionalMsgFields.capacity != nil {
15✔
2656
                        edge.Capacity = *nMsg.optionalMsgFields.capacity
1✔
2657
                }
1✔
2658
                if nMsg.optionalMsgFields.channelPoint != nil {
18✔
2659
                        cp := *nMsg.optionalMsgFields.channelPoint
4✔
2660
                        edge.ChannelPoint = cp
4✔
2661
                }
4✔
2662

2663
                // Optional tapscript root for custom channels.
2664
                tapscriptRoot = nMsg.optionalMsgFields.tapscriptRoot
14✔
2665
        }
2666

2667
        // Before we start validation or add the edge to the database, we obtain
2668
        // the mutex for this channel ID. We do this to ensure no other
2669
        // goroutine has read the database and is now making decisions based on
2670
        // this DB state, before it writes to the DB. It also ensures that we
2671
        // don't perform the expensive validation check on the same channel
2672
        // announcement at the same time.
2673
        d.channelMtx.Lock(scid.ToUint64())
231✔
2674

231✔
2675
        // If AssumeChannelValid is present, then we are unable to perform any
231✔
2676
        // of the expensive checks below, so we'll short-circuit our path
231✔
2677
        // straight to adding the edge to our graph. If the passed
231✔
2678
        // ShortChannelID is an alias, then we'll skip validation as it will
231✔
2679
        // not map to a legitimate tx. This is not a DoS vector as only we can
231✔
2680
        // add an alias ChannelAnnouncement from the gossiper.
231✔
2681
        if !(d.cfg.AssumeChannelValid || d.cfg.IsAlias(scid)) { //nolint:nestif
460✔
2682
                op, capacity, script, err := d.validateFundingTransaction(
229✔
2683
                        ann, tapscriptRoot,
229✔
2684
                )
229✔
2685
                if err != nil {
433✔
2686
                        defer d.channelMtx.Unlock(scid.ToUint64())
204✔
2687

204✔
2688
                        switch {
204✔
2689
                        case errors.Is(err, ErrNoFundingTransaction),
2690
                                errors.Is(err, ErrInvalidFundingOutput):
202✔
2691

202✔
2692
                                key := newRejectCacheKey(
202✔
2693
                                        scid.ToUint64(),
202✔
2694
                                        sourceToPub(nMsg.source),
202✔
2695
                                )
202✔
2696
                                _, _ = d.recentRejects.Put(
202✔
2697
                                        key, &cachedReject{},
202✔
2698
                                )
202✔
2699

202✔
2700
                                // Increment the peer's ban score. We check
202✔
2701
                                // isRemote so we don't actually ban the peer in
202✔
2702
                                // case of a local bug.
202✔
2703
                                if nMsg.isRemote {
404✔
2704
                                        d.banman.incrementBanScore(
202✔
2705
                                                nMsg.peer.PubKey(),
202✔
2706
                                        )
202✔
2707
                                }
202✔
2708

2709
                        case errors.Is(err, ErrChannelSpent):
2✔
2710
                                key := newRejectCacheKey(
2✔
2711
                                        scid.ToUint64(),
2✔
2712
                                        sourceToPub(nMsg.source),
2✔
2713
                                )
2✔
2714
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
2✔
2715

2✔
2716
                                // Since this channel has already been closed,
2✔
2717
                                // we'll add it to the graph's closed channel
2✔
2718
                                // index such that we won't attempt to do
2✔
2719
                                // expensive validation checks on it again.
2✔
2720
                                // TODO: Populate the ScidCloser by using closed
2✔
2721
                                // channel notifications.
2✔
2722
                                dbErr := d.cfg.ScidCloser.PutClosedScid(scid)
2✔
2723
                                if dbErr != nil {
2✔
2724
                                        log.Errorf("failed to mark scid(%v) "+
×
2725
                                                "as closed: %v", scid, dbErr)
×
2726

×
2727
                                        nMsg.err <- dbErr
×
2728

×
2729
                                        return nil, false
×
2730
                                }
×
2731

2732
                                // Increment the peer's ban score. We check
2733
                                // isRemote so we don't accidentally ban
2734
                                // ourselves in case of a bug.
2735
                                if nMsg.isRemote {
4✔
2736
                                        d.banman.incrementBanScore(
2✔
2737
                                                nMsg.peer.PubKey(),
2✔
2738
                                        )
2✔
2739
                                }
2✔
2740

2741
                        default:
×
2742
                                // Otherwise, this is just a regular rejected
×
2743
                                // edge.
×
2744
                                key := newRejectCacheKey(
×
2745
                                        scid.ToUint64(),
×
2746
                                        sourceToPub(nMsg.source),
×
2747
                                )
×
2748
                                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2749
                        }
2750

2751
                        if !nMsg.isRemote {
204✔
2752
                                log.Errorf("failed to add edge for local "+
×
2753
                                        "channel: %v", err)
×
2754
                                nMsg.err <- err
×
2755

×
2756
                                return nil, false
×
2757
                        }
×
2758

2759
                        shouldDc, dcErr := d.ShouldDisconnect(
204✔
2760
                                nMsg.peer.IdentityKey(),
204✔
2761
                        )
204✔
2762
                        if dcErr != nil {
204✔
2763
                                log.Errorf("failed to check if we should "+
×
2764
                                        "disconnect peer: %v", dcErr)
×
2765
                                nMsg.err <- dcErr
×
2766

×
2767
                                return nil, false
×
2768
                        }
×
2769

2770
                        if shouldDc {
205✔
2771
                                nMsg.peer.Disconnect(ErrPeerBanned)
1✔
2772
                        }
1✔
2773

2774
                        nMsg.err <- err
204✔
2775

204✔
2776
                        return nil, false
204✔
2777
                }
2778

2779
                edge.FundingScript = fn.Some(script)
25✔
2780

25✔
2781
                // TODO(roasbeef): this is a hack, needs to be removed after
25✔
2782
                //  commitment fees are dynamic.
25✔
2783
                edge.Capacity = capacity
25✔
2784
                edge.ChannelPoint = op
25✔
2785
        }
2786

2787
        log.Debugf("Adding edge for short_chan_id: %v", scid.ToUint64())
27✔
2788

27✔
2789
        // We will add the edge to the channel router. If the nodes present in
27✔
2790
        // this channel are not present in the database, a partial node will be
27✔
2791
        // added to represent each node while we wait for a node announcement.
27✔
2792
        err = d.cfg.Graph.AddEdge(edge, ops...)
27✔
2793
        if err != nil {
28✔
2794
                log.Debugf("Graph rejected edge for short_chan_id(%v): %v",
1✔
2795
                        scid.ToUint64(), err)
1✔
2796

1✔
2797
                defer d.channelMtx.Unlock(scid.ToUint64())
1✔
2798

1✔
2799
                // If the edge was rejected due to already being known, then it
1✔
2800
                // may be the case that this new message has a fresh channel
1✔
2801
                // proof, so we'll check.
1✔
2802
                if graph.IsError(err, graph.ErrIgnored) {
1✔
2803
                        // Attempt to process the rejected message to see if we
×
2804
                        // get any new announcements.
×
2805
                        anns, rErr := d.processRejectedEdge(ann, proof)
×
2806
                        if rErr != nil {
×
2807
                                key := newRejectCacheKey(
×
2808
                                        scid.ToUint64(),
×
2809
                                        sourceToPub(nMsg.source),
×
2810
                                )
×
2811
                                cr := &cachedReject{}
×
2812
                                _, _ = d.recentRejects.Put(key, cr)
×
2813

×
2814
                                nMsg.err <- rErr
×
2815

×
2816
                                return nil, false
×
2817
                        }
×
2818

2819
                        log.Debugf("Extracted %v announcements from rejected "+
×
2820
                                "msgs", len(anns))
×
2821

×
2822
                        // If while processing this rejected edge, we realized
×
2823
                        // there's a set of announcements we could extract,
×
2824
                        // then we'll return those directly.
×
2825
                        //
×
2826
                        // NOTE: since this is an ErrIgnored, we can return
×
2827
                        // true here to signal "allow" to its dependants.
×
2828
                        nMsg.err <- nil
×
2829

×
2830
                        return anns, true
×
2831
                }
2832

2833
                // Otherwise, this is just a regular rejected edge.
2834
                key := newRejectCacheKey(
1✔
2835
                        scid.ToUint64(),
1✔
2836
                        sourceToPub(nMsg.source),
1✔
2837
                )
1✔
2838
                _, _ = d.recentRejects.Put(key, &cachedReject{})
1✔
2839

1✔
2840
                if !nMsg.isRemote {
1✔
2841
                        log.Errorf("failed to add edge for local channel: %v",
×
2842
                                err)
×
2843
                        nMsg.err <- err
×
2844

×
2845
                        return nil, false
×
2846
                }
×
2847

2848
                shouldDc, dcErr := d.ShouldDisconnect(nMsg.peer.IdentityKey())
1✔
2849
                if dcErr != nil {
1✔
2850
                        log.Errorf("failed to check if we should disconnect "+
×
2851
                                "peer: %v", dcErr)
×
2852
                        nMsg.err <- dcErr
×
2853

×
2854
                        return nil, false
×
2855
                }
×
2856

2857
                if shouldDc {
1✔
2858
                        nMsg.peer.Disconnect(ErrPeerBanned)
×
2859
                }
×
2860

2861
                nMsg.err <- err
1✔
2862

1✔
2863
                return nil, false
1✔
2864
        }
2865

2866
        // If err is nil, release the lock immediately.
2867
        d.channelMtx.Unlock(scid.ToUint64())
26✔
2868

26✔
2869
        log.Debugf("Finish adding edge for short_chan_id: %v", scid.ToUint64())
26✔
2870

26✔
2871
        // If we earlier received any ChannelUpdates for this channel, we can
26✔
2872
        // now process them, as the channel is added to the graph.
26✔
2873
        var channelUpdates []*processedNetworkMsg
26✔
2874

26✔
2875
        earlyChanUpdates, err := d.prematureChannelUpdates.Get(scid.ToUint64())
26✔
2876
        if err == nil {
28✔
2877
                // There was actually an entry in the map, so we'll accumulate
2✔
2878
                // it. We don't worry about deletion, since it'll eventually
2✔
2879
                // fall out anyway.
2✔
2880
                chanMsgs := earlyChanUpdates
2✔
2881
                channelUpdates = append(channelUpdates, chanMsgs.msgs...)
2✔
2882
        }
2✔
2883

2884
        // Launch a new goroutine to handle each ChannelUpdate, this is to
2885
        // ensure we don't block here, as we can handle only one announcement
2886
        // at a time.
2887
        for _, cu := range channelUpdates {
28✔
2888
                // Skip if already processed.
2✔
2889
                if cu.processed {
2✔
2890
                        continue
×
2891
                }
2892

2893
                // Mark the ChannelUpdate as processed. This ensures that a
2894
                // subsequent announcement in the option-scid-alias case does
2895
                // not re-use an old ChannelUpdate.
2896
                cu.processed = true
2✔
2897

2✔
2898
                d.wg.Add(1)
2✔
2899
                go func(updMsg *networkMsg) {
4✔
2900
                        defer d.wg.Done()
2✔
2901

2✔
2902
                        switch msg := updMsg.msg.(type) {
2✔
2903
                        // Reprocess the message, making sure we return an
2904
                        // error to the original caller in case the gossiper
2905
                        // shuts down.
2906
                        case *lnwire.ChannelUpdate1:
2✔
2907
                                log.Debugf("Reprocessing ChannelUpdate for "+
2✔
2908
                                        "shortChanID=%v", scid.ToUint64())
2✔
2909

2✔
2910
                                select {
2✔
2911
                                case d.networkMsgs <- updMsg:
2✔
2912
                                case <-d.quit:
×
2913
                                        updMsg.err <- ErrGossiperShuttingDown
×
2914
                                }
2915

2916
                        // We don't expect any other message type than
2917
                        // ChannelUpdate to be in this cache.
2918
                        default:
×
2919
                                log.Errorf("Unsupported message type found "+
×
2920
                                        "among ChannelUpdates: %T", msg)
×
2921
                        }
2922
                }(cu.msg)
2923
        }
2924

2925
        // Channel announcement was successfully processed and now it might be
2926
        // broadcast to other connected nodes if it was an announcement with
2927
        // proof (remote).
2928
        var announcements []networkMsg
26✔
2929

26✔
2930
        if proof != nil {
38✔
2931
                announcements = append(announcements, networkMsg{
12✔
2932
                        peer:     nMsg.peer,
12✔
2933
                        isRemote: nMsg.isRemote,
12✔
2934
                        source:   nMsg.source,
12✔
2935
                        msg:      ann,
12✔
2936
                })
12✔
2937
        }
12✔
2938

2939
        nMsg.err <- nil
26✔
2940

26✔
2941
        log.Debugf("Processed ChannelAnnouncement1: peer=%v, short_chan_id=%v",
26✔
2942
                nMsg.peer, scid.ToUint64())
26✔
2943

26✔
2944
        return announcements, true
26✔
2945
}
2946

2947
// handleChanUpdate processes a new channel update.
2948
func (d *AuthenticatedGossiper) handleChanUpdate(nMsg *networkMsg,
2949
        upd *lnwire.ChannelUpdate1,
2950
        ops []batch.SchedulerOption) ([]networkMsg, bool) {
61✔
2951

61✔
2952
        log.Debugf("Processing ChannelUpdate: peer=%v, short_chan_id=%v, ",
61✔
2953
                nMsg.peer, upd.ShortChannelID.ToUint64())
61✔
2954

61✔
2955
        // We'll ignore any channel updates that target any chain other than
61✔
2956
        // the set of chains we know of.
61✔
2957
        if !bytes.Equal(upd.ChainHash[:], d.cfg.ChainHash[:]) {
61✔
2958
                err := fmt.Errorf("ignoring ChannelUpdate from chain=%v, "+
×
2959
                        "gossiper on chain=%v", upd.ChainHash, d.cfg.ChainHash)
×
2960
                log.Errorf(err.Error())
×
2961

×
2962
                key := newRejectCacheKey(
×
2963
                        upd.ShortChannelID.ToUint64(),
×
2964
                        sourceToPub(nMsg.source),
×
2965
                )
×
2966
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
2967

×
2968
                nMsg.err <- err
×
2969
                return nil, false
×
2970
        }
×
2971

2972
        blockHeight := upd.ShortChannelID.BlockHeight
61✔
2973
        shortChanID := upd.ShortChannelID.ToUint64()
61✔
2974

61✔
2975
        // If the advertised inclusionary block is beyond our knowledge of the
61✔
2976
        // chain tip, then we'll put the announcement in limbo to be fully
61✔
2977
        // verified once we advance forward in the chain. If the update has an
61✔
2978
        // alias SCID, we'll skip the isPremature check. This is necessary
61✔
2979
        // since aliases start at block height 16_000_000.
61✔
2980
        d.Lock()
61✔
2981
        if nMsg.isRemote && !d.cfg.IsAlias(upd.ShortChannelID) &&
61✔
2982
                d.isPremature(upd.ShortChannelID, 0, nMsg) {
61✔
2983

×
2984
                log.Warnf("Update announcement for short_chan_id(%v), is "+
×
2985
                        "premature: advertises height %v, only height %v is "+
×
2986
                        "known", shortChanID, blockHeight, d.bestHeight)
×
2987
                d.Unlock()
×
2988
                nMsg.err <- nil
×
2989
                return nil, false
×
2990
        }
×
2991
        d.Unlock()
61✔
2992

61✔
2993
        // Before we perform any of the expensive checks below, we'll check
61✔
2994
        // whether this update is stale or is for a zombie channel in order to
61✔
2995
        // quickly reject it.
61✔
2996
        timestamp := time.Unix(int64(upd.Timestamp), 0)
61✔
2997

61✔
2998
        // Fetch the SCID we should be using to lock the channelMtx and make
61✔
2999
        // graph queries with.
61✔
3000
        graphScid, err := d.cfg.FindBaseByAlias(upd.ShortChannelID)
61✔
3001
        if err != nil {
122✔
3002
                // Fallback and set the graphScid to the peer-provided SCID.
61✔
3003
                // This will occur for non-option-scid-alias channels and for
61✔
3004
                // public option-scid-alias channels after 6 confirmations.
61✔
3005
                // Once public option-scid-alias channels have 6 confs, we'll
61✔
3006
                // ignore ChannelUpdates with one of their aliases.
61✔
3007
                graphScid = upd.ShortChannelID
61✔
3008
        }
61✔
3009

3010
        // We make sure to obtain the mutex for this channel ID before we access
3011
        // the database. This ensures the state we read from the database has
3012
        // not changed between this point and when we call UpdateEdge() later.
3013
        d.channelMtx.Lock(graphScid.ToUint64())
61✔
3014
        defer d.channelMtx.Unlock(graphScid.ToUint64())
61✔
3015

61✔
3016
        if d.cfg.Graph.IsStaleEdgePolicy(
61✔
3017
                graphScid, timestamp, upd.ChannelFlags,
61✔
3018
        ) {
64✔
3019

3✔
3020
                log.Debugf("Ignored stale edge policy for short_chan_id(%v): "+
3✔
3021
                        "peer=%v, msg=%s, is_remote=%v", shortChanID,
3✔
3022
                        nMsg.peer, nMsg.msg.MsgType(), nMsg.isRemote,
3✔
3023
                )
3✔
3024

3✔
3025
                nMsg.err <- nil
3✔
3026
                return nil, true
3✔
3027
        }
3✔
3028

3029
        // Check that the ChanUpdate is not too far into the future, this could
3030
        // reveal some faulty implementation therefore we log an error.
3031
        if time.Until(timestamp) > graph.DefaultChannelPruneExpiry {
58✔
3032
                log.Errorf("Skewed timestamp (%v) for edge policy of "+
×
3033
                        "short_chan_id(%v), timestamp too far in the future: "+
×
3034
                        "peer=%v, msg=%s, is_remote=%v", timestamp.Unix(),
×
3035
                        shortChanID, nMsg.peer, nMsg.msg.MsgType(),
×
3036
                        nMsg.isRemote,
×
3037
                )
×
3038

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

×
3042
                return nil, false
×
3043
        }
×
3044

3045
        // Get the node pub key as far since we don't have it in the channel
3046
        // update announcement message. We'll need this to properly verify the
3047
        // message's signature.
3048
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(graphScid)
58✔
3049
        switch {
58✔
3050
        // No error, break.
3051
        case err == nil:
54✔
3052
                break
54✔
3053

3054
        case errors.Is(err, graphdb.ErrZombieEdge):
3✔
3055
                err = d.processZombieUpdate(chanInfo, graphScid, upd)
3✔
3056
                if err != nil {
5✔
3057
                        log.Debug(err)
2✔
3058
                        nMsg.err <- err
2✔
3059
                        return nil, false
2✔
3060
                }
2✔
3061

3062
                // We'll fallthrough to ensure we stash the update until we
3063
                // receive its corresponding ChannelAnnouncement. This is
3064
                // needed to ensure the edge exists in the graph before
3065
                // applying the update.
3066
                fallthrough
1✔
3067
        case errors.Is(err, graphdb.ErrGraphNotFound):
1✔
3068
                fallthrough
1✔
3069
        case errors.Is(err, graphdb.ErrGraphNoEdgesFound):
1✔
3070
                fallthrough
1✔
3071
        case errors.Is(err, graphdb.ErrEdgeNotFound):
2✔
3072
                // If the edge corresponding to this ChannelUpdate was not
2✔
3073
                // found in the graph, this might be a channel in the process
2✔
3074
                // of being opened, and we haven't processed our own
2✔
3075
                // ChannelAnnouncement yet, hence it is not not found in the
2✔
3076
                // graph. This usually gets resolved after the channel proofs
2✔
3077
                // are exchanged and the channel is broadcasted to the rest of
2✔
3078
                // the network, but in case this is a private channel this
2✔
3079
                // won't ever happen. This can also happen in the case of a
2✔
3080
                // zombie channel with a fresh update for which we don't have a
2✔
3081
                // ChannelAnnouncement for since we reject them. Because of
2✔
3082
                // this, we temporarily add it to a map, and reprocess it after
2✔
3083
                // our own ChannelAnnouncement has been processed.
2✔
3084
                //
2✔
3085
                // The shortChanID may be an alias, but it is fine to use here
2✔
3086
                // since we don't have an edge in the graph and if the peer is
2✔
3087
                // not buggy, we should be able to use it once the gossiper
2✔
3088
                // receives the local announcement.
2✔
3089
                pMsg := &processedNetworkMsg{msg: nMsg}
2✔
3090

2✔
3091
                earlyMsgs, err := d.prematureChannelUpdates.Get(shortChanID)
2✔
3092
                switch {
2✔
3093
                // Nothing in the cache yet, we can just directly insert this
3094
                // element.
3095
                case err == cache.ErrElementNotFound:
2✔
3096
                        _, _ = d.prematureChannelUpdates.Put(
2✔
3097
                                shortChanID, &cachedNetworkMsg{
2✔
3098
                                        msgs: []*processedNetworkMsg{pMsg},
2✔
3099
                                })
2✔
3100

3101
                // There's already something in the cache, so we'll combine the
3102
                // set of messages into a single value.
3103
                default:
×
3104
                        msgs := earlyMsgs.msgs
×
3105
                        msgs = append(msgs, pMsg)
×
3106
                        _, _ = d.prematureChannelUpdates.Put(
×
3107
                                shortChanID, &cachedNetworkMsg{
×
3108
                                        msgs: msgs,
×
3109
                                })
×
3110
                }
3111

3112
                log.Debugf("Got ChannelUpdate for edge not found in graph"+
2✔
3113
                        "(shortChanID=%v), saving for reprocessing later",
2✔
3114
                        shortChanID)
2✔
3115

2✔
3116
                // NOTE: We don't return anything on the error channel for this
2✔
3117
                // message, as we expect that will be done when this
2✔
3118
                // ChannelUpdate is later reprocessed.
2✔
3119
                return nil, false
2✔
3120

3121
        default:
×
3122
                err := fmt.Errorf("unable to validate channel update "+
×
3123
                        "short_chan_id=%v: %v", shortChanID, err)
×
3124
                log.Error(err)
×
3125
                nMsg.err <- err
×
3126

×
3127
                key := newRejectCacheKey(
×
3128
                        upd.ShortChannelID.ToUint64(),
×
3129
                        sourceToPub(nMsg.source),
×
3130
                )
×
3131
                _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3132

×
3133
                return nil, false
×
3134
        }
3135

3136
        // The least-significant bit in the flag on the channel update
3137
        // announcement tells us "which" side of the channels directed edge is
3138
        // being updated.
3139
        var (
54✔
3140
                pubKey       *btcec.PublicKey
54✔
3141
                edgeToUpdate *models.ChannelEdgePolicy
54✔
3142
        )
54✔
3143
        direction := upd.ChannelFlags & lnwire.ChanUpdateDirection
54✔
3144
        switch direction {
54✔
3145
        case 0:
38✔
3146
                pubKey, _ = chanInfo.NodeKey1()
38✔
3147
                edgeToUpdate = e1
38✔
3148
        case 1:
16✔
3149
                pubKey, _ = chanInfo.NodeKey2()
16✔
3150
                edgeToUpdate = e2
16✔
3151
        }
3152

3153
        log.Debugf("Validating ChannelUpdate: channel=%v, for node=%x, has "+
54✔
3154
                "edge policy=%v", chanInfo.ChannelID,
54✔
3155
                pubKey.SerializeCompressed(), edgeToUpdate != nil)
54✔
3156

54✔
3157
        // Validate the channel announcement with the expected public key and
54✔
3158
        // channel capacity. In the case of an invalid channel update, we'll
54✔
3159
        // return an error to the caller and exit early.
54✔
3160
        err = netann.ValidateChannelUpdateAnn(pubKey, chanInfo.Capacity, upd)
54✔
3161
        if err != nil {
58✔
3162
                rErr := fmt.Errorf("unable to validate channel update "+
4✔
3163
                        "announcement for short_chan_id=%v: %v",
4✔
3164
                        spew.Sdump(upd.ShortChannelID), err)
4✔
3165

4✔
3166
                log.Error(rErr)
4✔
3167
                nMsg.err <- rErr
4✔
3168
                return nil, false
4✔
3169
        }
4✔
3170

3171
        // If we have a previous version of the edge being updated, we'll want
3172
        // to rate limit its updates to prevent spam throughout the network.
3173
        if nMsg.isRemote && edgeToUpdate != nil {
67✔
3174
                // If it's a keep-alive update, we'll only propagate one if
17✔
3175
                // it's been a day since the previous. This follows our own
17✔
3176
                // heuristic of sending keep-alive updates after the same
17✔
3177
                // duration (see retransmitStaleAnns).
17✔
3178
                timeSinceLastUpdate := timestamp.Sub(edgeToUpdate.LastUpdate)
17✔
3179
                if IsKeepAliveUpdate(upd, edgeToUpdate) {
19✔
3180
                        if timeSinceLastUpdate < d.cfg.RebroadcastInterval {
3✔
3181
                                log.Debugf("Ignoring keep alive update not "+
1✔
3182
                                        "within %v period for channel %v",
1✔
3183
                                        d.cfg.RebroadcastInterval, shortChanID)
1✔
3184
                                nMsg.err <- nil
1✔
3185
                                return nil, false
1✔
3186
                        }
1✔
3187
                } else {
15✔
3188
                        // If it's not, we'll allow an update per minute with a
15✔
3189
                        // maximum burst of 10. If we haven't seen an update
15✔
3190
                        // for this channel before, we'll need to initialize a
15✔
3191
                        // rate limiter for each direction.
15✔
3192
                        //
15✔
3193
                        // Since the edge exists in the graph, we'll create a
15✔
3194
                        // rate limiter for chanInfo.ChannelID rather then the
15✔
3195
                        // SCID the peer sent. This is because there may be
15✔
3196
                        // multiple aliases for a channel and we may otherwise
15✔
3197
                        // rate-limit only a single alias of the channel,
15✔
3198
                        // instead of the whole channel.
15✔
3199
                        baseScid := chanInfo.ChannelID
15✔
3200
                        d.Lock()
15✔
3201
                        rls, ok := d.chanUpdateRateLimiter[baseScid]
15✔
3202
                        if !ok {
17✔
3203
                                r := rate.Every(d.cfg.ChannelUpdateInterval)
2✔
3204
                                b := d.cfg.MaxChannelUpdateBurst
2✔
3205
                                rls = [2]*rate.Limiter{
2✔
3206
                                        rate.NewLimiter(r, b),
2✔
3207
                                        rate.NewLimiter(r, b),
2✔
3208
                                }
2✔
3209
                                d.chanUpdateRateLimiter[baseScid] = rls
2✔
3210
                        }
2✔
3211
                        d.Unlock()
15✔
3212

15✔
3213
                        if !rls[direction].Allow() {
21✔
3214
                                log.Debugf("Rate limiting update for channel "+
6✔
3215
                                        "%v from direction %x", shortChanID,
6✔
3216
                                        pubKey.SerializeCompressed())
6✔
3217
                                nMsg.err <- nil
6✔
3218
                                return nil, false
6✔
3219
                        }
6✔
3220
                }
3221
        }
3222

3223
        // We'll use chanInfo.ChannelID rather than the peer-supplied
3224
        // ShortChannelID in the ChannelUpdate to avoid the router having to
3225
        // lookup the stored SCID. If we're sending the update, we'll always
3226
        // use the SCID stored in the database rather than a potentially
3227
        // different alias. This might mean that SigBytes is incorrect as it
3228
        // signs a different SCID than the database SCID, but since there will
3229
        // only be a difference if AuthProof == nil, this is fine.
3230
        update := &models.ChannelEdgePolicy{
43✔
3231
                SigBytes:                  upd.Signature.ToSignatureBytes(),
43✔
3232
                ChannelID:                 chanInfo.ChannelID,
43✔
3233
                LastUpdate:                timestamp,
43✔
3234
                MessageFlags:              upd.MessageFlags,
43✔
3235
                ChannelFlags:              upd.ChannelFlags,
43✔
3236
                TimeLockDelta:             upd.TimeLockDelta,
43✔
3237
                MinHTLC:                   upd.HtlcMinimumMsat,
43✔
3238
                MaxHTLC:                   upd.HtlcMaximumMsat,
43✔
3239
                FeeBaseMSat:               lnwire.MilliSatoshi(upd.BaseFee),
43✔
3240
                FeeProportionalMillionths: lnwire.MilliSatoshi(upd.FeeRate),
43✔
3241
                ExtraOpaqueData:           upd.ExtraOpaqueData,
43✔
3242
        }
43✔
3243

43✔
3244
        if err := d.cfg.Graph.UpdateEdge(update, ops...); err != nil {
43✔
3245
                if graph.IsError(
×
3246
                        err, graph.ErrOutdated,
×
3247
                        graph.ErrIgnored,
×
3248
                ) {
×
3249

×
3250
                        log.Debugf("Update edge for short_chan_id(%v) got: %v",
×
3251
                                shortChanID, err)
×
3252
                } else {
×
3253
                        // Since we know the stored SCID in the graph, we'll
×
3254
                        // cache that SCID.
×
3255
                        key := newRejectCacheKey(
×
3256
                                chanInfo.ChannelID,
×
3257
                                sourceToPub(nMsg.source),
×
3258
                        )
×
3259
                        _, _ = d.recentRejects.Put(key, &cachedReject{})
×
3260

×
3261
                        log.Errorf("Update edge for short_chan_id(%v) got: %v",
×
3262
                                shortChanID, err)
×
3263
                }
×
3264

3265
                nMsg.err <- err
×
3266
                return nil, false
×
3267
        }
3268

3269
        // If this is a local ChannelUpdate without an AuthProof, it means it
3270
        // is an update to a channel that is not (yet) supposed to be announced
3271
        // to the greater network. However, our channel counter party will need
3272
        // to be given the update, so we'll try sending the update directly to
3273
        // the remote peer.
3274
        if !nMsg.isRemote && chanInfo.AuthProof == nil {
54✔
3275
                if nMsg.optionalMsgFields != nil {
22✔
3276
                        remoteAlias := nMsg.optionalMsgFields.remoteAlias
11✔
3277
                        if remoteAlias != nil {
11✔
3278
                                // The remoteAlias field was specified, meaning
×
3279
                                // that we should replace the SCID in the
×
3280
                                // update with the remote's alias. We'll also
×
3281
                                // need to re-sign the channel update. This is
×
3282
                                // required for option-scid-alias feature-bit
×
3283
                                // negotiated channels.
×
3284
                                upd.ShortChannelID = *remoteAlias
×
3285

×
3286
                                sig, err := d.cfg.SignAliasUpdate(upd)
×
3287
                                if err != nil {
×
3288
                                        log.Error(err)
×
3289
                                        nMsg.err <- err
×
3290
                                        return nil, false
×
3291
                                }
×
3292

3293
                                lnSig, err := lnwire.NewSigFromSignature(sig)
×
3294
                                if err != nil {
×
3295
                                        log.Error(err)
×
3296
                                        nMsg.err <- err
×
3297
                                        return nil, false
×
3298
                                }
×
3299

3300
                                upd.Signature = lnSig
×
3301
                        }
3302
                }
3303

3304
                // Get our peer's public key.
3305
                remotePubKey := remotePubFromChanInfo(
11✔
3306
                        chanInfo, upd.ChannelFlags,
11✔
3307
                )
11✔
3308

11✔
3309
                log.Debugf("The message %v has no AuthProof, sending the "+
11✔
3310
                        "update to remote peer %x", upd.MsgType(), remotePubKey)
11✔
3311

11✔
3312
                // Now we'll attempt to send the channel update message
11✔
3313
                // reliably to the remote peer in the background, so that we
11✔
3314
                // don't block if the peer happens to be offline at the moment.
11✔
3315
                err := d.reliableSender.sendMessage(upd, remotePubKey)
11✔
3316
                if err != nil {
11✔
3317
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3318
                                "channel=%v to peer=%x: %v", upd.MsgType(),
×
3319
                                upd.ShortChannelID, remotePubKey, err)
×
3320
                        nMsg.err <- err
×
3321
                        return nil, false
×
3322
                }
×
3323
        }
3324

3325
        // Channel update announcement was successfully processed and now it
3326
        // can be broadcast to the rest of the network. However, we'll only
3327
        // broadcast the channel update announcement if it has an attached
3328
        // authentication proof. We also won't broadcast the update if it
3329
        // contains an alias because the network would reject this.
3330
        var announcements []networkMsg
43✔
3331
        if chanInfo.AuthProof != nil && !d.cfg.IsAlias(upd.ShortChannelID) {
66✔
3332
                announcements = append(announcements, networkMsg{
23✔
3333
                        peer:     nMsg.peer,
23✔
3334
                        source:   nMsg.source,
23✔
3335
                        isRemote: nMsg.isRemote,
23✔
3336
                        msg:      upd,
23✔
3337
                })
23✔
3338
        }
23✔
3339

3340
        nMsg.err <- nil
43✔
3341

43✔
3342
        log.Debugf("Processed ChannelUpdate: peer=%v, short_chan_id=%v, "+
43✔
3343
                "timestamp=%v", nMsg.peer, upd.ShortChannelID.ToUint64(),
43✔
3344
                timestamp)
43✔
3345
        return announcements, true
43✔
3346
}
3347

3348
// handleAnnSig processes a new announcement signatures message.
3349
func (d *AuthenticatedGossiper) handleAnnSig(nMsg *networkMsg,
3350
        ann *lnwire.AnnounceSignatures1) ([]networkMsg, bool) {
21✔
3351

21✔
3352
        needBlockHeight := ann.ShortChannelID.BlockHeight +
21✔
3353
                d.cfg.ProofMatureDelta
21✔
3354
        shortChanID := ann.ShortChannelID.ToUint64()
21✔
3355

21✔
3356
        prefix := "local"
21✔
3357
        if nMsg.isRemote {
32✔
3358
                prefix = "remote"
11✔
3359
        }
11✔
3360

3361
        log.Infof("Received new %v announcement signature for %v", prefix,
21✔
3362
                ann.ShortChannelID)
21✔
3363

21✔
3364
        // By the specification, channel announcement proofs should be sent
21✔
3365
        // after some number of confirmations after channel was registered in
21✔
3366
        // bitcoin blockchain. Therefore, we check if the proof is mature.
21✔
3367
        d.Lock()
21✔
3368
        premature := d.isPremature(
21✔
3369
                ann.ShortChannelID, d.cfg.ProofMatureDelta, nMsg,
21✔
3370
        )
21✔
3371
        if premature {
21✔
3372
                log.Warnf("Premature proof announcement, current block height"+
×
3373
                        "lower than needed: %v < %v", d.bestHeight,
×
3374
                        needBlockHeight)
×
3375
                d.Unlock()
×
3376
                nMsg.err <- nil
×
3377
                return nil, false
×
3378
        }
×
3379
        d.Unlock()
21✔
3380

21✔
3381
        // Ensure that we know of a channel with the target channel ID before
21✔
3382
        // proceeding further.
21✔
3383
        //
21✔
3384
        // We must acquire the mutex for this channel ID before getting the
21✔
3385
        // channel from the database, to ensure what we read does not change
21✔
3386
        // before we call AddProof() later.
21✔
3387
        d.channelMtx.Lock(ann.ShortChannelID.ToUint64())
21✔
3388
        defer d.channelMtx.Unlock(ann.ShortChannelID.ToUint64())
21✔
3389

21✔
3390
        chanInfo, e1, e2, err := d.cfg.Graph.GetChannelByID(
21✔
3391
                ann.ShortChannelID,
21✔
3392
        )
21✔
3393
        if err != nil {
22✔
3394
                _, err = d.cfg.FindChannel(nMsg.source, ann.ChannelID)
1✔
3395
                if err != nil {
1✔
3396
                        err := fmt.Errorf("unable to store the proof for "+
×
3397
                                "short_chan_id=%v: %v", shortChanID, err)
×
3398
                        log.Error(err)
×
3399
                        nMsg.err <- err
×
3400

×
3401
                        return nil, false
×
3402
                }
×
3403

3404
                proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
1✔
3405
                err := d.cfg.WaitingProofStore.Add(proof)
1✔
3406
                if err != nil {
1✔
3407
                        err := fmt.Errorf("unable to store the proof for "+
×
3408
                                "short_chan_id=%v: %v", shortChanID, err)
×
3409
                        log.Error(err)
×
3410
                        nMsg.err <- err
×
3411
                        return nil, false
×
3412
                }
×
3413

3414
                log.Infof("Orphan %v proof announcement with short_chan_id=%v"+
1✔
3415
                        ", adding to waiting batch", prefix, shortChanID)
1✔
3416
                nMsg.err <- nil
1✔
3417
                return nil, false
1✔
3418
        }
3419

3420
        nodeID := nMsg.source.SerializeCompressed()
20✔
3421
        isFirstNode := bytes.Equal(nodeID, chanInfo.NodeKey1Bytes[:])
20✔
3422
        isSecondNode := bytes.Equal(nodeID, chanInfo.NodeKey2Bytes[:])
20✔
3423

20✔
3424
        // Ensure that channel that was retrieved belongs to the peer which
20✔
3425
        // sent the proof announcement.
20✔
3426
        if !(isFirstNode || isSecondNode) {
20✔
3427
                err := fmt.Errorf("channel that was received doesn't belong "+
×
3428
                        "to the peer which sent the proof, short_chan_id=%v",
×
3429
                        shortChanID)
×
3430
                log.Error(err)
×
3431
                nMsg.err <- err
×
3432
                return nil, false
×
3433
        }
×
3434

3435
        // If proof was sent by a local sub-system, then we'll send the
3436
        // announcement signature to the remote node so they can also
3437
        // reconstruct the full channel announcement.
3438
        if !nMsg.isRemote {
30✔
3439
                var remotePubKey [33]byte
10✔
3440
                if isFirstNode {
20✔
3441
                        remotePubKey = chanInfo.NodeKey2Bytes
10✔
3442
                } else {
10✔
3443
                        remotePubKey = chanInfo.NodeKey1Bytes
×
3444
                }
×
3445

3446
                // Since the remote peer might not be online we'll call a
3447
                // method that will attempt to deliver the proof when it comes
3448
                // online.
3449
                err := d.reliableSender.sendMessage(ann, remotePubKey)
10✔
3450
                if err != nil {
10✔
3451
                        err := fmt.Errorf("unable to reliably send %v for "+
×
3452
                                "channel=%v to peer=%x: %v", ann.MsgType(),
×
3453
                                ann.ShortChannelID, remotePubKey, err)
×
3454
                        nMsg.err <- err
×
3455
                        return nil, false
×
3456
                }
×
3457
        }
3458

3459
        // Check if we already have the full proof for this channel.
3460
        if chanInfo.AuthProof != nil {
21✔
3461
                // If we already have the fully assembled proof, then the peer
1✔
3462
                // sending us their proof has probably not received our local
1✔
3463
                // proof yet. So be kind and send them the full proof.
1✔
3464
                if nMsg.isRemote {
2✔
3465
                        peerID := nMsg.source.SerializeCompressed()
1✔
3466
                        log.Debugf("Got AnnounceSignatures for channel with " +
1✔
3467
                                "full proof.")
1✔
3468

1✔
3469
                        d.wg.Add(1)
1✔
3470
                        go func() {
2✔
3471
                                defer d.wg.Done()
1✔
3472

1✔
3473
                                log.Debugf("Received half proof for channel "+
1✔
3474
                                        "%v with existing full proof. Sending"+
1✔
3475
                                        " full proof to peer=%x",
1✔
3476
                                        ann.ChannelID, peerID)
1✔
3477

1✔
3478
                                ca, _, _, err := netann.CreateChanAnnouncement(
1✔
3479
                                        chanInfo.AuthProof, chanInfo, e1, e2,
1✔
3480
                                )
1✔
3481
                                if err != nil {
1✔
3482
                                        log.Errorf("unable to gen ann: %v",
×
3483
                                                err)
×
3484
                                        return
×
3485
                                }
×
3486

3487
                                err = nMsg.peer.SendMessage(false, ca)
1✔
3488
                                if err != nil {
1✔
3489
                                        log.Errorf("Failed sending full proof"+
×
3490
                                                " to peer=%x: %v", peerID, err)
×
3491
                                        return
×
3492
                                }
×
3493

3494
                                log.Debugf("Full proof sent to peer=%x for "+
1✔
3495
                                        "chanID=%v", peerID, ann.ChannelID)
1✔
3496
                        }()
3497
                }
3498

3499
                log.Debugf("Already have proof for channel with chanID=%v",
1✔
3500
                        ann.ChannelID)
1✔
3501
                nMsg.err <- nil
1✔
3502
                return nil, true
1✔
3503
        }
3504

3505
        // Check that we received the opposite proof. If so, then we're now
3506
        // able to construct the full proof, and create the channel
3507
        // announcement. If we didn't receive the opposite half of the proof
3508
        // then we should store this one, and wait for the opposite to be
3509
        // received.
3510
        proof := channeldb.NewWaitingProof(nMsg.isRemote, ann)
19✔
3511
        oppProof, err := d.cfg.WaitingProofStore.Get(proof.OppositeKey())
19✔
3512
        if err != nil && err != channeldb.ErrWaitingProofNotFound {
19✔
3513
                err := fmt.Errorf("unable to get the opposite proof for "+
×
3514
                        "short_chan_id=%v: %v", shortChanID, err)
×
3515
                log.Error(err)
×
3516
                nMsg.err <- err
×
3517
                return nil, false
×
3518
        }
×
3519

3520
        if err == channeldb.ErrWaitingProofNotFound {
28✔
3521
                err := d.cfg.WaitingProofStore.Add(proof)
9✔
3522
                if err != nil {
9✔
3523
                        err := fmt.Errorf("unable to store the proof for "+
×
3524
                                "short_chan_id=%v: %v", shortChanID, err)
×
3525
                        log.Error(err)
×
3526
                        nMsg.err <- err
×
3527
                        return nil, false
×
3528
                }
×
3529

3530
                log.Infof("1/2 of channel ann proof received for "+
9✔
3531
                        "short_chan_id=%v, waiting for other half",
9✔
3532
                        shortChanID)
9✔
3533

9✔
3534
                nMsg.err <- nil
9✔
3535
                return nil, false
9✔
3536
        }
3537

3538
        // We now have both halves of the channel announcement proof, then
3539
        // we'll reconstruct the initial announcement so we can validate it
3540
        // shortly below.
3541
        var dbProof models.ChannelAuthProof
10✔
3542
        if isFirstNode {
11✔
3543
                dbProof.NodeSig1Bytes = ann.NodeSignature.ToSignatureBytes()
1✔
3544
                dbProof.NodeSig2Bytes = oppProof.NodeSignature.ToSignatureBytes()
1✔
3545
                dbProof.BitcoinSig1Bytes = ann.BitcoinSignature.ToSignatureBytes()
1✔
3546
                dbProof.BitcoinSig2Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
1✔
3547
        } else {
10✔
3548
                dbProof.NodeSig1Bytes = oppProof.NodeSignature.ToSignatureBytes()
9✔
3549
                dbProof.NodeSig2Bytes = ann.NodeSignature.ToSignatureBytes()
9✔
3550
                dbProof.BitcoinSig1Bytes = oppProof.BitcoinSignature.ToSignatureBytes()
9✔
3551
                dbProof.BitcoinSig2Bytes = ann.BitcoinSignature.ToSignatureBytes()
9✔
3552
        }
9✔
3553

3554
        chanAnn, e1Ann, e2Ann, err := netann.CreateChanAnnouncement(
10✔
3555
                &dbProof, chanInfo, e1, e2,
10✔
3556
        )
10✔
3557
        if err != nil {
10✔
3558
                log.Error(err)
×
3559
                nMsg.err <- err
×
3560
                return nil, false
×
3561
        }
×
3562

3563
        // With all the necessary components assembled validate the full
3564
        // channel announcement proof.
3565
        err = netann.ValidateChannelAnn(chanAnn, d.fetchPKScript)
10✔
3566
        if err != nil {
10✔
3567
                err := fmt.Errorf("channel announcement proof for "+
×
3568
                        "short_chan_id=%v isn't valid: %v", shortChanID, err)
×
3569

×
3570
                log.Error(err)
×
3571
                nMsg.err <- err
×
3572
                return nil, false
×
3573
        }
×
3574

3575
        // If the channel was returned by the router it means that existence of
3576
        // funding point and inclusion of nodes bitcoin keys in it already
3577
        // checked by the router. In this stage we should check that node keys
3578
        // attest to the bitcoin keys by validating the signatures of
3579
        // announcement. If proof is valid then we'll populate the channel edge
3580
        // with it, so we can announce it on peer connect.
3581
        err = d.cfg.Graph.AddProof(ann.ShortChannelID, &dbProof)
10✔
3582
        if err != nil {
10✔
3583
                err := fmt.Errorf("unable add proof to the channel chanID=%v:"+
×
3584
                        " %v", ann.ChannelID, err)
×
3585
                log.Error(err)
×
3586
                nMsg.err <- err
×
3587
                return nil, false
×
3588
        }
×
3589

3590
        err = d.cfg.WaitingProofStore.Remove(proof.OppositeKey())
10✔
3591
        if err != nil {
10✔
3592
                err := fmt.Errorf("unable to remove opposite proof for the "+
×
3593
                        "channel with chanID=%v: %v", ann.ChannelID, err)
×
3594
                log.Error(err)
×
3595
                nMsg.err <- err
×
3596
                return nil, false
×
3597
        }
×
3598

3599
        // Proof was successfully created and now can announce the channel to
3600
        // the remain network.
3601
        log.Infof("Fully valid channel proof for short_chan_id=%v constructed"+
10✔
3602
                ", adding to next ann batch", shortChanID)
10✔
3603

10✔
3604
        // Assemble the necessary announcements to add to the next broadcasting
10✔
3605
        // batch.
10✔
3606
        var announcements []networkMsg
10✔
3607
        announcements = append(announcements, networkMsg{
10✔
3608
                peer:   nMsg.peer,
10✔
3609
                source: nMsg.source,
10✔
3610
                msg:    chanAnn,
10✔
3611
        })
10✔
3612
        if src, err := chanInfo.NodeKey1(); err == nil && e1Ann != nil {
19✔
3613
                announcements = append(announcements, networkMsg{
9✔
3614
                        peer:   nMsg.peer,
9✔
3615
                        source: src,
9✔
3616
                        msg:    e1Ann,
9✔
3617
                })
9✔
3618
        }
9✔
3619
        if src, err := chanInfo.NodeKey2(); err == nil && e2Ann != nil {
18✔
3620
                announcements = append(announcements, networkMsg{
8✔
3621
                        peer:   nMsg.peer,
8✔
3622
                        source: src,
8✔
3623
                        msg:    e2Ann,
8✔
3624
                })
8✔
3625
        }
8✔
3626

3627
        // We'll also send along the node announcements for each channel
3628
        // participant if we know of them. To ensure our node announcement
3629
        // propagates to our channel counterparty, we'll set the source for
3630
        // each announcement to the node it belongs to, otherwise we won't send
3631
        // it since the source gets skipped. This isn't necessary for channel
3632
        // updates and announcement signatures since we send those directly to
3633
        // our channel counterparty through the gossiper's reliable sender.
3634
        node1Ann, err := d.fetchNodeAnn(chanInfo.NodeKey1Bytes)
10✔
3635
        if err != nil {
12✔
3636
                log.Debugf("Unable to fetch node announcement for %x: %v",
2✔
3637
                        chanInfo.NodeKey1Bytes, err)
2✔
3638
        } else {
10✔
3639
                if nodeKey1, err := chanInfo.NodeKey1(); err == nil {
16✔
3640
                        announcements = append(announcements, networkMsg{
8✔
3641
                                peer:   nMsg.peer,
8✔
3642
                                source: nodeKey1,
8✔
3643
                                msg:    node1Ann,
8✔
3644
                        })
8✔
3645
                }
8✔
3646
        }
3647

3648
        node2Ann, err := d.fetchNodeAnn(chanInfo.NodeKey2Bytes)
10✔
3649
        if err != nil {
14✔
3650
                log.Debugf("Unable to fetch node announcement for %x: %v",
4✔
3651
                        chanInfo.NodeKey2Bytes, err)
4✔
3652
        } else {
10✔
3653
                if nodeKey2, err := chanInfo.NodeKey2(); err == nil {
12✔
3654
                        announcements = append(announcements, networkMsg{
6✔
3655
                                peer:   nMsg.peer,
6✔
3656
                                source: nodeKey2,
6✔
3657
                                msg:    node2Ann,
6✔
3658
                        })
6✔
3659
                }
6✔
3660
        }
3661

3662
        nMsg.err <- nil
10✔
3663
        return announcements, true
10✔
3664
}
3665

3666
// isBanned returns true if the peer identified by pubkey is banned for sending
3667
// invalid channel announcements.
3668
func (d *AuthenticatedGossiper) isBanned(pubkey [33]byte) bool {
208✔
3669
        return d.banman.isBanned(pubkey)
208✔
3670
}
208✔
3671

3672
// ShouldDisconnect returns true if we should disconnect the peer identified by
3673
// pubkey.
3674
func (d *AuthenticatedGossiper) ShouldDisconnect(pubkey *btcec.PublicKey) (
3675
        bool, error) {
206✔
3676

206✔
3677
        pubkeySer := pubkey.SerializeCompressed()
206✔
3678

206✔
3679
        var pubkeyBytes [33]byte
206✔
3680
        copy(pubkeyBytes[:], pubkeySer)
206✔
3681

206✔
3682
        // If the public key is banned, check whether or not this is a channel
206✔
3683
        // peer.
206✔
3684
        if d.isBanned(pubkeyBytes) {
208✔
3685
                isChanPeer, err := d.cfg.ScidCloser.IsChannelPeer(pubkey)
2✔
3686
                if err != nil {
2✔
3687
                        return false, err
×
3688
                }
×
3689

3690
                // We should only disconnect non-channel peers.
3691
                if !isChanPeer {
3✔
3692
                        return true, nil
1✔
3693
                }
1✔
3694
        }
3695

3696
        return false, nil
205✔
3697
}
3698

3699
// validateFundingTransaction fetches the channel announcements claimed funding
3700
// transaction from chain to ensure that it exists, is not spent and matches
3701
// the channel announcement proof. The transaction's outpoint and value are
3702
// returned if we can glean them from the work done in this method.
3703
func (d *AuthenticatedGossiper) validateFundingTransaction(
3704
        ann *lnwire.ChannelAnnouncement1,
3705
        tapscriptRoot fn.Option[chainhash.Hash]) (wire.OutPoint, btcutil.Amount,
3706
        []byte, error) {
229✔
3707

229✔
3708
        scid := ann.ShortChannelID
229✔
3709

229✔
3710
        // Before we can add the channel to the channel graph, we need to obtain
229✔
3711
        // the full funding outpoint that's encoded within the channel ID.
229✔
3712
        fundingTx, err := lnwallet.FetchFundingTxWrapper(
229✔
3713
                d.cfg.ChainIO, &scid, d.quit,
229✔
3714
        )
229✔
3715
        if err != nil {
230✔
3716
                //nolint:ll
1✔
3717
                //
1✔
3718
                // In order to ensure we don't erroneously mark a channel as a
1✔
3719
                // zombie due to an RPC failure, we'll attempt to string match
1✔
3720
                // for the relevant errors.
1✔
3721
                //
1✔
3722
                // * btcd:
1✔
3723
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
1✔
3724
                //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
1✔
3725
                // * bitcoind:
1✔
3726
                //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
1✔
3727
                //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
1✔
3728
                switch {
1✔
3729
                case strings.Contains(err.Error(), "not found"):
1✔
3730
                        fallthrough
1✔
3731

3732
                case strings.Contains(err.Error(), "out of range"):
1✔
3733
                        // If the funding transaction isn't found at all, then
1✔
3734
                        // we'll mark the edge itself as a zombie so we don't
1✔
3735
                        // continue to request it. We use the "zero key" for
1✔
3736
                        // both node pubkeys so this edge can't be resurrected.
1✔
3737
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
1✔
3738
                        if zErr != nil {
1✔
3739
                                return wire.OutPoint{}, 0, nil, zErr
×
3740
                        }
×
3741

3742
                default:
×
3743
                }
3744

3745
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
1✔
3746
                        ErrNoFundingTransaction, err)
1✔
3747
        }
3748

3749
        // Recreate witness output to be sure that declared in channel edge
3750
        // bitcoin keys and channel value corresponds to the reality.
3751
        fundingPkScript, err := makeFundingScript(
228✔
3752
                ann.BitcoinKey1[:], ann.BitcoinKey2[:], ann.Features,
228✔
3753
                tapscriptRoot,
228✔
3754
        )
228✔
3755
        if err != nil {
228✔
3756
                return wire.OutPoint{}, 0, nil, err
×
3757
        }
×
3758

3759
        // Next we'll validate that this channel is actually well formed. If
3760
        // this check fails, then this channel either doesn't exist, or isn't
3761
        // the one that was meant to be created according to the passed channel
3762
        // proofs.
3763
        fundingPoint, err := chanvalidate.Validate(
228✔
3764
                &chanvalidate.Context{
228✔
3765
                        Locator: &chanvalidate.ShortChanIDChanLocator{
228✔
3766
                                ID: scid,
228✔
3767
                        },
228✔
3768
                        MultiSigPkScript: fundingPkScript,
228✔
3769
                        FundingTx:        fundingTx,
228✔
3770
                },
228✔
3771
        )
228✔
3772
        if err != nil {
429✔
3773
                // Mark the edge as a zombie so we won't try to re-validate it
201✔
3774
                // on start up.
201✔
3775
                zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
201✔
3776
                if zErr != nil {
201✔
3777
                        return wire.OutPoint{}, 0, nil, zErr
×
3778
                }
×
3779

3780
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: %w",
201✔
3781
                        ErrInvalidFundingOutput, err)
201✔
3782
        }
3783

3784
        // Now that we have the funding outpoint of the channel, ensure
3785
        // that it hasn't yet been spent. If so, then this channel has
3786
        // been closed so we'll ignore it.
3787
        chanUtxo, err := d.cfg.ChainIO.GetUtxo(
27✔
3788
                fundingPoint, fundingPkScript, scid.BlockHeight, d.quit,
27✔
3789
        )
27✔
3790
        if err != nil {
29✔
3791
                if errors.Is(err, btcwallet.ErrOutputSpent) {
4✔
3792
                        zErr := d.cfg.Graph.MarkZombieEdge(scid.ToUint64())
2✔
3793
                        if zErr != nil {
2✔
3794
                                return wire.OutPoint{}, 0, nil, zErr
×
3795
                        }
×
3796
                }
3797

3798
                return wire.OutPoint{}, 0, nil, fmt.Errorf("%w: unable to "+
2✔
3799
                        "fetch utxo for chan_id=%v, chan_point=%v: %w",
2✔
3800
                        ErrChannelSpent, scid.ToUint64(), fundingPoint, err)
2✔
3801
        }
3802

3803
        return *fundingPoint, btcutil.Amount(chanUtxo.Value), fundingPkScript,
25✔
3804
                nil
25✔
3805
}
3806

3807
// makeFundingScript is used to make the funding script for both segwit v0 and
3808
// segwit v1 (taproot) channels.
3809
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte,
3810
        features *lnwire.RawFeatureVector,
3811
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
228✔
3812

228✔
3813
        legacyFundingScript := func() ([]byte, error) {
456✔
3814
                witnessScript, err := input.GenMultiSigScript(
228✔
3815
                        bitcoinKey1, bitcoinKey2,
228✔
3816
                )
228✔
3817
                if err != nil {
228✔
3818
                        return nil, err
×
3819
                }
×
3820
                pkScript, err := input.WitnessScriptHash(witnessScript)
228✔
3821
                if err != nil {
228✔
3822
                        return nil, err
×
3823
                }
×
3824

3825
                return pkScript, nil
228✔
3826
        }
3827

3828
        if features.IsEmpty() {
456✔
3829
                return legacyFundingScript()
228✔
3830
        }
228✔
3831

3832
        chanFeatureBits := lnwire.NewFeatureVector(features, lnwire.Features)
×
3833
        if chanFeatureBits.HasFeature(
×
3834
                lnwire.SimpleTaprootChannelsOptionalStaging,
×
3835
        ) {
×
3836

×
3837
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
×
3838
                if err != nil {
×
3839
                        return nil, err
×
3840
                }
×
3841
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
×
3842
                if err != nil {
×
3843
                        return nil, err
×
3844
                }
×
3845

3846
                fundingScript, _, err := input.GenTaprootFundingScript(
×
3847
                        pubKey1, pubKey2, 0, tapscriptRoot,
×
3848
                )
×
3849
                if err != nil {
×
3850
                        return nil, err
×
3851
                }
×
3852

3853
                // TODO(roasbeef): add tapscript root to gossip v1.5
3854

3855
                return fundingScript, nil
×
3856
        }
3857

3858
        return legacyFundingScript()
×
3859
}
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