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

lightningnetwork / lnd / 13200849255

07 Feb 2025 01:27PM UTC coverage: 49.311% (-9.5%) from 58.818%
13200849255

Pull #9470

github

ziggie1984
fixup! docs: update release-notes
Pull Request #9470: Make BumpFee RPC user inputs more stricter.

42 of 65 new or added lines in 2 files covered. (64.62%)

27461 existing lines in 435 files now uncovered.

100754 of 204322 relevant lines covered (49.31%)

1.54 hits per line

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

59.21
/graph/builder.go
1
package graph
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

120
        ntfnClientCounter atomic.Uint64
121
        bestHeight        atomic.Uint32
122

123
        cfg *Config
124

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

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

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

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

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

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

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

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

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

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

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

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

×
192
        log.Info("Builder starting")
193

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

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

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

217
                default:
218
                        return err
219
                }
220
        }
3✔
UNCOV
221

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

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

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

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

3✔
261
                        return err
6✔
262
                }
3✔
263

3✔
264
                log.Infof("Filtering chain using %v channels active",
3✔
265
                        len(channelView))
3✔
UNCOV
266

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

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

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

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

3✔
298
                        return err
3✔
299
                }
3✔
300
        }
3✔
301

3✔
302
        b.wg.Add(1)
303
        go b.networkHandler()
304

305
        log.Debug("Builder started")
306

307
        return nil
3✔
308
}
3✔
UNCOV
309

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

3✔
UNCOV
318
        log.Info("Builder shutting down...")
×
UNCOV
319

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

3✔
328
        close(b.quit)
329
        b.wg.Wait()
330

331
        log.Debug("Builder shutdown complete")
332

333
        return nil
334
}
3✔
335

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

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

361
        log.Infof("Prune tip for Channel Graph: height=%v, hash=%v",
UNCOV
362
                pruneHeight, pruneHash)
×
UNCOV
363

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

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

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

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

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

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

408
                case err != nil:
×
409
                        return err
×
UNCOV
410

×
UNCOV
411
                default:
×
UNCOV
412
                }
×
UNCOV
413

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

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

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

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

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

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

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

478
        return nil
479
}
480

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

×
UNCOV
489
        chanExpiry := b.cfg.ChannelPruneExpiry
×
UNCOV
490

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

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

502
        return e1Zombie, e2Zombie, b.IsZombieChannel(e1Time, e2Time)
503
}
3✔
504

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

3✔
511
        chanExpiry := b.cfg.ChannelPruneExpiry
3✔
512

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
592
                return nil
×
UNCOV
593
        }
×
UNCOV
594

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

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

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

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

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

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

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

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

664
        return nil
665
}
3✔
666

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

3✔
674
        // Process the routing update to determine if this is either a new
3✔
675
        // update from our PoV or an update to a prior vertex/edge we
676
        // previously accepted.
3✔
677
        err := b.processUpdate(update.msg, update.op...)
3✔
678
        update.err <- err
679

3✔
680
        // If the error is not nil here, there's no need to send topology
3✔
681
        // change.
UNCOV
682
        if err != nil {
×
UNCOV
683
                // Log as a debug message if this is not an error we need to be
×
684
                // concerned about.
685
                if IsError(err, ErrIgnored, ErrOutdated) {
3✔
686
                        log.Debugf("process network updates got: %v", err)
3✔
687
                } else {
3✔
688
                        log.Errorf("process network updates got: %v", err)
3✔
689
                }
6✔
690

3✔
691
                return
3✔
692
        }
6✔
693

3✔
694
        // Otherwise, we'll send off a new notification for the newly accepted
3✔
UNCOV
695
        // update, if any.
×
UNCOV
696
        topChange := &TopologyChange{}
×
697
        err = addToTopologyChange(b.cfg.Graph, topChange, update.msg)
698
        if err != nil {
3✔
699
                log.Errorf("unable to update topology change notification: %v",
700
                        err)
701
                return
702
        }
703

3✔
704
        if !topChange.isEmpty() {
3✔
705
                b.notifyTopologyChange(topChange)
3✔
UNCOV
706
        }
×
UNCOV
707
}
×
UNCOV
708

