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

lightningnetwork / lnd / 13416360603

19 Feb 2025 03:34PM UTC coverage: 58.686% (-0.1%) from 58.794%
13416360603

Pull #9529

github

ellemouton
graph/db: move Topology client management to ChannelGraph
Pull Request #9529: [Concept ACK 🙏 ] graph: move graph cache out of CRUD layer & move topology change subscription

2732 of 3486 new or added lines in 9 files covered. (78.37%)

358 existing lines in 29 files now uncovered.

135967 of 231686 relevant lines covered (58.69%)

19334.46 hits per line

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

77.57
/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/kvdb"
17
        "github.com/lightningnetwork/lnd/lnutils"
18
        "github.com/lightningnetwork/lnd/lnwallet"
19
        "github.com/lightningnetwork/lnd/lnwire"
20
        "github.com/lightningnetwork/lnd/multimutex"
21
        "github.com/lightningnetwork/lnd/netann"
22
        "github.com/lightningnetwork/lnd/routing/chainview"
23
        "github.com/lightningnetwork/lnd/routing/route"
24
        "github.com/lightningnetwork/lnd/ticker"
25
)
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

112
        bestHeight atomic.Uint32
113

114
        cfg *Config
115

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

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

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

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

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

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

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

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

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

164
        log.Info("Builder starting")
22✔
165

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

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

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

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

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

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

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

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

×
233
                        return err
×
234
                }
×
235

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

21✔
239
                if len(channelView) != 0 {
30✔
240
                        err = b.cfg.ChainView.UpdateFilter(
9✔
241
                                channelView, uint32(bestHeight),
9✔
242
                        )
9✔
243
                        if err != nil {
9✔
244
                                return err
×
245
                        }
×
246
                }
247

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

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

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

×
270
                        return err
×
271
                }
×
272
        }
273

274
        b.wg.Add(1)
22✔
275
        go b.networkHandler()
22✔
276

22✔
277
        log.Debug("Builder started")
22✔
278

22✔
279
        return nil
22✔
280
}
281

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

290
        log.Info("Builder shutting down...")
20✔
291

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

300
        close(b.quit)
20✔
301
        b.wg.Wait()
20✔
302

20✔
303
        log.Debug("Builder shutdown complete")
20✔
304

20✔
305
        return nil
20✔
306
}
307

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

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

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

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

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

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

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

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

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

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

383
                default:
10✔
384
                }
385

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

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

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

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

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

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

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

4✔
450
        return nil
4✔
451
}
452

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5✔
564
                return nil
5✔
565
        }
566

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

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

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

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

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

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

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

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

636
        return nil
3✔
637
}
638

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

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

22✔
651
        defer b.statTicker.Stop()
22✔
652

22✔
653
        b.stats.Reset()
22✔
654

22✔
655
        for {
120✔
656
                // If there are stats, resume the statTicker.
98✔
657
                if !b.stats.Empty() {
130✔
658
                        b.statTicker.Resume()
32✔
659
                }
32✔
660

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

820
        return nil
1✔
821
}
822

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

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

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

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

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

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

67✔
860
        return nil
67✔
861
}
862

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

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

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

896
        return nil
10✔
897
}
898

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

912
        return nil
×
913
}
914

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

924
        var pubKey *btcec.PublicKey
2✔
925

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

930
        case 1:
2✔
931
                pubKey, _ = ch.NodeKey2()
2✔
932
        }
933

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

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

947
        err = b.UpdateEdge(&models.ChannelEdgePolicy{
2✔
948
                SigBytes:                  msg.Signature.ToSignatureBytes(),
2✔
949
                ChannelID:                 msg.ShortChannelID.ToUint64(),
2✔
950
                LastUpdate:                time.Unix(int64(msg.Timestamp), 0),
2✔
951
                MessageFlags:              msg.MessageFlags,
2✔
952
                ChannelFlags:              msg.ChannelFlags,
2✔
953
                TimeLockDelta:             msg.TimeLockDelta,
2✔
954
                MinHTLC:                   msg.HtlcMinimumMsat,
2✔
955
                MaxHTLC:                   msg.HtlcMaximumMsat,
2✔
956
                FeeBaseMSat:               lnwire.MilliSatoshi(msg.BaseFee),
2✔
957
                FeeProportionalMillionths: lnwire.MilliSatoshi(msg.FeeRate),
2✔
958
                ExtraOpaqueData:           msg.ExtraOpaqueData,
2✔
959
        })
