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

lightningnetwork / lnd / 15635919293

13 Jun 2025 01:37PM UTC coverage: 56.351% (-2.0%) from 58.333%
15635919293

Pull #9903

github

web-flow
Merge 174181006 into 35102e7c3
Pull Request #9903: docs: add sphinx replay description

108065 of 191770 relevant lines covered (56.35%)

22781.11 hits per line

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

68.13
/graph/builder.go
1
package graph
2

3
import (
4
        "fmt"
5
        "sync"
6
        "sync/atomic"
7
        "time"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/btcsuite/btcd/wire"
11
        "github.com/go-errors/errors"
12
        "github.com/lightningnetwork/lnd/batch"
13
        "github.com/lightningnetwork/lnd/chainntnfs"
14
        graphdb "github.com/lightningnetwork/lnd/graph/db"
15
        "github.com/lightningnetwork/lnd/graph/db/models"
16
        "github.com/lightningnetwork/lnd/lnutils"
17
        "github.com/lightningnetwork/lnd/lnwallet"
18
        "github.com/lightningnetwork/lnd/lnwire"
19
        "github.com/lightningnetwork/lnd/multimutex"
20
        "github.com/lightningnetwork/lnd/netann"
21
        "github.com/lightningnetwork/lnd/routing/chainview"
22
        "github.com/lightningnetwork/lnd/routing/route"
23
        "github.com/lightningnetwork/lnd/ticker"
24
)
25

26
const (
27
        // DefaultChannelPruneExpiry is the default duration used to determine
28
        // if a channel should be pruned or not.
29
        DefaultChannelPruneExpiry = time.Hour * 24 * 14
30

31
        // DefaultFirstTimePruneDelay is the time we'll wait after startup
32
        // before attempting to prune the graph for zombie channels. We don't
33
        // do it immediately after startup to allow lnd to start up without
34
        // getting blocked by this job.
35
        DefaultFirstTimePruneDelay = 30 * time.Second
36

37
        // defaultStatInterval governs how often the router will log non-empty
38
        // stats related to processing new channels, updates, or node
39
        // announcements.
40
        defaultStatInterval = time.Minute
41
)
42

43
var (
44
        // ErrGraphBuilderShuttingDown is returned if the graph builder is in
45
        // the process of shutting down.
46
        ErrGraphBuilderShuttingDown = fmt.Errorf("graph builder shutting down")
47
)
48

49
// Config holds the configuration required by the Builder.
50
type Config struct {
51
        // SelfNode is the public key of the node that this channel router
52
        // belongs to.
53
        SelfNode route.Vertex
54

55
        // Graph is the channel graph that the ChannelRouter will use to gather
56
        // metrics from and also to carry out path finding queries.
57
        Graph DB
58

59
        // Chain is the router's source to the most up-to-date blockchain data.
60
        // All incoming advertised channels will be checked against the chain
61
        // to ensure that the channels advertised are still open.
62
        Chain lnwallet.BlockChainIO
63

64
        // ChainView is an instance of a FilteredChainView which is used to
65
        // watch the sub-set of the UTXO set (the set of active channels) that
66
        // we need in order to properly maintain the channel graph.
67
        ChainView chainview.FilteredChainView
68

69
        // Notifier is a reference to the ChainNotifier, used to grab
70
        // the latest blocks if the router is missing any.
71
        Notifier chainntnfs.ChainNotifier
72

73
        // ChannelPruneExpiry is the duration used to determine if a channel
74
        // should be pruned or not. If the delta between now and when the
75
        // channel was last updated is greater than ChannelPruneExpiry, then
76
        // the channel is marked as a zombie channel eligible for pruning.
77
        ChannelPruneExpiry time.Duration
78

79
        // GraphPruneInterval is used as an interval to determine how often we
80
        // should examine the channel graph to garbage collect zombie channels.
81
        GraphPruneInterval time.Duration
82

83
        // FirstTimePruneDelay is the time we'll wait after startup before
84
        // attempting to prune the graph for zombie channels. We don't do it
85
        // immediately after startup to allow lnd to start up without getting
86
        // blocked by this job.
87
        FirstTimePruneDelay time.Duration
88

89
        // AssumeChannelValid toggles whether the builder will prune channels
90
        // based on their spentness vs using the fact that they are considered
91
        // zombies.
92
        AssumeChannelValid bool
93

94
        // StrictZombiePruning determines if we attempt to prune zombie
95
        // channels according to a stricter criteria. If true, then we'll prune
96
        // a channel if only *one* of the edges is considered a zombie.
97
        // Otherwise, we'll only prune the channel when both edges have a very
98
        // dated last update.
99
        StrictZombiePruning bool
100

101
        // IsAlias returns whether a passed ShortChannelID is an alias. This is
102
        // only used for our local channels.
103
        IsAlias func(scid lnwire.ShortChannelID) bool
104
}
105

106
// Builder builds and maintains a view of the Lightning Network graph.
107
type Builder struct {
108
        started atomic.Bool
109
        stopped atomic.Bool
110

111
        bestHeight atomic.Uint32
112

113
        cfg *Config
114

115
        // newBlocks is a channel in which new blocks connected to the end of
116
        // the main chain are sent over, and blocks updated after a call to
117
        // UpdateFilter.
118
        newBlocks <-chan *chainview.FilteredBlock
119

120
        // staleBlocks is a channel in which blocks disconnected from the end
121
        // of our currently known best chain are sent over.
122
        staleBlocks <-chan *chainview.FilteredBlock
123

124
        // channelEdgeMtx is a mutex we use to make sure we process only one
125
        // ChannelEdgePolicy at a time for a given channelID, to ensure
126
        // consistency between the various database accesses.
127
        channelEdgeMtx *multimutex.Mutex[uint64]
128

129
        // statTicker is a resumable ticker that logs the router's progress as
130
        // it discovers channels or receives updates.
131
        statTicker ticker.Ticker
132

133
        // stats tracks newly processed channels, updates, and node
134
        // announcements over a window of defaultStatInterval.
135
        stats *builderStats
136

137
        quit chan struct{}
138
        wg   sync.WaitGroup
139
}
140

141
// A compile time check to ensure Builder implements the
142
// ChannelGraphSource interface.
143
var _ ChannelGraphSource = (*Builder)(nil)
144

145
// NewBuilder constructs a new Builder.
146
func NewBuilder(cfg *Config) (*Builder, error) {
20✔
147
        return &Builder{
20✔
148
                cfg:            cfg,
20✔
149
                channelEdgeMtx: multimutex.NewMutex[uint64](),
20✔
150
                statTicker:     ticker.New(defaultStatInterval),
20✔
151
                stats:          new(builderStats),
20✔
152
                quit:           make(chan struct{}),
20✔
153
        }, nil
20✔
154
}
20✔
155