×
UNCOV
709
// networkHandler is the primary goroutine for the Builder. The roles of
×
710
// this goroutine include answering queries related to the state of the
711
// network, pruning the graph on new block notification, applying network
6✔
712
// updates, and registering new topology clients.
3✔
713
//
3✔
714
// NOTE: This MUST be run as a goroutine.
715
func (b *Builder) networkHandler() {
716
        defer b.wg.Done()
717

718
        graphPruneTicker := time.NewTicker(b.cfg.GraphPruneInterval)
719
        defer graphPruneTicker.Stop()
720

721
        defer b.statTicker.Stop()
722

3✔
723
        b.stats.Reset()
3✔
724

3✔
725
        for {
3✔
726
                // If there are stats, resume the statTicker.
3✔
727
                if !b.stats.Empty() {
3✔
728
                        b.statTicker.Resume()
3✔
729
                }
3✔
730

3✔
731
                select {
3✔
732
                // A new fully validated network update has just arrived. As a
6✔
733
                // result we'll modify the channel graph accordingly depending
3✔
734
                // on the exact type of the message.
6✔
735
                case update := <-b.networkUpdates:
3✔
736
                        b.wg.Add(1)
3✔
737
                        go b.handleNetworkUpdate(update)
738

3✔
739
                        // TODO(roasbeef): remove all unconnected vertexes
2✔
740
                        // after N blocks pass with no corresponding
2✔
741
                        // announcements.
2✔
742

2✔
UNCOV
743
                case chainUpdate, ok := <-b.staleBlocks:
×
UNCOV
744
                        // If the channel has been closed, then this indicates
×
745
                        // the daemon is shutting down, so we exit ourselves.
746
                        if !ok {
747
                                return
748
                        }
2✔
749

2✔
750
                        // Since this block is stale, we update our best height
2✔
751
                        // to the previous block.
2✔
752
                        blockHeight := chainUpdate.Height
2✔
753
                        b.bestHeight.Store(blockHeight - 1)
2✔
754

2✔
755
                        // Update the channel graph to reflect that this block
2✔
756
                        // was disconnected.
2✔
UNCOV
757
                        _, err := b.cfg.Graph.DisconnectBlockAtHeight(
×
UNCOV
758
                                blockHeight,
×
UNCOV
759
                        )
×
760
                        if err != nil {
761
                                log.Errorf("unable to prune graph with stale "+
762
                                        "block: %v", err)
763
                                continue
764
                        }
765

766
                        // TODO(halseth): notify client about the reorg?
3✔
767

3✔
768
                // A new block has arrived, so we can prune the channel graph
3✔
769
                // of any channels which were closed in the block.
3✔
UNCOV
770
                case chainUpdate, ok := <-b.newBlocks:
×
UNCOV
771
                        // If the channel has been closed, then this indicates
×
772
                        // the daemon is shutting down, so we exit ourselves.
773
                        if !ok {
774
                                return
775
                        }
776

777
                        // We'll ensure that any new blocks received attach
3✔
778
                        // directly to the end of our main chain. If not, then
3✔
779
                        // we've somehow missed some blocks. Here we'll catch
3✔
780
                        // up the chain with the latest blocks.
3✔
781
                        currentHeight := b.bestHeight.Load()
3✔
782
                        switch {
3✔
783
                        case chainUpdate.Height == currentHeight+1:
3✔
UNCOV
784
                                err := b.updateGraphWithClosedChannels(
×
UNCOV
785
                                        chainUpdate,
×
UNCOV
786
                                )
×
787
                                if err != nil {
788
                                        log.Errorf("unable to prune graph "+
×
789
                                                "with closed channels: %v", err)
×
790
                                }
×
UNCOV
791

×
UNCOV
792
                        case chainUpdate.Height > currentHeight+1:
×
UNCOV
793
                                log.Errorf("out of order block: expecting "+
×
UNCOV
794
                                        "height=%v, got height=%v",
×
UNCOV
795
                                        currentHeight+1, chainUpdate.Height)
×
UNCOV
796

×
UNCOV
797
                                err := b.getMissingBlocks(
×
UNCOV
798
                                        currentHeight, chainUpdate,
×
UNCOV
799
                                )
×
800
                                if err != nil {
801
                                        log.Errorf("unable to retrieve missing"+
1✔
802
                                                "blocks: %v", err)
1✔
803
                                }
1✔
804

1✔
805
                        case chainUpdate.Height < currentHeight+1:
1✔
806
                                log.Errorf("out of order block: expecting "+
1✔
807
                                        "height=%v, got height=%v",
1✔
808
                                        currentHeight+1, chainUpdate.Height)
1✔
809

810
                                log.Infof("Skipping channel pruning since "+
811
                                        "received block height %v was already"+
812
                                        " processed.", chainUpdate.Height)
813
                        }
814

3✔
815
                // A new notification client update has arrived. We're either
3✔
816
                // gaining a new client, or cancelling notifications for an
3✔
817
                // existing client.
6✔
818
                case ntfnUpdate := <-b.ntfnClientUpdates:
3✔
819
                        clientID := ntfnUpdate.clientID
3✔
820

3✔
821
                        if ntfnUpdate.cancel {
6✔
822
                                client, ok := b.topologyClients.LoadAndDelete(
3✔
823
                                        clientID,
3✔
824
                                )
3✔
825
                                if ok {
3✔
826
                                        close(client.exit)
3✔
827
                                        client.wg.Wait()
828

3✔
829
                                        close(client.ntfnChan)
830
                                }
831

3✔
832
                                continue
3✔
833
                        }
3✔
834

3✔
835
                        b.topologyClients.Store(clientID, &topologyClient{
836
                                ntfnChan: ntfnUpdate.ntfnChan,
837
                                exit:     make(chan struct{}),
838
                        })
UNCOV
839

×
UNCOV
840
                // The graph prune ticker has ticked, so we'll examine the
×
UNCOV
841
                // state of the known graph to filter out any zombie channels
×
UNCOV
842
                // for pruning.
×
843
                case <-graphPruneTicker.C:
844
                        if err := b.pruneZombieChans(); err != nil {
845
                                log.Errorf("Unable to prune zombies: %v", err)
846
                        }
847

848
                // Log any stats if we've processed a non-empty number of
3✔
849
                // channels, updates, or nodes. We'll only pause the ticker if
6✔
850
                // the last window contained no updates to avoid resuming and
3✔
851
                // pausing while consecutive windows contain new info.
3✔
UNCOV
852
                case <-b.statTicker.Ticks():
×
UNCOV
853
                        if !b.stats.Empty() {
×
854
                                log.Infof(b.stats.String())
3✔
855
                        } else {
856
                                b.statTicker.Pause()
857
                        }
858
                        b.stats.Reset()
3✔
859

3✔
860
                // The router has been signalled to exit, to we exit our main
861
                // loop so the wait group can be decremented.
862
                case <-b.quit:
863
                        return
864
                }
865
        }
866
}
UNCOV
867

×
UNCOV
868
// getMissingBlocks walks through all missing blocks and updates the graph
×
UNCOV
869
// closed channels accordingly.
×
UNCOV
870
func (b *Builder) getMissingBlocks(currentHeight uint32,
×
UNCOV
871
        chainUpdate *chainview.FilteredBlock) error {
×
UNCOV
872

×
873
        outdatedHash, err := b.cfg.Chain.GetBlockHash(int64(currentHeight))
UNCOV
874
        if err != nil {
×
875
                return err
×
876
        }
×
UNCOV
877

×
UNCOV
878
        outdatedBlock := &chainntnfs.BlockEpoch{
×
UNCOV
879
                Height: int32(currentHeight),
×
UNCOV
880
                Hash:   outdatedHash,
×
UNCOV
881
        }
×
UNCOV
882

×
UNCOV
883
        epochClient, err := b.cfg.Notifier.RegisterBlockEpochNtfn(
×
UNCOV
884
                outdatedBlock,
×
UNCOV
885
        )
×
UNCOV
886
        if err != nil {
×
887
                return err
×
888
        }
×
UNCOV
889
        defer epochClient.Cancel()
×
UNCOV
890

×
UNCOV
891
        blockDifference := int(chainUpdate.Height - currentHeight)
×
UNCOV
892

×
UNCOV
893
        // We'll walk through all the outdated blocks and make sure we're able
×
UNCOV
894
        // to update the graph with any closed channels from them.
×
UNCOV
895
        for i := 0; i < blockDifference; i++ {
×
UNCOV
896
                var (
×
UNCOV
897
                        missingBlock *chainntnfs.BlockEpoch
×
UNCOV
898
                        ok           bool
×
UNCOV
899
                )
×
UNCOV
900

×
UNCOV
901
                select {
×
902
                case missingBlock, ok = <-epochClient.Epochs:
UNCOV
903
                        if !ok {
×
904
                                return nil
×
905
                        }
906

907
                case <-b.quit:
×
908
                        return nil
×
UNCOV
909
                }
×
UNCOV
910

×
UNCOV
911
                filteredBlock, err := b.cfg.ChainView.FilterBlock(
×
UNCOV
912
                        missingBlock.Hash,
×
913
                )
UNCOV
914
                if err != nil {
×
915
                        return err
×
916
                }
×
UNCOV
917

×
UNCOV
918
                err = b.updateGraphWithClosedChannels(
×
UNCOV
919
                        filteredBlock,
×
920
                )
921
                if err != nil {
922
                        return err
×
923
                }
924
        }
925

926
        return nil
927
}
928

