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

lightningnetwork / lnd / 12263209213

10 Dec 2024 07:22PM UTC coverage: 49.808% (-0.01%) from 49.82%
12263209213

push

github

web-flow
Merge pull request #9316 from ziggie1984/fix-blindedpath-mc

routing: fix mc blinded path behaviour.

200 of 214 new or added lines in 4 files covered. (93.46%)

76 existing lines in 9 files now uncovered.

86592 of 173852 relevant lines covered (49.81%)

2.4 hits per line

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

59.27
/graph/builder.go
1
package graph
2

3
import (
4
        "bytes"
5
        "fmt"
6
        "runtime"
7
        "strings"
8
        "sync"
9
        "sync/atomic"
10
        "time"
11

12
        "github.com/btcsuite/btcd/btcec/v2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/btcsuite/btcd/wire"
16
        "github.com/go-errors/errors"
17
        "github.com/lightningnetwork/lnd/batch"
18
        "github.com/lightningnetwork/lnd/chainntnfs"
19
        "github.com/lightningnetwork/lnd/fn/v2"
20
        graphdb "github.com/lightningnetwork/lnd/graph/db"
21
        "github.com/lightningnetwork/lnd/graph/db/models"
22
        "github.com/lightningnetwork/lnd/input"
23
        "github.com/lightningnetwork/lnd/kvdb"
24
        "github.com/lightningnetwork/lnd/lnutils"
25
        "github.com/lightningnetwork/lnd/lnwallet"
26
        "github.com/lightningnetwork/lnd/lnwallet/btcwallet"
27
        "github.com/lightningnetwork/lnd/lnwallet/chanvalidate"
28
        "github.com/lightningnetwork/lnd/lnwire"
29
        "github.com/lightningnetwork/lnd/multimutex"
30
        "github.com/lightningnetwork/lnd/netann"
31
        "github.com/lightningnetwork/lnd/routing/chainview"
32
        "github.com/lightningnetwork/lnd/routing/route"
33
        "github.com/lightningnetwork/lnd/ticker"
34
)
35

36
const (
37
        // DefaultChannelPruneExpiry is the default duration used to determine
38
        // if a channel should be pruned or not.
39
        DefaultChannelPruneExpiry = time.Hour * 24 * 14
40

41
        // DefaultFirstTimePruneDelay is the time we'll wait after startup
42
        // before attempting to prune the graph for zombie channels. We don't
43
        // do it immediately after startup to allow lnd to start up without
44
        // getting blocked by this job.
45
        DefaultFirstTimePruneDelay = 30 * time.Second
46

47
        // defaultStatInterval governs how often the router will log non-empty
48
        // stats related to processing new channels, updates, or node
49
        // announcements.
50
        defaultStatInterval = time.Minute
51
)
52

53
var (
54
        // ErrGraphBuilderShuttingDown is returned if the graph builder is in
55
        // the process of shutting down.
56
        ErrGraphBuilderShuttingDown = fmt.Errorf("graph builder shutting down")
57
)
58

59
// Config holds the configuration required by the Builder.
60
type Config struct {
61
        // SelfNode is the public key of the node that this channel router
62
        // belongs to.
63
        SelfNode route.Vertex
64

65
        // Graph is the channel graph that the ChannelRouter will use to gather
66
        // metrics from and also to carry out path finding queries.
67
        Graph DB
68

69
        // Chain is the router's source to the most up-to-date blockchain data.
70
        // All incoming advertised channels will be checked against the chain
71
        // to ensure that the channels advertised are still open.
72
        Chain lnwallet.BlockChainIO
73

74
        // ChainView is an instance of a FilteredChainView which is used to
75
        // watch the sub-set of the UTXO set (the set of active channels) that
76
        // we need in order to properly maintain the channel graph.
77
        ChainView chainview.FilteredChainView
78

79
        // Notifier is a reference to the ChainNotifier, used to grab
80
        // the latest blocks if the router is missing any.
81
        Notifier chainntnfs.ChainNotifier
82

83
        // ChannelPruneExpiry is the duration used to determine if a channel
84
        // should be pruned or not. If the delta between now and when the
85
        // channel was last updated is greater than ChannelPruneExpiry, then
86
        // the channel is marked as a zombie channel eligible for pruning.
87
        ChannelPruneExpiry time.Duration
88

89
        // GraphPruneInterval is used as an interval to determine how often we
90
        // should examine the channel graph to garbage collect zombie channels.
91
        GraphPruneInterval time.Duration
92

93
        // FirstTimePruneDelay is the time we'll wait after startup before
94
        // attempting to prune the graph for zombie channels. We don't do it
95
        // immediately after startup to allow lnd to start up without getting
96
        // blocked by this job.
97
        FirstTimePruneDelay time.Duration
98

99
        // AssumeChannelValid toggles whether the router will check for
100
        // spentness of channel outpoints. For neutrino, this saves long rescans
101
        // from blocking initial usage of the daemon.
102
        AssumeChannelValid bool
103

104
        // StrictZombiePruning determines if we attempt to prune zombie
105
        // channels according to a stricter criteria. If true, then we'll prune
106
        // a channel if only *one* of the edges is considered a zombie.
107
        // Otherwise, we'll only prune the channel when both edges have a very
108
        // dated last update.
109
        StrictZombiePruning bool
110

111
        // IsAlias returns whether a passed ShortChannelID is an alias. This is
112
        // only used for our local channels.
113
        IsAlias func(scid lnwire.ShortChannelID) bool
114
}
115

116
// Builder builds and maintains a view of the Lightning Network graph.
117
type Builder struct {
118
        started atomic.Bool
119
        stopped atomic.Bool
120

121
        ntfnClientCounter atomic.Uint64
122
        bestHeight        atomic.Uint32
123

124
        cfg *Config
125

126
        // newBlocks is a channel in which new blocks connected to the end of
127
        // the main chain are sent over, and blocks updated after a call to
128
        // UpdateFilter.
129
        newBlocks <-chan *chainview.FilteredBlock
130

131
        // staleBlocks is a channel in which blocks disconnected from the end
132
        // of our currently known best chain are sent over.
133
        staleBlocks <-chan *chainview.FilteredBlock
134

135
        // networkUpdates is a channel that carries new topology updates
136
        // messages from outside the Builder to be processed by the
137
        // networkHandler.
138
        networkUpdates chan *routingMsg
139

140
        // topologyClients maps a client's unique notification ID to a
141
        // topologyClient client that contains its notification dispatch
142
        // channel.
143
        topologyClients *lnutils.SyncMap[uint64, *topologyClient]
144

145
        // ntfnClientUpdates is a channel that's used to send new updates to
146
        // topology notification clients to the Builder. Updates either
147
        // add a new notification client, or cancel notifications for an
148
        // existing client.
149
        ntfnClientUpdates chan *topologyClientUpdate
150

151
        // channelEdgeMtx is a mutex we use to make sure we process only one
152
        // ChannelEdgePolicy at a time for a given channelID, to ensure
153
        // consistency between the various database accesses.
154
        channelEdgeMtx *multimutex.Mutex[uint64]
155

156
        // statTicker is a resumable ticker that logs the router's progress as
157
        // it discovers channels or receives updates.
158
        statTicker ticker.Ticker
159

160
        // stats tracks newly processed channels, updates, and node
161
        // announcements over a window of defaultStatInterval.
162
        stats *routerStats
163

164
        quit chan struct{}
165
        wg   sync.WaitGroup
166
}
167

168
// A compile time check to ensure Builder implements the
169
// ChannelGraphSource interface.
170
var _ ChannelGraphSource = (*Builder)(nil)
171

172
// NewBuilder constructs a new Builder.
173
func NewBuilder(cfg *Config) (*Builder, error) {
4✔
174
        return &Builder{
4✔
175
                cfg:               cfg,
4✔
176
                networkUpdates:    make(chan *routingMsg),
4✔
177
                topologyClients:   &lnutils.SyncMap[uint64, *topologyClient]{},
4✔
178
                ntfnClientUpdates: make(chan *topologyClientUpdate),
4✔
179
                channelEdgeMtx:    multimutex.NewMutex[uint64](),
4✔
180
                statTicker:        ticker.New(defaultStatInterval),
4✔
181
                stats:             new(routerStats),
4✔
182
                quit:              make(chan struct{}),
4✔
183
        }, nil
4✔
184
}
4✔
185