156
// Start launches all the goroutines the Builder requires to carry out its
157
// duties. If the builder has already been started, then this method is a noop.
158
func (b *Builder) Start() error {
20✔
159
        if !b.started.CompareAndSwap(false, true) {
20✔
160
                return nil
×
161
        }
×
162

163
        log.Info("Builder starting")
20✔
164

20✔
165
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
20✔
166
        if err != nil {
20✔
167
                return err
×
168
        }
×
169

170
        // If the graph has never been pruned, or hasn't fully been created yet,
171
        // then we don't treat this as an explicit error.
172
        if _, _, err := b.cfg.Graph.PruneTip(); err != nil {
38✔
173
                switch {
18✔
174
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
18✔
175
                        fallthrough
18✔
176

177
                case errors.Is(err, graphdb.ErrGraphNotFound):
18✔
178
                        // If the graph has never been pruned, then we'll set
18✔
179
                        // the prune height to the current best height of the
18✔
180
                        // chain backend.
18✔
181
                        _, err = b.cfg.Graph.PruneGraph(
18✔
182
                                nil, bestHash, uint32(bestHeight),
18✔
183
                        )
18✔
184
                        if err != nil {
18✔
185
                                return err
×
186
                        }
×
187

188
                default:
×
189
                        return err
×
190
                }
191
        }
192

193
        // If AssumeChannelValid is present, then we won't rely on pruning
194
        // channels from the graph based on their spentness, but whether they
195
        // are considered zombies or not. We will start zombie pruning after a
196
        // small delay, to avoid slowing down startup of lnd.
197
        if b.cfg.AssumeChannelValid { //nolint:nestif
21✔
198
                time.AfterFunc(b.cfg.FirstTimePruneDelay, func() {
2✔
199
                        select {
1✔
200
                        case <-b.quit:
×
201
                                return
×
202
                        default:
1✔
203
                        }
204

205
                        log.Info("Initial zombie prune starting")
1✔
206
                        if err := b.pruneZombieChans(); err != nil {
1✔
207
                                log.Errorf("Unable to prune zombies: %v", err)
×
208
                        }
×
209
                })
210
        } else {
19✔
211
                // Otherwise, we'll use our filtered chain view to prune
19✔
212
                // channels as soon as they are detected as spent on-chain.
19✔
213
                if err := b.cfg.ChainView.Start(); err != nil {
19✔
214
                        return err
×
215
                }
×
216

217
                // Once the instance is active, we'll fetch the channel we'll
218
                // receive notifications over.
219
                b.newBlocks = b.cfg.ChainView.FilteredBlocks()
19✔
220
                b.staleBlocks = b.cfg.ChainView.DisconnectedBlocks()
19✔
221

19✔
222
                // Before we perform our manual block pruning, we'll construct
19✔
223
                // and apply a fresh chain filter to the active
19✔
224
                // FilteredChainView instance.  We do this before, as otherwise
19✔
225
                // we may miss on-chain events as the filter hasn't properly
19✔
226
                // been applied.
19✔
227
                channelView, err := b.cfg.Graph.ChannelView()
19✔
228
                if err != nil && !errors.Is(
19✔
229
                        err, graphdb.ErrGraphNoEdgesFound,
19✔
230
                ) {
19✔
231

×
232
                        return err
×
233
                }
×
234

235
                log.Infof("Filtering chain using %v channels active",
19✔
236
                        len(channelView))
19✔
237

19✔
238
                if len(channelView) != 0 {
26✔
239
                        err = b.cfg.ChainView.UpdateFilter(
7✔
240
                                channelView, uint32(bestHeight),
7✔
241
                        )
7✔
242
                        if err != nil {
7✔
243
                                return err
×
244
                        }
×
245
                }
246

247
                // The graph pruning might have taken a while and there could be
248
                // new blocks available.
249
                _, bestHeight, err = b.cfg.Chain.GetBestBlock()
19✔
250
                if err != nil {
19✔
251
                        return err
×
252
                }
×
253
                b.bestHeight.Store(uint32(bestHeight))
19✔
254

19✔
255
                // Before we begin normal operation of the router, we first need
19✔
256
                // to synchronize the channel graph to the latest state of the
19✔
257
                // UTXO set.
19✔
258
                if err := b.syncGraphWithChain(); err != nil {
19✔
259
                        return err
×
260
                }
×
261

262
                // Finally, before we proceed, we'll prune any unconnected nodes
263
                // from the graph in order to ensure we maintain a tight graph
264
                // of "useful" nodes.
265
                err = b.cfg.Graph.PruneGraphNodes()
19✔
266
                if err != nil &&
19✔
267
                        !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
19✔
268

×
269
                        return err
×
270
                }
×
271
        }
272

273
        b.wg.Add(1)
20✔
274
        go b.networkHandler()
20✔
275

20✔
276
        log.Debug("Builder started")
20✔
277

20✔
278
        return nil
20✔
279
}
280

281
// Stop signals to the Builder that it should halt all routines. This method
282
// will *block* until all goroutines have excited. If the builder has already
283
// stopped then this method will return immediately.
284
func (b *Builder) Stop() error {
20✔
285
        if !b.stopped.CompareAndSwap(false, true) {
22✔
286
                return nil
2✔
287
        }
2✔
288

289
        log.Info("Builder shutting down...")
18✔
290

18✔
291
        // Our filtered chain view could've only been started if
18✔
292
        // AssumeChannelValid isn't present.
18✔
293
        if !b.cfg.AssumeChannelValid {
35✔
294
                if err := b.cfg.ChainView.Stop(); err != nil {
17✔
295
                        return err
×
296
                }
×
297
        }
298

299
        close(b.quit)
18✔
300
        b.wg.Wait()
18✔
301

18✔
302
        log.Debug("Builder shutdown complete")
18✔
303

18✔
304
        return nil
18✔
305
}
306