3✔
929
// updateGraphWithClosedChannels prunes the channel graph of closed channels
3✔
930
// that are no longer needed.
3✔
931
func (b *Builder) updateGraphWithClosedChannels(
3✔
932
        chainUpdate *chainview.FilteredBlock) error {
3✔
933

3✔
934
        // Once a new block arrives, we update our running track of the height
3✔
935
        // of the chain tip.
3✔
936
        blockHeight := chainUpdate.Height
3✔
937

3✔
938
        b.bestHeight.Store(blockHeight)
3✔
939
        log.Infof("Pruning channel graph using block %v (height=%v)",
3✔
940
                chainUpdate.Hash, blockHeight)
3✔
941

3✔
942
        // We're only interested in all prior outputs that have been spent in
6✔
943
        // the block, so collate all the referenced previous outpoints within
6✔
944
        // each tx and input.
3✔
945
        var spentOutputs []*wire.OutPoint
3✔
946
        for _, tx := range chainUpdate.Transactions {
3✔
947
                for _, txIn := range tx.TxIn {
948
                        spentOutputs = append(spentOutputs,
949
                                &txIn.PreviousOutPoint)
950
                }
951
        }
952

3✔
953
        // With the spent outputs gathered, attempt to prune the channel graph,
3✔
954
        // also passing in the hash+height of the block being pruned so the
3✔
UNCOV
955
        // prune tip can be updated.
×
UNCOV
956
        chansClosed, err := b.cfg.Graph.PruneGraph(spentOutputs,
×
UNCOV
957
                &chainUpdate.Hash, chainUpdate.Height)
×
958
        if err != nil {
959
                log.Errorf("unable to prune routing table: %v", err)
3✔
960
                return err
3✔
961
        }
3✔
962

6✔
963
        log.Infof("Block %v (height=%v) closed %v channels", chainUpdate.Hash,
3✔
964
                blockHeight, len(chansClosed))
3✔
965

966
        if len(chansClosed) == 0 {
967
                return err
3✔
968
        }
3✔
969

3✔
970
        // Notify all currently registered clients of the newly closed channels.
3✔
971
        closeSummaries := createCloseSummaries(blockHeight, chansClosed...)
3✔
972
        b.notifyTopologyChange(&TopologyChange{
3✔
973
                ClosedChannels: closeSummaries,
974
        })
975

976
        return nil
977
}
978

979
// assertNodeAnnFreshness returns a non-nil error if we have an announcement in
980
// the database for the passed node with a timestamp newer than the passed
981
// timestamp. ErrIgnored will be returned if we already have the node, and
3✔
982
// ErrOutdated will be returned if we have a timestamp that's after the new
3✔
983
// timestamp.
3✔
984
func (b *Builder) assertNodeAnnFreshness(node route.Vertex,
3✔
985
        msgTimestamp time.Time) error {
3✔
986

3✔
987
        // If we are not already aware of this node, it means that we don't
3✔
988
        // know about any channel using this node. To avoid a DoS attack by
3✔
989
        // node announcements, we will ignore such nodes. If we do know about
3✔
UNCOV
990
        // this node, check that this update brings info newer than what we
×
UNCOV
991
        // already have.
×
UNCOV
992
        lastUpdate, exists, err := b.cfg.Graph.HasLightningNode(node)
×
993
        if err != nil {
6✔
994
                return errors.Errorf("unable to query for the "+
3✔
995
                        "existence of node: %v", err)
3✔
996
        }
3✔
997
        if !exists {
3✔
998
                return NewErrf(ErrIgnored, "Ignoring node announcement"+
999
                        " for node not found in channel graph (%x)",
1000
                        node[:])
1001
        }
1002

1003
        // If we've reached this point then we're aware of the vertex being
6✔
1004
        // advertised. So we now check if the new message has a new time stamp,
3✔
1005
        // if not then we won't accept the new data as it would override newer
3✔
1006
        // data.
3✔
1007
        if !lastUpdate.Before(msgTimestamp) {
1008
                return NewErrf(ErrOutdated, "Ignoring outdated "+
3✔
1009
                        "announcement for %x", node[:])
1010
        }
1011

1012
        return nil
UNCOV
1013
}
×
UNCOV
1014

×
UNCOV
1015
// addZombieEdge adds a channel that failed complete validation into the zombie
×
UNCOV
1016
// index so we can avoid having to re-validate it in the future.
×
UNCOV
1017
func (b *Builder) addZombieEdge(chanID uint64) error {
×
UNCOV
1018
        // If the edge fails validation we'll mark the edge itself as a zombie
×
UNCOV
1019
        // so we don't continue to request it. We use the "zero key" for both
×
UNCOV
1020
        // node pubkeys so this edge can't be resurrected.
×
UNCOV
1021
        var zeroKey [33]byte
×
UNCOV
1022
        err := b.cfg.Graph.MarkEdgeZombie(chanID, zeroKey, zeroKey)
×
1023
        if err != nil {
1024
                return fmt.Errorf("unable to mark spent chan(id=%v) as a "+
×
1025
                        "zombie: %w", chanID, err)
1026
        }
1027

1028
        return nil
1029
}
1030