186
// Start launches all the goroutines the Builder requires to carry out its
187
// duties. If the builder has already been started, then this method is a noop.
188
func (b *Builder) Start() error {
4✔
189
        if !b.started.CompareAndSwap(false, true) {
4✔
190
                return nil
×
191
        }
×
192

193
        log.Info("Builder starting")
4✔
194

4✔
195
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
4✔
196
        if err != nil {
4✔
197
                return err
×
198
        }
×
199

200
        // If the graph has never been pruned, or hasn't fully been created yet,
201
        // then we don't treat this as an explicit error.
202
        if _, _, err := b.cfg.Graph.PruneTip(); err != nil {
8✔
203
                switch {
4✔
204
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
4✔
205
                        fallthrough
4✔
206

207
                case errors.Is(err, graphdb.ErrGraphNotFound):
4✔
208
                        // If the graph has never been pruned, then we'll set
4✔
209
                        // the prune height to the current best height of the
4✔
210
                        // chain backend.
4✔
211
                        _, err = b.cfg.Graph.PruneGraph(
4✔
212
                                nil, bestHash, uint32(bestHeight),
4✔
213
                        )
4✔
214
                        if err != nil {
4✔
215
                                return err
×
216
                        }
×
217

218
                default:
×
219
                        return err
×
220
                }
221
        }
222

223
        // If AssumeChannelValid is present, then we won't rely on pruning
224
        // channels from the graph based on their spentness, but whether they
225
        // are considered zombies or not. We will start zombie pruning after a
226
        // small delay, to avoid slowing down startup of lnd.
227
        if b.cfg.AssumeChannelValid { //nolint:nestif
4✔
228
                time.AfterFunc(b.cfg.FirstTimePruneDelay, func() {
×
229
                        select {
×
230
                        case <-b.quit:
×
231
                                return
×
232
                        default:
×
233
                        }
234

235
                        log.Info("Initial zombie prune starting")
×
236
                        if err := b.pruneZombieChans(); err != nil {
×
237
                                log.Errorf("Unable to prune zombies: %v", err)
×
238
                        }
×
239
                })
240
        } else {
4✔
241
                // Otherwise, we'll use our filtered chain view to prune
4✔
242
                // channels as soon as they are detected as spent on-chain.
4✔
243
                if err := b.cfg.ChainView.Start(); err != nil {
4✔
244
                        return err
×
245
                }
×
246

247
                // Once the instance is active, we'll fetch the channel we'll
248
                // receive notifications over.
249
                b.newBlocks = b.cfg.ChainView.FilteredBlocks()
4✔
250
                b.staleBlocks = b.cfg.ChainView.DisconnectedBlocks()
4✔
251

4✔
252
                // Before we perform our manual block pruning, we'll construct
4✔
253
                // and apply a fresh chain filter to the active
4✔
254
                // FilteredChainView instance.  We do this before, as otherwise
4✔
255
                // we may miss on-chain events as the filter hasn't properly
4✔
256
                // been applied.
4✔
257
                channelView, err := b.cfg.Graph.ChannelView()
4✔
258
                if err != nil && !errors.Is(
4✔
259
                        err, graphdb.ErrGraphNoEdgesFound,
4✔
260
                ) {
4✔
261

×
262
                        return err
×
263
                }
×
264

265
                log.Infof("Filtering chain using %v channels active",
4✔
266
                        len(channelView))
4✔
267

4✔
268
                if len(channelView) != 0 {
8✔
269
                        err = b.cfg.ChainView.UpdateFilter(
4✔
270
                                channelView, uint32(bestHeight),
4✔
271
                        )
4✔
272
                        if err != nil {
4✔
273
                                return err
×
274
                        }
×
275
                }
276

277
                // The graph pruning might have taken a while and there could be
278
                // new blocks available.
279
                _, bestHeight, err = b.cfg.Chain.GetBestBlock()
4✔
280
                if err != nil {
4✔
281
                        return err
×
282
                }
×
283
                b.bestHeight.Store(uint32(bestHeight))
4✔
284

4✔
285
                // Before we begin normal operation of the router, we first need
4✔
286
                // to synchronize the channel graph to the latest state of the
4✔
287
                // UTXO set.
4✔
288
                if err := b.syncGraphWithChain(); err != nil {
4✔
289
                        return err
×
290
                }
×
291

292
                // Finally, before we proceed, we'll prune any unconnected nodes
293
                // from the graph in order to ensure we maintain a tight graph
294
                // of "useful" nodes.
295
                err = b.cfg.Graph.PruneGraphNodes()
4✔
296
                if err != nil &&
4✔
297
                        !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
4✔
298

×
299
                        return err
×
300
                }
×
301
        }
302

303
        b.wg.Add(1)
4✔
304
        go b.networkHandler()
4✔
305

4✔
306
        log.Debug("Builder started")
4✔
307

4✔
308
        return nil
4✔
309
}
310

311
// Stop signals to the Builder that it should halt all routines. This method
312
// will *block* until all goroutines have excited. If the builder has already
313
// stopped then this method will return immediately.
314
func (b *Builder) Stop() error {
4✔
315
        if !b.stopped.CompareAndSwap(false, true) {
4✔
316
                return nil
×
317
        }
×
318

319
        log.Info("Builder shutting down...")
4✔
320

4✔
321
        // Our filtered chain view could've only been started if
4✔
322
        // AssumeChannelValid isn't present.
4✔
323
        if !b.cfg.AssumeChannelValid {
8✔
324
                if err := b.cfg.ChainView.Stop(); err != nil {
4✔
325
                        return err
×
326
                }
×
327
        }
328

329
        close(b.quit)
4✔
330
        b.wg.Wait()
4✔
331

4✔
332
        log.Debug("Builder shutdown complete")
4✔
333

4✔
334
        return nil
4✔
335
}
336

337
// syncGraphWithChain attempts to synchronize the current channel graph with
338
// the latest UTXO set state. This process involves pruning from the channel
339
// graph any channels which have been closed by spending their funding output
340
// since we've been down.
341
func (b *Builder) syncGraphWithChain() error {
4✔
342
        // First, we'll need to check to see if we're already in sync with the
4✔
343
        // latest state of the UTXO set.
4✔
344
        bestHash, bestHeight, err := b.cfg.Chain.GetBestBlock()
4✔
345
        if err != nil {
4✔
346
                return err
×
347
        }
×
348
        b.bestHeight.Store(uint32(bestHeight))
4✔
349

4✔
350
        pruneHash, pruneHeight, err := b.cfg.Graph.PruneTip()
4✔
351
        if err != nil {
4✔
352
                switch {
×
353
                // If the graph has never been pruned, or hasn't fully been
354
                // created yet, then we don't treat this as an explicit error.
355
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
×
356
                case errors.Is(err, graphdb.ErrGraphNotFound):
×
357
                default:
×
358
                        return err
×
359
                }
360
        }
361

362
        log.Infof("Prune tip for Channel Graph: height=%v, hash=%v",
4✔
363
                pruneHeight, pruneHash)
4✔
364

4✔
365
        switch {
4✔
366
        // If the graph has never been pruned, then we can exit early as this
367
        // entails it's being created for the first time and hasn't seen any
368
        // block or created channels.
369
        case pruneHeight == 0 || pruneHash == nil:
×
370
                return nil
×
371

372
        // If the block hashes and heights match exactly, then we don't need to
373
        // prune the channel graph as we're already fully in sync.
374
        case bestHash.IsEqual(pruneHash) && uint32(bestHeight) == pruneHeight:
4✔
375
                return nil
4✔
376
        }
377

378
        // If the main chain blockhash at prune height is different from the
379
        // prune hash, this might indicate the database is on a stale branch.
380
        mainBlockHash, err := b.cfg.Chain.GetBlockHash(int64(pruneHeight))
4✔
381
        if err != nil {
4✔
382
                return err
×
383
        }
×
384

385
        // While we are on a stale branch of the chain, walk backwards to find
386
        // first common block.
387
        for !pruneHash.IsEqual(mainBlockHash) {
4✔
388
                log.Infof("channel graph is stale. Disconnecting block %v "+
×
389
                        "(hash=%v)", pruneHeight, pruneHash)
×
390
                // Prune the graph for every channel that was opened at height
×
391
                // >= pruneHeight.
×
392
                _, err := b.cfg.Graph.DisconnectBlockAtHeight(pruneHeight)
×
393
                if err != nil {
×
394
                        return err
×
395
                }
×
396

397
                pruneHash, pruneHeight, err = b.cfg.Graph.PruneTip()
×
398
                switch {
×
399
                // If at this point the graph has never been pruned, we can exit
400
                // as this entails we are back to the point where it hasn't seen
401
                // any block or created channels, alas there's nothing left to
402
                // prune.
403
                case errors.Is(err, graphdb.ErrGraphNeverPruned):
×
404
                        return nil
×
405

406
                case errors.Is(err, graphdb.ErrGraphNotFound):
×
407
                        return nil
×
408

409
                case err != nil:
×
410
                        return err
×
411

412
                default:
×
413
                }
414

415
                mainBlockHash, err = b.cfg.Chain.GetBlockHash(
×
416
                        int64(pruneHeight),
×
417
                )
×
418
                if err != nil {
×
419
                        return err
×
420
                }
×
421
        }
422

423
        log.Infof("Syncing channel graph from height=%v (hash=%v) to "+
4✔
424
                "height=%v (hash=%v)", pruneHeight, pruneHash, bestHeight,
4✔
425
                bestHash)
4✔
426

4✔
427
        // If we're not yet caught up, then we'll walk forward in the chain
4✔
428
        // pruning the channel graph with each new block that hasn't yet been
4✔
429
        // consumed by the channel graph.
4✔
430
        var spentOutputs []*wire.OutPoint
4✔
431
        for nextHeight := pruneHeight + 1; nextHeight <= uint32(bestHeight); nextHeight++ { //nolint:ll
8✔
432
                // Break out of the rescan early if a shutdown has been
4✔
433
                // requested, otherwise long rescans will block the daemon from
4✔
434
                // shutting down promptly.
4✔
435
                select {
4✔
436
                case <-b.quit:
×
437
                        return ErrGraphBuilderShuttingDown
×
438
                default:
4✔
439
                }
440

441
                // Using the next height, request a manual block pruning from
442
                // the chainview for the particular block hash.
443
                log.Infof("Filtering block for closed channels, at height: %v",
4✔
444
                        int64(nextHeight))
4✔
445
                nextHash, err := b.cfg.Chain.GetBlockHash(int64(nextHeight))
4✔
446
                if err != nil {
4✔
447
                        return err
×
448
                }
×
449
                log.Tracef("Running block filter on block with hash: %v",
4✔
450
                        nextHash)
4✔
451
                filterBlock, err := b.cfg.ChainView.FilterBlock(nextHash)
4✔
452
                if err != nil {
4✔
453
                        return err
×
454
                }
×
455

456
                // We're only interested in all prior outputs that have been
457
                // spent in the block, so collate all the referenced previous
458
                // outpoints within each tx and input.
459
                for _, tx := range filterBlock.Transactions {
8✔
460
                        for _, txIn := range tx.TxIn {
8✔
461
                                spentOutputs = append(spentOutputs,
4✔
462
                                        &txIn.PreviousOutPoint)
4✔
463
                        }
4✔
464
                }
465
        }
466

467
        // With the spent outputs gathered, attempt to prune the channel graph,
468
        // also passing in the best hash+height so the prune tip can be updated.
469
        closedChans, err := b.cfg.Graph.PruneGraph(
4✔
470
                spentOutputs, bestHash, uint32(bestHeight),
4✔
471
        )
4✔
472
        if err != nil {
4✔
473
                return err
×
474
        }
×
475

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

4✔
479
        return nil
4✔
480
}
481

