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

lightningnetwork / lnd / 13423774416

19 Feb 2025 10:39PM UTC coverage: 49.338% (-9.5%) from 58.794%
13423774416

Pull #9484

github

Abdulkbk
lnutils: add createdir util function

This utility function replaces repetitive logic patterns
throughout LND.
Pull Request #9484: lnutils: add createDir util function

0 of 13 new or added lines in 1 file covered. (0.0%)

27149 existing lines in 431 files now uncovered.

100732 of 204168 relevant lines covered (49.34%)

1.54 hits per line

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

60.54
/graph/builder.go
1
package graph
2

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

11
        "github.com/btcsuite/btcd/btcec/v2"
12
        "github.com/btcsuite/btcd/btcutil"
13
        "github.com/btcsuite/btcd/chaincfg/chainhash"
14
        "github.com/btcsuite/btcd/wire"
15
        "github.com/go-errors/errors"
16
        "github.com/lightningnetwork/lnd/batch"
17
        "github.com/lightningnetwork/lnd/chainntnfs"
18
        "github.com/lightningnetwork/lnd/fn/v2"
19
        graphdb "github.com/lightningnetwork/lnd/graph/db"
20
        "github.com/lightningnetwork/lnd/graph/db/models"
21
        "github.com/lightningnetwork/lnd/input"
22
        "github.com/lightningnetwork/lnd/kvdb"
23
        "github.com/lightningnetwork/lnd/lnutils"
24
        "github.com/lightningnetwork/lnd/lnwallet"
25
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
26
        "github.com/lightningnetwork/lnd/lnwallet/chanvalidate"
27
        "github.com/lightningnetwork/lnd/lnwire"
28
        "github.com/lightningnetwork/lnd/multimutex"
29
        "github.com/lightningnetwork/lnd/netann"
30
        "github.com/lightningnetwork/lnd/routing/chainview"
31
        "github.com/lightningnetwork/lnd/routing/route"
32
        "github.com/lightningnetwork/lnd/ticker"
33
)
34

35
const (
36
        // DefaultChannelPruneExpiry is the default duration used to determine
37
        // if a channel should be pruned or not.
38
        DefaultChannelPruneExpiry = time.Hour * 24 * 14
39

40
        // DefaultFirstTimePruneDelay is the time we'll wait after startup
41
        // before attempting to prune the graph for zombie channels. We don't
42
        // do it immediately after startup to allow lnd to start up without
43
        // getting blocked by this job.
44
        DefaultFirstTimePruneDelay = 30 * time.Second
45

46
        // defaultStatInterval governs how often the router will log non-empty
47
        // stats related to processing new channels, updates, or node
48
        // announcements.
49
        defaultStatInterval = time.Minute
50
)
51

52
var (
53
        // ErrGraphBuilderShuttingDown is returned if the graph builder is in
54
        // the process of shutting down.
55
        ErrGraphBuilderShuttingDown = fmt.Errorf("graph builder shutting down")
56
)
57

58
// Config holds the configuration required by the Builder.
59
type Config struct {
60
        // SelfNode is the public key of the node that this channel router
61
        // belongs to.
62
        SelfNode route.Vertex
63

64
        // Graph is the channel graph that the ChannelRouter will use to gather
65
        // metrics from and also to carry out path finding queries.
66
        Graph DB
67

68
        // Chain is the router's source to the most up-to-date blockchain data.
69
        // All incoming advertised channels will be checked against the chain
70
        // to ensure that the channels advertised are still open.
71
        Chain lnwallet.BlockChainIO
72

73
        // ChainView is an instance of a FilteredChainView which is used to
74
        // watch the sub-set of the UTXO set (the set of active channels) that
75
        // we need in order to properly maintain the channel graph.
76
        ChainView chainview.FilteredChainView
77

78
        // Notifier is a reference to the ChainNotifier, used to grab
79
        // the latest blocks if the router is missing any.
80
        Notifier chainntnfs.ChainNotifier
81

82
        // ChannelPruneExpiry is the duration used to determine if a channel
83
        // should be pruned or not. If the delta between now and when the
84
        // channel was last updated is greater than ChannelPruneExpiry, then
85
        // the channel is marked as a zombie channel eligible for pruning.
86
        ChannelPruneExpiry time.Duration
87

88
        // GraphPruneInterval is used as an interval to determine how often we
89
        // should examine the channel graph to garbage collect zombie channels.
90
        GraphPruneInterval time.Duration
91

92
        // FirstTimePruneDelay is the time we'll wait after startup before
93
        // attempting to prune the graph for zombie channels. We don't do it
94
        // immediately after startup to allow lnd to start up without getting
95
        // blocked by this job.
96
        FirstTimePruneDelay time.Duration
97

98
        // AssumeChannelValid toggles whether the router will check for
99
        // spentness of channel outpoints. For neutrino, this saves long rescans
100
        // from blocking initial usage of the daemon.
101
        AssumeChannelValid bool
102

103
        // StrictZombiePruning determines if we attempt to prune zombie
104
        // channels according to a stricter criteria. If true, then we'll prune
105
        // a channel if only *one* of the edges is considered a zombie.
106
        // Otherwise, we'll only prune the channel when both edges have a very
107
        // dated last update.
108
        StrictZombiePruning bool
109

110
        // IsAlias returns whether a passed ShortChannelID is an alias. This is
111
        // only used for our local channels.
112
        IsAlias func(scid lnwire.ShortChannelID) bool
113
}
114

115
// Builder builds and maintains a view of the Lightning Network graph.
116
type Builder struct {
117
        started atomic.Bool
118
        stopped atomic.Bool
119

120
        ntfnClientCounter atomic.Uint64
121
        bestHeight        atomic.Uint32
122

123
        cfg *Config
124

125
        // newBlocks is a channel in which new blocks connected to the end of
126
        // the main chain are sent over, and blocks updated after a call to
127
        // UpdateFilter.
128
        newBlocks <-chan *chainview.FilteredBlock
129

130
        // staleBlocks is a channel in which blocks disconnected from the end
131
        // of our currently known best chain are sent over.
132
        staleBlocks <-chan *chainview.FilteredBlock
133

134
        // networkUpdates is a channel that carries new topology updates
135
        // messages from outside the Builder to be processed by the
136
        // networkHandler.
137
        networkUpdates chan *routingMsg
138

139
        // topologyClients maps a client's unique notification ID to a
140
        // topologyClient client that contains its notification dispatch
141
        // channel.
142
        topologyClients *lnutils.SyncMap[uint64, *topologyClient]
143

144
        // ntfnClientUpdates is a channel that's used to send new updates to
145
        // topology notification clients to the Builder. Updates either
146
        // add a new notification client, or cancel notifications for an
147
        // existing client.
148
        ntfnClientUpdates chan *topologyClientUpdate
149

150
        // channelEdgeMtx is a mutex we use to make sure we process only one
151
        // ChannelEdgePolicy at a time for a given channelID, to ensure
152
        // consistency between the various database accesses.
153
        channelEdgeMtx *multimutex.Mutex[uint64]
154

155
        // statTicker is a resumable ticker that logs the router's progress as
156
        // it discovers channels or receives updates.
157
        statTicker ticker.Ticker
158

159
        // stats tracks newly processed channels, updates, and node
160
        // announcements over a window of defaultStatInterval.
161
        stats *routerStats
162

163
        quit chan struct{}
164
        wg   sync.WaitGroup
3✔
165
}
3✔
166

3✔
167
// A compile time check to ensure Builder implements the
3✔
168
// ChannelGraphSource interface.
3✔
169
var _ ChannelGraphSource = (*Builder)(nil)
3✔
170

3✔
171
// NewBuilder constructs a new Builder.
3✔
172
func NewBuilder(cfg *Config) (*Builder, error) {
3✔
173
        return &Builder{
3✔
174
                cfg:               cfg,
3✔
175
                networkUpdates:    make(chan *routingMsg),
3✔
176
                topologyClients:   &lnutils.SyncMap[uint64, *topologyClient]{},
177
                ntfnClientUpdates: make(chan *topologyClientUpdate),
178
                channelEdgeMtx:    multimutex.NewMutex[uint64](),
179
                statTicker:        ticker.New(defaultStatInterval),
3✔
180
                stats:             new(routerStats),
3✔
181
                quit:              make(chan struct{}),
×
182
        }, nil
×
183
}
184