1031
// makeFundingScript is used to make the funding script for both segwit v0 and
1032
// segwit v1 (taproot) channels.
3✔
1033
//
3✔
1034
// TODO(roasbeef: export and use elsewhere?
6✔
1035
func makeFundingScript(bitcoinKey1, bitcoinKey2 []byte, chanFeatures []byte,
3✔
1036
        tapscriptRoot fn.Option[chainhash.Hash]) ([]byte, error) {
3✔
1037

3✔
1038
        legacyFundingScript := func() ([]byte, error) {
3✔
UNCOV
1039
                witnessScript, err := input.GenMultiSigScript(
×
UNCOV
1040
                        bitcoinKey1, bitcoinKey2,
×
1041
                )
3✔
1042
                if err != nil {
3✔
1043
                        return nil, err
×
1044
                }
×
1045
                pkScript, err := input.WitnessScriptHash(witnessScript)
1046
                if err != nil {
3✔
1047
                        return nil, err
1048
                }
1049

3✔
UNCOV
1050
                return pkScript, nil
×
UNCOV
1051
        }
×
1052

1053
        if len(chanFeatures) == 0 {
1054
                return legacyFundingScript()
1055
        }
3✔
1056

3✔
1057
        // In order to make the correct funding script, we'll need to parse the
3✔
UNCOV
1058
        // chanFeatures bytes into a feature vector we can interact with.
×
UNCOV
1059
        rawFeatures := lnwire.NewRawFeatureVector()
×
UNCOV
1060
        err := rawFeatures.Decode(bytes.NewReader(chanFeatures))
×
1061
        if err != nil {
1062
                return nil, fmt.Errorf("unable to parse chan feature "+
3✔
1063
                        "bits: %w", err)
3✔
1064
        }
3✔
1065

3✔
1066
        chanFeatureBits := lnwire.NewFeatureVector(
3✔
1067
                rawFeatures, lnwire.Features,
6✔
1068
        )
3✔
1069
        if chanFeatureBits.HasFeature(
3✔
1070
                lnwire.SimpleTaprootChannelsOptionalStaging,
3✔
UNCOV
1071
        ) {
×
UNCOV
1072

×
1073
                pubKey1, err := btcec.ParsePubKey(bitcoinKey1)
3✔
1074
                if err != nil {
3✔
1075
                        return nil, err
×
1076
                }
×
1077
                pubKey2, err := btcec.ParsePubKey(bitcoinKey2)
1078
                if err != nil {
3✔
1079
                        return nil, err
3✔
1080
                }
3✔
1081

3✔
UNCOV
1082
                fundingScript, _, err := input.GenTaprootFundingScript(
×
UNCOV
1083
                        pubKey1, pubKey2, 0, tapscriptRoot,
×
1084
                )
1085
                if err != nil {
1086
                        return nil, err
1087
                }
3✔
1088

1089
                // TODO(roasbeef): add tapscript root to gossip v1.5
1090

3✔
1091
                return fundingScript, nil
1092
        }
1093

1094
        return legacyFundingScript()
1095
}
1096