307
// syncGraphWithChain attempts to synchronize the current channel graph with
308
// the latest UTXO set state. This process involves pruning from the channel
309
// graph any channels which have been closed by spending their funding output
310
// since we've been down.
311
func (b *Builder) syncGraphWithChain() error {
19✔
312
        // First, we'll need to check to see if we're already in sync with the
19✔
313
        // latest state of the UTXO set.
19✔
314
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
19✔
315
        if err != nil {
19✔
316
                return err
×
317
        }
×
318
        b.bestHeight.Store(uint32(bestHeight))
19✔
319

19✔
320
        pruneHash, pruneHeight, err := b.cfg.Graph.PruneTip()
19✔
321
        if err != nil {
19✔
322
                switch {
×
323
                // If the graph has never been pruned, or hasn't fully been
324
                // created yet, then we don't treat this as an explicit error.
325
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
×
326
                case errors.Is(err, graphdb.ErrGraphNotFound):
×
327
                default:
×
328
                        return err
×
329
                }
330
        }
331

332
        log.Infof("Prune tip for Channel Graph: height=%v, hash=%v",
19✔
333
                pruneHeight, pruneHash)
19✔
334

19✔
335
        switch {
19✔
336
        // If the graph has never been pruned, then we can exit early as this
337
        // entails it's being created for the first time and hasn't seen any
338
        // block or created channels.
339
        case pruneHeight == 0 || pruneHash == nil:
3✔
340
                return nil
3✔
341

342
        // If the block hashes and heights match exactly, then we don't need to
343
        // prune the channel graph as we're already fully in sync.
344
        case bestHash.IsEqual(pruneHash) && uint32(bestHeight) == pruneHeight:
14✔
345
                return nil
14✔
346
        }
347

348
        // If the main chain blockhash at prune height is different from the
349
        // prune hash, this might indicate the database is on a stale branch.
350
        mainBlockHash, err := b.cfg.Chain.GetBlockHash(int64(pruneHeight))
2✔
351
        if err != nil {
2✔
352
                return err
×
353
        }
×
354

355
        // While we are on a stale branch of the chain, walk backwards to find
356
        // first common block.
357
        for !pruneHash.IsEqual(mainBlockHash) {
12✔
358
                log.Infof("channel graph is stale. Disconnecting block %v "+
10✔
359
                        "(hash=%v)", pruneHeight, pruneHash)
10✔
360
                // Prune the graph for every channel that was opened at height
10✔
361
                // >= pruneHeight.
10✔
362
                _, err := b.cfg.Graph.DisconnectBlockAtHeight(pruneHeight)
10✔
363
                if err != nil {
10✔
364
                        return err
×
365
                }
×
366

367
                pruneHash, pruneHeight, err = b.cfg.Graph.PruneTip()
10✔
368
                switch {
10✔
369
                // If at this point the graph has never been pruned, we can exit
370
                // as this entails we are back to the point where it hasn't seen
371
                // any block or created channels, alas there's nothing left to
372
                // prune.
373
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
×
374
                        return nil
×
375

376
                case errors.Is(err, graphdb.ErrGraphNotFound):
×
377
                        return nil
×
378

379
                case err != nil:
×
380
                        return err
×
381

382
                default:
10✔
383
                }
384

385
                mainBlockHash, err = b.cfg.Chain.GetBlockHash(
10✔
386
                        int64(pruneHeight),
10✔
387
                )
10✔
388
                if err != nil {
10✔
389
                        return err
×
390
                }
×
391
        }
392

393
        log.Infof("Syncing channel graph from height=%v (hash=%v) to "+
2✔
394
                "height=%v (hash=%v)", pruneHeight, pruneHash, bestHeight,
2✔
395
                bestHash)
2✔
396

2✔
397
        // If we're not yet caught up, then we'll walk forward in the chain
2✔
398
        // pruning the channel graph with each new block that hasn't yet been
2✔
399
        // consumed by the channel graph.
2✔
400
        var spentOutputs []*wire.OutPoint
2✔
401
        for nextHeight := pruneHeight + 1; nextHeight <= uint32(bestHeight); nextHeight++ { //nolint:ll
25✔
402
                // Break out of the rescan early if a shutdown has been
23✔
403
                // requested, otherwise long rescans will block the daemon from
23✔
404
                // shutting down promptly.
23✔
405
                select {
23✔
406
                case <-b.quit:
×
407
                        return ErrGraphBuilderShuttingDown
×
408
                default:
23✔
409
                }
410

411
                // Using the next height, request a manual block pruning from
412
                // the chainview for the particular block hash.
413
                log.Infof("Filtering block for closed channels, at height: %v",
23✔
414
                        int64(nextHeight))
23✔
415
                nextHash, err := b.cfg.Chain.GetBlockHash(int64(nextHeight))
23✔
416
                if err != nil {
23✔
417
                        return err
×
418
                }
×
419
                log.Tracef("Running block filter on block with hash: %v",
23✔
420
                        nextHash)
23✔
421
                filterBlock, err := b.cfg.ChainView.FilterBlock(nextHash)
23✔
422
                if err != nil {
23✔
423
                        return err
×
424
                }
×
425

426
                // We're only interested in all prior outputs that have been
427
                // spent in the block, so collate all the referenced previous
428
                // outpoints within each tx and input.
429
                for _, tx := range filterBlock.Transactions {
24✔
430
                        for _, txIn := range tx.TxIn {
2✔
431
                                spentOutputs = append(spentOutputs,
1✔
432
                                        &txIn.PreviousOutPoint)
1✔
433
                        }
1✔
434
                }
435
        }
436

437
        // With the spent outputs gathered, attempt to prune the channel graph,
438
        // also passing in the best hash+height so the prune tip can be updated.
439
        closedChans, err := b.cfg.Graph.PruneGraph(
2✔
440
                spentOutputs, bestHash, uint32(bestHeight),
2✔
441
        )
2✔
442
        if err != nil {
2✔
443
                return err
×
444
        }
×
445

446
        log.Infof("Graph pruning complete: %v channels were closed since "+
2✔
447
                "height %v", len(closedChans), pruneHeight)
2✔
448

2✔
449
        return nil
2✔
450
}
451

452
// isZombieChannel takes two edge policy updates and determines if the
453
// corresponding channel should be considered a zombie. The first boolean is
454
// true if the policy update from node 1 is considered a zombie, the second
455
// boolean is that of node 2, and the final boolean is true if the channel
456
// is considered a zombie.
457
func (b *Builder) isZombieChannel(e1,
458
        e2 *models.ChannelEdgePolicy) (bool, bool, bool) {
6✔
459

6✔
460
        chanExpiry := b.cfg.ChannelPruneExpiry
6✔
461

6✔
462
        e1Zombie := e1 == nil || time.Since(e1.LastUpdate) >= chanExpiry
6✔
463
        e2Zombie := e2 == nil || time.Since(e2.LastUpdate) >= chanExpiry
6✔
464

6✔
465
        var e1Time, e2Time time.Time
6✔
466
        if e1 != nil {
10✔
467
                e1Time = e1.LastUpdate
4✔
468
        }
4✔
469
        if e2 != nil {
12✔
470
                e2Time = e2.LastUpdate
6✔
471
        }
6✔
472

473
        return e1Zombie, e2Zombie, b.IsZombieChannel(e1Time, e2Time)
6✔
474
}
475

476
// IsZombieChannel takes the timestamps of the latest channel updates for a
477
// channel and returns true if the channel should be considered a zombie based
478
// on these timestamps.
479
func (b *Builder) IsZombieChannel(updateTime1,
480
        updateTime2 time.Time) bool {
6✔
481

6✔
482
        chanExpiry := b.cfg.ChannelPruneExpiry
6✔
483

6✔
484
        e1Zombie := updateTime1.IsZero() ||
6✔
485
                time.Since(updateTime1) >= chanExpiry
6✔
486

6✔
487
        e2Zombie := updateTime2.IsZero() ||
6✔
488
                time.Since(updateTime2) >= chanExpiry
6✔
489

6✔
490
        // If we're using strict zombie pruning, then a channel is only
6✔
491
        // considered live if both edges have a recent update we know of.
6✔
492
        if b.cfg.StrictZombiePruning {
9✔
493
                return e1Zombie || e2Zombie
3✔
494
        }
3✔
495

496
        // Otherwise, if we're using the less strict variant, then a channel is
497
        // considered live if either of the edges have a recent update.
498
        return e1Zombie && e2Zombie
3✔
499
}
500