3✔
185
// Start launches all the goroutines the Builder requires to carry out its
3✔
186
// duties. If the builder has already been started, then this method is a noop.
3✔
187
func (b *Builder) Start() error {
3✔
188
        if !b.started.CompareAndSwap(false, true) {
×
189
                return nil
×
190
        }
191

192
        log.Info("Builder starting")
193

6✔
194
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
3✔
195
        if err != nil {
3✔
196
                return err
3✔
197
        }
198

3✔
199
        // If the graph has never been pruned, or hasn't fully been created yet,
3✔
200
        // then we don't treat this as an explicit error.
3✔
201
        if _, _, err := b.cfg.Graph.PruneTip(); err != nil {
3✔
202
                switch {
3✔
203
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
3✔
204
                        fallthrough
3✔
205

3✔
206
                case errors.Is(err, graphdb.ErrGraphNotFound):
×
207
                        // If the graph has never been pruned, then we'll set
×
208
                        // the prune height to the current best height of the
209
                        // chain backend.
×
210
                        _, err = b.cfg.Graph.PruneGraph(
×
211
                                nil, bestHash, uint32(bestHeight),
212
                        )
213
                        if err != nil {
214
                                return err
215
                        }
216

217
                default:
218
                        return err
3✔
UNCOV
219
                }
×
UNCOV
220
        }
×
221

×
222
        // If AssumeChannelValid is present, then we won't rely on pruning
×
UNCOV
223
        // channels from the graph based on their spentness, but whether they
×
224
        // are considered zombies or not. We will start zombie pruning after a
225
        // small delay, to avoid slowing down startup of lnd.
UNCOV
226
        if b.cfg.AssumeChannelValid { //nolint:nestif
×
UNCOV
227
                time.AfterFunc(b.cfg.FirstTimePruneDelay, func() {
×
228
                        select {
×
229
                        case <-b.quit:
×
230
                                return
231
                        default:
3✔
232
                        }
3✔
233

3✔
234
                        log.Info("Initial zombie prune starting")
3✔
235
                        if err := b.pruneZombieChans(); err != nil {
×
236
                                log.Errorf("Unable to prune zombies: %v", err)
×
237
                        }
238
                })
239
        } else {
240
                // Otherwise, we'll use our filtered chain view to prune
3✔
241
                // channels as soon as they are detected as spent on-chain.
3✔
242
                if err := b.cfg.ChainView.Start(); err != nil {
3✔
243
                        return err
3✔
244
                }
3✔
245

3✔
246
                // Once the instance is active, we'll fetch the channel we'll
3✔
247
                // receive notifications over.
3✔
248
                b.newBlocks = b.cfg.ChainView.FilteredBlocks()
3✔
249
                b.staleBlocks = b.cfg.ChainView.DisconnectedBlocks()
3✔
250

3✔
251
                // Before we perform our manual block pruning, we'll construct
3✔
252
                // and apply a fresh chain filter to the active
×
253
                // FilteredChainView instance.  We do this before, as otherwise
×
254
                // we may miss on-chain events as the filter hasn't properly
×
255
                // been applied.
256
                channelView, err := b.cfg.Graph.ChannelView()
3✔
257
                if err != nil && !errors.Is(
3✔
258
                        err, graphdb.ErrGraphNoEdgesFound,
3✔
259
                ) {
6✔
260

3✔
261
                        return err
3✔
262
                }
3✔
263

3✔
264
                log.Infof("Filtering chain using %v channels active",
×
265
                        len(channelView))
×
266

267
                if len(channelView) != 0 {
268
                        err = b.cfg.ChainView.UpdateFilter(
269
                                channelView, uint32(bestHeight),
270
                        )
3✔
271
                        if err != nil {
3✔
272
                                return err
×
273
                        }
×
274
                }
3✔
275

3✔
276
                // The graph pruning might have taken a while and there could be
3✔
277
                // new blocks available.
3✔
278
                _, bestHeight, err = b.cfg.Chain.GetBestBlock()
3✔
279
                if err != nil {
3✔
280
                        return err
×
281
                }
×
282
                b.bestHeight.Store(uint32(bestHeight))
283

284
                // Before we begin normal operation of the router, we first need
285
                // to synchronize the channel graph to the latest state of the
286
                // UTXO set.
3✔
287
                if err := b.syncGraphWithChain(); err != nil {
3✔
288
                        return err
3✔
289
                }
×
290

×
291
                // Finally, before we proceed, we'll prune any unconnected nodes
×
292
                // from the graph in order to ensure we maintain a tight graph
293
                // of "useful" nodes.
294
                err = b.cfg.Graph.PruneGraphNodes()
3✔
295
                if err != nil &&
3✔
296
                        !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
3✔
297

3✔
298
                        return err
3✔
299
                }
3✔
300
        }
301

302
        b.wg.Add(1)
303
        go b.networkHandler()
304

305
        log.Debug("Builder started")
3✔
306

3✔
UNCOV
307
        return nil
×
UNCOV
308
}
×
309

310
// Stop signals to the Builder that it should halt all routines. This method
3✔
311
// will *block* until all goroutines have excited. If the builder has already
3✔
312
// stopped then this method will return immediately.
3✔
313
func (b *Builder) Stop() error {
3✔
314
        if !b.stopped.CompareAndSwap(false, true) {
6✔
315
                return nil
3✔
316
        }
×
317

×
318
        log.Info("Builder shutting down...")
319

320
        // Our filtered chain view could've only been started if
3✔
321
        // AssumeChannelValid isn't present.
3✔
322
        if !b.cfg.AssumeChannelValid {
3✔
323
                if err := b.cfg.ChainView.Stop(); err != nil {
3✔
324
                        return err
3✔
325
                }
3✔
326
        }
327

328
        close(b.quit)
329
        b.wg.Wait()
330

331
        log.Debug("Builder shutdown complete")
332

3✔
333
        return nil
3✔
334
}
3✔
335

3✔
336
// syncGraphWithChain attempts to synchronize the current channel graph with
3✔
337
// the latest UTXO set state. This process involves pruning from the channel
×
338
// graph any channels which have been closed by spending their funding output
×
339
// since we've been down.
3✔
340
func (b *Builder) syncGraphWithChain() error {
3✔
341
        // First, we'll need to check to see if we're already in sync with the
3✔
342
        // latest state of the UTXO set.
3✔
343
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
×
344
        if err != nil {
345
                return err
346
        }
×
347
        b.bestHeight.Store(uint32(bestHeight))
×
348

×
349
        pruneHash, pruneHeight, err := b.cfg.Graph.PruneTip()
×
350
        if err != nil {
351
                switch {
352
                // If the graph has never been pruned, or hasn't fully been
353
                // created yet, then we don't treat this as an explicit error.
3✔
354
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
3✔
355
                case errors.Is(err, graphdb.ErrGraphNotFound):
3✔
356
                default:
3✔
357
                        return err
358
                }
359
        }
UNCOV
360

×
UNCOV
361
        log.Infof("Prune tip for Channel Graph: height=%v, hash=%v",
×
362
                pruneHeight, pruneHash)
363

364
        switch {
365
        // If the graph has never been pruned, then we can exit early as this
3✔
366
        // entails it's being created for the first time and hasn't seen any
3✔
367
        // block or created channels.
368
        case pruneHeight == 0 || pruneHash == nil:
369
                return nil
370

371
        // If the block hashes and heights match exactly, then we don't need to
3✔
372
        // prune the channel graph as we're already fully in sync.
3✔
373
        case bestHash.IsEqual(pruneHash) && uint32(bestHeight) == pruneHeight:
×
374
                return nil
×
375
        }
376

377
        // If the main chain blockhash at prune height is different from the
378
        // prune hash, this might indicate the database is on a stale branch.
3✔
UNCOV
379
        mainBlockHash, err := b.cfg.Chain.GetBlockHash(int64(pruneHeight))
×
UNCOV
380
        if err != nil {
×
UNCOV
381
                return err
×
UNCOV
382
        }
×
UNCOV
383

×
UNCOV
384
        // While we are on a stale branch of the chain, walk backwards to find
×
385
        // first common block.
×
386
        for !pruneHash.IsEqual(mainBlockHash) {
×
387
                log.Infof("channel graph is stale. Disconnecting block %v "+
UNCOV
388
                        "(hash=%v)", pruneHeight, pruneHash)
×
UNCOV
389
                // Prune the graph for every channel that was opened at height
×
390
                // >= pruneHeight.
391
                _, err := b.cfg.Graph.DisconnectBlockAtHeight(pruneHeight)
392
                if err != nil {
393
                        return err
394
                }
×
395

×
396
                pruneHash, pruneHeight, err = b.cfg.Graph.PruneTip()
397
                switch {
×
398
                // If at this point the graph has never been pruned, we can exit
×
399
                // as this entails we are back to the point where it hasn't seen
400
                // any block or created channels, alas there's nothing left to
×
401
                // prune.
×
402
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
UNCOV
403
                        return nil
×
404

405
                case errors.Is(err, graphdb.ErrGraphNotFound):
UNCOV
406
                        return nil
×
UNCOV
407

×
UNCOV
408
                case err != nil:
×
UNCOV
409
                        return err
×
410

×
411
                default:
×
412
                }
413

414
                mainBlockHash, err = b.cfg.Chain.GetBlockHash(
3✔
415
                        int64(pruneHeight),
3✔
416
                )
3✔
417
                if err != nil {
3✔
418
                        return err
3✔
419
                }
3✔
420
        }
3✔
421

3✔
422
        log.Infof("Syncing channel graph from height=%v (hash=%v) to "+
6✔
423
                "height=%v (hash=%v)", pruneHeight, pruneHash, bestHeight,
3✔
424
                bestHash)
3✔
425

3✔
426
        // If we're not yet caught up, then we'll walk forward in the chain
3✔
427
        // pruning the channel graph with each new block that hasn't yet been
×
428
        // consumed by the channel graph.
×
429
        var spentOutputs []*wire.OutPoint
3✔
430
        for nextHeight := pruneHeight + 1; nextHeight <= uint32(bestHeight); nextHeight++ { //nolint:ll
431
                // Break out of the rescan early if a shutdown has been
432
                // requested, otherwise long rescans will block the daemon from
433
                // shutting down promptly.
434
                select {
3✔
435
                case <-b.quit:
3✔
436
                        return ErrGraphBuilderShuttingDown
3✔
437
                default:
3✔
438
                }
×
439

×
440
                // Using the next height, request a manual block pruning from
3✔
441
                // the chainview for the particular block hash.
3✔
442
                log.Infof("Filtering block for closed channels, at height: %v",
3✔
443
                        int64(nextHeight))
3✔
444
                nextHash, err := b.cfg.Chain.GetBlockHash(int64(nextHeight))
×
445
                if err != nil {
×
446
                        return err
447
                }
448
                log.Tracef("Running block filter on block with hash: %v",
449
                        nextHash)
450
                filterBlock, err := b.cfg.ChainView.FilterBlock(nextHash)
6✔
451
                if err != nil {
6✔
452
                        return err
3✔
453
                }
3✔
454

3✔
455
                // We're only interested in all prior outputs that have been
456
                // spent in the block, so collate all the referenced previous
457
                // outpoints within each tx and input.
458
                for _, tx := range filterBlock.Transactions {
459
                        for _, txIn := range tx.TxIn {
460
                                spentOutputs = append(spentOutputs,
3✔
461
                                        &txIn.PreviousOutPoint)
3✔
462
                        }
3✔
463
                }
3✔
464
        }
×
465

×
466
        // With the spent outputs gathered, attempt to prune the channel graph,
467
        // also passing in the best hash+height so the prune tip can be updated.
3✔
468
        closedChans, err := b.cfg.Graph.PruneGraph(
3✔
469
                spentOutputs, bestHash, uint32(bestHeight),
3✔
470
        )
3✔
471
        if err != nil {
472
                return err
473
        }
474

475
        log.Infof("Graph pruning complete: %v channels were closed since "+
476
                "height %v", len(closedChans), pruneHeight)
477

478
        return nil
UNCOV
479
}
×
UNCOV
480

