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

lightningnetwork / lnd / 16948521526

13 Aug 2025 08:27PM UTC coverage: 54.877% (-12.1%) from 66.929%
16948521526

Pull #10155

github

web-flow
Merge 61c0fecf6 into c6a9116e3
Pull Request #10155: Add missing invoice index for native sql

108941 of 198518 relevant lines covered (54.88%)

22023.66 hits per line

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

68.05
/graph/builder.go
1
package graph
2

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

11
        "github.com/btcsuite/btcd/btcec/v2"
12
        "github.com/btcsuite/btcd/wire"
13
        "github.com/lightningnetwork/lnd/batch"
14
        "github.com/lightningnetwork/lnd/chainntnfs"
15
        graphdb "github.com/lightningnetwork/lnd/graph/db"
16
        "github.com/lightningnetwork/lnd/graph/db/models"
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) {
20✔
148
        return &Builder{
20✔
149
                cfg:            cfg,
20✔
150
                channelEdgeMtx: multimutex.NewMutex[uint64](),
20✔
151
                statTicker:     ticker.New(defaultStatInterval),
20✔
152
                stats:          new(builderStats),
20✔
153
                quit:           make(chan struct{}),
20✔
154
        }, nil
20✔
155
}
20✔
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 {
20✔
160
        if !b.started.CompareAndSwap(false, true) {
20✔
161
                return nil
×
162
        }
×
163

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

20✔
166
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
20✔
167
        if err != nil {
20✔
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 {
38✔
174
                switch {
18✔
175
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
18✔
176
                        fallthrough
18✔
177

178
                case errors.Is(err, graphdb.ErrGraphNotFound):
18✔
179
                        // If the graph has never been pruned, then we'll set
18✔
180
                        // the prune height to the current best height of the
18✔
181
                        // chain backend.
18✔
182
                        _, err = b.cfg.Graph.PruneGraph(
18✔
183
                                nil, bestHash, uint32(bestHeight),
18✔
184
                        )
18✔
185
                        if err != nil {
18✔
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
21✔
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 {
19✔
212
                // Otherwise, we'll use our filtered chain view to prune
19✔
213
                // channels as soon as they are detected as spent on-chain.
19✔
214
                if err := b.cfg.ChainView.Start(); err != nil {
19✔
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()
19✔
221
                b.staleBlocks = b.cfg.ChainView.DisconnectedBlocks()
19✔
222

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

×
233
                        return err
×
234
                }
×
235

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

19✔
239
                if len(channelView) != 0 {
26✔
240
                        err = b.cfg.ChainView.UpdateFilter(
7✔
241
                                channelView, uint32(bestHeight),
7✔
242
                        )
7✔
243
                        if err != nil {
7✔
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()
19✔
251
                if err != nil {
19✔
252
                        return err
×
253
                }
×
254
                b.bestHeight.Store(uint32(bestHeight))
19✔
255

19✔
256
                // Before we begin normal operation of the router, we first need
19✔
257
                // to synchronize the channel graph to the latest state of the
19✔
258
                // UTXO set.
19✔
259
                if err := b.syncGraphWithChain(); err != nil {
19✔
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()
19✔
267
                if err != nil &&
19✔
268
                        !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
19✔
269

×
270
                        return err
×
271
                }
×
272
        }
273

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

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

20✔
279
        return nil
20✔
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 {
20✔
286
        if !b.stopped.CompareAndSwap(false, true) {
22✔
287
                return nil
2✔
288
        }
2✔
289

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

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

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

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

18✔
305
        return nil
18✔
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 {
19✔
313
        // First, we'll need to check to see if we're already in sync with the
19✔
314
        // latest state of the UTXO set.
19✔
315
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
19✔
316
        if err != nil {
19✔
317
                return err
×
318
        }
×
319
        b.bestHeight.Store(uint32(bestHeight))
19✔
320

19✔
321
        pruneHash, pruneHeight, err := b.cfg.Graph.PruneTip()
19✔
322
        if err != nil {
19✔
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",
19✔
334
                pruneHeight, pruneHash)
19✔
335

19✔
336
        switch {
19✔
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:
14✔
346
                return nil
14✔
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))
2✔
352
        if err != nil {
2✔
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) {
12✔
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 "+
2✔
395
                "height=%v (hash=%v)", pruneHeight, pruneHash, bestHeight,
2✔
396
                bestHash)
2✔
397

2✔
398
        // If we're not yet caught up, then we'll walk forward in the chain
2✔
399
        // pruning the channel graph with each new block that hasn't yet been
2✔
400
        // consumed by the channel graph.
2✔
401
        var spentOutputs []*wire.OutPoint
2✔
402
        for nextHeight := pruneHeight + 1; nextHeight <= uint32(bestHeight); nextHeight++ { //nolint:ll
28✔
403
                // Break out of the rescan early if a shutdown has been
26✔
404
                // requested, otherwise long rescans will block the daemon from
26✔
405
                // shutting down promptly.
26✔
406
                select {
26✔
407
                case <-b.quit:
×
408
                        return ErrGraphBuilderShuttingDown
×
409
                default:
26✔
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",
26✔
415
                        int64(nextHeight))
26✔
416
                nextHash, err := b.cfg.Chain.GetBlockHash(int64(nextHeight))
26✔
417
                if err != nil {
26✔
418
                        return err
×
419
                }
×
420
                log.Tracef("Running block filter on block with hash: %v",
26✔
421
                        nextHash)
26✔
422
                filterBlock, err := b.cfg.ChainView.FilterBlock(nextHash)
26✔
423
                if err != nil {
26✔
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 {
2✔
432
                                spentOutputs = append(spentOutputs,
1✔
433
                                        &txIn.PreviousOutPoint)
1✔
434
                        }
1✔
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(
2✔
441
                spentOutputs, bestHash, uint32(bestHeight),
2✔
442
        )
2✔
443
        if err != nil {
2✔
444
                return err
×
445
        }
×
446

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

2✔
450
        return nil
2✔
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() {
20✔
646
        defer b.wg.Done()
20✔
647

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

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

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

20✔
655
        for {
112✔
656
                // If there are stats, resume the statTicker.
92✔
657
                if !b.stats.Empty() {
118✔
658
                        b.statTicker.Resume()
26✔
659
                }
26✔
660

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

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

10✔
674
                        // Update the channel graph to reflect that this block
10✔
675
                        // was disconnected.
10✔
676
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
10✔
677
                                blockHeight,
10✔
678
                        )
10✔
679
                        if err != nil {
10✔
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:
62✔
690
                        // If the channel has been closed, then this indicates
62✔
691
                        // the daemon is shutting down, so we exit ourselves.
62✔
692
                        if !ok {
62✔
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()
62✔
701
                        switch {
62✔
702
                        case chainUpdate.Height == currentHeight+1:
56✔
703
                                err := b.updateGraphWithClosedChannels(
56✔
704
                                        chainUpdate,
56✔
705
                                )
56✔
706
                                if err != nil {
56✔
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():
×
747
                        if !b.stats.Empty() {
×
748
                                log.Infof(b.stats.String())
×
749
                        } else {
×
750
                                b.statTicker.Pause()
×
751
                        }
×
752
                        b.stats.Reset()
×
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:
18✔
757
                        return
18✔
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 {
61✔
827

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

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

61✔
836
        // We're only interested in all prior outputs that have been spent in
61✔
837
        // the block, so collate all the referenced previous outpoints within
61✔
838
        // each tx and input.
61✔
839
        var spentOutputs []*wire.OutPoint
61✔
840
        for _, tx := range chainUpdate.Transactions {
62✔
841
                for _, txIn := range tx.TxIn {
2✔
842
                        spentOutputs = append(spentOutputs,
1✔
843
                                &txIn.PreviousOutPoint)
1✔
844
                }
1✔
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,
61✔
851
                &chainUpdate.Hash, chainUpdate.Height)
61✔
852
        if err != nil {
61✔
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,
61✔
858
                blockHeight, len(chansClosed))
61✔
859

61✔
860
        return nil
61✔
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(ctx context.Context, node route.Vertex,
869
        msgTimestamp time.Time) error {
10✔
870

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

896
        return nil
8✔
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 {
×
918
        ctx := context.TODO()
×
919

×
920
        ch, _, _, err := b.GetChannelByID(msg.ShortChannelID)
×
921
        if err != nil {
×
922
                log.Errorf("Unable to retrieve channel by id: %v", err)
×
923
                return false
×
924
        }
×
925

926
        var pubKey *btcec.PublicKey
×
927

×
928
        switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
×
929
        case 0:
×
930
                pubKey, _ = ch.NodeKey1()
×
931

932
        case 1:
×
933
                pubKey, _ = ch.NodeKey2()
×
934
        }
935

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

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

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

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

970
        return true
×
971
}
972

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

7✔
981
        err := b.addNode(ctx, node, op...)
7✔
982
        if err != nil {
8✔
983
                logNetworkMsgProcessError(err)
1✔
984

1✔
985
                return err
1✔
986
        }
1✔
987

988
        return nil
6✔
989
}
990

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

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

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

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

6✔
1014
        return nil
6✔
1015
}
1016

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

14✔
1025
        err := b.addEdge(ctx, edge, op...)
14✔
1026
        if err != nil {
14✔
1027
                logNetworkMsgProcessError(err)
×
1028

×
1029
                return err
×
1030
        }
×
1031

1032
        return nil
14✔
1033
}
1034

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

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

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

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

1070
        b.stats.incNumEdgesDiscovered()
14✔
1071

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

×
1082
                return nil
×
1083
        }
×
1084

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

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

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

14✔
1110
        err = b.cfg.ChainView.UpdateFilter(filterUpdate, b.bestHeight.Load())
14✔
1111
        if err != nil {
14✔
1112
                return fmt.Errorf("unable to update chain view: %w", err)
×
1113
        }
×
1114

1115
        return nil
14✔
1116
}
1117

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

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

1✔
1129
                return err
1✔
1130
        }
1✔
1131

1132
        return nil
5✔
1133
}
1134

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

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

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

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

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

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

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

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

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

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

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

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

5✔
1222
        return nil
5✔
1223
}
1224

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

2✔
1231
                return
2✔
1232
        }
2✔
1233

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

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

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

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

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

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

×
1271
        return b.cfg.Graph.FetchLightningNode(ctx, node)
×
1272
}
×
1273

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

×
1282
        return b.cfg.Graph.ForEachNodeChannel(
×
1283
                ctx, b.cfg.SelfNode,
×
1284
                func(c *models.ChannelEdgeInfo, e *models.ChannelEdgePolicy,
×
1285
                        _ *models.ChannelEdgePolicy) error {
×
1286

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

1292
                        return cb(c, e)
×
1293
                }, reset,
1294
        )
1295
}
1296

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

1✔
1304
        return b.cfg.Graph.AddEdgeProof(chanID, proof)
1✔
1305
}
1✔
1306

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

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

1322
        return false
2✔
1323
}
1324

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

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

1✔
1342
        return exists || isZombie
1✔
1343
}
1✔
1344

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

×
1352
        return isZombie, err
×
1353
}
×
1354

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

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

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

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

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

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

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

1409
        return false
×
1410
}
1411

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