1097
// processUpdate processes a new relate authenticated channel/edge, node or
1098
// channel/edge update network update. If the update didn't affect the internal
1099
// state of the draft due to either being out of date, invalid, or redundant,
1100
// then error is returned.
1101
//
1102
//nolint:funlen
1103
func (b *Builder) processUpdate(msg interface{},
3✔
1104
        op ...batch.SchedulerOption) error {
3✔
1105

6✔
1106
        switch msg := msg.(type) {
3✔
1107
        case *models.LightningNode:
3✔
1108
                // Before we add the node to the database, we'll check to see
3✔
1109
                // if the announcement is "fresh" or not. If it isn't, then
1110
                // we'll return an error.
3✔
1111
                err := b.assertNodeAnnFreshness(msg.PubKeyBytes, msg.LastUpdate)
3✔
1112
                if err != nil {
3✔
1113
                        return err
3✔
1114
                }
3✔
1115

1116
                if err := b.cfg.Graph.AddLightningNode(msg, op...); err != nil {
3✔
1117
                        return errors.Errorf("unable to add node %x to the "+
3✔
1118
                                "graph: %v", msg.PubKeyBytes, err)
1119
                }
1120

1121
                log.Tracef("Updated vertex data for node=%x", msg.PubKeyBytes)
3✔
UNCOV
1122
                b.stats.incNumNodeUpdates()
×
UNCOV
1123

×
UNCOV
1124
        case *models.ChannelEdgeInfo:
×
UNCOV
1125
                log.Debugf("Received ChannelEdgeInfo for channel %v",
×
1126
                        msg.ChannelID)
1127

3✔
1128
                // Prior to processing the announcement we first check if we
3✔
UNCOV
1129
                // already know of this channel, if so, then we can exit early.
×
UNCOV
1130
                _, _, exists, isZombie, err := b.cfg.Graph.HasChannelEdge(
×
UNCOV
1131
                        msg.ChannelID,
×
1132
                )
1133
                if err != nil &&
3✔
1134
                        !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
1135

3✔
1136
                        return errors.Errorf("unable to check for edge "+
3✔
1137
                                "existence: %v", err)
3✔
1138
                }
3✔
1139
                if isZombie {
3✔
1140
                        return NewErrf(ErrIgnored, "ignoring msg for zombie "+
3✔
1141
                                "chan_id=%v", msg.ChannelID)
3✔
1142
                }
3✔
1143
                if exists {
3✔
1144
                        return NewErrf(ErrIgnored, "ignoring msg for known "+
3✔
1145
                                "chan_id=%v", msg.ChannelID)
3✔
1146
                }
3✔
UNCOV
1147

×
UNCOV
1148
                // If AssumeChannelValid is present, then we are unable to
×
UNCOV
1149
                // perform any of the expensive checks below, so we'll
×
1150
                // short-circuit our path straight to adding the edge to our
1151
                // graph. If the passed ShortChannelID is an alias, then we'll
3✔
1152
                // skip validation as it will not map to a legitimate tx. This
1153
                // is not a DoS vector as only we can add an alias
1154
                // ChannelAnnouncement from the gossiper.
1155
                scid := lnwire.NewShortChanIDFromInt(msg.ChannelID)
1156
                if b.cfg.AssumeChannelValid || b.cfg.IsAlias(scid) {
1157
                        err := b.cfg.Graph.AddChannelEdge(msg, op...)
1158
                        if err != nil {
1159
                                return fmt.Errorf("unable to add edge: %w", err)
1160
                        }
3✔
1161
                        log.Tracef("New channel discovered! Link "+
3✔
1162
                                "connects %x and %x with ChannelID(%v)",
3✔
1163
                                msg.NodeKey1Bytes, msg.NodeKey2Bytes,
3✔
1164
                                msg.ChannelID)
3✔
1165
                        b.stats.incNumEdgesDiscovered()
3✔
1166

3✔
1167
                        break
3✔
1168
                }
3✔
1169

3✔
1170
                // Before we can add the channel to the channel graph, we need
3✔
1171
                // to obtain the full funding outpoint that's encoded within
3✔
1172
                // the channel ID.
3✔
1173
                channelID := lnwire.NewShortChanIDFromInt(msg.ChannelID)
3✔
UNCOV
1174
                fundingTx, err := lnwallet.FetchFundingTxWrapper(
×
UNCOV
1175
                        b.cfg.Chain, &channelID, b.quit,
×
1176
                )
1177
                if err != nil {
1178
                        //nolint:ll
1179
                        //
1180
                        // In order to ensure we don't erroneously mark a
1181
                        // channel as a zombie due to an RPC failure, we'll
1182
                        // attempt to string match for the relevant errors.
1183
                        //
1184
                        // * btcd:
3✔
1185
                        //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1316
3✔
1186
                        //    * https://github.com/btcsuite/btcd/blob/master/rpcserver.go#L1086
3✔
1187
                        // * bitcoind:
3✔
1188
                        //    * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L770
3✔
1189
                        //     * https://github.com/bitcoin/bitcoin/blob/7fcf53f7b4524572d1d0c9a5fdc388e87eb02416/src/rpc/blockchain.cpp#L954
3✔
1190
                        switch {
6✔
1191
                        case strings.Contains(err.Error(), "not found"):
3✔
1192
                                fallthrough
3✔
1193

1194
                        case strings.Contains(err.Error(), "out of range"):
3✔
UNCOV
1195
                                // If the funding transaction isn't found at
×
UNCOV
1196
                                // all, then we'll mark the edge itself as a
×
UNCOV
1197
                                // zombie so we don't continue to request it.
×
1198
                                // We use the "zero key" for both node pubkeys
1199
                                // so this edge can't be resurrected.
3✔
1200
                                zErr := b.addZombieEdge(msg.ChannelID)
3✔
1201
                                if zErr != nil {
3✔
1202
                                        return zErr
3✔
1203
                                }
1204

1205
                        default:
1206
                        }
1207

1208
                        return NewErrf(ErrNoFundingTransaction, "unable to "+
1209
                                "locate funding tx: %v", err)
1210
                }
1211

3✔
1212
                // Recreate witness output to be sure that declared in channel
3✔
1213
                // edge bitcoin keys and channel value corresponds to the
3✔
1214
                // reality.
3✔
1215
                fundingPkScript, err := makeFundingScript(
3✔
1216
                        msg.BitcoinKey1Bytes[:], msg.BitcoinKey2Bytes[:],
3✔
1217
                        msg.Features, msg.TapscriptRoot,
3✔
1218
                )
3✔
1219
                if err != nil {
3✔
1220
                        return err
3✔
1221
                }
3✔
1222

3✔
1223
                // Next we'll validate that this channel is actually well
3✔
1224
                // formed. If this check fails, then this channel either
3✔
UNCOV
1225
                // doesn't exist, or isn't the one that was meant to be created
×
UNCOV
1226
                // according to the passed channel proofs.
×
1227
                fundingPoint, err := chanvalidate.Validate(
1228
                        &chanvalidate.Context{
1229
                                Locator: &chanvalidate.ShortChanIDChanLocator{
1230
                                        ID: channelID,
1231
                                },
1232
                                MultiSigPkScript: fundingPkScript,
1233
                                FundingTx:        fundingTx,
1234
                        },
1235
                )
1236
                if err != nil {
1237
                        // Mark the edge as a zombie so we won't try to
1238
                        // re-validate it on start up.
1239
                        if err := b.addZombieEdge(msg.ChannelID); err != nil {
3✔
1240
                                return err
3✔
1241
                        }
3✔
1242

3✔
1243
                        return NewErrf(ErrInvalidFundingOutput, "output "+
3✔
1244
                                "failed validation: %w", err)
3✔
1245
                }
3✔
1246

3✔
1247
                // Now that we have the funding outpoint of the channel, ensure
3✔
1248
                // that it hasn't yet been spent. If so, then this channel has
3✔
UNCOV
1249
                // been closed so we'll ignore it.
×
UNCOV
1250
                chanUtxo, err := b.cfg.Chain.GetUtxo(
×
UNCOV
1251
                        fundingPoint, fundingPkScript, channelID.BlockHeight,
×
1252
                        b.quit,
3✔
UNCOV
1253
                )
×
UNCOV
1254
                if err != nil {
×
UNCOV
1255
                        if errors.Is(err, btcwallet.ErrOutputSpent) {
×
1256
                                zErr := b.addZombieEdge(msg.ChannelID)
6✔
1257
                                if zErr != nil {
3✔
1258
                                        return zErr
3✔
1259
                                }
3✔
1260
                        }
1261

1262
                        return NewErrf(ErrChannelSpent, "unable to fetch utxo "+
1263
                                "for chan_id=%v, chan_point=%v: %v",
1264
                                msg.ChannelID, fundingPoint, err)
1265
                }
1266

1267
                // TODO(roasbeef): this is a hack, needs to be removed
3✔
1268
                // after commitment fees are dynamic.
6✔
1269
                msg.Capacity = btcutil.Amount(chanUtxo.Value)
3✔
1270
                msg.ChannelPoint = *fundingPoint
3✔
UNCOV
1271
                if err := b.cfg.Graph.AddChannelEdge(msg, op...); err != nil {
×
1272
                        return errors.Errorf("unable to add edge: %v", err)
×
1273
                }
3✔
1274

3✔
1275
                log.Debugf("New channel discovered! Link "+
3✔
1276
                        "connects %x and %x with ChannelPoint(%v): "+
3✔
1277
                        "chan_id=%v, capacity=%v",
3✔
1278
                        msg.NodeKey1Bytes, msg.NodeKey2Bytes,
3✔
1279
                        fundingPoint, msg.ChannelID, msg.Capacity)
1280
                b.stats.incNumEdgesDiscovered()
1281

1282
                // As a new edge has been added to the channel graph, we'll
1283
                // update the current UTXO filter within our active
3✔
1284
                // FilteredChainView so we are notified if/when this channel is
3✔
1285
                // closed.
3✔
1286
                filterUpdate := []graphdb.EdgePoint{
3✔
1287
                        {
3✔
UNCOV
1288
                                FundingPkScript: fundingPkScript,
×
UNCOV
1289
                                OutPoint:        *fundingPoint,
×
UNCOV
1290
                        },
×
UNCOV
1291
                }
×
UNCOV
1292
                err = b.cfg.ChainView.UpdateFilter(
×
UNCOV
1293
                        filterUpdate, b.bestHeight.Load(),
×
UNCOV
1294
                )
×
UNCOV
1295
                if err != nil {
×
1296
                        return errors.Errorf("unable to update chain "+
×
1297
                                "view: %v", err)
×
1298
                }
×
UNCOV
1299

×
UNCOV
1300
        case *models.ChannelEdgePolicy:
×
UNCOV
1301
                log.Debugf("Received ChannelEdgePolicy for channel %v",
×
UNCOV
1302
                        msg.ChannelID)
×
1303

UNCOV
1304
                // We make sure to hold the mutex for this channel ID,
×
UNCOV
1305
                // such that no other goroutine is concurrently doing
×
UNCOV
1306
                // database accesses for the same channel ID.
×
UNCOV
1307
                b.channelEdgeMtx.Lock(msg.ChannelID)
×
UNCOV
1308
                defer b.channelEdgeMtx.Unlock(msg.ChannelID)
×
UNCOV
1309

×
UNCOV
1310
                edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
×
UNCOV
1311
                        b.cfg.Graph.HasChannelEdge(msg.ChannelID)
×
UNCOV
1312
                if err != nil && !errors.Is(
×
1313
                        err, graphdb.ErrGraphNoEdgesFound,
UNCOV
1314
                ) {
×
1315

1316
                        return errors.Errorf("unable to check for edge "+
1317
                                "existence: %v", err)
×
1318
                }
×
1319

1320
                // If the channel is marked as a zombie in our database, and
1321
                // we consider this a stale update, then we should not apply the
1322
                // policy.
1323
                isStaleUpdate := time.Since(msg.LastUpdate) >
3✔
1324
                        b.cfg.ChannelPruneExpiry
3✔
1325

3✔
1326
                if isZombie && isStaleUpdate {
3✔
1327
                        return NewErrf(ErrIgnored, "ignoring stale update "+
3✔
1328
                                "(flags=%v|%v) for zombie chan_id=%v",
×
1329
                                msg.MessageFlags, msg.ChannelFlags,
×
1330
                                msg.ChannelID)
1331
                }
1332

1333
                // If the channel doesn't exist in our database, we cannot
1334
                // apply the updated policy.
1335
                if !exists {
3✔
1336
                        return NewErrf(ErrIgnored, "ignoring update "+
3✔
1337
                                "(flags=%v|%v) for unknown chan_id=%v",
3✔
1338
                                msg.MessageFlags, msg.ChannelFlags,
3✔
1339
                                msg.ChannelID)
3✔
1340
                }
3✔
1341

3✔
1342
                log.Debugf("Found edge1Timestamp=%v, edge2Timestamp=%v",
3✔
1343
                        edge1Timestamp, edge2Timestamp)
3✔
1344

3✔
UNCOV
1345
                // As edges are directional edge node has a unique policy for
×
UNCOV
1346
                // the direction of the edge they control. Therefore, we first
×
UNCOV
1347
                // check if we already have the most up-to-date information for
×
UNCOV
1348
                // that edge. If this message has a timestamp not strictly
×
UNCOV
1349
                // newer than what we already know of we can exit early.
×
1350
                switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
UNCOV
1351
                // A flag set of 0 indicates this is an announcement for the
×
UNCOV
1352
                // "first" node in the channel.
×
1353
                case 0:
1354
                        // Ignore outdated message.
1355
                        if !edge1Timestamp.Before(msg.LastUpdate) {
1356
                                return NewErrf(ErrOutdated, "Ignoring "+
1357
                                        "outdated update (flags=%v|%v) for "+
1358
                                        "known chan_id=%v", msg.MessageFlags,
3✔
1359
                                        msg.ChannelFlags, msg.ChannelID)
3✔
1360
                        }
3✔
1361

3✔
UNCOV
1362
                // Similarly, a flag set of 1 indicates this is an announcement
×
UNCOV
1363
                // for the "second" node in the channel.
×
UNCOV
1364
                case 1:
×
UNCOV
1365
                        // Ignore outdated message.
×
UNCOV
1366
                        if !edge2Timestamp.Before(msg.LastUpdate) {
×
1367
                                return NewErrf(ErrOutdated, "Ignoring "+
1368
                                        "outdated update (flags=%v|%v) for "+
UNCOV
1369
                                        "known chan_id=%v", msg.MessageFlags,
×
UNCOV
1370
                                        msg.ChannelFlags, msg.ChannelID)
×
UNCOV
1371
                        }
×
1372
                }