2✔
960
        if err != nil && !IsError(err, ErrIgnored, ErrOutdated) {
2✔
961
                log.Errorf("Unable to apply channel update: %v", err)
×
962
                return false
×
963
        }
×
964

965
        return true
2✔
966
}
967

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

9✔
976
        err := b.addNode(node, op...)
9✔
977
        if err != nil {
12✔
978
                // Log as a debug message if this is not an error we need to be
3✔
979
                // concerned about.
3✔
980
                if IsError(err, ErrIgnored, ErrOutdated) {
6✔
981
                        log.Debugf("process network updates got: %v", err)
3✔
982
                } else {
3✔
NEW
983
                        log.Errorf("process network updates got: %v", err)
×
984
                }
×
985

986
                return err
3✔
987
        }
988

989
        return nil
8✔
990
}
991

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

9✔
999
        // Before we add the node to the database, we'll check to see if the
9✔
1000
        // announcement is "fresh" or not. If it isn't, then we'll return an
9✔
1001
        // error.
9✔
1002
        err := b.assertNodeAnnFreshness(node.PubKeyBytes, node.LastUpdate)
9✔
1003
        if err != nil {
12✔
1004
                return err
3✔
1005
        }
3✔
1006

1007
        if err := b.cfg.Graph.AddLightningNode(node, op...); err != nil {
8✔
1008
                return errors.Errorf("unable to add node %x to the "+
×
1009
                        "graph: %v", node.PubKeyBytes, err)
×
1010
        }
×
1011

1012
        log.Tracef("Updated vertex data for node=%x", node.PubKeyBytes)
8✔
1013
        b.stats.incNumNodeUpdates()
8✔
1014

8✔
1015
        return nil
8✔
1016
}
1017

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

16✔
1026
        err := b.addEdge(edge, op...)
16✔
1027
        if err != nil {
18✔
1028
                // Log as a debug message if this is not an error we need to be
2✔
1029
                // concerned about.
2✔
1030
                if IsError(err, ErrIgnored, ErrOutdated) {
4✔
1031
                        log.Debugf("process network updates got: %v", err)
2✔
1032
                } else {
2✔
NEW
1033
                        log.Errorf("process network updates got: %v", err)
×
1034
                }
×
1035

1036
                return err
2✔
1037
        }
1038

1039
        return nil
16✔
1040
}
1041

1042
// addEdge does some validation on the new channel edge against what we
1043
// currently have persisted in the graph, and then adds it to the graph. The
1044
// Chain View is updated with the new edge if it is successfully added to the
1045
// graph. We only persist the channel if we currently dont have it at all in
1046
// our graph.
1047
//
1048
// TODO(elle): this currently also does funding-transaction validation. But this
1049
// should be moved to the gossiper instead.
1050
func (b *Builder) addEdge(edge *models.ChannelEdgeInfo,
1051
        op ...batch.SchedulerOption) error {
16✔
1052

16✔
1053
        log.Debugf("Received ChannelEdgeInfo for channel %v", edge.ChannelID)
16✔
1054

16✔
1055
        // Prior to processing the announcement we first check if we
16✔
1056
        // already know of this channel, if so, then we can exit early.
16✔
1057
        _, _, exists, isZombie, err := b.cfg.Graph.HasChannelEdge(
16✔
1058
                edge.ChannelID,
16✔
1059
        )
16✔
1060
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
16✔
1061
                return errors.Errorf("unable to check for edge existence: %v",
×
1062
                        err)
×
1063
        }
×
1064
        if isZombie {
16✔
1065
                return NewErrf(ErrIgnored, "ignoring msg for zombie chan_id=%v",
×
1066
                        edge.ChannelID)
×
1067
        }
×
1068
        if exists {
18✔
1069
                return NewErrf(ErrIgnored, "ignoring msg for known chan_id=%v",
2✔
1070
                        edge.ChannelID)
2✔
1071
        }
2✔
1072

1073
        if err := b.cfg.Graph.AddChannelEdge(edge, op...); err != nil {
16✔
1074
                return fmt.Errorf("unable to add edge: %w", err)
×
1075
        }
×
1076

1077
        b.stats.incNumEdgesDiscovered()
16✔
1078

