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

lightningnetwork / lnd / 15951470896

29 Jun 2025 04:23AM UTC coverage: 67.594% (-0.01%) from 67.606%
15951470896

Pull #9751

github

web-flow
Merge 599d9b051 into 6290edf14
Pull Request #9751: multi: update Go to 1.23.10 and update some packages

135088 of 199851 relevant lines covered (67.59%)

21909.44 hits per line

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

78.13
/graph/builder.go
1
package graph
2

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

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

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

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

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

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

×
233
                        return err
×
234
                }
×
235

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

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

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

×
270
                        return err
×
271
                }
×
272
        }
273

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

23✔
655
        for {
119✔
656
                // If there are stats, resume the statTicker.
96✔
657
                if !b.stats.Empty() {
125✔
658
                        b.statTicker.Resume()
29✔
659
                }
29✔
660

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

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

12✔
674
                        // Update the channel graph to reflect that this block
12✔
675
                        // was disconnected.
12✔
676
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
12✔
677
                                blockHeight,
12✔
678
                        )
12✔
679
                        if err != nil {
12✔
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:
66✔
690
                        // If the channel has been closed, then this indicates
66✔
691
                        // the daemon is shutting down, so we exit ourselves.
66✔
692
                        if !ok {
66✔
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()
66✔
701
                        switch {
66✔
702
                        case chainUpdate.Height == currentHeight+1:
60✔
703
                                err := b.updateGraphWithClosedChannels(
60✔
704
                                        chainUpdate,
60✔
705
                                )
60✔
706
                                if err != nil {
60✔
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:
6✔
725
                                log.Errorf("out of order block: expecting "+
6✔
726
                                        "height=%v, got height=%v",
6✔
727
                                        currentHeight+1, chainUpdate.Height)
6✔
728

6✔
729
                                log.Infof("Skipping channel pruning since "+
6✔
730
                                        "received block height %v was already"+
6✔
731
                                        " processed.", chainUpdate.Height)
6✔
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():
2✔
747
                        if !b.stats.Empty() {
4✔
748
                                log.Infof(b.stats.String())
2✔
749
                        } else {
2✔
750
                                b.statTicker.Pause()
×
751
                        }
×
752
                        b.stats.Reset()
2✔
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:
21✔
757
                        return
21✔
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 {
65✔
827

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

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

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

65✔
860
        return nil
65✔
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 {
13✔
870

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

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

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

926
        var pubKey *btcec.PublicKey
3✔
927

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

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

936
        // Exit early if the pubkey cannot be decided.
937
        if pubKey == nil {
3✔
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)
3✔
944
        if err != nil {
3✔
945
                log.Errorf("Unable to validate channel update: %v", err)
×
946
                return false
×
947
        }
×
948

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

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

970
        return true
3✔
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 {
10✔
980

10✔
981
        err := b.addNode(ctx, node, op...)
10✔
982
        if err != nil {
14✔
983
                logNetworkMsgProcessError(err)
4✔
984

4✔
985
                return err
4✔
986
        }
4✔
987

988
        return nil
9✔
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 {
10✔
997

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

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

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

9✔
1014
        return nil
9✔
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 {
17✔
1024

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

3✔
1029
                return err
3✔
1030
        }
3✔
1031

1032
        return nil
17✔
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 {
17✔
1045

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

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

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

1070
        b.stats.incNumEdgesDiscovered()
17✔
1071

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

3✔
1082
                return nil
3✔
1083
        }
3✔
1084

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

17✔
1090
        // Otherwise, then we expect the funding script to be present on the
17✔
1091
        // edge since it would have been fetched when the gossiper validated the
17✔
1092
        // announcement.
17✔
1093
        fundingPkScript, err := edge.FundingScript.UnwrapOrErr(fmt.Errorf(
17✔
1094
                "expected the funding transaction script to be set",
17✔
1095
        ))
17✔
1096
        if err != nil {
17✔
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{
17✔
1104
                {
17✔
1105
                        FundingPkScript: fundingPkScript,
17✔
1106
                        OutPoint:        edge.ChannelPoint,
17✔
1107
                },
17✔
1108
        }
17✔
1109

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

1116
        return nil
17✔
1117
}
1118

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

9✔
1126
        err := b.updateEdge(ctx, update, op...)
9✔
1127
        if err != nil {
13✔
1128
                logNetworkMsgProcessError(err)
4✔
1129

4✔
1130
                return err
4✔
1131
        }
4✔
1132

1133
        return nil
8✔
1134
}
1135

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

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

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

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

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

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

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

1180
        log.Debugf("Found edge1Timestamp=%v, edge2Timestamp=%v",
8✔
1181
                edge1Timestamp, edge2Timestamp)
8✔
1182

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

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

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

1220
        log.Tracef("New channel update applied: %v",
8✔
1221
                lnutils.SpewLogClosure(policy))
8✔
1222
        b.stats.incNumChannelUpdates()
8✔
1223

8✔
1224
        return nil
8✔
1225
}
1226

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

5✔
1233
                return
5✔
1234
        }
5✔
1235

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

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

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

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

4✔
1262
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
4✔
1263
}
4✔
1264

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

3✔
1273
        return b.cfg.Graph.FetchLightningNode(ctx, node)
3✔
1274
}
3✔
1275

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

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

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

1292
                        return cb(c, e)
3✔
1293
                },
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 {
4✔
1303

4✔
1304
        return b.cfg.Graph.AddEdgeProof(chanID, proof)
4✔
1305
}
4✔
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 {
6✔
1313

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

1322
        return false
5✔
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) {
3✔
1330
        return b.cfg.Graph.IsPublicNode(node)
3✔
1331
}
3✔
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 {
4✔
1338
        _, _, exists, isZombie, _ := b.cfg.Graph.HasChannelEdge(
4✔
1339
                chanID.ToUint64(),
4✔
1340
        )
4✔
1341

4✔
1342
        return exists || isZombie
4✔
1343
}
4✔
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 {
9✔
1361

9✔
1362
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
9✔
1363
                b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
9✔
1364
        if err != nil {
9✔
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 {
9✔
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 {
14✔
1390
                return false
5✔
1391
        }
5✔
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 {
7✔
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:
5✔
1401
                return !edge1Timestamp.Before(timestamp)
5✔
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:
5✔
1406
                return !edge2Timestamp.Before(timestamp)
5✔
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