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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 hits per line

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

55.92
/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) {
3✔
148
        return &Builder{
3✔
149
                cfg:            cfg,
3✔
150
                channelEdgeMtx: multimutex.NewMutex[uint64](),
3✔
151
                statTicker:     ticker.New(defaultStatInterval),
3✔
152
                stats:          new(builderStats),
3✔
153
                quit:           make(chan struct{}),
3✔
154
        }, nil
3✔
155
}
3✔
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 {
3✔
160
        if !b.started.CompareAndSwap(false, true) {
3✔
161
                return nil
×
162
        }
×
163

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

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

178
                case errors.Is(err, graphdb.ErrGraphNotFound):
3✔
179
                        // If the graph has never been pruned, then we'll set
3✔
180
                        // the prune height to the current best height of the
3✔
181
                        // chain backend.
3✔
182
                        _, err = b.cfg.Graph.PruneGraph(
3✔
183
                                nil, bestHash, uint32(bestHeight),
3✔
184
                        )
3✔
185
                        if err != nil {
3✔
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
3✔
UNCOV
199
                time.AfterFunc(b.cfg.FirstTimePruneDelay, func() {
×
UNCOV
200
                        select {
×
201
                        case <-b.quit:
×
202
                                return
×
UNCOV
203
                        default:
×
204
                        }
205

UNCOV
206
                        log.Info("Initial zombie prune starting")
×
UNCOV
207
                        if err := b.pruneZombieChans(); err != nil {
×
208
                                log.Errorf("Unable to prune zombies: %v", err)
×
209
                        }
×
210
                })
211
        } else {
3✔
212
                // Otherwise, we'll use our filtered chain view to prune
3✔
213
                // channels as soon as they are detected as spent on-chain.
3✔
214
                if err := b.cfg.ChainView.Start(); err != nil {
3✔
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()
3✔
221
                b.staleBlocks = b.cfg.ChainView.DisconnectedBlocks()
3✔
222

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

×
233
                        return err
×
234
                }
×
235

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

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

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

×
270
                        return err
×
271
                }
×
272
        }
273

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

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

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

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

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

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

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

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

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