482
// isZombieChannel takes two edge policy updates and determines if the
483
// corresponding channel should be considered a zombie. The first boolean is
484
// true if the policy update from node 1 is considered a zombie, the second
485
// boolean is that of node 2, and the final boolean is true if the channel
486
// is considered a zombie.
487
func (b *Builder) isZombieChannel(e1,
488
        e2 *models.ChannelEdgePolicy) (bool, bool, bool) {
×
489

×
490
        chanExpiry := b.cfg.ChannelPruneExpiry
×
491

×
492
        e1Zombie := e1 == nil || time.Since(e1.LastUpdate) >= chanExpiry
×
493
        e2Zombie := e2 == nil || time.Since(e2.LastUpdate) >= chanExpiry
×
494

×
495
        var e1Time, e2Time time.Time
×
496
        if e1 != nil {
×
497
                e1Time = e1.LastUpdate
×
498
        }
×
499
        if e2 != nil {
×
500
                e2Time = e2.LastUpdate
×
501
        }
×
502

503
        return e1Zombie, e2Zombie, b.IsZombieChannel(e1Time, e2Time)
×
504
}
505

506
// IsZombieChannel takes the timestamps of the latest channel updates for a
507
// channel and returns true if the channel should be considered a zombie based
508
// on these timestamps.
509
func (b *Builder) IsZombieChannel(updateTime1,
510
        updateTime2 time.Time) bool {
4✔
511

4✔
512
        chanExpiry := b.cfg.ChannelPruneExpiry
4✔
513

4✔
514
        e1Zombie := updateTime1.IsZero() ||
4✔
515
                time.Since(updateTime1) >= chanExpiry
4✔
516

4✔
517
        e2Zombie := updateTime2.IsZero() ||
4✔
518
                time.Since(updateTime2) >= chanExpiry
4✔
519

4✔
520
        // If we're using strict zombie pruning, then a channel is only
4✔
521
        // considered live if both edges have a recent update we know of.
4✔
522
        if b.cfg.StrictZombiePruning {
5✔
523
                return e1Zombie || e2Zombie
1✔
524
        }
1✔
525

526
        // Otherwise, if we're using the less strict variant, then a channel is
527
        // considered live if either of the edges have a recent update.
528
        return e1Zombie && e2Zombie
3✔
529
}
530

531
// pruneZombieChans is a method that will be called periodically to prune out
532
// any "zombie" channels. We consider channels zombies if *both* edges haven't
533
// been updated since our zombie horizon. If AssumeChannelValid is present,
534
// we'll also consider channels zombies if *both* edges are disabled. This
535
// usually signals that a channel has been closed on-chain. We do this
536
// periodically to keep a healthy, lively routing table.
537
func (b *Builder) pruneZombieChans() error {
×
538
        chansToPrune := make(map[uint64]struct{})
×
539
        chanExpiry := b.cfg.ChannelPruneExpiry
×
540

×
541
        log.Infof("Examining channel graph for zombie channels")
×
542

×
543
        // A helper method to detect if the channel belongs to this node
×
544
        isSelfChannelEdge := func(info *models.ChannelEdgeInfo) bool {
×
545
                return info.NodeKey1Bytes == b.cfg.SelfNode ||
×
546
                        info.NodeKey2Bytes == b.cfg.SelfNode
×
547
        }
×
548

549
        // First, we'll collect all the channels which are eligible for garbage
550
        // collection due to being zombies.
551
        filterPruneChans := func(info *models.ChannelEdgeInfo,
×
552
                e1, e2 *models.ChannelEdgePolicy) error {
×
553

×
554
                // Exit early in case this channel is already marked to be
×
555
                // pruned
×
556
                _, markedToPrune := chansToPrune[info.ChannelID]
×
557
                if markedToPrune {
×
558
                        return nil
×
559
                }
×
560

561
                // We'll ensure that we don't attempt to prune our *own*
562
                // channels from the graph, as in any case this should be
563
                // re-advertised by the sub-system above us.
564
                if isSelfChannelEdge(info) {
×
565
                        return nil
×
566
                }
×
567

568
                e1Zombie, e2Zombie, isZombieChan := b.isZombieChannel(e1, e2)
×
569

×
570
                if e1Zombie {
×
571
                        log.Tracef("Node1 pubkey=%x of chan_id=%v is zombie",
×
572
                                info.NodeKey1Bytes, info.ChannelID)
×
573
                }
×
574

575
                if e2Zombie {
×
576
                        log.Tracef("Node2 pubkey=%x of chan_id=%v is zombie",
×
577
                                info.NodeKey2Bytes, info.ChannelID)
×
578
                }
×
579

580
                // If either edge hasn't been updated for a period of
581
                // chanExpiry, then we'll mark the channel itself as eligible
582
                // for graph pruning.
583
                if !isZombieChan {
×
584
                        return nil
×
585
                }
×
586

587
                log.Debugf("ChannelID(%v) is a zombie, collecting to prune",
×
588
                        info.ChannelID)
×
589

×
590
                // TODO(roasbeef): add ability to delete single directional edge
×
591
                chansToPrune[info.ChannelID] = struct{}{}
×
592

×
593
                return nil
×
594
        }
595

596
        // If AssumeChannelValid is present we'll look at the disabled bit for
597
        // both edges. If they're both disabled, then we can interpret this as
598
        // the channel being closed and can prune it from our graph.
599
        if b.cfg.AssumeChannelValid {
×
600
                disabledChanIDs, err := b.cfg.Graph.DisabledChannelIDs()
×
601
                if err != nil {
×
602
                        return fmt.Errorf("unable to get disabled channels "+
×
603
                                "ids chans: %v", err)
×
604
                }
×
605

606
                disabledEdges, err := b.cfg.Graph.FetchChanInfos(
×
607
                        disabledChanIDs,
×
608
                )
×
609
                if err != nil {
×
610
                        return fmt.Errorf("unable to fetch disabled channels "+
×
611
                                "edges chans: %v", err)
×
612
                }
×
613

614
                // Ensuring we won't prune our own channel from the graph.
615
                for _, disabledEdge := range disabledEdges {
×
616
                        if !isSelfChannelEdge(disabledEdge.Info) {
×
617
                                chansToPrune[disabledEdge.Info.ChannelID] =
×
618
                                        struct{}{}
×
619
                        }
×
620
                }
621
        }
622

623
        startTime := time.Unix(0, 0)
×
624
        endTime := time.Now().Add(-1 * chanExpiry)
×
625
        oldEdges, err := b.cfg.Graph.ChanUpdatesInHorizon(startTime, endTime)
×
626
        if err != nil {
×
627
                return fmt.Errorf("unable to fetch expired channel updates "+
×
628
                        "chans: %v", err)
×
629
        }
×
630

631
        for _, u := range oldEdges {
×
632
                err = filterPruneChans(u.Info, u.Policy1, u.Policy2)
×
633
                if err != nil {
×
634
                        return fmt.Errorf("error filtering channels to "+
×
635
                                "prune: %w", err)
×
636
                }
×
637
        }
638

639
        log.Infof("Pruning %v zombie channels", len(chansToPrune))
×
640
        if len(chansToPrune) == 0 {
×
641
                return nil
×
642
        }
×
643

644
        // With the set of zombie-like channels obtained, we'll do another pass
645
        // to delete them from the channel graph.
646
        toPrune := make([]uint64, 0, len(chansToPrune))
×
647
        for chanID := range chansToPrune {
×
648
                toPrune = append(toPrune, chanID)
×
649
                log.Tracef("Pruning zombie channel with ChannelID(%v)", chanID)
×
650
        }
×
651
        err = b.cfg.Graph.DeleteChannelEdges(
×
652
                b.cfg.StrictZombiePruning, true, toPrune...,
×
653
        )
×
654
        if err != nil {
×
655
                return fmt.Errorf("unable to delete zombie channels: %w", err)
×
656
        }
×
657

658
        // With the channels pruned, we'll also attempt to prune any nodes that
659
        // were a part of them.
660
        err = b.cfg.Graph.PruneGraphNodes()
×
661
        if err != nil && !errors.Is(err, graphdb.ErrGraphNodesNotFound) {
×
662
                return fmt.Errorf("unable to prune graph nodes: %w", err)
×
663
        }
×
664

665
        return nil
×
666
}
667