×
UNCOV
481
// isZombieChannel takes two edge policy updates and determines if the
×
UNCOV
482
// corresponding channel should be considered a zombie. The first boolean is
×
UNCOV
483
// true if the policy update from node 1 is considered a zombie, the second
×
UNCOV
484
// boolean is that of node 2, and the final boolean is true if the channel
×
UNCOV
485
// is considered a zombie.
×
UNCOV
486
func (b *Builder) isZombieChannel(e1,
×
UNCOV
487
        e2 *models.ChannelEdgePolicy) (bool, bool, bool) {
×
UNCOV
488

×
UNCOV
489
        chanExpiry := b.cfg.ChannelPruneExpiry
×
UNCOV
490

×
UNCOV
491
        e1Zombie := e1 == nil || time.Since(e1.LastUpdate) >= chanExpiry
×
UNCOV
492
        e2Zombie := e2 == nil || time.Since(e2.LastUpdate) >= chanExpiry
×
493

UNCOV
494
        var e1Time, e2Time time.Time
×
495
        if e1 != nil {
496
                e1Time = e1.LastUpdate
497
        }
498
        if e2 != nil {
499
                e2Time = e2.LastUpdate
500
        }
501

3✔
502
        return e1Zombie, e2Zombie, b.IsZombieChannel(e1Time, e2Time)
3✔
503
}
3✔
504

3✔
505
// IsZombieChannel takes the timestamps of the latest channel updates for a
3✔
506
// channel and returns true if the channel should be considered a zombie based
3✔
507
// on these timestamps.
3✔
508
func (b *Builder) IsZombieChannel(updateTime1,
3✔
509
        updateTime2 time.Time) bool {
3✔
510

3✔
511
        chanExpiry := b.cfg.ChannelPruneExpiry
3✔
512

3✔
513
        e1Zombie := updateTime1.IsZero() ||
4✔
514
                time.Since(updateTime1) >= chanExpiry
1✔
515

1✔
516
        e2Zombie := updateTime2.IsZero() ||
517
                time.Since(updateTime2) >= chanExpiry
518

519
        // If we're using strict zombie pruning, then a channel is only
2✔
520
        // considered live if both edges have a recent update we know of.
521
        if b.cfg.StrictZombiePruning {
522
                return e1Zombie || e2Zombie
523
        }
524

525
        // Otherwise, if we're using the less strict variant, then a channel is
526
        // considered live if either of the edges have a recent update.
527
        return e1Zombie && e2Zombie
UNCOV
528
}
×
UNCOV
529

×
UNCOV
530
// pruneZombieChans is a method that will be called periodically to prune out
×
UNCOV
531
// any "zombie" channels. We consider channels zombies if *both* edges haven't
×
UNCOV
532
// been updated since our zombie horizon. If AssumeChannelValid is present,
×
UNCOV
533
// we'll also consider channels zombies if *both* edges are disabled. This
×
UNCOV
534
// usually signals that a channel has been closed on-chain. We do this
×
UNCOV
535
// periodically to keep a healthy, lively routing table.
×
UNCOV
536
func (b *Builder) pruneZombieChans() error {
×
UNCOV
537
        chansToPrune := make(map[uint64]struct{})
×
UNCOV
538
        chanExpiry := b.cfg.ChannelPruneExpiry
×
539

540
        log.Infof("Examining channel graph for zombie channels")
541

UNCOV
542
        // A helper method to detect if the channel belongs to this node
×
UNCOV
543
        isSelfChannelEdge := func(info *models.ChannelEdgeInfo) bool {
×
UNCOV
544
                return info.NodeKey1Bytes == b.cfg.SelfNode ||
×
UNCOV
545
                        info.NodeKey2Bytes == b.cfg.SelfNode
×
UNCOV
546
        }
×
UNCOV
547

×
UNCOV
548
        // First, we'll collect all the channels which are eligible for garbage
×
549
        // collection due to being zombies.
×
550
        filterPruneChans := func(info *models.ChannelEdgeInfo,
×
551
                e1, e2 *models.ChannelEdgePolicy) error {
552

553
                // Exit early in case this channel is already marked to be
554
                // pruned
UNCOV
555
                _, markedToPrune := chansToPrune[info.ChannelID]
×
UNCOV
556
                if markedToPrune {
×
UNCOV
557
                        return nil
×
558
                }
UNCOV
559

×
UNCOV
560
                // We'll ensure that we don't attempt to prune our *own*
×
UNCOV
561
                // channels from the graph, as in any case this should be
×
UNCOV
562
                // re-advertised by the sub-system above us.
×
UNCOV
563
                if isSelfChannelEdge(info) {
×
UNCOV
564
                        return nil
×
565
                }
UNCOV
566

×
UNCOV
567
                e1Zombie, e2Zombie, isZombieChan := b.isZombieChannel(e1, e2)
×
UNCOV
568

×
UNCOV
569
                if e1Zombie {
×
570
                        log.Tracef("Node1 pubkey=%x of chan_id=%v is zombie",
571
                                info.NodeKey1Bytes, info.ChannelID)
572
                }
573

UNCOV
574
                if e2Zombie {
×
UNCOV
575
                        log.Tracef("Node2 pubkey=%x of chan_id=%v is zombie",
×
UNCOV
576
                                info.NodeKey2Bytes, info.ChannelID)
×
577
                }
UNCOV
578

×
UNCOV
579
                // If either edge hasn't been updated for a period of
×
UNCOV
580
                // chanExpiry, then we'll mark the channel itself as eligible
×
UNCOV
581
                // for graph pruning.
×
UNCOV
582
                if !isZombieChan {
×
UNCOV
583
                        return nil
×
UNCOV
584
                }
×
585

586
                log.Debugf("ChannelID(%v) is a zombie, collecting to prune",
587
                        info.ChannelID)
588

589
                // TODO(roasbeef): add ability to delete single directional edge
UNCOV
590
                chansToPrune[info.ChannelID] = struct{}{}
×
UNCOV
591

×
UNCOV
592
                return nil
×
593
        }
×
594

×
595
        // If AssumeChannelValid is present we'll look at the disabled bit for
×
596
        // both edges. If they're both disabled, then we can interpret this as
UNCOV
597
        // the channel being closed and can prune it from our graph.
×
UNCOV
598
        if b.cfg.AssumeChannelValid {
×
UNCOV
599
                disabledChanIDs, err := b.cfg.Graph.DisabledChannelIDs()
×
UNCOV
600
                if err != nil {
×
601
                        return fmt.Errorf("unable to get disabled channels "+
×
602
                                "ids chans: %v", err)
×
603
                }
×
604

605
                disabledEdges, err := b.cfg.Graph.FetchChanInfos(
UNCOV
606
                        disabledChanIDs,
×
UNCOV
607
                )
×
UNCOV
608
                if err != nil {
×
UNCOV
609
                        return fmt.Errorf("unable to fetch disabled channels "+
×
UNCOV
610
                                "edges chans: %v", err)
×
611
                }
612

613
                // Ensuring we won't prune our own channel from the graph.
UNCOV
614
                for _, disabledEdge := range disabledEdges {
×
UNCOV
615
                        if !isSelfChannelEdge(disabledEdge.Info) {
×
UNCOV
616
                                chansToPrune[disabledEdge.Info.ChannelID] =
×
UNCOV
617
                                        struct{}{}
×
618
                        }
×
619
                }
×
620
        }
×
621

UNCOV
622
        startTime := time.Unix(0, 0)
×
UNCOV
623
        endTime := time.Now().Add(-1 * chanExpiry)
×
UNCOV
624
        oldEdges, err := b.cfg.Graph.ChanUpdatesInHorizon(startTime, endTime)
×
625
        if err != nil {
×
626
                return fmt.Errorf("unable to fetch expired channel updates "+
×
627
                        "chans: %v", err)
×
628
        }
629

UNCOV
630
        for _, u := range oldEdges {
×
UNCOV
631
                err = filterPruneChans(u.Info, u.Policy1, u.Policy2)
×
UNCOV
632
                if err != nil {
×
UNCOV
633
                        return fmt.Errorf("error filtering channels to "+
×
634
                                "prune: %w", err)
635
                }
636
        }
UNCOV
637

×
UNCOV
638
        log.Infof("Pruning %v zombie channels", len(chansToPrune))
×
UNCOV
639
        if len(chansToPrune) == 0 {
×
UNCOV
640
                return nil
×
UNCOV
641
        }
×
UNCOV
642

×
UNCOV
643
        // With the set of zombie-like channels obtained, we'll do another pass
×
UNCOV
644
        // to delete them from the channel graph.
×
UNCOV
645
        toPrune := make([]uint64, 0, len(chansToPrune))
×
646
        for chanID := range chansToPrune {
×
647
                toPrune = append(toPrune, chanID)
×
648
                log.Tracef("Pruning zombie channel with ChannelID(%v)", chanID)
649
        }
650
        err = b.cfg.Graph.DeleteChannelEdges(
UNCOV
651
                b.cfg.StrictZombiePruning, true, toPrune...,
×
UNCOV
652
        )
×
653
        if err != nil {
×
654
                return fmt.Errorf("unable to delete zombie channels: %w", err)
×
655
        }
UNCOV
656

×
657
        // With the channels pruned, we'll also attempt to prune any nodes that
658
        // were a part of them.
659
        err = b.cfg.Graph.PruneGraphNodes()
660
        if err != nil && !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
661
                return fmt.Errorf("unable to prune graph nodes: %w", err)
662
        }