16✔
1079
        // If AssumeChannelValid is present, of if the SCID is an alias, then
16✔
1080
        // the gossiper would not have done the expensive work of fetching
16✔
1081
        // a funding transaction and validating it. So we won't have the channel
16✔
1082
        // capacity nor the funding script. So we just log and return here.
16✔
1083
        scid := lnwire.NewShortChanIDFromInt(edge.ChannelID)
16✔
1084
        if b.cfg.AssumeChannelValid || b.cfg.IsAlias(scid) {
18✔
1085
                log.Tracef("New channel discovered! Link connects %x and %x "+
2✔
1086
                        "with ChannelID(%v)", edge.NodeKey1Bytes,
2✔
1087
                        edge.NodeKey2Bytes, edge.ChannelID)
2✔
1088

2✔
1089
                return nil
2✔
1090
        }
2✔
1091

1092
        log.Debugf("New channel discovered! Link connects %x and %x with "+
16✔
1093
                "ChannelPoint(%v): chan_id=%v, capacity=%v", edge.NodeKey1Bytes,
16✔
1094
                edge.NodeKey2Bytes, edge.ChannelPoint, edge.ChannelID,
16✔
1095
                edge.Capacity)
16✔
1096

16✔
1097
        // Otherwise, then we expect the funding script to be present on the
16✔
1098
        // edge since it would have been fetched when the gossiper validated the
16✔
1099
        // announcement.
16✔
1100
        fundingPkScript, err := edge.FundingScript.UnwrapOrErr(fmt.Errorf(
16✔
1101
                "expected the funding transaction script to be set",
16✔
1102
        ))
16✔
1103
        if err != nil {
16✔
1104
                return err
×
1105
        }
×
1106

1107
        // As a new edge has been added to the channel graph, we'll update the
1108
        // current UTXO filter within our active FilteredChainView so we are
1109
        // notified if/when this channel is closed.
1110
        filterUpdate := []graphdb.EdgePoint{
16✔
1111
                {
16✔
1112
                        FundingPkScript: fundingPkScript,
16✔
1113
                        OutPoint:        edge.ChannelPoint,
16✔
1114
                },
16✔
1115
        }
16✔
1116

16✔
1117
        err = b.cfg.ChainView.UpdateFilter(filterUpdate, b.bestHeight.Load())
16✔
1118
        if err != nil {
16✔
1119
                return errors.Errorf("unable to update chain "+
×
1120
                        "view: %v", err)
×
1121
        }
×
1122

1123
        return nil
16✔
1124
}
1125

1126
// UpdateEdge is used to update edge information, without this message edge
1127
// considered as not fully constructed.
1128
//
1129
// NOTE: This method is part of the ChannelGraphSource interface.
1130
func (b *Builder) UpdateEdge(update *models.ChannelEdgePolicy,
1131
        op ...batch.SchedulerOption) error {
8✔
1132

8✔
1133
        err := b.updateEdge(update, op...)
8✔
1134
        if err != nil {
11✔
1135
                // Log as a debug message if this is not an error we need to be
3✔
1136
                // concerned about.
3✔
1137
                if IsError(err, ErrIgnored, ErrOutdated) {
6✔
1138
                        log.Debugf("process network updates got: %v", err)
3✔
1139
                } else {
3✔
NEW
1140
                        log.Errorf("process network updates got: %v", err)
×
1141
                }
×
1142

1143
                return err
3✔
1144
        }
1145

1146
        return nil
7✔
1147
}
1148

1149
// updateEdge validates the new edge policy against what we currently have
1150
// persisted in the graph, and then applies it to the graph if the update is
1151
// considered fresh enough and if we actually have a channel persisted for the
1152
// given update.
1153
func (b *Builder) updateEdge(policy *models.ChannelEdgePolicy,
1154
        op ...batch.SchedulerOption) error {
8✔
1155

8✔
1156
        log.Debugf("Received ChannelEdgePolicy for channel %v",
8✔
1157
                policy.ChannelID)
8✔
1158

8✔
1159
        // We make sure to hold the mutex for this channel ID, such that no
8✔
1160
        // other goroutine is concurrently doing database accesses for the same
8✔
1161
        // channel ID.
8✔
1162
        b.channelEdgeMtx.Lock(policy.ChannelID)
8✔
1163
        defer b.channelEdgeMtx.Unlock(policy.ChannelID)
8✔
1164

8✔
1165
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
8✔
1166
                b.cfg.Graph.HasChannelEdge(policy.ChannelID)
8✔
1167
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
8✔
1168
                return errors.Errorf("unable to check for edge existence: %v",
×
1169
                        err)
×
1170
        }