668
// handleNetworkUpdate is responsible for processing the update message and
669
// notifies topology changes, if any.
670
//
671
// NOTE: must be run inside goroutine.
672
func (b *Builder) handleNetworkUpdate(vb *ValidationBarrier,
673
        update *routingMsg) {
4✔
674

4✔
675
        defer b.wg.Done()
4✔
676
        defer vb.CompleteJob()
4✔
677

4✔
678
        // If this message has an existing dependency, then we'll wait until
4✔
679
        // that has been fully validated before we proceed.
4✔
680
        err := vb.WaitForDependants(update.msg)
4✔
681
        if err != nil {
4✔
682
                switch {
×
683
                case IsError(err, ErrVBarrierShuttingDown):
×
684
                        update.err <- err
×
685

686
                case IsError(err, ErrParentValidationFailed):
×
687
                        update.err <- NewErrf(ErrIgnored, err.Error()) //nolint
×
688

689
                default:
×
690
                        log.Warnf("unexpected error during validation "+
×
691
                                "barrier shutdown: %v", err)
×
692
                        update.err <- err
×
693
                }
694

695
                return
×
696
        }
697

698
        // Process the routing update to determine if this is either a new
699
        // update from our PoV or an update to a prior vertex/edge we
700
        // previously accepted.
701
        err = b.processUpdate(update.msg, update.op...)
4✔
702
        update.err <- err
4✔
703

4✔
704
        // If this message had any dependencies, then we can now signal them to
4✔
705
        // continue.
4✔
706
        allowDependents := err == nil || IsError(err, ErrIgnored, ErrOutdated)
4✔
707
        vb.SignalDependants(update.msg, allowDependents)
4✔
708

4✔
709
        // If the error is not nil here, there's no need to send topology
4✔
710
        // change.
4✔
711
        if err != nil {
8✔
712
                // We now decide to log an error or not. If allowDependents is
4✔
713
                // false, it means there is an error and the error is neither
4✔
714
                // ErrIgnored or ErrOutdated. In this case, we'll log an error.
4✔
715
                // Otherwise, we'll add debug log only.
4✔
716
                if allowDependents {
8✔
717
                        log.Debugf("process network updates got: %v", err)
4✔
718
                } else {
4✔
719
                        log.Errorf("process network updates got: %v", err)
×
720
                }
×
721

722
                return
4✔
723
        }
724

725
        // Otherwise, we'll send off a new notification for the newly accepted
726
        // update, if any.
727
        topChange := &TopologyChange{}
4✔
728
        err = addToTopologyChange(b.cfg.Graph, topChange, update.msg)
4✔
729
        if err != nil {
4✔
730
                log.Errorf("unable to update topology change notification: %v",
×
731
                        err)
×
732
                return
×
733
        }
×
734

735
        if !topChange.isEmpty() {
8✔
736
                b.notifyTopologyChange(topChange)
4✔
737
        }
4✔
738
}
739

740
// networkHandler is the primary goroutine for the Builder. The roles of
741
// this goroutine include answering queries related to the state of the
742
// network, pruning the graph on new block notification, applying network
743
// updates, and registering new topology clients.
744
//
745
// NOTE: This MUST be run as a goroutine.
746
func (b *Builder) networkHandler() {
4✔
747
        defer b.wg.Done()
4✔
748

4✔
749
        graphPruneTicker := time.NewTicker(b.cfg.GraphPruneInterval)
4✔
750
        defer graphPruneTicker.Stop()
4✔
751

4✔
752
        defer b.statTicker.Stop()
4✔
753

4✔
754
        b.stats.Reset()
4✔
755

4✔
756
        // We'll use this validation barrier to ensure that we process all jobs
4✔
757
        // in the proper order during parallel validation.
4✔
758
        //
4✔
759
        // NOTE: For AssumeChannelValid, we bump up the maximum number of
4✔
760
        // concurrent validation requests since there are no blocks being
4✔
761
        // fetched. This significantly increases the performance of IGD for
4✔
762
        // neutrino nodes.
4✔
763
        //
4✔
764
        // However, we dial back to use multiple of the number of cores when
4✔
765
        // fully validating, to avoid fetching up to 1000 blocks from the
4✔
766
        // backend. On bitcoind, this will empirically cause massive latency
4✔
767
        // spikes when executing this many concurrent RPC calls. Critical
4✔
768
        // subsystems or basic rpc calls that rely on calls such as GetBestBlock
4✔
769
        // will hang due to excessive load.
4✔
770
        //
4✔
771
        // See https://github.com/lightningnetwork/lnd/issues/4892.
4✔
772
        var validationBarrier *ValidationBarrier
4✔
773
        if b.cfg.AssumeChannelValid {
4✔
774
                validationBarrier = NewValidationBarrier(1000, b.quit)
×
775
        } else {
4✔
776
                validationBarrier = NewValidationBarrier(
4✔
777
                        4*runtime.NumCPU(), b.quit,
4✔
778
                )
4✔
779
        }
4✔
780

781
        for {
8✔
782
                // If there are stats, resume the statTicker.
4✔
783
                if !b.stats.Empty() {
8✔
784
                        b.statTicker.Resume()
4✔
785
                }
4✔
786

787
                select {
4✔
788
                // A new fully validated network update has just arrived. As a
789
                // result we'll modify the channel graph accordingly depending
790
                // on the exact type of the message.
791
                case update := <-b.networkUpdates:
4✔
792
                        // We'll set up any dependants, and wait until a free
4✔
793
                        // slot for this job opens up, this allows us to not
4✔
794
                        // have thousands of goroutines active.
4✔
795
                        validationBarrier.InitJobDependencies(update.msg)
4✔
796

4✔
797
                        b.wg.Add(1)
4✔
798
                        go b.handleNetworkUpdate(validationBarrier, update)
4✔
799

800
                        // TODO(roasbeef): remove all unconnected vertexes
801
                        // after N blocks pass with no corresponding
802
                        // announcements.
803

804
                case chainUpdate, ok := <-b.staleBlocks:
3✔
805
                        // If the channel has been closed, then this indicates
3✔
806
                        // the daemon is shutting down, so we exit ourselves.
3✔
807
                        if !ok {
3✔
808
                                return
×
809
                        }
×
810

811
                        // Since this block is stale, we update our best height
812
                        // to the previous block.
813
                        blockHeight := chainUpdate.Height
3✔
814
                        b.bestHeight.Store(blockHeight - 1)
3✔
815

3✔
816
                        // Update the channel graph to reflect that this block
3✔
817
                        // was disconnected.
3✔
818
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
3✔
819
                                blockHeight,
3✔
820
                        )
3✔
821
                        if err != nil {
3✔
822
                                log.Errorf("unable to prune graph with stale "+
×
823
                                        "block: %v", err)
×
824
                                continue
×
825
                        }
826

827
                        // TODO(halseth): notify client about the reorg?
828

829
                // A new block has arrived, so we can prune the channel graph
830
                // of any channels which were closed in the block.
831
                case chainUpdate, ok := <-b.newBlocks:
4✔
832
                        // If the channel has been closed, then this indicates
4✔
833
                        // the daemon is shutting down, so we exit ourselves.
4✔
834
                        if !ok {
4✔
835
                                return
×
836
                        }
×
837

838
                        // We'll ensure that any new blocks received attach
839
                        // directly to the end of our main chain. If not, then
840
                        // we've somehow missed some blocks. Here we'll catch
841
                        // up the chain with the latest blocks.
842
                        currentHeight := b.bestHeight.Load()
4✔
843
                        switch {
4✔
844
                        case chainUpdate.Height == currentHeight+1:
4✔
845
                                err := b.updateGraphWithClosedChannels(
4✔
846
                                        chainUpdate,
4✔
847
                                )
4✔
848
                                if err != nil {
4✔
849
                                        log.Errorf("unable to prune graph "+
×
850
                                                "with closed channels: %v", err)
×
851
                                }
×
852

853
                        case chainUpdate.Height > currentHeight+1:
×
854
                                log.Errorf("out of order block: expecting "+
×
855
                                        "height=%v, got height=%v",
×
856
                                        currentHeight+1, chainUpdate.Height)
×
857

×
858
                                err := b.getMissingBlocks(
×
859
                                        currentHeight, chainUpdate,
×
860
                                )
×
861
                                if err != nil {
×
862
                                        log.Errorf("unable to retrieve missing"+
×
863
                                                "blocks: %v", err)
×
864
                                }
×
865

UNCOV
866
                        case chainUpdate.Height < currentHeight+1:
×
UNCOV
867
                                log.Errorf("out of order block: expecting "+
×
UNCOV
868
                                        "height=%v, got height=%v",
×
UNCOV
869
                                        currentHeight+1, chainUpdate.Height)
×
UNCOV
870

×
UNCOV
871
                                log.Infof("Skipping channel pruning since "+
×
UNCOV
872
                                        "received block height %v was already"+
×
UNCOV
873
                                        " processed.", chainUpdate.Height)
×
874
                        }
875

876
                // A new notification client update has arrived. We're either
877
                // gaining a new client, or cancelling notifications for an
878
                // existing client.
879
                case ntfnUpdate := <-b.ntfnClientUpdates:
4✔
880
                        clientID := ntfnUpdate.clientID
4✔
881

4✔
882
                        if ntfnUpdate.cancel {
8✔
883
                                client, ok := b.topologyClients.LoadAndDelete(
4✔
884
                                        clientID,
4✔
885
                                )
4✔
886
                                if ok {
8✔
887
                                        close(client.exit)
4✔
888
                                        client.wg.Wait()
4✔
889

4✔
890
                                        close(client.ntfnChan)
4✔
891
                                }
4✔
892

893
                                continue
4✔
894
                        }
895

896
                        b.topologyClients.Store(clientID, &topologyClient{
4✔
897
                                ntfnChan: ntfnUpdate.ntfnChan,
4✔
898
                                exit:     make(chan struct{}),
4✔
899
                        })
4✔
900

901
                // The graph prune ticker has ticked, so we'll examine the
902
                // state of the known graph to filter out any zombie channels
903
                // for pruning.
904
                case <-graphPruneTicker.C:
×
905
                        if err := b.pruneZombieChans(); err != nil {
×
906
                                log.Errorf("Unable to prune zombies: %v", err)
×
907
                        }
×
908

909
                // Log any stats if we've processed a non-empty number of
910
                // channels, updates, or nodes. We'll only pause the ticker if
911
                // the last window contained no updates to avoid resuming and
912
                // pausing while consecutive windows contain new info.
913
                case <-b.statTicker.Ticks():
4✔
914
                        if !b.stats.Empty() {
8✔
915
                                log.Infof(b.stats.String())
4✔
916
                        } else {
4✔
UNCOV
917
                                b.statTicker.Pause()
×
UNCOV
918
                        }
×
919
                        b.stats.Reset()
4✔
920

921
                // The router has been signalled to exit, to we exit our main
922
                // loop so the wait group can be decremented.
923
                case <-b.quit:
4✔
924
                        return
4✔
925
                }
926
        }