3✔
336
        switch {
3✔
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.
UNCOV
340
        case pruneHeight == 0 || pruneHash == nil:
×
UNCOV
341
                return nil
×
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:
3✔
346
                return nil
3✔
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))
3✔
352
        if err != nil {
3✔
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) {
3✔
UNCOV
359
                log.Infof("channel graph is stale. Disconnecting block %v "+
×
UNCOV
360
                        "(hash=%v)", pruneHeight, pruneHash)
×
UNCOV
361
                // Prune the graph for every channel that was opened at height
×
UNCOV
362
                // >= pruneHeight.
×
UNCOV
363
                _, err := b.cfg.Graph.DisconnectBlockAtHeight(pruneHeight)
×
UNCOV
364
                if err != nil {
×
365
                        return err
×
366
                }
×
367

UNCOV
368
                pruneHash, pruneHeight, err = b.cfg.Graph.PruneTip()
×
UNCOV
369
                switch {
×
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

UNCOV
383
                default:
×
384
                }
385

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

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

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

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

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

3✔
450
        return nil
3✔
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,
UNCOV
459
        e2 *models.ChannelEdgePolicy) (bool, bool, bool) {
×
UNCOV
460

×
UNCOV
461
        chanExpiry := b.cfg.ChannelPruneExpiry
×
UNCOV
462

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

×
UNCOV
466
        var e1Time, e2Time time.Time
×
UNCOV
467
        if e1 != nil {
×
UNCOV
468
                e1Time = e1.LastUpdate
×
UNCOV
469
        }
×
UNCOV
470
        if e2 != nil {
×
UNCOV
471
                e2Time = e2.LastUpdate
×
UNCOV
472
        }
×
473

UNCOV
474
        return e1Zombie, e2Zombie, b.IsZombieChannel(e1Time, e2Time)
×
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,
UNCOV
481
        updateTime2 time.Time) bool {
×
UNCOV
482

×
UNCOV
483
        chanExpiry := b.cfg.ChannelPruneExpiry
×
UNCOV
484

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

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

×
UNCOV
491
        // If we're using strict zombie pruning, then a channel is only
×
UNCOV
492
        // considered live if both edges have a recent update we know of.
×
UNCOV
493
        if b.cfg.StrictZombiePruning {
×
UNCOV
494
                return e1Zombie || e2Zombie
×
UNCOV
495
        }
×
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.
UNCOV
499
        return e1Zombie && e2Zombie
×
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.
UNCOV
508
func (b *Builder) pruneZombieChans() error {
×
UNCOV
509
        chansToPrune := make(map[uint64]struct{})
×
UNCOV
510
        chanExpiry := b.cfg.ChannelPruneExpiry
×
UNCOV
511

×
UNCOV
512
        log.Infof("Examining channel graph for zombie channels")
×
UNCOV
513

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

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

×
UNCOV
525
                // Exit early in case this channel is already marked to be
×
UNCOV
526
                // pruned
×
UNCOV
527
                _, markedToPrune := chansToPrune[info.ChannelID]
×
UNCOV
528
                if markedToPrune {
×
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.
UNCOV
535
                if isSelfChannelEdge(info) {
×
UNCOV
536
                        return nil
×
UNCOV
537
                }
×
538

UNCOV
539
                e1Zombie, e2Zombie, isZombieChan := b.isZombieChannel(e1, e2)
×
UNCOV
540

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

UNCOV
546
                if e2Zombie {
×
UNCOV
547
                        log.Tracef("Node2 pubkey=%x of chan_id=%v is zombie",
×
UNCOV
548
                                info.NodeKey2Bytes, info.ChannelID)
×
UNCOV
549
                }
×
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.
UNCOV
554
                if !isZombieChan {
×
UNCOV
555
                        return nil
×
UNCOV
556
                }
×
557

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

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

×
UNCOV
564
                return nil
×
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.
UNCOV
570
        if b.cfg.AssumeChannelValid {
×
UNCOV
571
                disabledChanIDs, err := b.cfg.Graph.DisabledChannelIDs()
×
UNCOV
572
                if err != nil {
×
573
                        return fmt.Errorf("unable to get disabled channels "+
×
574
                                "ids chans: %v", err)
×
575
                }
×
576

UNCOV
577
                disabledEdges, err := b.cfg.Graph.FetchChanInfos(
×
UNCOV
578
                        disabledChanIDs,
×
UNCOV
579
                )
×
UNCOV
580
                if err != nil {
×
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.
UNCOV
586
                for _, disabledEdge := range disabledEdges {
×
UNCOV
587
                        if !isSelfChannelEdge(disabledEdge.Info) {
×
UNCOV
588
                                chansToPrune[disabledEdge.Info.ChannelID] =
×
UNCOV
589
                                        struct{}{}
×
UNCOV
590
                        }
×
591
                }
592
        }
593

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

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

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

615
        // With the set of zombie-like channels obtained, we'll do another pass
616
        // to delete them from the channel graph.
UNCOV
617
        toPrune := make([]uint64, 0, len(chansToPrune))
×
UNCOV
618
        for chanID := range chansToPrune {
×
UNCOV
619
                toPrune = append(toPrune, chanID)
×
UNCOV
620
                log.Tracef("Pruning zombie channel with ChannelID(%v)", chanID)
×
UNCOV
621
        }
×
UNCOV
622
        err = b.cfg.Graph.DeleteChannelEdges(
×
UNCOV
623
                b.cfg.StrictZombiePruning, true, toPrune...,
×
UNCOV
624
        )
×
UNCOV
625
        if err != nil {
×
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.
UNCOV
631
        err = b.cfg.Graph.PruneGraphNodes()
×
UNCOV
632
        if err != nil && !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
×
633
                return fmt.Errorf("unable to prune graph nodes: %w", err)
×
634
        }
×
635

UNCOV
636
        return nil
×
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() {
3✔
646
        defer b.wg.Done()
3✔
647

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

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

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

3✔
655
        for {
6✔
656
                // If there are stats, resume the statTicker.
3✔
657
                if !b.stats.Empty() {
6✔
658
                        b.statTicker.Resume()
3✔
659
                }
3✔
660

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

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

2✔
674
                        // Update the channel graph to reflect that this block
2✔
675
                        // was disconnected.
2✔
676
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
2✔
677
                                blockHeight,
2✔
678
                        )
2✔
679
                        if err != nil {
2✔
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:
3✔
690
                        // If the channel has been closed, then this indicates
3✔
691
                        // the daemon is shutting down, so we exit ourselves.
3✔
692
                        if !ok {
3✔
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()
3✔
701
                        switch {
3✔
702
                        case chainUpdate.Height == currentHeight+1:
3✔
703
                                err := b.updateGraphWithClosedChannels(
3✔
704
                                        chainUpdate,
3✔
705
                                )
3✔
706
                                if err != nil {
3✔
707
                                        log.Errorf("unable to prune graph "+
×
708
                                                "with closed channels: %v", err)
×
709
                                }
×
710

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

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

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

×
UNCOV
729
                                log.Infof("Skipping channel pruning since "+
×
UNCOV
730
                                        "received block height %v was already"+
×
UNCOV
731
                                        " processed.", chainUpdate.Height)
×
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:
3✔
757
                        return
3✔
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,
UNCOV
765
        chainUpdate *chainview.FilteredBlock) error {
×
UNCOV
766

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

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

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

×
UNCOV
785
        blockDifference := int(chainUpdate.Height - currentHeight)
×
UNCOV
786

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

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

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

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

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

UNCOV
820
        return nil
×
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 {
3✔
827

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

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

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

847
        // With the spent outputs gathered, attempt to prune the channel graph,
848
        // also passing in the hash+height of the block being pruned so the
849
        // prune tip can be updated.
850
        chansClosed, err := b.cfg.Graph.PruneGraph(spentOutputs,
3✔
851
                &chainUpdate.Hash, chainUpdate.Height)
3✔
852
        if err != nil {
3✔
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,
3✔
858
                blockHeight, len(chansClosed))
3✔
859

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

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

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

896
        return nil
3✔
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
        ch, _, _, err := b.GetChannelByID(msg.ShortChannelID)
3✔
919
        if err != nil {
6✔
920
                log.Errorf("Unable to retrieve channel by id: %v", err)
3✔
921
                return false
3✔
922
        }
3✔
923

924
        var pubKey *btcec.PublicKey
3✔
925

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

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

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

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

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

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

968
        return true
3✔
969
}
970

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

3✔
979
        err := b.addNode(ctx, node, op...)
3✔
980
        if err != nil {
6✔
981
                logNetworkMsgProcessError(err)
3✔
982

3✔
983
                return err
3✔
984
        }
3✔
985

986
        return nil
3✔
987
}
988

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

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

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

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

3✔
1012
        return nil
3✔
1013
}
1014

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

3✔
1023
        err := b.addEdge(edge, op...)
3✔
1024
        if err != nil {
6✔
1025
                logNetworkMsgProcessError(err)
3✔
1026

3✔
1027
                return err
3✔
1028
        }
3✔
1029

1030
        return nil
3✔
1031
}
1032

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

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

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

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

1068
        b.stats.incNumEdgesDiscovered()
3✔
1069

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

3✔
1080
                return nil
3✔
1081
        }
3✔
1082

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

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

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

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

1114
        return nil
3✔
1115
}
1116

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

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

3✔
1128
                return err
3✔
1129
        }
3✔
1130

1131
        return nil
3✔
1132
}
1133

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

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

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

3✔
1150
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
3✔
1151
                b.cfg.Graph.HasChannelEdge(policy.ChannelID)
3✔
1152
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
1153
                return errors.Errorf("unable to check for edge existence: %v",
×
1154
                        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) >
3✔
1161
                b.cfg.ChannelPruneExpiry
3✔
1162

3✔
1163
        if isZombie && isStaleUpdate {
3✔
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 {
3✔
UNCOV
1173
                return NewErrf(ErrIgnored, "ignoring update (flags=%v|%v) for "+
×
UNCOV
1174
                        "unknown chan_id=%v", policy.MessageFlags,
×
UNCOV
1175
                        policy.ChannelFlags, policy.ChannelID)
×
UNCOV
1176
        }
×
1177

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

3✔
1181
        // As edges are directional edge node has a unique policy for the
3✔
1182
        // direction of the edge they control. Therefore, we first check if we
3✔
1183
        // already have the most up-to-date information for that edge. If this
3✔
1184
        // message has a timestamp not strictly newer than what we already know
3✔
1185
        // of we can exit early.
3✔
1186
        switch policy.ChannelFlags & lnwire.ChanUpdateDirection {
3✔
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) {
5✔
1192
                        return NewErrf(ErrOutdated, "Ignoring "+
2✔
1193
                                "outdated update (flags=%v|%v) for "+
2✔
1194
                                "known chan_id=%v", policy.MessageFlags,
2✔
1195
                                policy.ChannelFlags, policy.ChannelID)
2✔
1196
                }
2✔
1197

1198
        // Similarly, a flag set of 1 indicates this is an announcement
1199
        // for the "second" node in the channel.
1200
        case 1:
3✔
1201
                // Ignore outdated message.
3✔
1202
                if !edge2Timestamp.Before(policy.LastUpdate) {
5✔
1203
                        return NewErrf(ErrOutdated, "Ignoring "+
2✔
1204
                                "outdated update (flags=%v|%v) for "+
2✔
1205
                                "known chan_id=%v", policy.MessageFlags,
2✔
1206
                                policy.ChannelFlags, policy.ChannelID)
2✔
1207
                }
2✔
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(policy, op...); err != nil {
3✔
1213
                err := errors.Errorf("unable to add channel: %v", err)
×
1214
                log.Error(err)
×
1215
                return err
×
1216
        }
×
1217

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

3✔
1222
        return nil
3✔
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) {
3✔
1228
        if IsError(err, ErrIgnored, ErrOutdated) {
6✔
1229
                log.Debugf("process network updates got: %v", err)
3✔
1230

3✔
1231
                return
3✔
1232
        }
3✔
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) {
3✔
1241
        _, height, err := b.cfg.Chain.GetBestBlock()
3✔
1242
        return uint32(height), err
3✔
1243
}
3✔
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 {
3✔
1249
        return b.bestHeight.Load()
3✔
1250
}
3✔
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) {
3✔
1259

3✔
1260
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
3✔
1261
}
3✔
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) {
3✔
1270

3✔
1271
        return b.cfg.Graph.FetchLightningNode(ctx, node)
3✔
1272
}
3✔
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(cb func(*models.ChannelEdgeInfo,
1279
        *models.ChannelEdgePolicy) error) error {
3✔
1280

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

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

1290
                        return cb(c, e)
3✔
1291
                },
1292
        )
1293
}
1294

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

3✔
1302
        return b.cfg.Graph.AddEdgeProof(chanID, proof)
3✔
1303
}
3✔
1304

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

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

1320
        return false
3✔
1321
}
1322

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

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

3✔
1340
        return exists || isZombie
3✔
1341
}
3✔
1342

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

×
1350
        return isZombie, err
×
1351
}
×
1352

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

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

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

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

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

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

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

1407
        return false
×
1408
}
1409

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