×
1171

1172
        // If the channel is marked as a zombie in our database, and
1173
        // we consider this a stale update, then we should not apply the
1174
        // policy.
1175
        isStaleUpdate := time.Since(policy.LastUpdate) >
8✔
1176
                b.cfg.ChannelPruneExpiry
8✔
1177

8✔
1178
        if isZombie && isStaleUpdate {
8✔
1179
                return NewErrf(ErrIgnored, "ignoring stale update "+
×
1180
                        "(flags=%v|%v) for zombie chan_id=%v",
×
1181
                        policy.MessageFlags, policy.ChannelFlags,
×
1182
                        policy.ChannelID)
×
1183
        }
×
1184

1185
        // If the channel doesn't exist in our database, we cannot apply the
1186
        // updated policy.
1187
        if !exists {
9✔
1188
                return NewErrf(ErrIgnored, "ignoring update (flags=%v|%v) for "+
1✔
1189
                        "unknown chan_id=%v", policy.MessageFlags,
1✔
1190
                        policy.ChannelFlags, policy.ChannelID)
1✔
1191
        }
1✔
1192

1193
        log.Debugf("Found edge1Timestamp=%v, edge2Timestamp=%v",
7✔
1194
                edge1Timestamp, edge2Timestamp)
7✔
1195

7✔
1196
        // As edges are directional edge node has a unique policy for the
7✔
1197
        // direction of the edge they control. Therefore, we first check if we
7✔
1198
        // already have the most up-to-date information for that edge. If this
7✔
1199
        // message has a timestamp not strictly newer than what we already know
7✔
1200
        // of we can exit early.
7✔
1201
        switch policy.ChannelFlags & lnwire.ChanUpdateDirection {
7✔
1202
        // A flag set of 0 indicates this is an announcement for the "first"
1203
        // node in the channel.
1204
        case 0:
5✔
1205
                // Ignore outdated message.
5✔
1206
                if !edge1Timestamp.Before(policy.LastUpdate) {
7✔
1207
                        return NewErrf(ErrOutdated, "Ignoring "+
2✔
1208
                                "outdated update (flags=%v|%v) for "+
2✔
1209
                                "known chan_id=%v", policy.MessageFlags,
2✔
1210
                                policy.ChannelFlags, policy.ChannelID)
2✔
1211
                }
2✔
1212

1213
        // Similarly, a flag set of 1 indicates this is an announcement
1214
        // for the "second" node in the channel.
1215
        case 1:
4✔
1216
                // Ignore outdated message.
4✔
1217
                if !edge2Timestamp.Before(policy.LastUpdate) {
6✔
1218
                        return NewErrf(ErrOutdated, "Ignoring "+
2✔
1219
                                "outdated update (flags=%v|%v) for "+
2✔
1220
                                "known chan_id=%v", policy.MessageFlags,
2✔
1221
                                policy.ChannelFlags, policy.ChannelID)
2✔
1222
                }
2✔
1223
        }
1224

1225
        // Now that we know this isn't a stale update, we'll apply the new edge
1226
        // policy to the proper directional edge within the channel graph.
1227
        if err = b.cfg.Graph.UpdateEdgePolicy(policy, op...); err != nil {
7✔
1228
                err := errors.Errorf("unable to add channel: %v", err)
×
1229
                log.Error(err)
×
1230
                return err
×
1231
        }
×
1232

1233
        log.Tracef("New channel update applied: %v",
7✔
1234
                lnutils.SpewLogClosure(policy))
7✔
1235
        b.stats.incNumChannelUpdates()
7✔
1236

7✔
1237
        return nil
7✔
1238
}
1239

1240
// CurrentBlockHeight returns the block height from POV of the router subsystem.
1241
//
1242
// NOTE: This method is part of the ChannelGraphSource interface.
1243
func (b *Builder) CurrentBlockHeight() (uint32, error) {
2✔
1244
        _, height, err := b.cfg.Chain.GetBestBlock()
2✔
1245
        return uint32(height), err
2✔
1246
}
2✔
1247

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