927
}
928

929
// getMissingBlocks walks through all missing blocks and updates the graph
930
// closed channels accordingly.
931
func (b *Builder) getMissingBlocks(currentHeight uint32,
932
        chainUpdate *chainview.FilteredBlock) error {
×
933

×
934
        outdatedHash, err := b.cfg.Chain.GetBlockHash(int64(currentHeight))
×
935
        if err != nil {
×
936
                return err
×
937
        }
×
938

939
        outdatedBlock := &chainntnfs.BlockEpoch{
×
940
                Height: int32(currentHeight),
×
941
                Hash:   outdatedHash,
×
942
        }
×
943

×
944
        epochClient, err := b.cfg.Notifier.RegisterBlockEpochNtfn(
×
945
                outdatedBlock,
×
946
        )
×
947
        if err != nil {
×
948
                return err
×
949
        }
×
950
        defer epochClient.Cancel()
×
951

×
952
        blockDifference := int(chainUpdate.Height - currentHeight)
×
953

×
954
        // We'll walk through all the outdated blocks and make sure we're able
×
955
        // to update the graph with any closed channels from them.
×
956
        for i := 0; i < blockDifference; i++ {
×
957
                var (
×
958
                        missingBlock *chainntnfs.BlockEpoch
×
959
                        ok           bool
×
960
                )
×
961

×
962
                select {
×
963
                case missingBlock, ok = <-epochClient.Epochs:
×
964
                        if !ok {
×
965
                                return nil
×
966
                        }
×
967

968
                case <-b.quit:
×
969
                        return nil
×
970
                }
971

972
                filteredBlock, err := b.cfg.ChainView.FilterBlock(
×
973
                        missingBlock.Hash,
×
974
                )
×
975
                if err != nil {
×
976
                        return err
×
977
                }
×
978

979
                err = b.updateGraphWithClosedChannels(
×
980
                        filteredBlock,
×
981
                )
×
982
                if err != nil {
×
983
                        return err
×
984
                }
×
985
        }
986

987
        return nil
×
988
}
989

990
// updateGraphWithClosedChannels prunes the channel graph of closed channels
991
// that are no longer needed.
992
func (b *Builder) updateGraphWithClosedChannels(
993
        chainUpdate *chainview.FilteredBlock) error {
4✔
994

4✔
995
        // Once a new block arrives, we update our running track of the height
4✔
996
        // of the chain tip.
4✔
997
        blockHeight := chainUpdate.Height
4✔
998

4✔
999
        b.bestHeight.Store(blockHeight)
4✔
1000
        log.Infof("Pruning channel graph using block %v (height=%v)",
4✔
1001
                chainUpdate.Hash, blockHeight)
4✔
1002

4✔
1003
        // We're only interested in all prior outputs that have been spent in
4✔
1004
        // the block, so collate all the referenced previous outpoints within
4✔
1005
        // each tx and input.
4✔
1006
        var spentOutputs []*wire.OutPoint
4✔
1007
        for _, tx := range chainUpdate.Transactions {
8✔
1008
                for _, txIn := range tx.TxIn {
8✔
1009
                        spentOutputs = append(spentOutputs,
4✔
1010
                                &txIn.PreviousOutPoint)
4✔
1011
                }
4✔
1012
        }
1013

1014
        // With the spent outputs gathered, attempt to prune the channel graph,
1015
        // also passing in the hash+height of the block being pruned so the
1016
        // prune tip can be updated.
1017
        chansClosed, err := b.cfg.Graph.PruneGraph(spentOutputs,
4✔
1018
                &chainUpdate.Hash, chainUpdate.Height)
4✔
1019
        if err != nil {
4✔
1020
                log.Errorf("unable to prune routing table: %v", err)
×
1021
                return err
×
1022
        }
×
1023

1024
        log.Infof("Block %v (height=%v) closed %v channels", chainUpdate.Hash,
4✔
1025
                blockHeight, len(chansClosed))
4✔
1026

4✔
1027
        if len(chansClosed) == 0 {
8✔
1028
                return err
4✔
1029
        }
4✔
1030

1031
        // Notify all currently registered clients of the newly closed channels.
1032
        closeSummaries := createCloseSummaries(blockHeight, chansClosed...)
4✔
1033
        b.notifyTopologyChange(&TopologyChange{
4✔
1034
                ClosedChannels: closeSummaries,
4✔
1035
        })
4✔
1036

4✔
1037
        return nil
4✔
1038
}
1039

1040
// assertNodeAnnFreshness returns a non-nil error if we have an announcement in
1041
// the database for the passed node with a timestamp newer than the passed
1042
// timestamp. ErrIgnored will be returned if we already have the node, and
1043
// ErrOutdated will be returned if we have a timestamp that's after the new
1044
// timestamp.
1045
func (b *Builder) assertNodeAnnFreshness(node route.Vertex,
1046
        msgTimestamp time.Time) error {
4✔
1047

4✔
1048
        // If we are not already aware of this node, it means that we don't
4✔
1049
        // know about any channel using this node. To avoid a DoS attack by
4✔
1050
        // node announcements, we will ignore such nodes. If we do know about
4✔
1051
        // this node, check that this update brings info newer than what we
4✔
1052
        // already have.
4✔
1053
        lastUpdate, exists, err := b.cfg.Graph.HasLightningNode(node)
4✔
1054
        if err != nil {
4✔
1055
                return errors.Errorf("unable to query for the "+
×
1056
                        "existence of node: %v", err)
×
1057
        }
×
1058
        if !exists {
8✔
1059
                return NewErrf(ErrIgnored, "Ignoring node announcement"+
4✔
1060
                        " for node not found in channel graph (%x)",
4✔
1061
                        node[:])
4✔
1062
        }
4✔
1063

1064
        // If we've reached this point then we're aware of the vertex being
1065
        // advertised. So we now check if the new message has a new time stamp,
1066
        // if not then we won't accept the new data as it would override newer
1067
        // data.
1068
        if !lastUpdate.Before(msgTimestamp) {
8✔
1069
                return NewErrf(ErrOutdated, "Ignoring outdated "+
4✔
1070
                        "announcement for %x", node[:])
4✔
1071
        }
4✔
1072

1073
        return nil
4✔
1074
}
1075

1076
// addZombieEdge adds a channel that failed complete validation into the zombie
1077
// index so we can avoid having to re-validate it in the future.
1078
func (b *Builder) addZombieEdge(chanID uint64) error {
×
1079
        // If the edge fails validation we'll mark the edge itself as a zombie
×
1080
        // so we don't continue to request it. We use the "zero key" for both
×
1081
        // node pubkeys so this edge can't be resurrected.
×
1082
        var zeroKey [33]byte
×
1083
        err := b.cfg.Graph.MarkEdgeZombie(chanID, zeroKey, zeroKey)
×
1084
        if err != nil {
×
1085
                return fmt.Errorf("unable to mark spent chan(id=%v) as a "+
×
1086
                        "zombie: %w", chanID, err)
×
1087
        }
×
1088

1089
        return nil
×
1090
}
1091

1092
// makeFundingScript is used to make the funding script for both segwit v0 and
1093
// segwit v1 (taproot) channels.
1094
//
1095
// TODO(roasbeef: export and use elsewhere?
1096
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte, chanFeatures []byte,
1097
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
4✔
1098

4✔
1099
        legacyFundingScript := func() ([]byte, error) {
8✔
1100
                witnessScript, err := input.GenMultiSigScript(
4✔
1101
                        bitcoinKey1, bitcoinKey2,
4✔
1102
                )
4✔
1103
                if err != nil {
4✔
1104
                        return nil, err
×
1105
                }
×
1106
                pkScript, err := input.WitnessScriptHash(witnessScript)
4✔
1107
                if err != nil {
4✔
1108
                        return nil, err
×
1109
                }
×
1110

1111
                return pkScript, nil
4✔
1112
        }
1113

1114
        if len(chanFeatures) == 0 {
4✔
1115
                return legacyFundingScript()
×
1116
        }
×
1117

1118
        // In order to make the correct funding script, we'll need to parse the
1119
        // chanFeatures bytes into a feature vector we can interact with.
1120
        rawFeatures := lnwire.NewRawFeatureVector()
4✔
1121
        err := rawFeatures.Decode(bytes.NewReader(chanFeatures))
4✔
1122
        if err != nil {
4✔
1123
                return nil, fmt.Errorf("unable to parse chan feature "+
×
1124
                        "bits: %w", err)
×
1125
        }
×
1126

1127
        chanFeatureBits := lnwire.NewFeatureVector(
4✔
1128
                rawFeatures, lnwire.Features,
4✔
1129
        )
4✔
1130
        if chanFeatureBits.HasFeature(
4✔
1131
                lnwire.SimpleTaprootChannelsOptionalStaging,
4✔
1132
        ) {
8✔
1133

4✔
1134
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
4✔
1135
                if err != nil {
4✔
1136
                        return nil, err
×
1137
                }
×
1138
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
4✔
1139
                if err != nil {
4✔
1140
                        return nil, err
×
1141
                }
×
1142

1143
                fundingScript, _, err := input.GenTaprootFundingScript(
4✔
1144
                        pubKey1, pubKey2, 0, tapscriptRoot,
4✔
1145
                )
4✔
1146
                if err != nil {
4✔
1147
                        return nil, err
×
1148
                }
×
1149

1150
                // TODO(roasbeef): add tapscript root to gossip v1.5
1151

1152
                return fundingScript, nil
4✔
1153
        }