501
// pruneZombieChans is a method that will be called periodically to prune out
502
// any "zombie" channels. We consider channels zombies if *both* edges haven't
503
// been updated since our zombie horizon. If AssumeChannelValid is present,
504
// we'll also consider channels zombies if *both* edges are disabled. This
505
// usually signals that a channel has been closed on-chain. We do this
506
// periodically to keep a healthy, lively routing table.
507
func (b *Builder) pruneZombieChans() error {
5✔
508
        chansToPrune := make(map[uint64]struct{})
5✔
509
        chanExpiry := b.cfg.ChannelPruneExpiry
5✔
510

5✔
511
        log.Infof("Examining channel graph for zombie channels")
5✔
512

5✔
513
        // A helper method to detect if the channel belongs to this node
5✔
514
        isSelfChannelEdge := func(info *models.ChannelEdgeInfo) bool {
16✔
515
                return info.NodeKey1Bytes == b.cfg.SelfNode ||
11✔
516
                        info.NodeKey2Bytes == b.cfg.SelfNode
11✔
517
        }
11✔
518

519
        // First, we'll collect all the channels which are eligible for garbage
520
        // collection due to being zombies.
521
        filterPruneChans := func(info *models.ChannelEdgeInfo,
5✔
522
                e1, e2 *models.ChannelEdgePolicy) error {
13✔
523

8✔
524
                // Exit early in case this channel is already marked to be
8✔
525
                // pruned
8✔
526
                _, markedToPrune := chansToPrune[info.ChannelID]
8✔
527
                if markedToPrune {
8✔
528
                        return nil
×
529
                }
×
530

531
                // We'll ensure that we don't attempt to prune our *own*
532
                // channels from the graph, as in any case this should be
533
                // re-advertised by the sub-system above us.
534
                if isSelfChannelEdge(info) {
10✔
535
                        return nil
2✔
536
                }
2✔
537

538
                e1Zombie, e2Zombie, isZombieChan := b.isZombieChannel(e1, e2)
6✔
539

6✔
540
                if e1Zombie {
10✔
541
                        log.Tracef("Node1 pubkey=%x of chan_id=%v is zombie",
4✔
542
                                info.NodeKey1Bytes, info.ChannelID)
4✔
543
                }
4✔
544

545
                if e2Zombie {
12✔
546
                        log.Tracef("Node2 pubkey=%x of chan_id=%v is zombie",
6✔
547
                                info.NodeKey2Bytes, info.ChannelID)
6✔
548
                }
6✔
549

550
                // If either edge hasn't been updated for a period of
551
                // chanExpiry, then we'll mark the channel itself as eligible
552
                // for graph pruning.
553
                if !isZombieChan {
7✔
554
                        return nil
1✔
555
                }
1✔
556

557
                log.Debugf("ChannelID(%v) is a zombie, collecting to prune",
5✔
558
                        info.ChannelID)
5✔
559

5✔
560
                // TODO(roasbeef): add ability to delete single directional edge
5✔
561
                chansToPrune[info.ChannelID] = struct{}{}
5✔
562

5✔
563
                return nil
5✔
564
        }
565

566
        // If AssumeChannelValid is present we'll look at the disabled bit for
567
        // both edges. If they're both disabled, then we can interpret this as
568
        // the channel being closed and can prune it from our graph.
569
        if b.cfg.AssumeChannelValid {
7✔
570
                disabledChanIDs, err := b.cfg.Graph.DisabledChannelIDs()
2✔
571
                if err != nil {
2✔
572
                        return fmt.Errorf("unable to get disabled channels "+
×
573
                                "ids chans: %v", err)
×
574
                }
×
575

576
                disabledEdges, err := b.cfg.Graph.FetchChanInfos(
2✔
577
                        disabledChanIDs,
2✔
578
                )
2✔
579
                if err != nil {
2✔
580
                        return fmt.Errorf("unable to fetch disabled channels "+
×
581
                                "edges chans: %v", err)
×
582
                }
×
583

584
                // Ensuring we won't prune our own channel from the graph.
585
                for _, disabledEdge := range disabledEdges {
5✔
586
                        if !isSelfChannelEdge(disabledEdge.Info) {
4✔
587
                                chansToPrune[disabledEdge.Info.ChannelID] =
1✔
588
                                        struct{}{}
1✔
589
                        }
1✔
590
                }
591
        }
592

593
        startTime := time.Unix(0, 0)
5✔
594
        endTime := time.Now().Add(-1 * chanExpiry)
5✔
595
        oldEdges, err := b.cfg.Graph.ChanUpdatesInHorizon(startTime, endTime)
5✔
596
        if err != nil {
5✔
597
                return fmt.Errorf("unable to fetch expired channel updates "+
×
598
                        "chans: %v", err)
×
599
        }
×
600

601
        for _, u := range oldEdges {
13✔
602
                err = filterPruneChans(u.Info, u.Policy1, u.Policy2)
8✔
603
                if err != nil {
8✔
604
                        return fmt.Errorf("error filtering channels to "+
×
605
                                "prune: %w", err)
×
606
                }
×
607
        }
608

609
        log.Infof("Pruning %v zombie channels", len(chansToPrune))
5✔
610
        if len(chansToPrune) == 0 {
7✔
611
                return nil
2✔
612
        }
2✔
613

614
        // With the set of zombie-like channels obtained, we'll do another pass
615
        // to delete them from the channel graph.
616
        toPrune := make([]uint64, 0, len(chansToPrune))
3✔
617
        for chanID := range chansToPrune {
9✔
618
                toPrune = append(toPrune, chanID)
6✔
619
                log.Tracef("Pruning zombie channel with ChannelID(%v)", chanID)
6✔
620
        }
6✔
621
        err = b.cfg.Graph.DeleteChannelEdges(
3✔
622
                b.cfg.StrictZombiePruning, true, toPrune...,
3✔
623
        )
3✔
624
        if err != nil {
3✔
625
                return fmt.Errorf("unable to delete zombie channels: %w", err)
×
626
        }
×
627

628
        // With the channels pruned, we'll also attempt to prune any nodes that
629
        // were a part of them.
630
        err = b.cfg.Graph.PruneGraphNodes()
3✔
631
        if err != nil && !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
3✔
632
                return fmt.Errorf("unable to prune graph nodes: %w", err)
×
633
        }
×
634

635
        return nil
3✔
636
}
637

638
// networkHandler is the primary goroutine for the Builder. The roles of
639
// this goroutine include answering queries related to the state of the
640
// network, pruning the graph on new block notification, applying network
641
// updates, and registering new topology clients.
642
//
643
// NOTE: This MUST be run as a goroutine.
644
func (b *Builder) networkHandler() {
20✔
645
        defer b.wg.Done()
20✔
646

20✔
647
        graphPruneTicker := time.NewTicker(b.cfg.GraphPruneInterval)
20✔
648
        defer graphPruneTicker.Stop()
20✔
649

20✔
650
        defer b.statTicker.Stop()
20✔
651

20✔
652
        b.stats.Reset()
20✔
653

20✔
654
        for {
115✔
655
                // If there are stats, resume the statTicker.
95✔
656
                if !b.stats.Empty() {
123✔
657
                        b.statTicker.Resume()
28✔
658
                }
28✔
659

660
                select {
95✔
661
                case chainUpdate, ok := <-b.staleBlocks:
10✔
662
                        // If the channel has been closed, then this indicates
10✔
663
                        // the daemon is shutting down, so we exit ourselves.
10✔
664
                        if !ok {
10✔
665
                                return
×
666
                        }
×
667

668
                        // Since this block is stale, we update our best height
669
                        // to the previous block.
670
                        blockHeight := chainUpdate.Height
10✔
671
                        b.bestHeight.Store(blockHeight - 1)
10✔
672

10✔
673
                        // Update the channel graph to reflect that this block
10✔
674
                        // was disconnected.
10✔
675
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
10✔
676
                                blockHeight,
10✔
677
                        )
10✔
678
                        if err != nil {
10✔
679
                                log.Errorf("unable to prune graph with stale "+
×
680
                                        "block: %v", err)
×
681
                                continue
×
682
                        }
683

684
                        // TODO(halseth): notify client about the reorg?
685

686
                // A new block has arrived, so we can prune the channel graph
687
                // of any channels which were closed in the block.
688
                case chainUpdate, ok := <-b.newBlocks:
65✔
689
                        // If the channel has been closed, then this indicates
65✔
690
                        // the daemon is shutting down, so we exit ourselves.
65✔
691
                        if !ok {
65✔
692
                                return
×
693
                        }
×
694

695
                        // We'll ensure that any new blocks received attach
696
                        // directly to the end of our main chain. If not, then
697
                        // we've somehow missed some blocks. Here we'll catch
698
                        // up the chain with the latest blocks.
699
                        currentHeight := b.bestHeight.Load()
65✔
700
                        switch {
65✔
701
                        case chainUpdate.Height == currentHeight+1:
59✔
702
                                err := b.updateGraphWithClosedChannels(
59✔
703
                                        chainUpdate,
59✔
704
                                )
59✔
705
                                if err != nil {
59✔
706
                                        log.Errorf("unable to prune graph "+
×
707
                                                "with closed channels: %v", err)
×
708
                                }
×
709

710
                        case chainUpdate.Height > currentHeight+1:
1✔
711
                                log.Errorf("out of order block: expecting "+
1✔
712
                                        "height=%v, got height=%v",
1✔
713
                                        currentHeight+1, chainUpdate.Height)
1✔
714

1✔
715
                                err := b.getMissingBlocks(
1✔
716
                                        currentHeight, chainUpdate,
1✔
717
                                )
1✔
718
                                if err != nil {
1✔
719
                                        log.Errorf("unable to retrieve missing"+
×
720
                                                "blocks: %v", err)
×
721
                                }
×
722

723
                        case chainUpdate.Height < currentHeight+1:
5✔
724
                                log.Errorf("out of order block: expecting "+
5✔
725
                                        "height=%v, got height=%v",
5✔
726
                                        currentHeight+1, chainUpdate.Height)
5✔
727

5✔
728
                                log.Infof("Skipping channel pruning since "+
5✔
729
                                        "received block height %v was already"+
5✔
730
                                        " processed.", chainUpdate.Height)
5✔
731
                        }
732

733
                // The graph prune ticker has ticked, so we'll examine the
734
                // state of the known graph to filter out any zombie channels
735
                // for pruning.
736
                case <-graphPruneTicker.C:
×
737
                        if err := b.pruneZombieChans(); err != nil {
×
738
                                log.Errorf("Unable to prune zombies: %v", err)
×
739
                        }
×
740

741
                // Log any stats if we've processed a non-empty number of
742
                // channels, updates, or nodes. We'll only pause the ticker if
743
                // the last window contained no updates to avoid resuming and
744
                // pausing while consecutive windows contain new info.
745
                case <-b.statTicker.Ticks():
×
746
                        if !b.stats.Empty() {
×
747
                                log.Infof(b.stats.String())
×
748
                        } else {
×
749
                                b.statTicker.Pause()
×
750
                        }
×
751
                        b.stats.Reset()
×
752

753
                // The router has been signalled to exit, to we exit our main
754
                // loop so the wait group can be decremented.
755
                case <-b.quit:
18✔
756
                        return
18✔
757
                }
758
        }