663

3✔
664
        return nil
3✔
665
}
3✔
666

3✔
667
// handleNetworkUpdate is responsible for processing the update message and
3✔
668
// notifies topology changes, if any.
3✔
669
//
3✔
670
// NOTE: must be run inside goroutine.
3✔
671
func (b *Builder) handleNetworkUpdate(update *routingMsg) {
3✔
672
        defer b.wg.Done()
3✔
673

674
        // Process the routing update to determine if this is either a new
3✔
675
        // update from our PoV or an update to a prior vertex/edge we
3✔
676
        // previously accepted.
677
        err := b.processUpdate(update.msg, update.op...)
3✔
678
        update.err <- err
3✔
679

680
        // If the error is not nil here, there's no need to send topology
×
681
        // change.
×
682
        if err != nil {
683
                // Log as a debug message if this is not an error we need to be
3✔
684
                // concerned about.
3✔
685
                if IsError(err, ErrIgnored, ErrOutdated) {
3✔
686
                        log.Debugf("process network updates got: %v", err)
3✔
687
                } else {
6✔
688
                        log.Errorf("process network updates got: %v", err)
3✔
689
                }
3✔
690

6✔
691
                return
3✔
692
        }
3✔
693

×
694
        // Otherwise, we'll send off a new notification for the newly accepted
×
695
        // update, if any.
696
        topChange := &TopologyChange{}
3✔
697
        err = addToTopologyChange(b.cfg.Graph, topChange, update.msg)
698
        if err != nil {
699
                log.Errorf("unable to update topology change notification: %v",
700
                        err)
701
                return
3✔
702
        }
3✔
703

3✔
704
        if !topChange.isEmpty() {
×
705
                b.notifyTopologyChange(topChange)
×
706
        }
×
707
}
×
708

709
// networkHandler is the primary goroutine for the Builder. The roles of
6✔
710
// this goroutine include answering queries related to the state of the
3✔
711
// network, pruning the graph on new block notification, applying network
3✔
712
// updates, and registering new topology clients.
713
//
714
// NOTE: This MUST be run as a goroutine.
715
func (b *Builder) networkHandler() {
716
        defer b.wg.Done()
717

718
        graphPruneTicker := time.NewTicker(b.cfg.GraphPruneInterval)
719
        defer graphPruneTicker.Stop()
720

3✔
721
        defer b.statTicker.Stop()
3✔
722

3✔
723
        b.stats.Reset()
3✔
724

3✔
725
        for {
3✔
726
                // If there are stats, resume the statTicker.
3✔
727
                if !b.stats.Empty() {
3✔
728
                        b.statTicker.Resume()
3✔
729
                }
3✔
730

6✔
731
                select {
3✔
732
                // A new fully validated network update has just arrived. As a
6✔
733
                // result we'll modify the channel graph accordingly depending
3✔
734
                // on the exact type of the message.
3✔
735
                case update := <-b.networkUpdates:
736
                        b.wg.Add(1)
3✔
737
                        go b.handleNetworkUpdate(update)
738

739
                        // TODO(roasbeef): remove all unconnected vertexes
740
                        // after N blocks pass with no corresponding
3✔
741
                        // announcements.
3✔
742

3✔
743
                case chainUpdate, ok := <-b.staleBlocks:
744
                        // If the channel has been closed, then this indicates
745
                        // the daemon is shutting down, so we exit ourselves.
746
                        if !ok {
747
                                return
748
                        }
2✔
749

2✔
750
                        // Since this block is stale, we update our best height
2✔
751
                        // to the previous block.
2✔
752
                        blockHeight := chainUpdate.Height
×
753
                        b.bestHeight.Store(blockHeight - 1)
×
754

755
                        // Update the channel graph to reflect that this block
756
                        // was disconnected.
757
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
2✔
758
                                blockHeight,
2✔
759
                        )
2✔
760
                        if err != nil {
2✔
761
                                log.Errorf("unable to prune graph with stale "+
2✔
762
                                        "block: %v", err)
2✔
763
                                continue
2✔
764
                        }
2✔
765

2✔
766
                        // TODO(halseth): notify client about the reorg?
×
767

×
768
                // A new block has arrived, so we can prune the channel graph
×
769
                // of any channels which were closed in the block.
770
                case chainUpdate, ok := <-b.newBlocks:
771
                        // If the channel has been closed, then this indicates
772
                        // the daemon is shutting down, so we exit ourselves.
773
                        if !ok {
774
                                return
775
                        }
3✔
776

3✔
777
                        // We'll ensure that any new blocks received attach
3✔
778
                        // directly to the end of our main chain. If not, then
3✔
779
                        // we've somehow missed some blocks. Here we'll catch
×
780
                        // up the chain with the latest blocks.
×
781
                        currentHeight := b.bestHeight.Load()
782
                        switch {
783
                        case chainUpdate.Height == currentHeight+1:
784
                                err := b.updateGraphWithClosedChannels(
785
                                        chainUpdate,
786
                                )
3✔
787
                                if err != nil {
3✔
788
                                        log.Errorf("unable to prune graph "+
3✔
789
                                                "with closed channels: %v", err)
3✔
790
                                }
3✔
791

3✔
792
                        case chainUpdate.Height > currentHeight+1:
3✔
793
                                log.Errorf("out of order block: expecting "+
×
794
                                        "height=%v, got height=%v",
×
795
                                        currentHeight+1, chainUpdate.Height)
×
796

UNCOV
797
                                err := b.getMissingBlocks(
×
UNCOV
798
                                        currentHeight, chainUpdate,
×
UNCOV
799
                                )
×
UNCOV
800
                                if err != nil {
×
UNCOV
801
                                        log.Errorf("unable to retrieve missing"+
×
UNCOV
802
                                                "blocks: %v", err)
×
UNCOV
803
                                }
×
UNCOV
804

×
UNCOV
805
                        case chainUpdate.Height < currentHeight+1:
×
806
                                log.Errorf("out of order block: expecting "+
×
807
                                        "height=%v, got height=%v",
×
808
                                        currentHeight+1, chainUpdate.Height)
×
809

810
                                log.Infof("Skipping channel pruning since "+
1✔
811
                                        "received block height %v was already"+
1✔
812
                                        " processed.", chainUpdate.Height)
1✔
813
                        }
1✔
814

1✔
815
                // A new notification client update has arrived. We're either
1✔
816
                // gaining a new client, or cancelling notifications for an
1✔
817
                // existing client.
1✔
818
                case ntfnUpdate := <-b.ntfnClientUpdates:
819
                        clientID := ntfnUpdate.clientID
820

821
                        if ntfnUpdate.cancel {
822
                                client, ok := b.topologyClients.LoadAndDelete(
823
                                        clientID,
3✔
824
                                )
3✔
825
                                if ok {
3✔
826
                                        close(client.exit)
6✔
827
                                        client.wg.Wait()
3✔
828

3✔
829
                                        close(client.ntfnChan)
3✔
830
                                }
6✔
831

3✔
832
                                continue
3✔
833
                        }
3✔
834

3✔
835
                        b.topologyClients.Store(clientID, &topologyClient{
3✔
836
                                ntfnChan: ntfnUpdate.ntfnChan,
837
                                exit:     make(chan struct{}),
3✔
838
                        })
839

840
                // The graph prune ticker has ticked, so we'll examine the
3✔
841
                // state of the known graph to filter out any zombie channels
3✔
842
                // for pruning.
3✔
843
                case <-graphPruneTicker.C:
3✔
844
                        if err := b.pruneZombieChans(); err != nil {
845
                                log.Errorf("Unable to prune zombies: %v", err)
846
                        }
847

848
                // Log any stats if we've processed a non-empty number of
×
849
                // channels, updates, or nodes. We'll only pause the ticker if
×
850
                // the last window contained no updates to avoid resuming and
×
851
                // pausing while consecutive windows contain new info.
×
852
                case <-b.statTicker.Ticks():
853
                        if !b.stats.Empty() {
854
                                log.Infof(b.stats.String())
855
                        } else {
856
                                b.statTicker.Pause()
857
                        }
3✔
858
                        b.stats.Reset()
6✔
859

3✔
860
                // The router has been signalled to exit, to we exit our main
3✔
861
                // loop so the wait group can be decremented.
×
862
                case <-b.quit:
×
863
                        return
3✔
864
                }
865
        }