1154

1155
        return legacyFundingScript()
4✔
1156
}
1157

1158
// processUpdate processes a new relate authenticated channel/edge, node or
1159
// channel/edge update network update. If the update didn't affect the internal
1160
// state of the draft due to either being out of date, invalid, or redundant,
1161
// then error is returned.
1162
//
1163
//nolint:funlen
1164
func (b *Builder) processUpdate(msg interface{},
1165
        op ...batch.SchedulerOption) error {
4✔
1166

4✔
1167
        switch msg := msg.(type) {
4✔
1168
        case *models.LightningNode:
4✔
1169
                // Before we add the node to the database, we'll check to see
4✔
1170
                // if the announcement is "fresh" or not. If it isn't, then
4✔
1171
                // we'll return an error.
4✔
1172
                err := b.assertNodeAnnFreshness(msg.PubKeyBytes, msg.LastUpdate)
4✔
1173
                if err != nil {
8✔
1174
                        return err
4✔
1175
                }
4✔
1176

1177
                if err := b.cfg.Graph.AddLightningNode(msg, op...); err != nil {
4✔
1178
                        return errors.Errorf("unable to add node %x to the "+
×
1179
                                "graph: %v", msg.PubKeyBytes, err)
×
1180
                }
×
1181

1182
                log.Tracef("Updated vertex data for node=%x", msg.PubKeyBytes)
4✔
1183
                b.stats.incNumNodeUpdates()
4✔
1184

1185
        case *models.ChannelEdgeInfo:
4✔
1186
                log.Debugf("Received ChannelEdgeInfo for channel %v",
4✔
1187
                        msg.ChannelID)
4✔
1188

4✔
1189
                // Prior to processing the announcement we first check if we
4✔
1190
                // already know of this channel, if so, then we can exit early.
4✔
1191
                _, _, exists, isZombie, err := b.cfg.Graph.HasChannelEdge(
4✔
1192
                        msg.ChannelID,
4✔
1193
                )
4✔
1194
                if err != nil &&
4✔
1195
                        !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
4✔
1196

×
1197
                        return errors.Errorf("unable to check for edge "+
×
1198
                                "existence: %v", err)
×
1199
                }
×
1200
                if isZombie {
4✔
1201
                        return NewErrf(ErrIgnored, "ignoring msg for zombie "+
×
1202
                                "chan_id=%v", msg.ChannelID)
×
1203
                }
×
1204
                if exists {
8✔
1205
                        return NewErrf(ErrIgnored, "ignoring msg for known "+
4✔
1206
                                "chan_id=%v", msg.ChannelID)
4✔
1207
                }
4✔
1208

1209
                // If AssumeChannelValid is present, then we are unable to
1210
                // perform any of the expensive checks below, so we'll
1211
                // short-circuit our path straight to adding the edge to our
1212
                // graph. If the passed ShortChannelID is an alias, then we'll
1213
                // skip validation as it will not map to a legitimate tx. This
1214
                // is not a DoS vector as only we can add an alias
1215
                // ChannelAnnouncement from the gossiper.
1216
                scid := lnwire.NewShortChanIDFromInt(msg.ChannelID)
4✔
1217
                if b.cfg.AssumeChannelValid || b.cfg.IsAlias(scid) {
8✔
1218
                        err := b.cfg.Graph.AddChannelEdge(msg, op...)
4✔
1219
                        if err != nil {
4✔
1220
                                return fmt.Errorf("unable to add edge: %w", err)
×
1221
                        }
×
1222
                        log.Tracef("New channel discovered! Link "+
4✔
1223
                                "connects %x and %x with ChannelID(%v)",
4✔
1224
                                msg.NodeKey1Bytes, msg.NodeKey2Bytes,
4✔
1225
                                msg.ChannelID)
4✔
1226
                        b.stats.incNumEdgesDiscovered()
4✔
1227

4✔
1228
                        break
4✔
1229
                }
1230

1231
                // Before we can add the channel to the channel graph, we need
1232
                // to obtain the full funding outpoint that's encoded within
1233
                // the channel ID.
1234
                channelID := lnwire.NewShortChanIDFromInt(msg.ChannelID)
4✔
1235
                fundingTx, err := lnwallet.FetchFundingTxWrapper(
4✔
1236
                        b.cfg.Chain, &channelID, b.quit,
4✔
1237
                )
4✔
1238
                if err != nil {
4✔
1239
                        //nolint:ll
×
1240
                        //
×
1241
                        // In order to ensure we don't erroneously mark a
×
1242
                        // channel as a zombie due to an RPC failure, we'll
×
1243
                        // attempt to string match for the relevant errors.
×
1244
                        //
×
1245
                        // * btcd:
×
1246
                        //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
×
1247
                        //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
×
1248
                        // * bitcoind:
×
1249
                        //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
×
1250
                        //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
×
1251
                        switch {
×
1252
                        case strings.Contains(err.Error(), "not found"):
×
1253
                                fallthrough
×
1254

1255
                        case strings.Contains(err.Error(), "out of range"):
×
1256
                                // If the funding transaction isn't found at
×
1257
                                // all, then we'll mark the edge itself as a
×
1258
                                // zombie so we don't continue to request it.
×
1259
                                // We use the "zero key" for both node pubkeys
×
1260
                                // so this edge can't be resurrected.
×
1261
                                zErr := b.addZombieEdge(msg.ChannelID)
×
1262
                                if zErr != nil {
×
1263
                                        return zErr
×
1264
                                }
×
1265

1266
                        default:
×
1267
                        }
1268

1269
                        return NewErrf(ErrNoFundingTransaction, "unable to "+
×
1270
                                "locate funding tx: %v", err)
×
1271
                }
1272

1273
                // Recreate witness output to be sure that declared in channel
1274
                // edge bitcoin keys and channel value corresponds to the
1275
                // reality.
1276
                fundingPkScript, err := makeFundingScript(
4✔
1277
                        msg.BitcoinKey1Bytes[:], msg.BitcoinKey2Bytes[:],
4✔
1278
                        msg.Features, msg.TapscriptRoot,
4✔
1279
                )
4✔
1280
                if err != nil {
4✔
1281
                        return err
×
1282
                }
×
1283

1284
                // Next we'll validate that this channel is actually well
1285
                // formed. If this check fails, then this channel either
1286
                // doesn't exist, or isn't the one that was meant to be created
1287
                // according to the passed channel proofs.
1288
                fundingPoint, err := chanvalidate.Validate(
4✔
1289
                        &chanvalidate.Context{
4✔
1290
                                Locator: &chanvalidate.ShortChanIDChanLocator{
4✔
1291
                                        ID: channelID,
4✔
1292
                                },
4✔
1293
                                MultiSigPkScript: fundingPkScript,
4✔
1294
                                FundingTx:        fundingTx,
4✔
1295
                        },
4✔
1296
                )
4✔
1297
                if err != nil {
4✔
1298
                        // Mark the edge as a zombie so we won't try to
×
1299
                        // re-validate it on start up.
×
1300
                        if err := b.addZombieEdge(msg.ChannelID); err != nil {
×
1301
                                return err
×
1302
                        }
×
1303

1304
                        return NewErrf(ErrInvalidFundingOutput, "output "+
×
1305
                                "failed validation: %w", err)
×
1306
                }
1307

1308
                // Now that we have the funding outpoint of the channel, ensure
1309
                // that it hasn't yet been spent. If so, then this channel has
1310
                // been closed so we'll ignore it.
1311
                chanUtxo, err := b.cfg.Chain.GetUtxo(
4✔
1312
                        fundingPoint, fundingPkScript, channelID.BlockHeight,
4✔
1313
                        b.quit,
4✔
1314
                )
4✔
1315
                if err != nil {
4✔
1316
                        if errors.Is(err, btcwallet.ErrOutputSpent) {
×
1317
                                zErr := b.addZombieEdge(msg.ChannelID)
×
1318
                                if zErr != nil {
×
1319
                                        return zErr
×
1320
                                }
×
1321
                        }
1322

1323
                        return NewErrf(ErrChannelSpent, "unable to fetch utxo "+
×
1324
                                "for chan_id=%v, chan_point=%v: %v",
×
1325
                                msg.ChannelID, fundingPoint, err)
×
1326
                }
1327

1328
                // TODO(roasbeef): this is a hack, needs to be removed
1329
                // after commitment fees are dynamic.
1330
                msg.Capacity = btcutil.Amount(chanUtxo.Value)
4✔
1331
                msg.ChannelPoint = *fundingPoint
4✔
1332
                if err := b.cfg.Graph.AddChannelEdge(msg, op...); err != nil {
4✔
1333
                        return errors.Errorf("unable to add edge: %v", err)
×
1334
                }
×
1335

1336
                log.Debugf("New channel discovered! Link "+
4✔
1337
                        "connects %x and %x with ChannelPoint(%v): "+
4✔
1338
                        "chan_id=%v, capacity=%v",
4✔
1339
                        msg.NodeKey1Bytes, msg.NodeKey2Bytes,
4✔
1340
                        fundingPoint, msg.ChannelID, msg.Capacity)
4✔
1341
                b.stats.incNumEdgesDiscovered()
4✔
1342

4✔
1343
                // As a new edge has been added to the channel graph, we'll
4✔
1344
                // update the current UTXO filter within our active
4✔
1345
                // FilteredChainView so we are notified if/when this channel is
4✔
1346
                // closed.
4✔
1347
                filterUpdate := []graphdb.EdgePoint{
4✔
1348
                        {
4✔
1349
                                FundingPkScript: fundingPkScript,
4✔
1350
                                OutPoint:        *fundingPoint,
4✔
1351
                        },
4✔
1352
                }
4✔
1353
                err = b.cfg.ChainView.UpdateFilter(
4✔
1354
                        filterUpdate, b.bestHeight.Load(),
4✔
1355
                )
4✔
1356
                if err != nil {
4✔
1357
                        return errors.Errorf("unable to update chain "+
×
1358
                                "view: %v", err)
×
1359
                }
×
1360

1361
        case *models.ChannelEdgePolicy:
4✔
1362
                log.Debugf("Received ChannelEdgePolicy for channel %v",
4✔
1363
                        msg.ChannelID)
4✔
1364

4✔
1365
                // We make sure to hold the mutex for this channel ID,
4✔
1366
                // such that no other goroutine is concurrently doing
4✔
1367
                // database accesses for the same channel ID.
4✔
1368
                b.channelEdgeMtx.Lock(msg.ChannelID)
4✔
1369
                defer b.channelEdgeMtx.Unlock(msg.ChannelID)
4✔
1370

4✔
1371
                edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
4✔
1372
                        b.cfg.Graph.HasChannelEdge(msg.ChannelID)
4✔
1373
                if err != nil && !errors.Is(
4✔
1374
                        err, graphdb.ErrGraphNoEdgesFound,
4✔
1375
                ) {
4✔
1376

×
1377
                        return errors.Errorf("unable to check for edge "+
×
1378
                                "existence: %v", err)
×
1379
                }
×
1380

1381
                // If the channel is marked as a zombie in our database, and
1382
                // we consider this a stale update, then we should not apply the
1383
                // policy.
1384
                isStaleUpdate := time.Since(msg.LastUpdate) >
4✔
1385
                        b.cfg.ChannelPruneExpiry
4✔
1386

4✔
1387
                if isZombie && isStaleUpdate {
4✔
1388
                        return NewErrf(ErrIgnored, "ignoring stale update "+
×
1389
                                "(flags=%v|%v) for zombie chan_id=%v",
×
1390
                                msg.MessageFlags, msg.ChannelFlags,
×
1391
                                msg.ChannelID)
×
1392
                }
×
1393

1394
                // If the channel doesn't exist in our database, we cannot
1395
                // apply the updated policy.
1396
                if !exists {
4✔
1397
                        return NewErrf(ErrIgnored, "ignoring update "+
×
1398
                                "(flags=%v|%v) for unknown chan_id=%v",
×
1399
                                msg.MessageFlags, msg.ChannelFlags,
×
1400
                                msg.ChannelID)
×
1401
                }
×
1402

1403
                // As edges are directional edge node has a unique policy for
1404
                // the direction of the edge they control. Therefore, we first
1405
                // check if we already have the most up-to-date information for
1406
                // that edge. If this message has a timestamp not strictly
1407
                // newer than what we already know of we can exit early.
1408
                switch {
4✔
1409
                // A flag set of 0 indicates this is an announcement for the
1410
                // "first" node in the channel.
1411
                case msg.ChannelFlags&lnwire.ChanUpdateDirection == 0:
4✔
1412

4✔
1413
                        // Ignore outdated message.
4✔
1414
                        if !edge1Timestamp.Before(msg.LastUpdate) {
8✔
1415
                                return NewErrf(ErrOutdated, "Ignoring "+
4✔
1416
                                        "outdated update (flags=%v|%v) for "+
4✔
1417
                                        "known chan_id=%v", msg.MessageFlags,
4✔
1418
                                        msg.ChannelFlags, msg.ChannelID)
4✔
1419
                        }
4✔
1420

1421
                // Similarly, a flag set of 1 indicates this is an announcement
1422
                // for the "second" node in the channel.
1423
                case msg.ChannelFlags&lnwire.ChanUpdateDirection == 1:
4✔
1424

4✔
1425
                        // Ignore outdated message.
4✔
1426
                        if !edge2Timestamp.Before(msg.LastUpdate) {
8✔
1427
                                return NewErrf(ErrOutdated, "Ignoring "+
4✔
1428
                                        "outdated update (flags=%v|%v) for "+
4✔
1429
                                        "known chan_id=%v", msg.MessageFlags,
4✔
1430
                                        msg.ChannelFlags, msg.ChannelID)
4✔
1431
                        }
4✔
1432
                }
1433

1434
                // Now that we know this isn't a stale update, we'll apply the
1435
                // new edge policy to the proper directional edge within the
1436
                // channel graph.
1437
                if err = b.cfg.Graph.UpdateEdgePolicy(msg, op...); err != nil {
4✔
1438
                        err := errors.Errorf("unable to add channel: %v", err)
×
1439
                        log.Error(err)
×
1440
                        return err
×
1441
                }
×
1442

1443
                log.Tracef("New channel update applied: %v",
4✔
1444
                        lnutils.SpewLogClosure(msg))
4✔
1445
                b.stats.incNumChannelUpdates()
4✔
1446

1447
        default:
×
1448
                return errors.Errorf("wrong routing update message type")
×
1449
        }