1373

1374
                // Now that we know this isn't a stale update, we'll apply the
1375
                // new edge policy to the proper directional edge within the
1376
                // channel graph.
3✔
1377
                if err = b.cfg.Graph.UpdateEdgePolicy(msg, op...); err != nil {
3✔
1378
                        err := errors.Errorf("unable to add channel: %v", err)
3✔
1379
                        log.Error(err)
×
1380
                        return err
×
1381
                }
1382

3✔
1383
                log.Tracef("New channel update applied: %v",
3✔
1384
                        lnutils.SpewLogClosure(msg))
3✔
1385
                b.stats.incNumChannelUpdates()
3✔
1386

3✔
1387
        default:
3✔
1388
                return errors.Errorf("wrong routing update message type")
3✔
1389
        }
3✔
1390

3✔
1391
        return nil
3✔
1392
}
3✔
1393

3✔
1394
// routingMsg couples a routing related routing topology update to the
3✔
1395
// error channel.
3✔
1396
type routingMsg struct {
3✔
1397
        msg interface{}
3✔
1398
        op  []batch.SchedulerOption
3✔
UNCOV
1399
        err chan error
×
UNCOV
1400
}
×
UNCOV
1401

×
1402
// ApplyChannelUpdate validates a channel update and if valid, applies it to the
1403
// database. It returns a bool indicating whether the updates were successful.
3✔
1404
func (b *Builder) ApplyChannelUpdate(msg *lnwire.ChannelUpdate1) bool {
1405
        ch, _, _, err := b.GetChannelByID(msg.ShortChannelID)
1406
        if err != nil {
1407
                log.Errorf("Unable to retrieve channel by id: %v", err)
1408
                return false
1409
        }
1410

1411
        var pubKey *btcec.PublicKey
3✔
1412

3✔
1413
        switch msg.ChannelFlags & lnwire.ChanUpdateDirection {
3✔
1414
        case 0:
3✔
1415
                pubKey, _ = ch.NodeKey1()
3✔
1416

3✔
1417
        case 1:
3✔
1418
                pubKey, _ = ch.NodeKey2()
3✔
1419
        }
3✔
1420

3✔
1421
        // Exit early if the pubkey cannot be decided.
3✔
1422
        if pubKey == nil {
3✔
1423
                log.Errorf("Unable to decide pubkey with ChannelFlags=%v",
3✔
1424
                        msg.ChannelFlags)
3✔
1425
                return false
×
1426
        }
×
1427

1428
        err = netann.ValidateChannelUpdateAnn(pubKey, ch.Capacity, msg)
1429
        if err != nil {
1430
                log.Errorf("Unable to validate channel update: %v", err)
1431
                return false
1432
        }
1433

1434
        err = b.UpdateEdge(&models.ChannelEdgePolicy{
1435
                SigBytes:                  msg.Signature.ToSignatureBytes(),
3✔
1436
                ChannelID:                 msg.ShortChannelID.ToUint64(),
3✔
1437
                LastUpdate:                time.Unix(int64(msg.Timestamp), 0),
3✔
1438
                MessageFlags:              msg.MessageFlags,
3✔
1439
                ChannelFlags:              msg.ChannelFlags,
3✔
1440
                TimeLockDelta:             msg.TimeLockDelta,
3✔
1441
                MinHTLC:                   msg.HtlcMinimumMsat,
3✔
1442
                MaxHTLC:                   msg.HtlcMaximumMsat,
3✔
1443
                FeeBaseMSat:               lnwire.MilliSatoshi(msg.BaseFee),
3✔
1444
                FeeProportionalMillionths: lnwire.MilliSatoshi(msg.FeeRate),
3✔
1445
                ExtraOpaqueData:           msg.ExtraOpaqueData,
3✔
1446
        })
3✔
1447
        if err != nil && !IsError(err, ErrIgnored, ErrOutdated) {
3✔
1448
                log.Errorf("Unable to apply channel update: %v", err)
3✔
1449
                return false
×
1450
        }
×
UNCOV
1451

×
1452
        return true
1453
}
1454