866
}
867

3✔
868
// getMissingBlocks walks through all missing blocks and updates the graph
3✔
869
// closed channels accordingly.
870
func (b *Builder) getMissingBlocks(currentHeight uint32,
871
        chainUpdate *chainview.FilteredBlock) error {
872

873
        outdatedHash, err := b.cfg.Chain.GetBlockHash(int64(currentHeight))
874
        if err != nil {
875
                return err
UNCOV
876
        }
×
UNCOV
877

×
UNCOV
878
        outdatedBlock := &chainntnfs.BlockEpoch{
×
UNCOV
879
                Height: int32(currentHeight),
×
880
                Hash:   outdatedHash,
×
881
        }
×
882

UNCOV
883
        epochClient, err := b.cfg.Notifier.RegisterBlockEpochNtfn(
×
UNCOV
884
                outdatedBlock,
×
UNCOV
885
        )
×
UNCOV
886
        if err != nil {
×
UNCOV
887
                return err
×
UNCOV
888
        }
×
UNCOV
889
        defer epochClient.Cancel()
×
UNCOV
890

×
UNCOV
891
        blockDifference := int(chainUpdate.Height - currentHeight)
×
892

×
893
        // We'll walk through all the outdated blocks and make sure we're able
×
UNCOV
894
        // to update the graph with any closed channels from them.
×
UNCOV
895
        for i := 0; i < blockDifference; i++ {
×
UNCOV
896
                var (
×
UNCOV
897
                        missingBlock *chainntnfs.BlockEpoch
×
UNCOV
898
                        ok           bool
×
UNCOV
899
                )
×
UNCOV
900

×
UNCOV
901
                select {
×
UNCOV
902
                case missingBlock, ok = <-epochClient.Epochs:
×
UNCOV
903
                        if !ok {
×
UNCOV
904
                                return nil
×
UNCOV
905
                        }
×
UNCOV
906

×
UNCOV
907
                case <-b.quit:
×
UNCOV
908
                        return nil
×
909
                }
×
910

×
911
                filteredBlock, err := b.cfg.ChainView.FilterBlock(
912
                        missingBlock.Hash,
×
913
                )
×
914
                if err != nil {
915
                        return err
UNCOV
916
                }
×
UNCOV
917

×
UNCOV
918
                err = b.updateGraphWithClosedChannels(
×
UNCOV
919
                        filteredBlock,
×
920
                )
×
921
                if err != nil {
×
922
                        return err
UNCOV
923
                }
×
UNCOV
924
        }
×
UNCOV
925

×
UNCOV
926
        return nil
×
927
}
×
928

×
929
// updateGraphWithClosedChannels prunes the channel graph of closed channels
930
// that are no longer needed.
UNCOV
931
func (b *Builder) updateGraphWithClosedChannels(
×
932
        chainUpdate *chainview.FilteredBlock) error {
933

934
        // Once a new block arrives, we update our running track of the height
935
        // of the chain tip.
936
        blockHeight := chainUpdate.Height
937

3✔
938
        b.bestHeight.Store(blockHeight)
3✔
939
        log.Infof("Pruning channel graph using block %v (height=%v)",
3✔
940
                chainUpdate.Hash, blockHeight)
3✔
941

3✔
942
        // We're only interested in all prior outputs that have been spent in
3✔
943
        // the block, so collate all the referenced previous outpoints within
3✔
944
        // each tx and input.
3✔
945
        var spentOutputs []*wire.OutPoint
3✔
946
        for _, tx := range chainUpdate.Transactions {
3✔
947
                for _, txIn := range tx.TxIn {
3✔
948
                        spentOutputs = append(spentOutputs,
3✔
949
                                &txIn.PreviousOutPoint)
3✔
950
                }
3✔
951
        }
6✔
952

6✔
953
        // With the spent outputs gathered, attempt to prune the channel graph,
3✔
954
        // also passing in the hash+height of the block being pruned so the
3✔
955
        // prune tip can be updated.
3✔
956
        chansClosed, err := b.cfg.Graph.PruneGraph(spentOutputs,
957
                &chainUpdate.Hash, chainUpdate.Height)
958
        if err != nil {
959
                log.Errorf("unable to prune routing table: %v", err)
960
                return err
961
        }
3✔
962

3✔
963
        log.Infof("Block %v (height=%v) closed %v channels", chainUpdate.Hash,
3✔
964
                blockHeight, len(chansClosed))
×
965

×
966
        if len(chansClosed) == 0 {
×
967
                return err
968
        }
3✔
969

3✔
970
        // Notify all currently registered clients of the newly closed channels.
3✔
971
        closeSummaries := createCloseSummaries(blockHeight, chansClosed...)
6✔
972
        b.notifyTopologyChange(&TopologyChange{
3✔
973
                ClosedChannels: closeSummaries,
3✔
974
        })
975

976
        return nil
3✔
977
}
3✔
978

3✔
979
// assertNodeAnnFreshness returns a non-nil error if we have an announcement in
3✔
980
// the database for the passed node with a timestamp newer than the passed
3✔
981
// timestamp. ErrIgnored will be returned if we already have the node, and
3✔
982
// ErrOutdated will be returned if we have a timestamp that's after the new
983
// timestamp.
984
func (b *Builder) assertNodeAnnFreshness(node route.Vertex,
985
        msgTimestamp time.Time) error {
986

987
        // If we are not already aware of this node, it means that we don't
988
        // know about any channel using this node. To avoid a DoS attack by
989
        // node announcements, we will ignore such nodes. If we do know about
990
        // this node, check that this update brings info newer than what we
3✔
991
        // already have.
3✔
992
        lastUpdate, exists, err := b.cfg.Graph.HasLightningNode(node)
3✔
993
        if err != nil {
3✔
994
                return errors.Errorf("unable to query for the "+
3✔
995
                        "existence of node: %v", err)
3✔
996
        }
3✔
997
        if !exists {
3✔
998
                return NewErrf(ErrIgnored, "Ignoring node announcement"+
3✔
999
                        " for node not found in channel graph (%x)",
×
1000
                        node[:])
×
1001
        }
×
1002

6✔
1003
        // If we've reached this point then we're aware of the vertex being
3✔
1004
        // advertised. So we now check if the new message has a new time stamp,
3✔
1005
        // if not then we won't accept the new data as it would override newer
3✔
1006
        // data.
3✔
1007
        if !lastUpdate.Before(msgTimestamp) {
1008
                return NewErrf(ErrOutdated, "Ignoring outdated "+
1009
                        "announcement for %x", node[:])
1010
        }
1011

1012
        return nil
6✔
1013
}
3✔
1014

3✔
1015
// addZombieEdge adds a channel that failed complete validation into the zombie
3✔
1016
// index so we can avoid having to re-validate it in the future.
1017
func (b *Builder) addZombieEdge(chanID uint64) error {
3✔
1018
        // If the edge fails validation we'll mark the edge itself as a zombie
1019
        // so we don't continue to request it. We use the "zero key" for both
1020
        // node pubkeys so this edge can't be resurrected.
1021
        var zeroKey [33]byte
1022
        err := b.cfg.Graph.MarkEdgeZombie(chanID, zeroKey, zeroKey)
×
1023
        if err != nil {
×
1024
                return fmt.Errorf("unable to mark spent chan(id=%v) as a "+
×
1025
                        "zombie: %w", chanID, err)
×
1026
        }
×
1027

×
1028
        return nil
×
1029
}
×
1030

×
1031
// makeFundingScript is used to make the funding script for both segwit v0 and
×
1032
// segwit v1 (taproot) channels.
1033
//
×
1034
// TODO(roasbeef: export and use elsewhere?
1035
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte, chanFeatures []byte,
1036
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
1037

1038
        legacyFundingScript := func() ([]byte, error) {
1039
                witnessScript, err := input.GenMultiSigScript(
1040
                        bitcoinKey1, bitcoinKey2,
1041
                )
1042
                if err != nil {
1043
                        return nil, err
1044
                }
1045
                pkScript, err := input.WitnessScriptHash(witnessScript)
1046
                if err != nil {
3✔
1047
                        return nil, err
3✔
1048
                }
6✔
1049

3✔
1050
                return pkScript, nil
3✔
1051
        }
3✔
1052

1053
        if len(chanFeatures) == 0 {
3✔
1054
                return legacyFundingScript()
3✔
1055
        }
3✔
1056

3✔
1057
        // In order to make the correct funding script, we'll need to parse the
3✔
1058
        // chanFeatures bytes into a feature vector we can interact with.
1059
        rawFeatures := lnwire.NewRawFeatureVector()
3✔
1060
        err := rawFeatures.Decode(bytes.NewReader(chanFeatures))
3✔
1061
        if err != nil {
1062
                return nil, fmt.Errorf("unable to parse chan feature "+
1063
                        "bits: %w", err)
1064
        }
3✔
1065

×
1066
        chanFeatureBits := lnwire.NewFeatureVector(
×
1067
                rawFeatures, lnwire.Features,
×
1068
        )