1450

1451
        return nil
4✔
1452
}
1453

1454
// routingMsg couples a routing related routing topology update to the
1455
// error channel.
1456
type routingMsg struct {
1457
        msg interface{}
1458
        op  []batch.SchedulerOption
1459
        err chan error
1460
}
1461

1462
// ApplyChannelUpdate validates a channel update and if valid, applies it to the
1463
// database. It returns a bool indicating whether the updates were successful.
1464
func (b *Builder) ApplyChannelUpdate(msg *lnwire.ChannelUpdate1) bool {
4✔
1465
        ch, _, _, err := b.GetChannelByID(msg.ShortChannelID)
4✔
1466
        if err != nil {
8✔
1467
                log.Errorf("Unable to retrieve channel by id: %v", err)
4✔
1468
                return false
4✔
1469
        }
4✔
1470

1471
        var pubKey *btcec.PublicKey
4✔
1472

4✔
1473
        switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
4✔
1474
        case 0:
4✔
1475
                pubKey, _ = ch.NodeKey1()
4✔
1476

1477
        case 1:
4✔
1478
                pubKey, _ = ch.NodeKey2()
4✔
1479
        }
1480

1481
        // Exit early if the pubkey cannot be decided.
1482
        if pubKey == nil {
4✔
1483
                log.Errorf("Unable to decide pubkey with ChannelFlags=%v",
×
1484
                        msg.ChannelFlags)
×
1485
                return false
×
1486
        }
×
1487

1488
        err = netann.ValidateChannelUpdateAnn(pubKey, ch.Capacity, msg)
4✔
1489
        if err != nil {
4✔
1490
                log.Errorf("Unable to validate channel update: %v", err)
×
1491
                return false
×
1492
        }
×
1493

1494
        err = b.UpdateEdge(&models.ChannelEdgePolicy{
4✔
1495
                SigBytes:                  msg.Signature.ToSignatureBytes(),
4✔
1496
                ChannelID:                 msg.ShortChannelID.ToUint64(),
4✔
1497
                LastUpdate:                time.Unix(int64(msg.Timestamp), 0),
4✔
1498
                MessageFlags:              msg.MessageFlags,
4✔
1499
                ChannelFlags:              msg.ChannelFlags,
4✔
1500
                TimeLockDelta:             msg.TimeLockDelta,
4✔
1501
                MinHTLC:                   msg.HtlcMinimumMsat,
4✔
1502
                MaxHTLC:                   msg.HtlcMaximumMsat,
4✔
1503
                FeeBaseMSat:               lnwire.MilliSatoshi(msg.BaseFee),
4✔
1504
                FeeProportionalMillionths: lnwire.MilliSatoshi(msg.FeeRate),
4✔
1505
                ExtraOpaqueData:           msg.ExtraOpaqueData,
4✔
1506
        })
4✔
1507
        if err != nil && !IsError(err, ErrIgnored, ErrOutdated) {
4✔
1508
                log.Errorf("Unable to apply channel update: %v", err)
×
1509
                return false
×
1510
        }
×
1511

1512
        return true
4✔
1513
}
1514

1515
// AddNode is used to add information about a node to the router database. If
1516
// the node with this pubkey is not present in an existing channel, it will
1517
// be ignored.
1518
//
1519
// NOTE: This method is part of the ChannelGraphSource interface.
1520
func (b *Builder) AddNode(node *models.LightningNode,
1521
        op ...batch.SchedulerOption) error {
4✔
1522

4✔
1523
        rMsg := &routingMsg{
4✔
1524
                msg: node,
4✔
1525
                op:  op,
4✔
1526
                err: make(chan error, 1),
4✔
1527
        }
4✔
1528

4✔
1529
        select {
4✔
1530
        case b.networkUpdates <- rMsg:
4✔
1531
                select {
4✔
1532
                case err := <-rMsg.err:
4✔
1533
                        return err
4✔
1534
                case <-b.quit:
×
1535
                        return ErrGraphBuilderShuttingDown
×
1536
                }
1537
        case <-b.quit:
×
1538
                return ErrGraphBuilderShuttingDown
×
1539
        }
1540
}
1541

1542
// AddEdge is used to add edge/channel to the topology of the router, after all
1543
// information about channel will be gathered this edge/channel might be used
1544
// in construction of payment path.
1545
//
1546
// NOTE: This method is part of the ChannelGraphSource interface.
1547
func (b *Builder) AddEdge(edge *models.ChannelEdgeInfo,
1548
        op ...batch.SchedulerOption) error {
4✔
1549

4✔
1550
        rMsg := &routingMsg{
4✔
1551
                msg: edge,
4✔
1552
                op:  op,
4✔
1553
                err: make(chan error, 1),
4✔
1554
        }
4✔
1555

4✔
1556
        select {
4✔
1557
        case b.networkUpdates <- rMsg:
4✔
1558
                select {
4✔
1559
                case err := <-rMsg.err:
4✔
1560
                        return err
4✔
1561
                case <-b.quit:
×
1562
                        return ErrGraphBuilderShuttingDown
×
1563
                }
1564
        case <-b.quit:
×
1565
                return ErrGraphBuilderShuttingDown
×
1566
        }
1567
}
1568