759
}
760

761
// getMissingBlocks walks through all missing blocks and updates the graph
762
// closed channels accordingly.
763
func (b *Builder) getMissingBlocks(currentHeight uint32,
764
        chainUpdate *chainview.FilteredBlock) error {
1✔
765

1✔
766
        outdatedHash, err := b.cfg.Chain.GetBlockHash(int64(currentHeight))
1✔
767
        if err != nil {
1✔
768
                return err
×
769
        }
×
770

771
        outdatedBlock := &chainntnfs.BlockEpoch{
1✔
772
                Height: int32(currentHeight),
1✔
773
                Hash:   outdatedHash,
1✔
774
        }
1✔
775

1✔
776
        epochClient, err := b.cfg.Notifier.RegisterBlockEpochNtfn(
1✔
777
                outdatedBlock,
1✔
778
        )
1✔
779
        if err != nil {
1✔
780
                return err
×
781
        }
×
782
        defer epochClient.Cancel()
1✔
783

1✔
784
        blockDifference := int(chainUpdate.Height - currentHeight)
1✔
785

1✔
786
        // We'll walk through all the outdated blocks and make sure we're able
1✔
787
        // to update the graph with any closed channels from them.
1✔
788
        for i := 0; i < blockDifference; i++ {
6✔
789
                var (
5✔
790
                        missingBlock *chainntnfs.BlockEpoch
5✔
791
                        ok           bool
5✔
792
                )
5✔
793

5✔
794
                select {
5✔
795
                case missingBlock, ok = <-epochClient.Epochs:
5✔
796
                        if !ok {
5✔
797
                                return nil
×
798
                        }
×
799

800
                case <-b.quit:
×
801
                        return nil
×
802
                }
803

804
                filteredBlock, err := b.cfg.ChainView.FilterBlock(
5✔
805
                        missingBlock.Hash,
5✔
806
                )
5✔
807
                if err != nil {
5✔
808
                        return err
×
809
                }
×
810

811
                err = b.updateGraphWithClosedChannels(
5✔
812
                        filteredBlock,
5✔
813
                )
5✔
814
                if err != nil {
5✔
815
                        return err
×
816
                }
×
817
        }
818

819
        return nil
1✔
820
}
821

822
// updateGraphWithClosedChannels prunes the channel graph of closed channels
823
// that are no longer needed.
824
func (b *Builder) updateGraphWithClosedChannels(
825
        chainUpdate *chainview.FilteredBlock) error {
64✔
826

64✔
827
        // Once a new block arrives, we update our running track of the height
64✔
828
        // of the chain tip.
64✔
829
        blockHeight := chainUpdate.Height
64✔
830

64✔
831
        b.bestHeight.Store(blockHeight)
64✔
832
        log.Infof("Pruning channel graph using block %v (height=%v)",
64✔
833
                chainUpdate.Hash, blockHeight)
64✔
834

64✔
835
        // We're only interested in all prior outputs that have been spent in
64✔
836
        // the block, so collate all the referenced previous outpoints within
64✔
837
        // each tx and input.
64✔
838
        var spentOutputs []*wire.OutPoint
64✔
839
        for _, tx := range chainUpdate.Transactions {
65✔
840
                for _, txIn := range tx.TxIn {
2✔
841
                        spentOutputs = append(spentOutputs,
1✔
842
                                &txIn.PreviousOutPoint)
1✔
843
                }
1✔
844
        }
845

846
        // With the spent outputs gathered, attempt to prune the channel graph,
847
        // also passing in the hash+height of the block being pruned so the
848
        // prune tip can be updated.
849
        chansClosed, err := b.cfg.Graph.PruneGraph(spentOutputs,
64✔
850
                &chainUpdate.Hash, chainUpdate.Height)
64✔
851
        if err != nil {
64✔
852
                log.Errorf("unable to prune routing table: %v", err)
×
853
                return err
×
854
        }
×
855

856
        log.Infof("Block %v (height=%v) closed %v channels", chainUpdate.Hash,
64✔
857
                blockHeight, len(chansClosed))
64✔
858

64✔
859
        return nil
64✔
860
}
861

862
// assertNodeAnnFreshness returns a non-nil error if we have an announcement in
863
// the database for the passed node with a timestamp newer than the passed
864
// timestamp. ErrIgnored will be returned if we already have the node, and
865
// ErrOutdated will be returned if we have a timestamp that's after the new
866
// timestamp.
867
func (b *Builder) assertNodeAnnFreshness(node route.Vertex,
868
        msgTimestamp time.Time) error {
10✔
869

10✔
870
        // If we are not already aware of this node, it means that we don't
10✔
871
        // know about any channel using this node. To avoid a DoS attack by
10✔
872
        // node announcements, we will ignore such nodes. If we do know about
10✔
873
        // this node, check that this update brings info newer than what we
10✔
874
        // already have.
10✔
875
        lastUpdate, exists, err := b.cfg.Graph.HasLightningNode(node)
10✔
876
        if err != nil {
10✔
877
                return errors.Errorf("unable to query for the "+
×
878
                        "existence of node: %v", err)
×
879
        }
×
880
        if !exists {
11✔
881
                return NewErrf(ErrIgnored, "Ignoring node announcement"+
1✔
882
                        " for node not found in channel graph (%x)",
1✔
883
                        node[:])
1✔
884
        }
1✔
885

886
        // If we've reached this point then we're aware of the vertex being
887
        // advertised. So we now check if the new message has a new time stamp,
888
        // if not then we won't accept the new data as it would override newer
889
        // data.
890
        if !lastUpdate.Before(msgTimestamp) {
10✔
891
                return NewErrf(ErrOutdated, "Ignoring outdated "+
1✔
892
                        "announcement for %x", node[:])
1✔
893
        }
1✔
894

895
        return nil
8✔
896
}
897

898
// MarkZombieEdge adds a channel that failed complete validation into the zombie
899
// index so we can avoid having to re-validate it in the future.
900
func (b *Builder) MarkZombieEdge(chanID uint64) error {
×
901
        // If the edge fails validation we'll mark the edge itself as a zombie
×
902
        // so we don't continue to request it. We use the "zero key" for both
×
903
        // node pubkeys so this edge can't be resurrected.
×
904
        var zeroKey [33]byte
×
905
        err := b.cfg.Graph.MarkEdgeZombie(chanID, zeroKey, zeroKey)
×
906
        if err != nil {
×
907
                return fmt.Errorf("unable to mark spent chan(id=%v) as a "+
×
908
                        "zombie: %w", chanID, err)
×
909
        }
×
910

911
        return nil
×
912
}
913