×
1069
        if chanFeatureBits.HasFeature(
1070
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
1071
        ) {
3✔
1072

×
1073
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
×
1074
                if err != nil {
×
1075
                        return nil, err
1076
                }
3✔
1077
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
3✔
1078
                if err != nil {
3✔
1079
                        return nil, err
3✔
1080
                }
3✔
1081

3✔
1082
                fundingScript, _, err := input.GenTaprootFundingScript(
3✔
1083
                        pubKey1, pubKey2, 0, tapscriptRoot,
3✔
1084
                )
3✔
1085
                if err != nil {
3✔
1086
                        return nil, err
3✔
1087
                }
3✔
1088

3✔
1089
                // TODO(roasbeef): add tapscript root to gossip v1.5
3✔
1090

×
1091
                return fundingScript, nil
×
1092
        }
×
1093

1094
        return legacyFundingScript()
3✔
1095
}
1096

1097
// processUpdate processes a new relate authenticated channel/edge, node or
1098
// channel/edge update network update. If the update didn't affect the internal
1099
// state of the draft due to either being out of date, invalid, or redundant,
1100
// then error is returned.
1101
//
1102
//nolint:funlen
1103
func (b *Builder) processUpdate(msg interface{},
3✔
1104
        op ...batch.SchedulerOption) error {
3✔
1105

3✔
1106
        switch msg := msg.(type) {
3✔
1107
        case *models.LightningNode:
3✔
1108
                // Before we add the node to the database, we'll check to see
3✔
1109
                // if the announcement is "fresh" or not. If it isn't, then
3✔
1110
                // we'll return an error.
3✔
1111
                err := b.assertNodeAnnFreshness(msg.PubKeyBytes, msg.LastUpdate)
3✔
1112
                if err != nil {
3✔
1113
                        return err
3✔
1114
                }
3✔
1115

3✔
1116
                if err := b.cfg.Graph.AddLightningNode(msg, op...); err != nil {
×
1117
                        return errors.Errorf("unable to add node %x to the "+
×
1118
                                "graph: %v", msg.PubKeyBytes, err)
1119
                }
×
1120

×
1121
                log.Tracef("Updated vertex data for node=%x", msg.PubKeyBytes)
1122
                b.stats.incNumNodeUpdates()
1123

1124
        case *models.ChannelEdgeInfo:
1125
                log.Debugf("Received ChannelEdgeInfo for channel %v",
1126
                        msg.ChannelID)
1127

1128
                // Prior to processing the announcement we first check if we
1129
                // already know of this channel, if so, then we can exit early.
3✔
1130
                _, _, exists, isZombie, err := b.cfg.Graph.HasChannelEdge(
3✔
1131
                        msg.ChannelID,
3✔
1132
                )
3✔
1133
                if err != nil &&
3✔
1134
                        !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
1135

6✔
1136
                        return errors.Errorf("unable to check for edge "+
3✔
1137
                                "existence: %v", err)
3✔
1138
                }
1139
                if isZombie {
3✔
1140
                        return NewErrf(ErrIgnored, "ignoring msg for zombie "+
×
1141
                                "chan_id=%v", msg.ChannelID)
×
1142
                }
×
1143
                if exists {
1144
                        return NewErrf(ErrIgnored, "ignoring msg for known "+
3✔
1145
                                "chan_id=%v", msg.ChannelID)
3✔
1146
                }
3✔
1147

3✔
1148
                // If AssumeChannelValid is present, then we are unable to
1149
                // perform any of the expensive checks below, so we'll
1150
                // short-circuit our path straight to adding the edge to our
1151
                // graph. If the passed ShortChannelID is an alias, then we'll
1152
                // skip validation as it will not map to a legitimate tx. This
1153
                // is not a DoS vector as only we can add an alias
1154
                // ChannelAnnouncement from the gossiper.
1155
                scid := lnwire.NewShortChanIDFromInt(msg.ChannelID)
1156
                if b.cfg.AssumeChannelValid || b.cfg.IsAlias(scid) {
3✔
1157
                        err := b.cfg.Graph.AddChannelEdge(msg, op...)
3✔
1158
                        if err != nil {
3✔
1159
                                return fmt.Errorf("unable to add edge: %w", err)
3✔
1160
                        }
3✔
1161
                        log.Tracef("New channel discovered! Link "+
3✔
1162
                                "connects %x and %x with ChannelID(%v)",
3✔
1163
                                msg.NodeKey1Bytes, msg.NodeKey2Bytes,
3✔
1164
                                msg.ChannelID)
3✔
1165
                        b.stats.incNumEdgesDiscovered()
3✔
1166

3✔
1167
                        break
3✔
1168
                }
3✔
1169

×
1170
                // Before we can add the channel to the channel graph, we need
×
1171
                // to obtain the full funding outpoint that's encoded within
1172
                // the channel ID.
×
1173
                channelID := lnwire.NewShortChanIDFromInt(msg.ChannelID)
×
1174
                fundingTx, err := lnwallet.FetchFundingTxWrapper(
1175
                        b.cfg.Chain, &channelID, b.quit,
1176
                )
1177
                if err != nil {
1178
                        //nolint:ll
1179
                        //
1180
                        // In order to ensure we don't erroneously mark a
1181
                        // channel as a zombie due to an RPC failure, we'll
1182
                        // attempt to string match for the relevant errors.
1183
                        //
1184
                        // * btcd:
1185
                        //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
1186
                        //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
3✔
1187
                        // * bitcoind:
3✔
1188
                        //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
3✔
1189
                        //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
3✔
1190
                        switch {
3✔
1191
                        case strings.Contains(err.Error(), "not found"):
3✔
1192
                                fallthrough
3✔
1193

3✔
1194
                        case strings.Contains(err.Error(), "out of range"):
3✔
1195
                                // If the funding transaction isn't found at
3✔
1196
                                // all, then we'll mark the edge itself as a
×
1197
                                // zombie so we don't continue to request it.
×
1198
                                // We use the "zero key" for both node pubkeys
×
1199
                                // so this edge can't be resurrected.
3✔
1200
                                zErr := b.addZombieEdge(msg.ChannelID)
×
1201
                                if zErr != nil {
×
1202
                                        return zErr
×
1203
                                }
6✔
1204

3✔
1205
                        default:
3✔
1206
                        }
3✔
1207

1208
                        return NewErrf(ErrNoFundingTransaction, "unable to "+
3✔
1209
                                "locate funding tx: %v", err)
×
1210
                }
×
1211

1212
                // Recreate witness output to be sure that declared in channel
3✔
1213
                // edge bitcoin keys and channel value corresponds to the
3✔
1214
                // reality.
3✔
1215
                fundingPkScript, err := makeFundingScript(
3✔
1216
                        msg.BitcoinKey1Bytes[:], msg.BitcoinKey2Bytes[:],
3✔
1217
                        msg.Features, msg.TapscriptRoot,
3✔
1218
                )
3✔
1219
                if err != nil {
6✔
1220
                        return err
3✔
1221
                }
3✔
1222

3✔
1223
                // Next we'll validate that this channel is actually well
3✔
1224
                // formed. If this check fails, then this channel either
3✔
1225
                // doesn't exist, or isn't the one that was meant to be created
3✔
1226
                // according to the passed channel proofs.
1227
                fundingPoint, err := chanvalidate.Validate(
3✔
1228
                        &chanvalidate.Context{
3✔
1229
                                Locator: &chanvalidate.ShortChanIDChanLocator{
3✔
1230
                                        ID: channelID,
3✔
1231
                                },
3✔
1232
                                MultiSigPkScript: fundingPkScript,
3✔
1233
                                FundingTx:        fundingTx,
3✔
1234
                        },
3✔
1235
                )
3✔
1236
                if err != nil {
3✔
1237
                        // Mark the edge as a zombie so we won't try to
3✔
1238
                        // re-validate it on start up.
3✔
1239
                        if err := b.addZombieEdge(msg.ChannelID); err != nil {
×
1240
                                return err
×
1241
                        }
1242

1243
                        return NewErrf(ErrInvalidFundingOutput, "output "+
1244
                                "failed validation: %w", err)
1245
                }
3✔
1246

3✔
1247
                // Now that we have the funding outpoint of the channel, ensure
3✔
1248
                // that it hasn't yet been spent. If so, then this channel has
3✔
1249
                // been closed so we'll ignore it.
3✔
1250
                chanUtxo, err := b.cfg.Chain.GetUtxo(
3✔
1251
                        fundingPoint, fundingPkScript, channelID.BlockHeight,
3✔
1252
                        b.quit,
3✔
1253
                )
3✔
1254
                if err != nil {
×
1255
                        if errors.Is(err, btcwallet.ErrOutputSpent) {
×
1256
                                zErr := b.addZombieEdge(msg.ChannelID)
×
1257
                                if zErr != nil {
1258
                                        return zErr
3✔
1259
                                }
1260
                        }
1261

1262
                        return NewErrf(ErrChannelSpent, "unable to fetch utxo "+
1263
                                "for chan_id=%v, chan_point=%v: %v",
1264
                                msg.ChannelID, fundingPoint, err)
1265
                }
1266

3✔
1267
                // TODO(roasbeef): this is a hack, needs to be removed
3✔
1268
                // after commitment fees are dynamic.
3✔
1269
                msg.Capacity = btcutil.Amount(chanUtxo.Value)
3✔
1270
                msg.ChannelPoint = *fundingPoint
3✔
1271
                if err := b.cfg.Graph.AddChannelEdge(msg, op...); err != nil {
3✔
1272
                        return errors.Errorf("unable to add edge: %v", err)
3✔
1273
                }
3✔
1274

3✔
1275
                log.Debugf("New channel discovered! Link "+
3✔
1276
                        "connects %x and %x with ChannelPoint(%v): "+
3✔
1277
                        "chan_id=%v, capacity=%v",
3✔
1278
                        msg.NodeKey1Bytes, msg.NodeKey2Bytes,
3✔
1279
                        fundingPoint, msg.ChannelID, msg.Capacity)
×
1280
                b.stats.incNumEdgesDiscovered()
×
1281

1282
                // As a new edge has been added to the channel graph, we'll
×
1283
                // update the current UTXO filter within our active
×
1284
                // FilteredChainView so we are notified if/when this channel is
1285
                // closed.
1286
                filterUpdate := []graphdb.EdgePoint{
1287
                        {
1288
                                FundingPkScript: fundingPkScript,
1289
                                OutPoint:        *fundingPoint,
1290
                        },
1291
                }
1292
                err = b.cfg.ChainView.UpdateFilter(
3✔
1293
                        filterUpdate, b.bestHeight.Load(),
3✔
1294
                )
3✔
1295
                if err != nil {
3✔
1296
                        return errors.Errorf("unable to update chain "+
3✔
1297
                                "view: %v", err)
3✔
1298
                }
3✔
1299

3✔
1300
        case *models.ChannelEdgePolicy:
3✔
1301
                log.Debugf("Received ChannelEdgePolicy for channel %v",
3✔
1302
                        msg.ChannelID)
3✔
1303

3✔
1304
                // We make sure to hold the mutex for this channel ID,
3✔
1305
                // such that no other goroutine is concurrently doing
3✔
1306
                // database accesses for the same channel ID.
×
1307
                b.channelEdgeMtx.Lock(msg.ChannelID)
×
1308
                defer b.channelEdgeMtx.Unlock(msg.ChannelID)
×
1309

1310
                edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
1311
                        b.cfg.Graph.HasChannelEdge(msg.ChannelID)
1312
                if err != nil && !errors.Is(
1313
                        err, graphdb.ErrGraphNoEdgesFound,
3✔
1314
                ) {
3✔
1315

3✔
1316
                        return errors.Errorf("unable to check for edge "+
3✔
1317
                                "existence: %v", err)
×
1318
                }
×
1319

×
1320
                // If the channel is marked as a zombie in our database, and
×
1321
                // we consider this a stale update, then we should not apply the
×
1322
                // policy.
1323
                isStaleUpdate := time.Since(msg.LastUpdate) >
1324
                        b.cfg.ChannelPruneExpiry
1325

3✔
UNCOV
1326
                if isZombie && isStaleUpdate {
×
UNCOV
1327
                        return NewErrf(ErrIgnored, "ignoring stale update "+
×
UNCOV
1328
                                "(flags=%v|%v) for zombie chan_id=%v",
×
UNCOV
1329
                                msg.MessageFlags, msg.ChannelFlags,
×
1330
                                msg.ChannelID)
1331
                }
3✔
1332

3✔
1333
                // If the channel doesn't exist in our database, we cannot
3✔
1334
                // apply the updated policy.
3✔
1335
                if !exists {
3✔
1336
                        return NewErrf(ErrIgnored, "ignoring update "+
3✔
1337
                                "(flags=%v|%v) for unknown chan_id=%v",
3✔
1338
                                msg.MessageFlags, msg.ChannelFlags,
3✔
1339
                                msg.ChannelID)
3✔
1340
                }
1341

1342
                log.Debugf("Found edge1Timestamp=%v, edge2Timestamp=%v",
3✔
1343
                        edge1Timestamp, edge2Timestamp)
3✔
1344

6✔
1345
                // As edges are directional edge node has a unique policy for
3✔
1346
                // the direction of the edge they control. Therefore, we first
3✔
1347
                // check if we already have the most up-to-date information for
3✔
1348
                // that edge. If this message has a timestamp not strictly
3✔
1349
                // newer than what we already know of we can exit early.
3✔
1350
                switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
1351
                // A flag set of 0 indicates this is an announcement for the
1352
                // "first" node in the channel.
1353
                case 0:
3✔
1354
                        // Ignore outdated message.
3✔
1355
                        if !edge1Timestamp.Before(msg.LastUpdate) {
6✔
1356
                                return NewErrf(ErrOutdated, "Ignoring "+
3✔
1357
                                        "outdated update (flags=%v|%v) for "+
3✔
1358
                                        "known chan_id=%v", msg.MessageFlags,
3✔
1359
                                        msg.ChannelFlags, msg.ChannelID)
3✔
1360
                        }
3✔
1361

1362
                // Similarly, a flag set of 1 indicates this is an announcement
1363
                // for the "second" node in the channel.
1364
                case 1:
1365
                        // Ignore outdated message.
3✔
1366
                        if !edge2Timestamp.Before(msg.LastUpdate) {
×
1367
                                return NewErrf(ErrOutdated, "Ignoring "+
×
1368
                                        "outdated update (flags=%v|%v) for "+
×
1369
                                        "known chan_id=%v", msg.MessageFlags,
×
1370
                                        msg.ChannelFlags, msg.ChannelID)
1371
                        }
3✔
1372
                }