1569
// UpdateEdge is used to update edge information, without this message edge
1570
// considered as not fully constructed.
1571
//
1572
// NOTE: This method is part of the ChannelGraphSource interface.
1573
func (b *Builder) UpdateEdge(update *models.ChannelEdgePolicy,
1574
        op ...batch.SchedulerOption) error {
4✔
1575

4✔
1576
        rMsg := &routingMsg{
4✔
1577
                msg: update,
4✔
1578
                op:  op,
4✔
1579
                err: make(chan error, 1),
4✔
1580
        }
4✔
1581

4✔
1582
        select {
4✔
1583
        case b.networkUpdates <- rMsg:
4✔
1584
                select {
4✔
1585
                case err := <-rMsg.err:
4✔
1586
                        return err
4✔
1587
                case <-b.quit:
×
1588
                        return ErrGraphBuilderShuttingDown
×
1589
                }
1590
        case <-b.quit:
×
1591
                return ErrGraphBuilderShuttingDown
×
1592
        }
1593
}
1594

1595
// CurrentBlockHeight returns the block height from POV of the router subsystem.
1596
//
1597
// NOTE: This method is part of the ChannelGraphSource interface.
1598
func (b *Builder) CurrentBlockHeight() (uint32, error) {
4✔
1599
        _, height, err := b.cfg.Chain.GetBestBlock()
4✔
1600
        return uint32(height), err
4✔
1601
}
4✔
1602

1603
// SyncedHeight returns the block height to which the router subsystem currently
1604
// is synced to. This can differ from the above chain height if the goroutine
1605
// responsible for processing the blocks isn't yet up to speed.
1606
func (b *Builder) SyncedHeight() uint32 {
4✔
1607
        return b.bestHeight.Load()
4✔
1608
}
4✔
1609

1610
// GetChannelByID return the channel by the channel id.
1611
//
1612
// NOTE: This method is part of the ChannelGraphSource interface.
1613
func (b *Builder) GetChannelByID(chanID lnwire.ShortChannelID) (
1614
        *models.ChannelEdgeInfo,
1615
        *models.ChannelEdgePolicy,
1616
        *models.ChannelEdgePolicy, error) {
4✔
1617

4✔
1618
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
4✔
1619
}
4✔
1620

1621
// FetchLightningNode attempts to look up a target node by its identity public
1622
// key. graphdb.ErrGraphNodeNotFound is returned if the node doesn't exist
1623
// within the graph.
1624
//
1625
// NOTE: This method is part of the ChannelGraphSource interface.
1626
func (b *Builder) FetchLightningNode(
1627
        node route.Vertex) (*models.LightningNode, error) {
4✔
1628

4✔
1629
        return b.cfg.Graph.FetchLightningNode(node)
4✔
1630
}
4✔
1631

1632
// ForEachNode is used to iterate over every node in router topology.
1633
//
1634
// NOTE: This method is part of the ChannelGraphSource interface.
1635
func (b *Builder) ForEachNode(
1636
        cb func(*models.LightningNode) error) error {
×
1637

×
1638
        return b.cfg.Graph.ForEachNode(
×
1639
                func(_ kvdb.RTx, n *models.LightningNode) error {
×
1640
                        return cb(n)
×
1641
                })
×
1642
}
1643

1644
// ForAllOutgoingChannels is used to iterate over all outgoing channels owned by
1645
// the router.
1646
//
1647
// NOTE: This method is part of the ChannelGraphSource interface.
1648
func (b *Builder) ForAllOutgoingChannels(cb func(*models.ChannelEdgeInfo,
1649
        *models.ChannelEdgePolicy) error) error {
4✔
1650

4✔
1651
        return b.cfg.Graph.ForEachNodeChannel(b.cfg.SelfNode,
4✔
1652
                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
4✔
1653
                        e *models.ChannelEdgePolicy,
4✔
1654
                        _ *models.ChannelEdgePolicy) error {
8✔
1655

4✔
1656
                        if e == nil {
4✔
1657
                                return fmt.Errorf("channel from self node " +
×
1658
                                        "has no policy")
×
1659
                        }
×
1660

1661
                        return cb(c, e)
4✔
1662
                },
1663
        )
1664
}
1665

1666
// AddProof updates the channel edge info with proof which is needed to
1667
// properly announce the edge to the rest of the network.
1668
//
1669
// NOTE: This method is part of the ChannelGraphSource interface.
1670
func (b *Builder) AddProof(chanID lnwire.ShortChannelID,
1671
        proof *models.ChannelAuthProof) error {
4✔
1672

4✔
1673
        info, _, _, err := b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
4✔
1674
        if err != nil {
4✔
1675
                return err
×
1676
        }
×
1677

1678
        info.AuthProof = proof
4✔
1679

4✔
1680
        return b.cfg.Graph.UpdateChannelEdge(info)
4✔
1681
}
1682

1683
// IsStaleNode returns true if the graph source has a node announcement for the
1684
// target node with a more recent timestamp.
1685
//
1686
// NOTE: This method is part of the ChannelGraphSource interface.
1687
func (b *Builder) IsStaleNode(node route.Vertex,
1688
        timestamp time.Time) bool {
4✔
1689

4✔
1690
        // If our attempt to assert that the node announcement is fresh fails,
4✔
1691
        // then we know that this is actually a stale announcement.
4✔
1692
        err := b.assertNodeAnnFreshness(node, timestamp)
4✔
1693
        if err != nil {
8✔
1694
                log.Debugf("Checking stale node %x got %v", node, err)
4✔
1695
                return true
4✔
1696
        }
4✔
1697

1698
        return false
4✔
1699
}
1700

1701
// IsPublicNode determines whether the given vertex is seen as a public node in
1702
// the graph from the graph's source node's point of view.
1703
//
1704
// NOTE: This method is part of the ChannelGraphSource interface.
1705
func (b *Builder) IsPublicNode(node route.Vertex) (bool, error) {
4✔
1706
        return b.cfg.Graph.IsPublicNode(node)
4✔
1707
}
4✔
1708

1709
// IsKnownEdge returns true if the graph source already knows of the passed
1710
// channel ID either as a live or zombie edge.
1711
//
1712
// NOTE: This method is part of the ChannelGraphSource interface.
1713
func (b *Builder) IsKnownEdge(chanID lnwire.ShortChannelID) bool {
4✔
1714
        _, _, exists, isZombie, _ := b.cfg.Graph.HasChannelEdge(
4✔
1715
                chanID.ToUint64(),
4✔
1716
        )
4✔
1717

4✔
1718
        return exists || isZombie
4✔
1719
}
4✔
1720

1721
// IsStaleEdgePolicy returns true if the graph source has a channel edge for
1722
// the passed channel ID (and flags) that have a more recent timestamp.
1723
//
1724
// NOTE: This method is part of the ChannelGraphSource interface.
1725
func (b *Builder) IsStaleEdgePolicy(chanID lnwire.ShortChannelID,
1726
        timestamp time.Time, flags lnwire.ChanUpdateChanFlags) bool {
4✔
1727

4✔
1728
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
4✔
1729
                b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
4✔
1730
        if err != nil {
4✔
1731
                log.Debugf("Check stale edge policy got error: %v", err)
×
1732
                return false
×
1733
        }
×
1734

1735
        // If we know of the edge as a zombie, then we'll make some additional
1736
        // checks to determine if the new policy is fresh.
1737
        if isZombie {
8✔
1738
                // When running with AssumeChannelValid, we also prune channels
4✔
1739
                // if both of their edges are disabled. We'll mark the new
4✔
1740
                // policy as stale if it remains disabled.
4✔
1741
                if b.cfg.AssumeChannelValid {
4✔
1742
                        isDisabled := flags&lnwire.ChanUpdateDisabled ==
×
1743
                                lnwire.ChanUpdateDisabled
×
1744
                        if isDisabled {
×
1745
                                return true
×
1746
                        }
×
1747
                }
1748

1749
                // Otherwise, we'll fall back to our usual ChannelPruneExpiry.
1750
                return time.Since(timestamp) > b.cfg.ChannelPruneExpiry
4✔
1751
        }
1752

1753
        // If we don't know of the edge, then it means it's fresh (thus not
1754
        // stale).
1755
        if !exists {
8✔
1756
                return false
4✔
1757
        }
4✔
1758

1759
        // As edges are directional edge node has a unique policy for the
1760
        // direction of the edge they control. Therefore, we first check if we
1761
        // already have the most up-to-date information for that edge. If so,
1762
        // then we can exit early.
1763
        switch {
4✔
1764
        // A flag set of 0 indicates this is an announcement for the "first"
1765
        // node in the channel.
1766
        case flags&lnwire.ChanUpdateDirection == 0:
4✔
1767
                return !edge1Timestamp.Before(timestamp)
4✔
1768

1769
        // Similarly, a flag set of 1 indicates this is an announcement for the
1770
        // "second" node in the channel.
1771
        case flags&lnwire.ChanUpdateDirection == 1:
4✔
1772
                return !edge2Timestamp.Before(timestamp)
4✔
1773
        }
1774

1775
        return false
×
1776
}
1777

1778
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
1779
//
1780
// NOTE: This method is part of the ChannelGraphSource interface.
1781
func (b *Builder) MarkEdgeLive(chanID lnwire.ShortChannelID) error {
4✔
1782
        return b.cfg.Graph.MarkEdgeLive(chanID.ToUint64())
4✔
1783
}
4✔
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