914
// ApplyChannelUpdate validates a channel update and if valid, applies it to the
915
// database. It returns a bool indicating whether the updates were successful.
916
func (b *Builder) ApplyChannelUpdate(msg *lnwire.ChannelUpdate1) bool {
×
917
        ch, _, _, err := b.GetChannelByID(msg.ShortChannelID)
×
918
        if err != nil {
×
919
                log.Errorf("Unable to retrieve channel by id: %v", err)
×
920
                return false
×
921
        }
×
922

923
        var pubKey *btcec.PublicKey
×
924

×
925
        switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
×
926
        case 0:
×
927
                pubKey, _ = ch.NodeKey1()
×
928

929
        case 1:
×
930
                pubKey, _ = ch.NodeKey2()
×
931
        }
932

933
        // Exit early if the pubkey cannot be decided.
934
        if pubKey == nil {
×
935
                log.Errorf("Unable to decide pubkey with ChannelFlags=%v",
×
936
                        msg.ChannelFlags)
×
937
                return false
×
938
        }
×
939

940
        err = netann.ValidateChannelUpdateAnn(pubKey, ch.Capacity, msg)
×
941
        if err != nil {
×
942
                log.Errorf("Unable to validate channel update: %v", err)
×
943
                return false
×
944
        }
×
945

946
        update := &models.ChannelEdgePolicy{
×
947
                SigBytes:                  msg.Signature.ToSignatureBytes(),
×
948
                ChannelID:                 msg.ShortChannelID.ToUint64(),
×
949
                LastUpdate:                time.Unix(int64(msg.Timestamp), 0),
×
950
                MessageFlags:              msg.MessageFlags,
×
951
                ChannelFlags:              msg.ChannelFlags,
×
952
                TimeLockDelta:             msg.TimeLockDelta,
×
953
                MinHTLC:                   msg.HtlcMinimumMsat,
×
954
                MaxHTLC:                   msg.HtlcMaximumMsat,
×
955
                FeeBaseMSat:               lnwire.MilliSatoshi(msg.BaseFee),
×
956
                FeeProportionalMillionths: lnwire.MilliSatoshi(msg.FeeRate),
×
957
                InboundFee:                msg.InboundFee.ValOpt(),
×
958
                ExtraOpaqueData:           msg.ExtraOpaqueData,
×
959
        }
×
960

×
961
        err = b.UpdateEdge(update)
×
962
        if err != nil && !IsError(err, ErrIgnored, ErrOutdated) {
×
963
                log.Errorf("Unable to apply channel update: %v", err)
×
964
                return false
×
965
        }
×
966

967
        return true
×
968
}
969

970
// AddNode is used to add information about a node to the router database. If
971
// the node with this pubkey is not present in an existing channel, it will
972
// be ignored.
973
//
974
// NOTE: This method is part of the ChannelGraphSource interface.
975
func (b *Builder) AddNode(node *models.LightningNode,
976
        op ...batch.SchedulerOption) error {
7✔
977

7✔
978
        err := b.addNode(node, op...)
7✔
979
        if err != nil {
8✔
980
                logNetworkMsgProcessError(err)
1✔
981

1✔
982
                return err
1✔
983
        }
1✔
984

985
        return nil
6✔
986
}
987

988
// addNode does some basic checks on the given LightningNode against what we
989
// currently have persisted in the graph, and then adds it to the graph. If we
990
// already know about the node, then we only update our DB if the new update
991
// has a newer timestamp than the last one we received.
992
func (b *Builder) addNode(node *models.LightningNode,
993
        op ...batch.SchedulerOption) error {
7✔
994

7✔
995
        // Before we add the node to the database, we'll check to see if the
7✔
996
        // announcement is "fresh" or not. If it isn't, then we'll return an
7✔
997
        // error.
7✔
998
        err := b.assertNodeAnnFreshness(node.PubKeyBytes, node.LastUpdate)
7✔
999
        if err != nil {
8✔
1000
                return err
1✔
1001
        }
1✔
1002

1003
        if err := b.cfg.Graph.AddLightningNode(node, op...); err != nil {
6✔
1004
                return errors.Errorf("unable to add node %x to the "+
×
1005
                        "graph: %v", node.PubKeyBytes, err)
×
1006
        }
×
1007

1008
        log.Tracef("Updated vertex data for node=%x", node.PubKeyBytes)
6✔
1009
        b.stats.incNumNodeUpdates()
6✔
1010

6✔
1011
        return nil
6✔
1012
}
1013

1014
// AddEdge is used to add edge/channel to the topology of the router, after all
1015
// information about channel will be gathered this edge/channel might be used
1016
// in construction of payment path.
1017
//
1018
// NOTE: This method is part of the ChannelGraphSource interface.
1019
func (b *Builder) AddEdge(edge *models.ChannelEdgeInfo,
1020
        op ...batch.SchedulerOption) error {
14✔
1021

14✔
1022
        err := b.addEdge(edge, op...)
14✔
1023
        if err != nil {
14✔
1024
                logNetworkMsgProcessError(err)
×
1025

×
1026
                return err
×
1027
        }
×
1028

1029
        return nil
14✔
1030
}
1031

1032
// addEdge does some validation on the new channel edge against what we
1033
// currently have persisted in the graph, and then adds it to the graph. The
1034
// Chain View is updated with the new edge if it is successfully added to the
1035
// graph. We only persist the channel if we currently dont have it at all in
1036
// our graph.
1037
//
1038
// TODO(elle): this currently also does funding-transaction validation. But this
1039
// should be moved to the gossiper instead.
1040
func (b *Builder) addEdge(edge *models.ChannelEdgeInfo,
1041
        op ...batch.SchedulerOption) error {
14✔
1042

14✔
1043
        log.Debugf("Received ChannelEdgeInfo for channel %v", edge.ChannelID)
14✔
1044

14✔
1045
        // Prior to processing the announcement we first check if we
14✔
1046
        // already know of this channel, if so, then we can exit early.
14✔
1047
        _, _, exists, isZombie, err := b.cfg.Graph.HasChannelEdge(
14✔
1048
                edge.ChannelID,
14✔
1049
        )
14✔
1050
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
14✔
1051
                return errors.Errorf("unable to check for edge existence: %v",
×
1052
                        err)
×
1053
        }
×
1054
        if isZombie {
14✔
1055
                return NewErrf(ErrIgnored, "ignoring msg for zombie chan_id=%v",
×
1056
                        edge.ChannelID)
×
1057
        }
×
1058
        if exists {
14✔
1059
                return NewErrf(ErrIgnored, "ignoring msg for known chan_id=%v",
×
1060
                        edge.ChannelID)
×
1061
        }
×
1062

1063
        if err := b.cfg.Graph.AddChannelEdge(edge, op...); err != nil {
14✔
1064
                return fmt.Errorf("unable to add edge: %w", err)
×
1065
        }
×
1066

1067
        b.stats.incNumEdgesDiscovered()
14✔
1068

14✔
1069
        // If AssumeChannelValid is present, of if the SCID is an alias, then
14✔
1070
        // the gossiper would not have done the expensive work of fetching
14✔
1071
        // a funding transaction and validating it. So we won't have the channel
14✔
1072
        // capacity nor the funding script. So we just log and return here.
14✔
1073
        scid := lnwire.NewShortChanIDFromInt(edge.ChannelID)
14✔
1074
        if b.cfg.AssumeChannelValid || b.cfg.IsAlias(scid) {
14✔
1075
                log.Tracef("New channel discovered! Link connects %x and %x "+
×
1076
                        "with ChannelID(%v)", edge.NodeKey1Bytes,
×
1077
                        edge.NodeKey2Bytes, edge.ChannelID)
×
1078

×
1079
                return nil
×
1080
        }