3✔
1373

3✔
1374
                // Now that we know this isn't a stale update, we'll apply the
3✔
1375
                // new edge policy to the proper directional edge within the
3✔
1376
                // channel graph.
1377
                if err = b.cfg.Graph.UpdateEdgePolicy(msg, op...); err != nil {
1378
                        err := errors.Errorf("unable to add channel: %v", err)
1379
                        log.Error(err)
1380
                        return err
1381
                }
3✔
1382

3✔
1383
                log.Tracef("New channel update applied: %v",
3✔
1384
                        lnutils.SpewLogClosure(msg))
3✔
1385
                b.stats.incNumChannelUpdates()
1386

1387
        default:
1388
                return errors.Errorf("wrong routing update message type")
1389
        }
3✔
1390

3✔
1391
        return nil
3✔
1392
}
1393

1394
// routingMsg couples a routing related routing topology update to the
1395
// error channel.
1396
type routingMsg struct {
1397
        msg interface{}
1398
        op  []batch.SchedulerOption
1399
        err chan error
3✔
1400
}
3✔
1401

3✔
1402
// ApplyChannelUpdate validates a channel update and if valid, applies it to the
3✔
1403
// database. It returns a bool indicating whether the updates were successful.
1404
func (b *Builder) ApplyChannelUpdate(msg *lnwire.ChannelUpdate1) bool {
1405
        ch, _, _, err := b.GetChannelByID(msg.ShortChannelID)
1406
        if err != nil {
1407
                log.Errorf("Unable to retrieve channel by id: %v", err)
1408
                return false
1409
        }
1410

3✔
1411
        var pubKey *btcec.PublicKey
3✔
1412

3✔
1413
        switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
3✔
1414
        case 0:
1415
                pubKey, _ = ch.NodeKey1()
1416

1417
        case 1:
1418
                pubKey, _ = ch.NodeKey2()
1419
        }
1420

3✔
1421
        // Exit early if the pubkey cannot be decided.
3✔
1422
        if pubKey == nil {
3✔
1423
                log.Errorf("Unable to decide pubkey with ChannelFlags=%v",
3✔
1424
                        msg.ChannelFlags)
3✔
1425
                return false
6✔
1426
        }
3✔
1427

3✔
1428
        err = netann.ValidateChannelUpdateAnn(pubKey, ch.Capacity, msg)
×
1429
        if err != nil {
×
1430
                log.Errorf("Unable to validate channel update: %v", err)
×
1431
                return false
1432
        }
3✔
1433

1434
        err = b.UpdateEdge(&models.ChannelEdgePolicy{
1435
                SigBytes:                  msg.Signature.ToSignatureBytes(),
1436
                ChannelID:                 msg.ShortChannelID.ToUint64(),
1437
                LastUpdate:                time.Unix(int64(msg.Timestamp), 0),
1438
                MessageFlags:              msg.MessageFlags,
1439
                ChannelFlags:              msg.ChannelFlags,
1440
                TimeLockDelta:             msg.TimeLockDelta,
1441
                MinHTLC:                   msg.HtlcMinimumMsat,
1442
                MaxHTLC:                   msg.HtlcMaximumMsat,
3✔
1443
                FeeBaseMSat:               lnwire.MilliSatoshi(msg.BaseFee),
3✔
1444
                FeeProportionalMillionths: lnwire.MilliSatoshi(msg.FeeRate),
3✔
1445
                ExtraOpaqueData:           msg.ExtraOpaqueData,
3✔
1446
        })
1447
        if err != nil && !IsError(err, ErrIgnored, ErrOutdated) {
1448
                log.Errorf("Unable to apply channel update: %v", err)
1449
                return false
1450
        }
1451

1452
        return true
3✔
1453
}
3✔
1454

3✔
1455
// AddNode is used to add information about a node to the router database. If
3✔
1456
// the node with this pubkey is not present in an existing channel, it will
3✔
1457
// be ignored.
6✔
1458
//
3✔
1459
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
1460
func (b *Builder) AddNode(node *models.LightningNode,
3✔
1461
        op ...batch.SchedulerOption) error {
1462

3✔
1463
        rMsg := &routingMsg{
1464
                msg: node,
1465
                op:  op,
1466
                err: make(chan error, 1),
1467
        }
1468

1469
        select {
3✔
1470
        case b.networkUpdates <- rMsg:
3✔
1471
                select {
3✔
1472
                case err := <-rMsg.err:
1473
                        return err
1474
                case <-b.quit:
1475
                        return ErrGraphBuilderShuttingDown
1476
                }
1477
        case <-b.quit:
3✔
1478
                return ErrGraphBuilderShuttingDown
3✔
1479
        }
3✔
1480
}
3✔
1481