1255
// GetChannelByID return the channel by the channel id.
1256
//
1257
// NOTE: This method is part of the ChannelGraphSource interface.
1258
func (b *Builder) GetChannelByID(chanID lnwire.ShortChannelID) (
1259
        *models.ChannelEdgeInfo,
1260
        *models.ChannelEdgePolicy,
1261
        *models.ChannelEdgePolicy, error) {
3✔
1262

3✔
1263
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
3✔
1264
}
3✔
1265

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

2✔
1274
        return b.cfg.Graph.FetchLightningNode(node)
2✔
1275
}
2✔
1276

1277
// ForAllOutgoingChannels is used to iterate over all outgoing channels owned by
1278
// the router.
1279
//
1280
// NOTE: This method is part of the ChannelGraphSource interface.
1281
func (b *Builder) ForAllOutgoingChannels(cb func(*models.ChannelEdgeInfo,
1282
        *models.ChannelEdgePolicy) error) error {
2✔
1283

2✔
1284
        return b.cfg.Graph.ForEachNodeChannel(b.cfg.SelfNode,
2✔
1285
                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
2✔
1286
                        e *models.ChannelEdgePolicy,
2✔
1287
                        _ *models.ChannelEdgePolicy) error {
4✔
1288

2✔
1289
                        if e == nil {
2✔
1290
                                return fmt.Errorf("channel from self node " +
×
1291
                                        "has no policy")
×
1292
                        }
×
1293

1294
                        return cb(c, e)
2✔
1295
                },
1296
        )
1297
}
1298

1299
// AddProof updates the channel edge info with proof which is needed to
1300
// properly announce the edge to the rest of the network.
1301
//
1302
// NOTE: This method is part of the ChannelGraphSource interface.
1303
func (b *Builder) AddProof(chanID lnwire.ShortChannelID,
1304
        proof *models.ChannelAuthProof) error {
3✔
1305

3✔
1306
        return b.cfg.Graph.AddEdgeProof(chanID, proof)
3✔
1307
}
3✔
1308

1309
// IsStaleNode returns true if the graph source has a node announcement for the
1310
// target node with a more recent timestamp.
1311
//
1312
// NOTE: This method is part of the ChannelGraphSource interface.
1313
func (b *Builder) IsStaleNode(node route.Vertex,
1314
        timestamp time.Time) bool {
5✔
1315

5✔
1316
        // If our attempt to assert that the node announcement is fresh fails,
5✔
1317
        // then we know that this is actually a stale announcement.
5✔
1318
        err := b.assertNodeAnnFreshness(node, timestamp)
5✔
1319
        if err != nil {
8✔
1320
                log.Debugf("Checking stale node %x got %v", node, err)
3✔
1321
                return true
3✔
1322
        }
3✔
1323

1324
        return false
4✔
1325
}
1326

1327
// IsPublicNode determines whether the given vertex is seen as a public node in
1328
// the graph from the graph's source node's point of view.
1329
//
1330
// NOTE: This method is part of the ChannelGraphSource interface.
1331
func (b *Builder) IsPublicNode(node route.Vertex) (bool, error) {
2✔
1332
        return b.cfg.Graph.IsPublicNode(node)
2✔
1333
}
2✔
1334

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

3✔
1344
        return exists || isZombie
3✔
1345
}
3✔
1346

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

×
1354
        return isZombie, err
×
1355
}
×
1356

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

8✔
1364
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
8✔
1365
                b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
8✔
1366
        if err != nil {
8✔
1367
                log.Debugf("Check stale edge policy got error: %v", err)
×
1368
                return false
×
1369
        }
×
1370

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

1385
                // Otherwise, we'll fall back to our usual ChannelPruneExpiry.
1386
                return time.Since(timestamp) > b.cfg.ChannelPruneExpiry
×
1387
        }
1388

1389
        // If we don't know of the edge, then it means it's fresh (thus not
1390
        // stale).
1391
        if !exists {
12✔
1392
                return false
4✔
1393
        }
4✔
1394

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

1405
        // Similarly, a flag set of 1 indicates this is an announcement for the
1406
        // "second" node in the channel.
1407
        case flags&lnwire.ChanUpdateDirection == 1:
4✔
1408
                return !edge2Timestamp.Before(timestamp)
4✔
1409
        }
1410

1411
        return false
×
1412
}
1413

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