×
1081

1082
        log.Debugf("New channel discovered! Link connects %x and %x with "+
14✔
1083
                "ChannelPoint(%v): chan_id=%v, capacity=%v", edge.NodeKey1Bytes,
14✔
1084
                edge.NodeKey2Bytes, edge.ChannelPoint, edge.ChannelID,
14✔
1085
                edge.Capacity)
14✔
1086

14✔
1087
        // Otherwise, then we expect the funding script to be present on the
14✔
1088
        // edge since it would have been fetched when the gossiper validated the
14✔
1089
        // announcement.
14✔
1090
        fundingPkScript, err := edge.FundingScript.UnwrapOrErr(fmt.Errorf(
14✔
1091
                "expected the funding transaction script to be set",
14✔
1092
        ))
14✔
1093
        if err != nil {
14✔
1094
                return err
×
1095
        }
×
1096

1097
        // As a new edge has been added to the channel graph, we'll update the
1098
        // current UTXO filter within our active FilteredChainView so we are
1099
        // notified if/when this channel is closed.
1100
        filterUpdate := []graphdb.EdgePoint{
14✔
1101
                {
14✔
1102
                        FundingPkScript: fundingPkScript,
14✔
1103
                        OutPoint:        edge.ChannelPoint,
14✔
1104
                },
14✔
1105
        }
14✔
1106

14✔
1107
        err = b.cfg.ChainView.UpdateFilter(filterUpdate, b.bestHeight.Load())
14✔
1108
        if err != nil {
14✔
1109
                return errors.Errorf("unable to update chain "+
×
1110
                        "view: %v", err)
×
1111
        }
×
1112

1113
        return nil
14✔
1114
}
1115

1116
// UpdateEdge is used to update edge information, without this message edge
1117
// considered as not fully constructed.
1118
//
1119
// NOTE: This method is part of the ChannelGraphSource interface.
1120
func (b *Builder) UpdateEdge(update *models.ChannelEdgePolicy,
1121
        op ...batch.SchedulerOption) error {
6✔
1122

6✔
1123
        err := b.updateEdge(update, op...)
6✔
1124
        if err != nil {
7✔
1125
                logNetworkMsgProcessError(err)
1✔
1126

1✔
1127
                return err
1✔
1128
        }
1✔
1129

1130
        return nil
5✔
1131
}
1132

1133
// updateEdge validates the new edge policy against what we currently have
1134
// persisted in the graph, and then applies it to the graph if the update is
1135
// considered fresh enough and if we actually have a channel persisted for the
1136
// given update.
1137
func (b *Builder) updateEdge(policy *models.ChannelEdgePolicy,
1138
        op ...batch.SchedulerOption) error {
6✔
1139

6✔
1140
        log.Debugf("Received ChannelEdgePolicy for channel %v",
6✔
1141
                policy.ChannelID)
6✔
1142

6✔
1143
        // We make sure to hold the mutex for this channel ID, such that no
6✔
1144
        // other goroutine is concurrently doing database accesses for the same
6✔
1145
        // channel ID.
6✔
1146
        b.channelEdgeMtx.Lock(policy.ChannelID)
6✔
1147
        defer b.channelEdgeMtx.Unlock(policy.ChannelID)
6✔
1148

6✔
1149
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
6✔
1150
                b.cfg.Graph.HasChannelEdge(policy.ChannelID)
6✔
1151
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
6✔
1152
                return errors.Errorf("unable to check for edge existence: %v",
×
1153
                        err)
×
1154
        }
×
1155

1156
        // If the channel is marked as a zombie in our database, and
1157
        // we consider this a stale update, then we should not apply the
1158
        // policy.
1159
        isStaleUpdate := time.Since(policy.LastUpdate) >
6✔
1160
                b.cfg.ChannelPruneExpiry
6✔
1161

6✔
1162
        if isZombie && isStaleUpdate {
6✔
1163
                return NewErrf(ErrIgnored, "ignoring stale update "+
×
1164
                        "(flags=%v|%v) for zombie chan_id=%v",
×
1165
                        policy.MessageFlags, policy.ChannelFlags,
×
1166
                        policy.ChannelID)
×
1167
        }
×
1168

1169
        // If the channel doesn't exist in our database, we cannot apply the
1170
        // updated policy.
1171
        if !exists {
7✔
1172
                return NewErrf(ErrIgnored, "ignoring update (flags=%v|%v) for "+
1✔
1173
                        "unknown chan_id=%v", policy.MessageFlags,
1✔
1174
                        policy.ChannelFlags, policy.ChannelID)
1✔
1175
        }
1✔
1176

1177
        log.Debugf("Found edge1Timestamp=%v, edge2Timestamp=%v",
5✔
1178
                edge1Timestamp, edge2Timestamp)
5✔
1179

5✔
1180
        // As edges are directional edge node has a unique policy for the
5✔
1181
        // direction of the edge they control. Therefore, we first check if we
5✔
1182
        // already have the most up-to-date information for that edge. If this
5✔
1183
        // message has a timestamp not strictly newer than what we already know
5✔
1184
        // of we can exit early.
5✔
1185
        switch policy.ChannelFlags & lnwire.ChanUpdateDirection {
5✔
1186
        // A flag set of 0 indicates this is an announcement for the "first"
1187
        // node in the channel.
1188
        case 0:
3✔
1189
                // Ignore outdated message.
3✔
1190
                if !edge1Timestamp.Before(policy.LastUpdate) {
3✔
1191
                        return NewErrf(ErrOutdated, "Ignoring "+
×
1192
                                "outdated update (flags=%v|%v) for "+
×
1193
                                "known chan_id=%v", policy.MessageFlags,
×
1194
                                policy.ChannelFlags, policy.ChannelID)
×
1195
                }
×
1196

1197
        // Similarly, a flag set of 1 indicates this is an announcement
1198
        // for the "second" node in the channel.
1199
        case 1:
2✔
1200
                // Ignore outdated message.
2✔
1201
                if !edge2Timestamp.Before(policy.LastUpdate) {
2✔
1202
                        return NewErrf(ErrOutdated, "Ignoring "+
×
1203
                                "outdated update (flags=%v|%v) for "+
×
1204
                                "known chan_id=%v", policy.MessageFlags,
×
1205
                                policy.ChannelFlags, policy.ChannelID)
×
1206
                }
×
1207
        }
1208

1209
        // Now that we know this isn't a stale update, we'll apply the new edge
1210
        // policy to the proper directional edge within the channel graph.
1211
        if err = b.cfg.Graph.UpdateEdgePolicy(policy, op...); err != nil {
5✔
1212
                err := errors.Errorf("unable to add channel: %v", err)
×
1213
                log.Error(err)
×
1214
                return err
×
1215
        }
×
1216

1217
        log.Tracef("New channel update applied: %v",
5✔
1218
                lnutils.SpewLogClosure(policy))
5✔
1219
        b.stats.incNumChannelUpdates()
5✔
1220

5✔
1221
        return nil
5✔
1222
}
1223

1224
// logNetworkMsgProcessError logs the error received from processing a network
1225
// message. It logs as a debug message if the error is not critical.
1226
func logNetworkMsgProcessError(err error) {
2✔
1227
        if IsError(err, ErrIgnored, ErrOutdated) {
4✔
1228
                log.Debugf("process network updates got: %v", err)
2✔
1229

2✔
1230
                return
2✔
1231
        }
2✔
1232

1233
        log.Errorf("process network updates got: %v", err)
×
1234
}
1235

1236
// CurrentBlockHeight returns the block height from POV of the router subsystem.
1237
//
1238
// NOTE: This method is part of the ChannelGraphSource interface.
1239
func (b *Builder) CurrentBlockHeight() (uint32, error) {
×
1240
        _, height, err := b.cfg.Chain.GetBestBlock()
×
1241
        return uint32(height), err
×
1242
}
×
1243