1455
// AddNode is used to add information about a node to the router database. If
1456
// the node with this pubkey is not present in an existing channel, it will
3✔
1457
// be ignored.
3✔
1458
//
3✔
1459
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
UNCOV
1460
func (b *Builder) AddNode(node *models.LightningNode,
×
UNCOV
1461
        op ...batch.SchedulerOption) error {
×
UNCOV
1462

×
UNCOV
1463
        rMsg := &routingMsg{
×
UNCOV
1464
                msg: node,
×
1465
                op:  op,
1466
                err: make(chan error, 1),
1467
        }
1468

3✔
UNCOV
1469
        select {
×
UNCOV
1470
        case b.networkUpdates <- rMsg:
×
UNCOV
1471
                select {
×
UNCOV
1472
                case err := <-rMsg.err:
×
1473
                        return err
1474
                case <-b.quit:
3✔
1475
                        return ErrGraphBuilderShuttingDown
3✔
1476
                }
3✔
1477
        case <-b.quit:
3✔
1478
                return ErrGraphBuilderShuttingDown
3✔
1479
        }
3✔
1480
}
3✔
1481

3✔
1482
// AddEdge is used to add edge/channel to the topology of the router, after all
3✔
1483
// information about channel will be gathered this edge/channel might be used
1484
// in construction of payment path.
1485
//
3✔
1486
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
1487
func (b *Builder) AddEdge(edge *models.ChannelEdgeInfo,
6✔
1488
        op ...batch.SchedulerOption) error {
3✔
1489

3✔
1490
        rMsg := &routingMsg{
3✔
1491
                msg: edge,
3✔
1492
                op:  op,
3✔
1493
                err: make(chan error, 1),
1494
        }
1495

1496
        select {
3✔
1497
        case b.networkUpdates <- rMsg:
3✔
1498
                select {
6✔
1499
                case err := <-rMsg.err:
3✔
1500
                        return err
3✔
1501
                case <-b.quit:
3✔
1502
                        return ErrGraphBuilderShuttingDown
3✔
1503
                }
3✔
1504
        case <-b.quit:
1505
                return ErrGraphBuilderShuttingDown
1506
        }
1507
}
1508

3✔
UNCOV
1509
// UpdateEdge is used to update edge information, without this message edge
×
UNCOV
1510
// considered as not fully constructed.
×
UNCOV
1511
//
×
UNCOV
1512
// NOTE: This method is part of the ChannelGraphSource interface.
×
1513
func (b *Builder) UpdateEdge(update *models.ChannelEdgePolicy,
1514
        op ...batch.SchedulerOption) error {
3✔
1515

3✔
1516
        rMsg := &routingMsg{
3✔
1517
                msg: update,
3✔
1518
                op:  op,
3✔
1519
                err: make(chan error, 1),
1520
        }
1521

1522
        select {
1523
        case b.networkUpdates <- rMsg:
1524
                select {
3✔
1525
                case err := <-rMsg.err:
3✔
1526
                        return err
3✔
1527
                case <-b.quit:
3✔
1528
                        return ErrGraphBuilderShuttingDown
1529
                }
1530
        case <-b.quit:
1531
                return ErrGraphBuilderShuttingDown
1532
        }
3✔
1533
}
3✔
1534

3✔
1535
// CurrentBlockHeight returns the block height from POV of the router subsystem.
1536
//
1537
// NOTE: This method is part of the ChannelGraphSource interface.
1538
func (b *Builder) CurrentBlockHeight() (uint32, error) {
1539
        _, height, err := b.cfg.Chain.GetBestBlock()
1540
        return uint32(height), err
1541
}
1542

3✔
1543
// SyncedHeight returns the block height to which the router subsystem currently
3✔
1544
// is synced to. This can differ from the above chain height if the goroutine
3✔
1545
// responsible for processing the blocks isn't yet up to speed.
3✔
1546
func (b *Builder) SyncedHeight() uint32 {
1547
        return b.bestHeight.Load()
1548
}
1549

1550
// GetChannelByID return the channel by the channel id.
1551
//
1552
// NOTE: This method is part of the ChannelGraphSource interface.
1553
func (b *Builder) GetChannelByID(chanID lnwire.ShortChannelID) (
3✔
1554
        *models.ChannelEdgeInfo,
3✔
1555
        *models.ChannelEdgePolicy,
3✔
1556
        *models.ChannelEdgePolicy, error) {
3✔
1557

1558
        return b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
1559
}
1560

1561
// FetchLightningNode attempts to look up a target node by its identity public
UNCOV
1562
// key. graphdb.ErrGraphNodeNotFound is returned if the node doesn't exist
×
UNCOV
1563
// within the graph.
×
UNCOV
1564
//
×
UNCOV
1565
// NOTE: This method is part of the ChannelGraphSource interface.
×
UNCOV
1566
func (b *Builder) FetchLightningNode(
×
UNCOV
1567
        node route.Vertex) (*models.LightningNode, error) {
×
1568

1569
        return b.cfg.Graph.FetchLightningNode(node)
1570
}
1571

1572
// ForEachNode is used to iterate over every node in router topology.
1573
//
1574
// NOTE: This method is part of the ChannelGraphSource interface.
1575
func (b *Builder) ForEachNode(
3✔
1576
        cb func(*models.LightningNode) error) error {
3✔
1577

3✔
1578
        return b.cfg.Graph.ForEachNode(
3✔
1579
                func(_ kvdb.RTx, n *models.LightningNode) error {
3✔
1580
                        return cb(n)
6✔
1581
                })
3✔
1582
}
3✔
UNCOV
1583