3✔
1482
// AddEdge is used to add edge/channel to the topology of the router, after all
3✔
1483
// information about channel will be gathered this edge/channel might be used
3✔
1484
// in construction of payment path.
1485
//
1486
// NOTE: This method is part of the ChannelGraphSource interface.
1487
func (b *Builder) AddEdge(edge *models.ChannelEdgeInfo,
1488
        op ...batch.SchedulerOption) error {
1489

×
1490
        rMsg := &routingMsg{
×
1491
                msg: edge,
×
1492
                op:  op,
×
1493
                err: make(chan error, 1),
×
1494
        }
1495

1496
        select {
1497
        case b.networkUpdates <- rMsg:
1498
                select {
1499
                case err := <-rMsg.err:
1500
                        return err
3✔
1501
                case <-b.quit:
3✔
1502
                        return ErrGraphBuilderShuttingDown
3✔
1503
                }
3✔
1504
        case <-b.quit:
3✔
1505
                return ErrGraphBuilderShuttingDown
×
1506
        }
×
1507
}
×
1508

1509
// UpdateEdge is used to update edge information, without this message edge
1510
// considered as not fully constructed.
1511
//
3✔
1512
// NOTE: This method is part of the ChannelGraphSource interface.
×
1513
func (b *Builder) UpdateEdge(update *models.ChannelEdgePolicy,
×
1514
        op ...batch.SchedulerOption) error {
×
1515

×
1516
        rMsg := &routingMsg{
×
1517
                msg: update,
×
1518
                op:  op,
×
1519
                err: make(chan error, 1),
×
1520
        }
×
1521

1522
        select {
1523
        case b.networkUpdates <- rMsg:
1524
                select {
×
1525
                case err := <-rMsg.err:
1526
                        return err
1527
                case <-b.quit:
1528
                        return ErrGraphBuilderShuttingDown
1529
                }
6✔
1530
        case <-b.quit:
3✔
1531
                return ErrGraphBuilderShuttingDown
3✔
1532
        }
1533
}
1534

1535
// CurrentBlockHeight returns the block height from POV of the router subsystem.
1536
//
1537
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
1538
func (b *Builder) CurrentBlockHeight() (uint32, error) {
1539
        _, height, err := b.cfg.Chain.GetBestBlock()
1540
        return uint32(height), err
3✔
1541
}
3✔
1542

1543
// SyncedHeight returns the block height to which the router subsystem currently
1544
// is synced to. This can differ from the above chain height if the goroutine
1545
// responsible for processing the blocks isn't yet up to speed.
3✔
1546
func (b *Builder) SyncedHeight() uint32 {
3✔
1547
        return b.bestHeight.Load()
1548
}
1549

×
1550
// GetChannelByID return the channel by the channel id.
1551
//
1552
// NOTE: This method is part of the ChannelGraphSource interface.
1553
func (b *Builder) GetChannelByID(chanID lnwire.ShortChannelID) (
1554
        *models.ChannelEdgeInfo,
1555
        *models.ChannelEdgePolicy,
×
1556
        *models.ChannelEdgePolicy, error) {
×
1557

×
1558
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
1559
}
1560

1561
// FetchLightningNode attempts to look up a target node by its identity public
1562
// key. graphdb.ErrGraphNodeNotFound is returned if the node doesn't exist
1563
// within the graph.
1564
//
1565
// NOTE: This method is part of the ChannelGraphSource interface.
1566
func (b *Builder) FetchLightningNode(
1567
        node route.Vertex) (*models.LightningNode, error) {
1568

1569
        return b.cfg.Graph.FetchLightningNode(node)
1570
}
1571

1572
// ForEachNode is used to iterate over every node in router topology.
1573
//
1574
// NOTE: This method is part of the ChannelGraphSource interface.
1575
func (b *Builder) ForEachNode(
1576
        cb func(*models.LightningNode) error) error {
1577

1578
        return b.cfg.Graph.ForEachNode(
1579
                func(_ kvdb.RTx, n *models.LightningNode) error {
1580
                        return cb(n)
1581
                })
1582
}
1583

1584
// ForAllOutgoingChannels is used to iterate over all outgoing channels owned by
1585
// the router.
1586
//
1587
// NOTE: This method is part of the ChannelGraphSource interface.
1588
func (b *Builder) ForAllOutgoingChannels(cb func(*models.ChannelEdgeInfo,
1589
        *models.ChannelEdgePolicy) error) error {
1590

1591
        return b.cfg.Graph.ForEachNodeChannel(b.cfg.SelfNode,
1592
                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
1593
                        e *models.ChannelEdgePolicy,
1594
                        _ *models.ChannelEdgePolicy) error {
1595

1596
                        if e == nil {
1597
                                return fmt.Errorf("channel from self node " +
1598
                                        "has no policy")
1599
                        }
1600

1601
                        return cb(c, e)
1602
                },
1603
        )
1604
}
1605

1606
// AddProof updates the channel edge info with proof which is needed to
1607
// properly announce the edge to the rest of the network.
1608
//
1609
// NOTE: This method is part of the ChannelGraphSource interface.
1610
func (b *Builder) AddProof(chanID lnwire.ShortChannelID,
1611
        proof *models.ChannelAuthProof) error {
1612

1613
        info, _, _, err := b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
1614
        if err != nil {
1615
                return err
1616
        }
1617

1618
        info.AuthProof = proof
1619

1620
        return b.cfg.Graph.UpdateChannelEdge(info)
1621
}
1622

1623
// IsStaleNode returns true if the graph source has a node announcement for the
1624
// target node with a more recent timestamp.
1625
//
1626
// NOTE: This method is part of the ChannelGraphSource interface.
1627
func (b *Builder) IsStaleNode(node route.Vertex,
1628
        timestamp time.Time) bool {
1629

1630
        // If our attempt to assert that the node announcement is fresh fails,
1631
        // then we know that this is actually a stale announcement.
1632
        err := b.assertNodeAnnFreshness(node, timestamp)
1633
        if err != nil {
1634
                log.Debugf("Checking stale node %x got %v", node, err)
1635
                return true
1636
        }
1637

1638
        return false
1639
}
1640

1641
// IsPublicNode determines whether the given vertex is seen as a public node in
1642
// the graph from the graph's source node's point of view.
1643
//
1644
// NOTE: This method is part of the ChannelGraphSource interface.
1645
func (b *Builder) IsPublicNode(node route.Vertex) (bool, error) {
1646
        return b.cfg.Graph.IsPublicNode(node)
1647
}
1648

1649
// IsKnownEdge returns true if the graph source already knows of the passed
1650
// channel ID either as a live or zombie edge.
1651
//
1652
// NOTE: This method is part of the ChannelGraphSource interface.
1653
func (b *Builder) IsKnownEdge(chanID lnwire.ShortChannelID) bool {
1654
        _, _, exists, isZombie, _ := b.cfg.Graph.HasChannelEdge(
1655
                chanID.ToUint64(),
1656
        )
1657

1658
        return exists || isZombie
1659
}
1660

1661
// IsStaleEdgePolicy returns true if the graph source has a channel edge for
1662
// the passed channel ID (and flags) that have a more recent timestamp.
1663
//
1664
// NOTE: This method is part of the ChannelGraphSource interface.
1665
func (b *Builder) IsStaleEdgePolicy(chanID lnwire.ShortChannelID,
1666
        timestamp time.Time, flags lnwire.ChanUpdateChanFlags) bool {
1667

1668
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
1669
                b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
1670
        if err != nil {
1671
                log.Debugf("Check stale edge policy got error: %v", err)
1672
                return false
1673
        }
1674

1675
        // If we know of the edge as a zombie, then we'll make some additional
1676
        // checks to determine if the new policy is fresh.
1677
        if isZombie {
1678
                // When running with AssumeChannelValid, we also prune channels
1679
                // if both of their edges are disabled. We'll mark the new
1680
                // policy as stale if it remains disabled.
1681
                if b.cfg.AssumeChannelValid {
1682
                        isDisabled := flags&lnwire.ChanUpdateDisabled ==
1683
                                lnwire.ChanUpdateDisabled
1684
                        if isDisabled {
1685
                                return true
1686
                        }
1687
                }
1688

1689
                // Otherwise, we'll fall back to our usual ChannelPruneExpiry.
1690
                return time.Since(timestamp) > b.cfg.ChannelPruneExpiry
1691
        }
1692

1693
        // If we don't know of the edge, then it means it's fresh (thus not
1694
        // stale).
1695
        if !exists {
1696
                return false
1697
        }
1698

1699
        // As edges are directional edge node has a unique policy for the
1700
        // direction of the edge they control. Therefore, we first check if we
1701
        // already have the most up-to-date information for that edge. If so,
1702
        // then we can exit early.
1703
        switch {
1704
        // A flag set of 0 indicates this is an announcement for the "first"
1705
        // node in the channel.
1706
        case flags&lnwire.ChanUpdateDirection == 0:
1707
                return !edge1Timestamp.Before(timestamp)
1708

1709
        // Similarly, a flag set of 1 indicates this is an announcement for the
1710
        // "second" node in the channel.
1711
        case flags&lnwire.ChanUpdateDirection == 1:
1712
                return !edge2Timestamp.Before(timestamp)
1713
        }
1714

1715
        return false
1716
}
1717

1718
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
1719
//
1720
// NOTE: This method is part of the ChannelGraphSource interface.
1721
func (b *Builder) MarkEdgeLive(chanID lnwire.ShortChannelID) error {
1722
        return b.cfg.Graph.MarkEdgeLive(chanID.ToUint64())
1723
}
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