1244
// SyncedHeight returns the block height to which the router subsystem currently
1245
// is synced to. This can differ from the above chain height if the goroutine
1246
// responsible for processing the blocks isn't yet up to speed.
1247
func (b *Builder) SyncedHeight() uint32 {
×
1248
        return b.bestHeight.Load()
×
1249
}
×
1250

1251
// GetChannelByID return the channel by the channel id.
1252
//
1253
// NOTE: This method is part of the ChannelGraphSource interface.
1254
func (b *Builder) GetChannelByID(chanID lnwire.ShortChannelID) (
1255
        *models.ChannelEdgeInfo,
1256
        *models.ChannelEdgePolicy,
1257
        *models.ChannelEdgePolicy, error) {
1✔
1258

1✔
1259
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
1✔
1260
}
1✔
1261

1262
// FetchLightningNode attempts to look up a target node by its identity public
1263
// key. graphdb.ErrGraphNodeNotFound is returned if the node doesn't exist
1264
// within the graph.
1265
//
1266
// NOTE: This method is part of the ChannelGraphSource interface.
1267
func (b *Builder) FetchLightningNode(
1268
        node route.Vertex) (*models.LightningNode, error) {
×
1269

×
1270
        return b.cfg.Graph.FetchLightningNode(node)
×
1271
}
×
1272

1273
// ForAllOutgoingChannels is used to iterate over all outgoing channels owned by
1274
// the router.
1275
//
1276
// NOTE: This method is part of the ChannelGraphSource interface.
1277
func (b *Builder) ForAllOutgoingChannels(cb func(*models.ChannelEdgeInfo,
1278
        *models.ChannelEdgePolicy) error) error {
×
1279

×
1280
        return b.cfg.Graph.ForEachNodeChannel(b.cfg.SelfNode,
×
1281
                func(c *models.ChannelEdgeInfo, e *models.ChannelEdgePolicy,
×
1282
                        _ *models.ChannelEdgePolicy) error {
×
1283

×
1284
                        if e == nil {
×
1285
                                return fmt.Errorf("channel from self node " +
×
1286
                                        "has no policy")
×
1287
                        }
×
1288

1289
                        return cb(c, e)
×
1290
                },
1291
        )
1292
}
1293

1294
// AddProof updates the channel edge info with proof which is needed to
1295
// properly announce the edge to the rest of the network.
1296
//
1297
// NOTE: This method is part of the ChannelGraphSource interface.
1298
func (b *Builder) AddProof(chanID lnwire.ShortChannelID,
1299
        proof *models.ChannelAuthProof) error {
1✔
1300

1✔
1301
        return b.cfg.Graph.AddEdgeProof(chanID, proof)
1✔
1302
}
1✔
1303

1304
// IsStaleNode returns true if the graph source has a node announcement for the
1305
// target node with a more recent timestamp.
1306
//
1307
// NOTE: This method is part of the ChannelGraphSource interface.
1308
func (b *Builder) IsStaleNode(node route.Vertex,
1309
        timestamp time.Time) bool {
3✔
1310

3✔
1311
        // If our attempt to assert that the node announcement is fresh fails,
3✔
1312
        // then we know that this is actually a stale announcement.
3✔
1313
        err := b.assertNodeAnnFreshness(node, timestamp)
3✔
1314
        if err != nil {
4✔
1315
                log.Debugf("Checking stale node %x got %v", node, err)
1✔
1316
                return true
1✔
1317
        }
1✔
1318

1319
        return false
2✔
1320
}
1321

1322
// IsPublicNode determines whether the given vertex is seen as a public node in
1323
// the graph from the graph's source node's point of view.
1324
//
1325
// NOTE: This method is part of the ChannelGraphSource interface.
1326
func (b *Builder) IsPublicNode(node route.Vertex) (bool, error) {
×
1327
        return b.cfg.Graph.IsPublicNode(node)
×
1328
}
×
1329

1330
// IsKnownEdge returns true if the graph source already knows of the passed
1331
// channel ID either as a live or zombie edge.
1332
//
1333
// NOTE: This method is part of the ChannelGraphSource interface.
1334
func (b *Builder) IsKnownEdge(chanID lnwire.ShortChannelID) bool {
1✔
1335
        _, _, exists, isZombie, _ := b.cfg.Graph.HasChannelEdge(
1✔
1336
                chanID.ToUint64(),
1✔
1337
        )
1✔
1338

1✔
1339
        return exists || isZombie
1✔
1340
}
1✔
1341

1342
// IsZombieEdge returns true if the graph source has marked the given channel ID
1343
// as a zombie edge.
1344
//
1345
// NOTE: This method is part of the ChannelGraphSource interface.
1346
func (b *Builder) IsZombieEdge(chanID lnwire.ShortChannelID) (bool, error) {
×
1347
        _, _, _, isZombie, err := b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
×
1348

×
1349
        return isZombie, err
×
1350
}
×
1351

1352
// IsStaleEdgePolicy returns true if the graph source has a channel edge for
1353
// the passed channel ID (and flags) that have a more recent timestamp.
1354
//
1355
// NOTE: This method is part of the ChannelGraphSource interface.
1356
func (b *Builder) IsStaleEdgePolicy(chanID lnwire.ShortChannelID,
1357
        timestamp time.Time, flags lnwire.ChanUpdateChanFlags) bool {
6✔
1358

6✔
1359
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
6✔
1360
                b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
6✔
1361
        if err != nil {
6✔
1362
                log.Debugf("Check stale edge policy got error: %v", err)
×
1363
                return false
×
1364
        }
×
1365

1366
        // If we know of the edge as a zombie, then we'll make some additional
1367
        // checks to determine if the new policy is fresh.
1368
        if isZombie {
6✔
1369
                // When running with AssumeChannelValid, we also prune channels
×
1370
                // if both of their edges are disabled. We'll mark the new
×
1371
                // policy as stale if it remains disabled.
×
1372
                if b.cfg.AssumeChannelValid {
×
1373
                        isDisabled := flags&lnwire.ChanUpdateDisabled ==
×
1374
                                lnwire.ChanUpdateDisabled
×
1375
                        if isDisabled {
×
1376
                                return true
×
1377
                        }
×
1378
                }
1379

1380
                // Otherwise, we'll fall back to our usual ChannelPruneExpiry.
1381
                return time.Since(timestamp) > b.cfg.ChannelPruneExpiry
×
1382
        }
1383

1384
        // If we don't know of the edge, then it means it's fresh (thus not
1385
        // stale).
1386
        if !exists {
8✔
1387
                return false
2✔
1388
        }
2✔
1389

1390
        // As edges are directional edge node has a unique policy for the
1391
        // direction of the edge they control. Therefore, we first check if we
1392
        // already have the most up-to-date information for that edge. If so,
1393
        // then we can exit early.
1394
        switch {
4✔
1395
        // A flag set of 0 indicates this is an announcement for the "first"
1396
        // node in the channel.
1397
        case flags&lnwire.ChanUpdateDirection == 0:
2✔
1398
                return !edge1Timestamp.Before(timestamp)
2✔
1399

1400
        // Similarly, a flag set of 1 indicates this is an announcement for the
1401
        // "second" node in the channel.
1402
        case flags&lnwire.ChanUpdateDirection == 1:
2✔
1403
                return !edge2Timestamp.Before(timestamp)
2✔
1404
        }
1405

1406
        return false
×
1407
}
1408

1409
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
1410
//
1411
// NOTE: This method is part of the ChannelGraphSource interface.
1412
func (b *Builder) MarkEdgeLive(chanID lnwire.ShortChannelID) error {
×
1413
        return b.cfg.Graph.MarkEdgeLive(chanID.ToUint64())
×
1414
}
×
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