×
UNCOV
1584
// ForAllOutgoingChannels is used to iterate over all outgoing channels owned by
×
UNCOV
1585
// the router.
×
1586
//
1587
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
1588
func (b *Builder) ForAllOutgoingChannels(cb func(*models.ChannelEdgeInfo,
1589
        *models.ChannelEdgePolicy) error) error {
1590

1591
        return b.cfg.Graph.ForEachNodeChannel(b.cfg.SelfNode,
1592
                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
1593
                        e *models.ChannelEdgePolicy,
1594
                        _ *models.ChannelEdgePolicy) error {
1595

1596
                        if e == nil {
1597
                                return fmt.Errorf("channel from self node " +
3✔
1598
                                        "has no policy")
3✔
1599
                        }
3✔
1600

3✔
UNCOV
1601
                        return cb(c, e)
×
UNCOV
1602
                },
×
1603
        )
1604
}
3✔
1605

3✔
1606
// AddProof updates the channel edge info with proof which is needed to
3✔
1607
// properly announce the edge to the rest of the network.
1608
//
1609
// NOTE: This method is part of the ChannelGraphSource interface.
1610
func (b *Builder) AddProof(chanID lnwire.ShortChannelID,
1611
        proof *models.ChannelAuthProof) error {
1612

1613
        info, _, _, err := b.cfg.Graph.FetchChannelEdgesByID(chanID.ToUint64())
1614
        if err != nil {
3✔
1615
                return err
3✔
1616
        }
3✔
1617

3✔
1618
        info.AuthProof = proof
3✔
1619

6✔
1620
        return b.cfg.Graph.UpdateChannelEdge(info)
3✔
1621
}
3✔
1622

3✔
1623
// IsStaleNode returns true if the graph source has a node announcement for the
1624
// target node with a more recent timestamp.
3✔
1625
//
1626
// NOTE: This method is part of the ChannelGraphSource interface.
1627
func (b *Builder) IsStaleNode(node route.Vertex,
1628
        timestamp time.Time) bool {
1629

1630
        // If our attempt to assert that the node announcement is fresh fails,
1631
        // then we know that this is actually a stale announcement.
3✔
1632
        err := b.assertNodeAnnFreshness(node, timestamp)
3✔
1633
        if err != nil {
3✔
1634
                log.Debugf("Checking stale node %x got %v", node, err)
1635
                return true
1636
        }
1637

1638
        return false
1639
}
3✔
1640

3✔
1641
// IsPublicNode determines whether the given vertex is seen as a public node in
3✔
1642
// the graph from the graph's source node's point of view.
3✔
1643
//
3✔
1644
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
1645
func (b *Builder) IsPublicNode(node route.Vertex) (bool, error) {
3✔
1646
        return b.cfg.Graph.IsPublicNode(node)
1647
}
1648

1649
// IsKnownEdge returns true if the graph source already knows of the passed
1650
// channel ID either as a live or zombie edge.
1651
//
1652
// NOTE: This method is part of the ChannelGraphSource interface.
3✔
1653
func (b *Builder) IsKnownEdge(chanID lnwire.ShortChannelID) bool {
3✔
1654
        _, _, exists, isZombie, _ := b.cfg.Graph.HasChannelEdge(
3✔
1655
                chanID.ToUint64(),
3✔
1656
        )
3✔
UNCOV
1657

×
UNCOV
1658
        return exists || isZombie
×
UNCOV
1659
}
×
1660

1661
// IsStaleEdgePolicy returns true if the graph source has a channel edge for
1662
// the passed channel ID (and flags) that have a more recent timestamp.
1663
//
3✔
UNCOV
1664
// NOTE: This method is part of the ChannelGraphSource interface.
×
UNCOV
1665
func (b *Builder) IsStaleEdgePolicy(chanID lnwire.ShortChannelID,
×
UNCOV
1666
        timestamp time.Time, flags lnwire.ChanUpdateChanFlags) bool {
×
UNCOV
1667

×
UNCOV
1668
        edge1Timestamp, edge2Timestamp, exists, isZombie, err :=
×
UNCOV
1669
                b.cfg.Graph.HasChannelEdge(chanID.ToUint64())
×
UNCOV
1670
        if err != nil {
×
1671
                log.Debugf("Check stale edge policy got error: %v", err)
×
1672
                return false
×
1673
        }
1674

1675
        // If we know of the edge as a zombie, then we'll make some additional
UNCOV
1676
        // checks to determine if the new policy is fresh.
×
1677
        if isZombie {
1678
                // When running with AssumeChannelValid, we also prune channels
1679
                // if both of their edges are disabled. We'll mark the new
1680
                // policy as stale if it remains disabled.
1681
                if b.cfg.AssumeChannelValid {
6✔
1682
                        isDisabled := flags&lnwire.ChanUpdateDisabled ==
3✔
1683
                                lnwire.ChanUpdateDisabled
3✔
1684
                        if isDisabled {
1685
                                return true
1686
                        }
1687
                }
1688

1689
                // Otherwise, we'll fall back to our usual ChannelPruneExpiry.
3✔
1690
                return time.Since(timestamp) > b.cfg.ChannelPruneExpiry
1691
        }
1692

3✔
1693
        // If we don't know of the edge, then it means it's fresh (thus not
3✔
1694
        // stale).
1695
        if !exists {
1696
                return false
1697
        }
3✔
1698

3✔
1699
        // As edges are directional edge node has a unique policy for the
1700
        // direction of the edge they control. Therefore, we first check if we
UNCOV
1701
        // already have the most up-to-date information for that edge. If so,
×
1702
        // then we can exit early.
1703
        switch {
1704
        // A flag set of 0 indicates this is an announcement for the "first"
1705
        // node in the channel.
1706
        case flags&lnwire.ChanUpdateDirection == 0:
UNCOV
1707
                return !edge1Timestamp.Before(timestamp)
×
UNCOV
1708

×
UNCOV
1709
        // Similarly, a flag set of 1 indicates this is an announcement for the
×
1710
        // "second" node in the channel.
1711
        case flags&lnwire.ChanUpdateDirection == 1:
1712
                return !edge2Timestamp.Before(timestamp)
1713
        }
1714

1715
        return false
1716
}
1717

1718
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
1719
//
1720
// NOTE: This method is part of the ChannelGraphSource interface.
1721
func (b *Builder) MarkEdgeLive(chanID lnwire.ShortChannelID) error {
1722
        return b.cfg.Graph.MarkEdgeLive(chanID.ToUint64())
1723
}
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