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

lightningnetwork / lnd / 13396663489

18 Feb 2025 05:34PM UTC coverage: 58.636% (-0.2%) from 58.804%
13396663489

push

github

web-flow
Merge pull request #9525 from ellemouton/graph10

graph: Restrict interface to update channel proof instead of entire channel

9 of 10 new or added lines in 2 files covered. (90.0%)

446 existing lines in 31 files now uncovered.

135736 of 231488 relevant lines covered (58.64%)

19383.26 hits per line

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

77.42
/graph/db/graph.go
1
package graphdb
2

3
import (
4
        "bytes"
5
        "crypto/sha256"
6
        "encoding/binary"
7
        "errors"
8
        "fmt"
9
        "io"
10
        "math"
11
        "net"
12
        "sort"
13
        "sync"
14
        "testing"
15
        "time"
16

17
        "github.com/btcsuite/btcd/btcec/v2"
18
        "github.com/btcsuite/btcd/chaincfg/chainhash"
19
        "github.com/btcsuite/btcd/txscript"
20
        "github.com/btcsuite/btcd/wire"
21
        "github.com/lightningnetwork/lnd/aliasmgr"
22
        "github.com/lightningnetwork/lnd/batch"
23
        "github.com/lightningnetwork/lnd/graph/db/models"
24
        "github.com/lightningnetwork/lnd/input"
25
        "github.com/lightningnetwork/lnd/kvdb"
26
        "github.com/lightningnetwork/lnd/lnwire"
27
        "github.com/lightningnetwork/lnd/routing/route"
28
)
29

30
var (
31
        // nodeBucket is a bucket which houses all the vertices or nodes within
32
        // the channel graph. This bucket has a single-sub bucket which adds an
33
        // additional index from pubkey -> alias. Within the top-level of this
34
        // bucket, the key space maps a node's compressed public key to the
35
        // serialized information for that node. Additionally, there's a
36
        // special key "source" which stores the pubkey of the source node. The
37
        // source node is used as the starting point for all graph/queries and
38
        // traversals. The graph is formed as a star-graph with the source node
39
        // at the center.
40
        //
41
        // maps: pubKey -> nodeInfo
42
        // maps: source -> selfPubKey
43
        nodeBucket = []byte("graph-node")
44

45
        // nodeUpdateIndexBucket is a sub-bucket of the nodeBucket. This bucket
46
        // will be used to quickly look up the "freshness" of a node's last
47
        // update to the network. The bucket only contains keys, and no values,
48
        // it's mapping:
49
        //
50
        // maps: updateTime || nodeID -> nil
51
        nodeUpdateIndexBucket = []byte("graph-node-update-index")
52

53
        // sourceKey is a special key that resides within the nodeBucket. The
54
        // sourceKey maps a key to the public key of the "self node".
55
        sourceKey = []byte("source")
56

57
        // aliasIndexBucket is a sub-bucket that's nested within the main
58
        // nodeBucket. This bucket maps the public key of a node to its
59
        // current alias. This bucket is provided as it can be used within a
60
        // future UI layer to add an additional degree of confirmation.
61
        aliasIndexBucket = []byte("alias")
62

63
        // edgeBucket is a bucket which houses all of the edge or channel
64
        // information within the channel graph. This bucket essentially acts
65
        // as an adjacency list, which in conjunction with a range scan, can be
66
        // used to iterate over all the incoming and outgoing edges for a
67
        // particular node. Key in the bucket use a prefix scheme which leads
68
        // with the node's public key and sends with the compact edge ID.
69
        // For each chanID, there will be two entries within the bucket, as the
70
        // graph is directed: nodes may have different policies w.r.t to fees
71
        // for their respective directions.
72
        //
73
        // maps: pubKey || chanID -> channel edge policy for node
74
        edgeBucket = []byte("graph-edge")
75

76
        // unknownPolicy is represented as an empty slice. It is
77
        // used as the value in edgeBucket for unknown channel edge policies.
78
        // Unknown policies are still stored in the database to enable efficient
79
        // lookup of incoming channel edges.
80
        unknownPolicy = []byte{}
81

82
        // chanStart is an array of all zero bytes which is used to perform
83
        // range scans within the edgeBucket to obtain all of the outgoing
84
        // edges for a particular node.
85
        chanStart [8]byte
86

87
        // edgeIndexBucket is an index which can be used to iterate all edges
88
        // in the bucket, grouping them according to their in/out nodes.
89
        // Additionally, the items in this bucket also contain the complete
90
        // edge information for a channel. The edge information includes the
91
        // capacity of the channel, the nodes that made the channel, etc. This
92
        // bucket resides within the edgeBucket above. Creation of an edge
93
        // proceeds in two phases: first the edge is added to the edge index,
94
        // afterwards the edgeBucket can be updated with the latest details of
95
        // the edge as they are announced on the network.
96
        //
97
        // maps: chanID -> pubKey1 || pubKey2 || restofEdgeInfo
98
        edgeIndexBucket = []byte("edge-index")
99

100
        // edgeUpdateIndexBucket is a sub-bucket of the main edgeBucket. This
101
        // bucket contains an index which allows us to gauge the "freshness" of
102
        // a channel's last updates.
103
        //
104
        // maps: updateTime || chanID -> nil
105
        edgeUpdateIndexBucket = []byte("edge-update-index")
106

107
        // channelPointBucket maps a channel's full outpoint (txid:index) to
108
        // its short 8-byte channel ID. This bucket resides within the
109
        // edgeBucket above, and can be used to quickly remove an edge due to
110
        // the outpoint being spent, or to query for existence of a channel.
111
        //
112
        // maps: outPoint -> chanID
113
        channelPointBucket = []byte("chan-index")
114

115
        // zombieBucket is a sub-bucket of the main edgeBucket bucket
116
        // responsible for maintaining an index of zombie channels. Each entry
117
        // exists within the bucket as follows:
118
        //
119
        // maps: chanID -> pubKey1 || pubKey2
120
        //
121
        // The chanID represents the channel ID of the edge that is marked as a
122
        // zombie and is used as the key, which maps to the public keys of the
123
        // edge's participants.
124
        zombieBucket = []byte("zombie-index")
125

126
        // disabledEdgePolicyBucket is a sub-bucket of the main edgeBucket
127
        // bucket responsible for maintaining an index of disabled edge
128
        // policies. Each entry exists within the bucket as follows:
129
        //
130
        // maps: <chanID><direction> -> []byte{}
131
        //
132
        // The chanID represents the channel ID of the edge and the direction is
133
        // one byte representing the direction of the edge. The main purpose of
134
        // this index is to allow pruning disabled channels in a fast way without
135
        // the need to iterate all over the graph.
136
        disabledEdgePolicyBucket = []byte("disabled-edge-policy-index")
137

138
        // graphMetaBucket is a top-level bucket which stores various meta-deta
139
        // related to the on-disk channel graph. Data stored in this bucket
140
        // includes the block to which the graph has been synced to, the total
141
        // number of channels, etc.
142
        graphMetaBucket = []byte("graph-meta")
143

144
        // pruneLogBucket is a bucket within the graphMetaBucket that stores
145
        // a mapping from the block height to the hash for the blocks used to
146
        // prune the graph.
147
        // Once a new block is discovered, any channels that have been closed
148
        // (by spending the outpoint) can safely be removed from the graph, and
149
        // the block is added to the prune log. We need to keep such a log for
150
        // the case where a reorg happens, and we must "rewind" the state of the
151
        // graph by removing channels that were previously confirmed. In such a
152
        // case we'll remove all entries from the prune log with a block height
153
        // that no longer exists.
154
        pruneLogBucket = []byte("prune-log")
155

156
        // closedScidBucket is a top-level bucket that stores scids for
157
        // channels that we know to be closed. This is used so that we don't
158
        // need to perform expensive validation checks if we receive a channel
159
        // announcement for the channel again.
160
        //
161
        // maps: scid -> []byte{}
162
        closedScidBucket = []byte("closed-scid")
163
)
164

165
const (
166
        // MaxAllowedExtraOpaqueBytes is the largest amount of opaque bytes that
167
        // we'll permit to be written to disk. We limit this as otherwise, it
168
        // would be possible for a node to create a ton of updates and slowly
169
        // fill our disk, and also waste bandwidth due to relaying.
170
        MaxAllowedExtraOpaqueBytes = 10000
171
)
172

173
// ChannelGraph is a persistent, on-disk graph representation of the Lightning
174
// Network. This struct can be used to implement path finding algorithms on top
175
// of, and also to update a node's view based on information received from the
176
// p2p network. Internally, the graph is stored using a modified adjacency list
177
// representation with some added object interaction possible with each
178
// serialized edge/node. The graph is stored is directed, meaning that are two
179
// edges stored for each channel: an inbound/outbound edge for each node pair.
180
// Nodes, edges, and edge information can all be added to the graph
181
// independently. Edge removal results in the deletion of all edge information
182
// for that edge.
183
type ChannelGraph struct {
184
        db kvdb.Backend
185

186
        // cacheMu guards all caches (rejectCache, chanCache, graphCache). If
187
        // this mutex will be acquired at the same time as the DB mutex then
188
        // the cacheMu MUST be acquired first to prevent deadlock.
189
        cacheMu     sync.RWMutex
190
        rejectCache *rejectCache
191
        chanCache   *channelCache
192
        graphCache  *GraphCache
193

194
        chanScheduler batch.Scheduler
195
        nodeScheduler batch.Scheduler
196
}
197

198
// NewChannelGraph allocates a new ChannelGraph backed by a DB instance. The
199
// returned instance has its own unique reject cache and channel cache.
200
func NewChannelGraph(db kvdb.Backend, options ...OptionModifier) (*ChannelGraph,
201
        error) {
175✔
202

175✔
203
        opts := DefaultOptions()
175✔
204
        for _, o := range options {
279✔
205
                o(opts)
104✔
206
        }
104✔
207

208
        if !opts.NoMigration {
350✔
209
                if err := initChannelGraph(db); err != nil {
175✔
210
                        return nil, err
×
211
                }
×
212
        }
213

214
        g := &ChannelGraph{
175✔
215
                db:          db,
175✔
216
                rejectCache: newRejectCache(opts.RejectCacheSize),
175✔
217
                chanCache:   newChannelCache(opts.ChannelCacheSize),
175✔
218
        }
175✔
219
        g.chanScheduler = batch.NewTimeScheduler(
175✔
220
                db, &g.cacheMu, opts.BatchCommitInterval,
175✔
221
        )
175✔
222
        g.nodeScheduler = batch.NewTimeScheduler(
175✔
223
                db, nil, opts.BatchCommitInterval,
175✔
224
        )
175✔
225

175✔
226
        // The graph cache can be turned off (e.g. for mobile users) for a
175✔
227
        // speed/memory usage tradeoff.
175✔
228
        if opts.UseGraphCache {
317✔
229
                g.graphCache = NewGraphCache(opts.PreAllocCacheNumNodes)
142✔
230
                startTime := time.Now()
142✔
231
                log.Debugf("Populating in-memory channel graph, this might " +
142✔
232
                        "take a while...")
142✔
233

142✔
234
                err := g.ForEachNodeCacheable(func(node route.Vertex,
142✔
235
                        features *lnwire.FeatureVector) error {
244✔
236

102✔
237
                        g.graphCache.AddNodeFeatures(node, features)
102✔
238

102✔
239
                        return nil
102✔
240
                })
102✔
241
                if err != nil {
142✔
242
                        return nil, err
×
243
                }
×
244

245
                err = g.ForEachChannel(func(info *models.ChannelEdgeInfo,
142✔
246
                        policy1, policy2 *models.ChannelEdgePolicy) error {
540✔
247

398✔
248
                        g.graphCache.AddChannel(info, policy1, policy2)
398✔
249

398✔
250
                        return nil
398✔
251
                })
398✔
252
                if err != nil {
142✔
253
                        return nil, err
×
254
                }
×
255

256
                log.Debugf("Finished populating in-memory channel graph (took "+
142✔
257
                        "%v, %s)", time.Since(startTime), g.graphCache.Stats())
142✔
258
        }
259

260
        return g, nil
175✔
261
}
262

263
// channelMapKey is the key structure used for storing channel edge policies.
264
type channelMapKey struct {
265
        nodeKey route.Vertex
266
        chanID  [8]byte
267
}
268

269
// getChannelMap loads all channel edge policies from the database and stores
270
// them in a map.
271
func (c *ChannelGraph) getChannelMap(edges kvdb.RBucket) (
272
        map[channelMapKey]*models.ChannelEdgePolicy, error) {
146✔
273

146✔
274
        // Create a map to store all channel edge policies.
146✔
275
        channelMap := make(map[channelMapKey]*models.ChannelEdgePolicy)
146✔
276

146✔
277
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
1,719✔
278
                // Skip embedded buckets.
1,573✔
279
                if bytes.Equal(k, edgeIndexBucket) ||
1,573✔
280
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
1,573✔
281
                        bytes.Equal(k, zombieBucket) ||
1,573✔
282
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
1,573✔
283
                        bytes.Equal(k, channelPointBucket) {
2,156✔
284

583✔
285
                        return nil
583✔
286
                }
583✔
287

288
                // Validate key length.
289
                if len(k) != 33+8 {
992✔
290
                        return fmt.Errorf("invalid edge key %x encountered", k)
×
291
                }
×
292

293
                var key channelMapKey
992✔
294
                copy(key.nodeKey[:], k[:33])
992✔
295
                copy(key.chanID[:], k[33:])
992✔
296

992✔
297
                // No need to deserialize unknown policy.
992✔
298
                if bytes.Equal(edgeBytes, unknownPolicy) {
992✔
299
                        return nil
×
300
                }
×
301

302
                edgeReader := bytes.NewReader(edgeBytes)
992✔
303
                edge, err := deserializeChanEdgePolicyRaw(
992✔
304
                        edgeReader,
992✔
305
                )
992✔
306

992✔
307
                switch {
992✔
308
                // If the db policy was missing an expected optional field, we
309
                // return nil as if the policy was unknown.
310
                case err == ErrEdgePolicyOptionalFieldNotFound:
×
311
                        return nil
×
312

313
                case err != nil:
×
314
                        return err
×
315
                }
316

317
                channelMap[key] = edge
992✔
318

992✔
319
                return nil
992✔
320
        })
321
        if err != nil {
146✔
322
                return nil, err
×
323
        }
×
324

325
        return channelMap, nil
146✔
326
}
327

328
var graphTopLevelBuckets = [][]byte{
329
        nodeBucket,
330
        edgeBucket,
331
        graphMetaBucket,
332
        closedScidBucket,
333
}
334

335
// Wipe completely deletes all saved state within all used buckets within the
336
// database. The deletion is done in a single transaction, therefore this
337
// operation is fully atomic.
338
func (c *ChannelGraph) Wipe() error {
×
339
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
340
                for _, tlb := range graphTopLevelBuckets {
×
341
                        err := tx.DeleteTopLevelBucket(tlb)
×
342
                        if err != nil && err != kvdb.ErrBucketNotFound {
×
343
                                return err
×
344
                        }
×
345
                }
346
                return nil
×
347
        }, func() {})
×
348
        if err != nil {
×
349
                return err
×
350
        }
×
351

352
        return initChannelGraph(c.db)
×
353
}
354

355
// createChannelDB creates and initializes a fresh version of  In
356
// the case that the target path has not yet been created or doesn't yet exist,
357
// then the path is created. Additionally, all required top-level buckets used
358
// within the database are created.
359
func initChannelGraph(db kvdb.Backend) error {
175✔
360
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
350✔
361
                for _, tlb := range graphTopLevelBuckets {
869✔
362
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
694✔
363
                                return err
×
364
                        }
×
365
                }
366

367
                nodes := tx.ReadWriteBucket(nodeBucket)
175✔
368
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
175✔
369
                if err != nil {
175✔
370
                        return err
×
371
                }
×
372
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
175✔
373
                if err != nil {
175✔
374
                        return err
×
375
                }
×
376

377
                edges := tx.ReadWriteBucket(edgeBucket)
175✔
378
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
175✔
379
                if err != nil {
175✔
380
                        return err
×
381
                }
×
382
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
175✔
383
                if err != nil {
175✔
384
                        return err
×
385
                }
×
386
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
175✔
387
                if err != nil {
175✔
388
                        return err
×
389
                }
×
390
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
175✔
391
                if err != nil {
175✔
392
                        return err
×
393
                }
×
394

395
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
175✔
396
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
175✔
397
                return err
175✔
398
        }, func() {})
175✔
399
        if err != nil {
175✔
400
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
401
        }
×
402

403
        return nil
175✔
404
}
405

406
// AddrsForNode returns all known addresses for the target node public key that
407
// the graph DB is aware of. The returned boolean indicates if the given node is
408
// unknown to the graph DB or not.
409
//
410
// NOTE: this is part of the channeldb.AddrSource interface.
411
func (c *ChannelGraph) AddrsForNode(nodePub *btcec.PublicKey) (bool, []net.Addr,
412
        error) {
3✔
413

3✔
414
        pubKey, err := route.NewVertexFromBytes(nodePub.SerializeCompressed())
3✔
415
        if err != nil {
3✔
416
                return false, nil, err
×
417
        }
×
418

419
        node, err := c.FetchLightningNode(pubKey)
3✔
420
        // We don't consider it an error if the graph is unaware of the node.
3✔
421
        switch {
3✔
422
        case err != nil && !errors.Is(err, ErrGraphNodeNotFound):
×
423
                return false, nil, err
×
424

425
        case errors.Is(err, ErrGraphNodeNotFound):
2✔
426
                return false, nil, nil
2✔
427
        }
428

429
        return true, node.Addresses, nil
3✔
430
}
431

432
// ForEachChannel iterates through all the channel edges stored within the
433
// graph and invokes the passed callback for each edge. The callback takes two
434
// edges as since this is a directed graph, both the in/out edges are visited.
435
// If the callback returns an error, then the transaction is aborted and the
436
// iteration stops early.
437
//
438
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
439
// for that particular channel edge routing policy will be passed into the
440
// callback.
441
func (c *ChannelGraph) ForEachChannel(cb func(*models.ChannelEdgeInfo,
442
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
146✔
443

146✔
444
        return c.db.View(func(tx kvdb.RTx) error {
292✔
445
                edges := tx.ReadBucket(edgeBucket)
146✔
446
                if edges == nil {
146✔
447
                        return ErrGraphNoEdgesFound
×
448
                }
×
449

450
                // First, load all edges in memory indexed by node and channel
451
                // id.
452
                channelMap, err := c.getChannelMap(edges)
146✔
453
                if err != nil {
146✔
454
                        return err
×
455
                }
×
456

457
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
146✔
458
                if edgeIndex == nil {
146✔
459
                        return ErrGraphNoEdgesFound
×
460
                }
×
461

462
                // Load edge index, recombine each channel with the policies
463
                // loaded above and invoke the callback.
464
                return kvdb.ForAll(
146✔
465
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
643✔
466
                                var chanID [8]byte
497✔
467
                                copy(chanID[:], k)
497✔
468

497✔
469
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
497✔
470
                                info, err := deserializeChanEdgeInfo(
497✔
471
                                        edgeInfoReader,
497✔
472
                                )
497✔
473
                                if err != nil {
497✔
474
                                        return err
×
475
                                }
×
476

477
                                policy1 := channelMap[channelMapKey{
497✔
478
                                        nodeKey: info.NodeKey1Bytes,
497✔
479
                                        chanID:  chanID,
497✔
480
                                }]
497✔
481

497✔
482
                                policy2 := channelMap[channelMapKey{
497✔
483
                                        nodeKey: info.NodeKey2Bytes,
497✔
484
                                        chanID:  chanID,
497✔
485
                                }]
497✔
486

497✔
487
                                return cb(&info, policy1, policy2)
497✔
488
                        },
489
                )
490
        }, func() {})
146✔
491
}
492

493
// forEachNodeDirectedChannel iterates through all channels of a given node,
494
// executing the passed callback on the directed edge representing the channel
495
// and its incoming policy. If the callback returns an error, then the iteration
496
// is halted with the error propagated back up to the caller. An optional read
497
// transaction may be provided. If none is provided, a new one will be created.
498
//
499
// Unknown policies are passed into the callback as nil values.
500
func (c *ChannelGraph) forEachNodeDirectedChannel(tx kvdb.RTx,
501
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
705✔
502

705✔
503
        if c.graphCache != nil {
1,168✔
504
                return c.graphCache.ForEachChannel(node, cb)
463✔
505
        }
463✔
506

507
        // Fallback that uses the database.
508
        toNodeCallback := func() route.Vertex {
378✔
509
                return node
134✔
510
        }
134✔
511
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
244✔
512
        if err != nil {
244✔
513
                return err
×
514
        }
×
515

516
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
244✔
517
                p2 *models.ChannelEdgePolicy) error {
742✔
518

498✔
519
                var cachedInPolicy *models.CachedEdgePolicy
498✔
520
                if p2 != nil {
993✔
521
                        cachedInPolicy = models.NewCachedPolicy(p2)
495✔
522
                        cachedInPolicy.ToNodePubKey = toNodeCallback
495✔
523
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
495✔
524
                }
495✔
525

526
                var inboundFee lnwire.Fee
498✔
527
                if p1 != nil {
995✔
528
                        // Extract inbound fee. If there is a decoding error,
497✔
529
                        // skip this edge.
497✔
530
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
497✔
531
                        if err != nil {
498✔
532
                                return nil
1✔
533
                        }
1✔
534
                }
535

536
                directedChannel := &DirectedChannel{
497✔
537
                        ChannelID:    e.ChannelID,
497✔
538
                        IsNode1:      node == e.NodeKey1Bytes,
497✔
539
                        OtherNode:    e.NodeKey2Bytes,
497✔
540
                        Capacity:     e.Capacity,
497✔
541
                        OutPolicySet: p1 != nil,
497✔
542
                        InPolicy:     cachedInPolicy,
497✔
543
                        InboundFee:   inboundFee,
497✔
544
                }
497✔
545

497✔
546
                if node == e.NodeKey2Bytes {
749✔
547
                        directedChannel.OtherNode = e.NodeKey1Bytes
252✔
548
                }
252✔
549

550
                return cb(directedChannel)
497✔
551
        }
552
        return nodeTraversal(tx, node[:], c.db, dbCallback)
244✔
553
}
554

555
// fetchNodeFeatures returns the features of a given node. If no features are
556
// known for the node, an empty feature vector is returned. An optional read
557
// transaction may be provided. If none is provided, a new one will be created.
558
func (c *ChannelGraph) fetchNodeFeatures(tx kvdb.RTx,
559
        node route.Vertex) (*lnwire.FeatureVector, error) {
1,141✔
560

1,141✔
561
        if c.graphCache != nil {
1,596✔
562
                return c.graphCache.GetFeatures(node), nil
455✔
563
        }
455✔
564

565
        // Fallback that uses the database.
566
        targetNode, err := c.FetchLightningNodeTx(tx, node)
688✔
567
        switch err {
688✔
568
        // If the node exists and has features, return them directly.
569
        case nil:
677✔
570
                return targetNode.Features, nil
677✔
571

572
        // If we couldn't find a node announcement, populate a blank feature
573
        // vector.
574
        case ErrGraphNodeNotFound:
11✔
575
                return lnwire.EmptyFeatureVector(), nil
11✔
576

577
        // Otherwise, bubble the error up.
578
        default:
×
579
                return nil, err
×
580
        }
581
}
582

583
// ForEachNodeDirectedChannel iterates through all channels of a given node,
584
// executing the passed callback on the directed edge representing the channel
585
// and its incoming policy. If the callback returns an error, then the iteration
586
// is halted with the error propagated back up to the caller. If the graphCache
587
// is available, then it will be used to retrieve the node's channels instead
588
// of the database.
589
//
590
// Unknown policies are passed into the callback as nil values.
591
//
592
// NOTE: this is part of the graphdb.NodeTraverser interface.
593
func (c *ChannelGraph) ForEachNodeDirectedChannel(nodePub route.Vertex,
594
        cb func(channel *DirectedChannel) error) error {
113✔
595

113✔
596
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
113✔
597
}
113✔
598

599
// FetchNodeFeatures returns the features of the given node. If no features are
600
// known for the node, an empty feature vector is returned.
601
// If the graphCache is available, then it will be used to retrieve the node's
602
// features instead of the database.
603
//
604
// NOTE: this is part of the graphdb.NodeTraverser interface.
605
func (c *ChannelGraph) FetchNodeFeatures(nodePub route.Vertex) (
606
        *lnwire.FeatureVector, error) {
89✔
607

89✔
608
        return c.fetchNodeFeatures(nil, nodePub)
89✔
609
}
89✔
610

611
// ForEachNodeCached is similar to forEachNode, but it utilizes the channel
612
// graph cache instead. Note that this doesn't return all the information the
613
// regular forEachNode method does.
614
//
615
// NOTE: The callback contents MUST not be modified.
616
func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex,
617
        chans map[uint64]*DirectedChannel) error) error {
1✔
618

1✔
619
        if c.graphCache != nil {
1✔
620
                return c.graphCache.ForEachNode(cb)
×
621
        }
×
622

623
        // Otherwise call back to a version that uses the database directly.
624
        // We'll iterate over each node, then the set of channels for each
625
        // node, and construct a similar callback functiopn signature as the
626
        // main funcotin expects.
627
        return c.forEachNode(func(tx kvdb.RTx,
1✔
628
                node *models.LightningNode) error {
21✔
629

20✔
630
                channels := make(map[uint64]*DirectedChannel)
20✔
631

20✔
632
                err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes,
20✔
633
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
634
                                p1 *models.ChannelEdgePolicy,
20✔
635
                                p2 *models.ChannelEdgePolicy) error {
210✔
636

190✔
637
                                toNodeCallback := func() route.Vertex {
190✔
638
                                        return node.PubKeyBytes
×
639
                                }
×
640
                                toNodeFeatures, err := c.fetchNodeFeatures(
190✔
641
                                        tx, node.PubKeyBytes,
190✔
642
                                )
190✔
643
                                if err != nil {
190✔
644
                                        return err
×
645
                                }
×
646

647
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
648
                                if p2 != nil {
380✔
649
                                        cachedInPolicy =
190✔
650
                                                models.NewCachedPolicy(p2)
190✔
651
                                        cachedInPolicy.ToNodePubKey =
190✔
652
                                                toNodeCallback
190✔
653
                                        cachedInPolicy.ToNodeFeatures =
190✔
654
                                                toNodeFeatures
190✔
655
                                }
190✔
656

657
                                directedChannel := &DirectedChannel{
190✔
658
                                        ChannelID: e.ChannelID,
190✔
659
                                        IsNode1: node.PubKeyBytes ==
190✔
660
                                                e.NodeKey1Bytes,
190✔
661
                                        OtherNode:    e.NodeKey2Bytes,
190✔
662
                                        Capacity:     e.Capacity,
190✔
663
                                        OutPolicySet: p1 != nil,
190✔
664
                                        InPolicy:     cachedInPolicy,
190✔
665
                                }
190✔
666

190✔
667
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
668
                                        directedChannel.OtherNode =
95✔
669
                                                e.NodeKey1Bytes
95✔
670
                                }
95✔
671

672
                                channels[e.ChannelID] = directedChannel
190✔
673

190✔
674
                                return nil
190✔
675
                        })
676
                if err != nil {
20✔
677
                        return err
×
678
                }
×
679

680
                return cb(node.PubKeyBytes, channels)
20✔
681
        })
682
}
683

684
// DisabledChannelIDs returns the channel ids of disabled channels.
685
// A channel is disabled when two of the associated ChanelEdgePolicies
686
// have their disabled bit on.
687
func (c *ChannelGraph) DisabledChannelIDs() ([]uint64, error) {
6✔
688
        var disabledChanIDs []uint64
6✔
689
        var chanEdgeFound map[uint64]struct{}
6✔
690

6✔
691
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
692
                edges := tx.ReadBucket(edgeBucket)
6✔
693
                if edges == nil {
6✔
694
                        return ErrGraphNoEdgesFound
×
695
                }
×
696

697
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
698
                        disabledEdgePolicyBucket,
6✔
699
                )
6✔
700
                if disabledEdgePolicyIndex == nil {
7✔
701
                        return nil
1✔
702
                }
1✔
703

704
                // We iterate over all disabled policies and we add each channel
705
                // that has more than one disabled policy to disabledChanIDs
706
                // array.
707
                return disabledEdgePolicyIndex.ForEach(
5✔
708
                        func(k, v []byte) error {
16✔
709
                                chanID := byteOrder.Uint64(k[:8])
11✔
710
                                _, edgeFound := chanEdgeFound[chanID]
11✔
711
                                if edgeFound {
15✔
712
                                        delete(chanEdgeFound, chanID)
4✔
713
                                        disabledChanIDs = append(
4✔
714
                                                disabledChanIDs, chanID,
4✔
715
                                        )
4✔
716

4✔
717
                                        return nil
4✔
718
                                }
4✔
719

720
                                chanEdgeFound[chanID] = struct{}{}
7✔
721

7✔
722
                                return nil
7✔
723
                        },
724
                )
725
        }, func() {
6✔
726
                disabledChanIDs = nil
6✔
727
                chanEdgeFound = make(map[uint64]struct{})
6✔
728
        })
6✔
729
        if err != nil {
6✔
730
                return nil, err
×
731
        }
×
732

733
        return disabledChanIDs, nil
6✔
734
}
735

736
// ForEachNode iterates through all the stored vertices/nodes in the graph,
737
// executing the passed callback with each node encountered. If the callback
738
// returns an error, then the transaction is aborted and the iteration stops
739
// early. Any operations performed on the NodeTx passed to the call-back are
740
// executed under the same read transaction and so, methods on the NodeTx object
741
// _MUST_ only be called from within the call-back.
742
func (c *ChannelGraph) ForEachNode(cb func(tx NodeRTx) error) error {
122✔
743
        return c.forEachNode(func(tx kvdb.RTx,
122✔
744
                node *models.LightningNode) error {
1,094✔
745

972✔
746
                return cb(newChanGraphNodeTx(tx, c, node))
972✔
747
        })
972✔
748
}
749

750
// forEachNode iterates through all the stored vertices/nodes in the graph,
751
// executing the passed callback with each node encountered. If the callback
752
// returns an error, then the transaction is aborted and the iteration stops
753
// early.
754
//
755
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
756
// traversal when graph gets mega.
757
func (c *ChannelGraph) forEachNode(
758
        cb func(kvdb.RTx, *models.LightningNode) error) error {
131✔
759

131✔
760
        traversal := func(tx kvdb.RTx) error {
262✔
761
                // First grab the nodes bucket which stores the mapping from
131✔
762
                // pubKey to node information.
131✔
763
                nodes := tx.ReadBucket(nodeBucket)
131✔
764
                if nodes == nil {
131✔
765
                        return ErrGraphNotFound
×
766
                }
×
767

768
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,572✔
769
                        // If this is the source key, then we skip this
1,441✔
770
                        // iteration as the value for this key is a pubKey
1,441✔
771
                        // rather than raw node information.
1,441✔
772
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,704✔
773
                                return nil
263✔
774
                        }
263✔
775

776
                        nodeReader := bytes.NewReader(nodeBytes)
1,180✔
777
                        node, err := deserializeLightningNode(nodeReader)
1,180✔
778
                        if err != nil {
1,180✔
779
                                return err
×
780
                        }
×
781

782
                        // Execute the callback, the transaction will abort if
783
                        // this returns an error.
784
                        return cb(tx, &node)
1,180✔
785
                })
786
        }
787

788
        return kvdb.View(c.db, traversal, func() {})
262✔
789
}
790

791
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
792
// graph, executing the passed callback with each node encountered. If the
793
// callback returns an error, then the transaction is aborted and the iteration
794
// stops early.
795
func (c *ChannelGraph) ForEachNodeCacheable(cb func(route.Vertex,
796
        *lnwire.FeatureVector) error) error {
143✔
797

143✔
798
        traversal := func(tx kvdb.RTx) error {
286✔
799
                // First grab the nodes bucket which stores the mapping from
143✔
800
                // pubKey to node information.
143✔
801
                nodes := tx.ReadBucket(nodeBucket)
143✔
802
                if nodes == nil {
143✔
803
                        return ErrGraphNotFound
×
804
                }
×
805

806
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
547✔
807
                        // If this is the source key, then we skip this
404✔
808
                        // iteration as the value for this key is a pubKey
404✔
809
                        // rather than raw node information.
404✔
810
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
688✔
811
                                return nil
284✔
812
                        }
284✔
813

814
                        nodeReader := bytes.NewReader(nodeBytes)
122✔
815
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
122✔
816
                                nodeReader,
122✔
817
                        )
122✔
818
                        if err != nil {
122✔
819
                                return err
×
820
                        }
×
821

822
                        // Execute the callback, the transaction will abort if
823
                        // this returns an error.
824
                        return cb(node, features)
122✔
825
                })
826
        }
827

828
        return kvdb.View(c.db, traversal, func() {})
286✔
829
}
830

831
// SourceNode returns the source node of the graph. The source node is treated
832
// as the center node within a star-graph. This method may be used to kick off
833
// a path finding algorithm in order to explore the reachability of another
834
// node based off the source node.
835
func (c *ChannelGraph) SourceNode() (*models.LightningNode, error) {
233✔
836
        var source *models.LightningNode
233✔
837
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
466✔
838
                // First grab the nodes bucket which stores the mapping from
233✔
839
                // pubKey to node information.
233✔
840
                nodes := tx.ReadBucket(nodeBucket)
233✔
841
                if nodes == nil {
233✔
842
                        return ErrGraphNotFound
×
843
                }
×
844

845
                node, err := c.sourceNode(nodes)
233✔
846
                if err != nil {
234✔
847
                        return err
1✔
848
                }
1✔
849
                source = node
232✔
850

232✔
851
                return nil
232✔
852
        }, func() {
233✔
853
                source = nil
233✔
854
        })
233✔
855
        if err != nil {
234✔
856
                return nil, err
1✔
857
        }
1✔
858

859
        return source, nil
232✔
860
}
861

862
// sourceNode uses an existing database transaction and returns the source node
863
// of the graph. The source node is treated as the center node within a
864
// star-graph. This method may be used to kick off a path finding algorithm in
865
// order to explore the reachability of another node based off the source node.
866
func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
867
        error) {
502✔
868

502✔
869
        selfPub := nodes.Get(sourceKey)
502✔
870
        if selfPub == nil {
503✔
871
                return nil, ErrSourceNodeNotSet
1✔
872
        }
1✔
873

874
        // With the pubKey of the source node retrieved, we're able to
875
        // fetch the full node information.
876
        node, err := fetchLightningNode(nodes, selfPub)
501✔
877
        if err != nil {
501✔
878
                return nil, err
×
879
        }
×
880

881
        return &node, nil
501✔
882
}
883

884
// SetSourceNode sets the source node within the graph database. The source
885
// node is to be used as the center of a star-graph within path finding
886
// algorithms.
887
func (c *ChannelGraph) SetSourceNode(node *models.LightningNode) error {
119✔
888
        nodePubBytes := node.PubKeyBytes[:]
119✔
889

119✔
890
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
238✔
891
                // First grab the nodes bucket which stores the mapping from
119✔
892
                // pubKey to node information.
119✔
893
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
119✔
894
                if err != nil {
119✔
895
                        return err
×
896
                }
×
897

898
                // Next we create the mapping from source to the targeted
899
                // public key.
900
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
119✔
901
                        return err
×
902
                }
×
903

904
                // Finally, we commit the information of the lightning node
905
                // itself.
906
                return addLightningNode(tx, node)
119✔
907
        }, func() {})
119✔
908
}
909

910
// AddLightningNode adds a vertex/node to the graph database. If the node is not
911
// in the database from before, this will add a new, unconnected one to the
912
// graph. If it is present from before, this will update that node's
913
// information. Note that this method is expected to only be called to update an
914
// already present node from a node announcement, or to insert a node found in a
915
// channel update.
916
//
917
// TODO(roasbeef): also need sig of announcement
918
func (c *ChannelGraph) AddLightningNode(node *models.LightningNode,
919
        op ...batch.SchedulerOption) error {
802✔
920

802✔
921
        r := &batch.Request{
802✔
922
                Update: func(tx kvdb.RwTx) error {
1,604✔
923
                        if c.graphCache != nil {
1,417✔
924
                                c.graphCache.AddNodeFeatures(
615✔
925
                                        node.PubKeyBytes, node.Features,
615✔
926
                                )
615✔
927
                        }
615✔
928

929
                        return addLightningNode(tx, node)
802✔
930
                },
931
        }
932

933
        for _, f := range op {
804✔
934
                f(r)
2✔
935
        }
2✔
936

937
        return c.nodeScheduler.Execute(r)
802✔
938
}
939

940
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
998✔
941
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
998✔
942
        if err != nil {
998✔
943
                return err
×
944
        }
×
945

946
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
998✔
947
        if err != nil {
998✔
948
                return err
×
949
        }
×
950

951
        updateIndex, err := nodes.CreateBucketIfNotExists(
998✔
952
                nodeUpdateIndexBucket,
998✔
953
        )
998✔
954
        if err != nil {
998✔
955
                return err
×
956
        }
×
957

958
        return putLightningNode(nodes, aliases, updateIndex, node)
998✔
959
}
960

961
// LookupAlias attempts to return the alias as advertised by the target node.
962
// TODO(roasbeef): currently assumes that aliases are unique...
963
func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error) {
4✔
964
        var alias string
4✔
965

4✔
966
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
967
                nodes := tx.ReadBucket(nodeBucket)
4✔
968
                if nodes == nil {
4✔
969
                        return ErrGraphNodesNotFound
×
970
                }
×
971

972
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
4✔
973
                if aliases == nil {
4✔
974
                        return ErrGraphNodesNotFound
×
975
                }
×
976

977
                nodePub := pub.SerializeCompressed()
4✔
978
                a := aliases.Get(nodePub)
4✔
979
                if a == nil {
5✔
980
                        return ErrNodeAliasNotFound
1✔
981
                }
1✔
982

983
                // TODO(roasbeef): should actually be using the utf-8
984
                // package...
985
                alias = string(a)
3✔
986
                return nil
3✔
987
        }, func() {
4✔
988
                alias = ""
4✔
989
        })
4✔
990
        if err != nil {
5✔
991
                return "", err
1✔
992
        }
1✔
993

994
        return alias, nil
3✔
995
}
996

997
// DeleteLightningNode starts a new database transaction to remove a vertex/node
998
// from the database according to the node's public key.
999
func (c *ChannelGraph) DeleteLightningNode(nodePub route.Vertex) error {
3✔
1000
        // TODO(roasbeef): ensure dangling edges are removed...
3✔
1001
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1002
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1003
                if nodes == nil {
3✔
1004
                        return ErrGraphNodeNotFound
×
1005
                }
×
1006

1007
                if c.graphCache != nil {
6✔
1008
                        c.graphCache.RemoveNode(nodePub)
3✔
1009
                }
3✔
1010

1011
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
1012
        }, func() {})
3✔
1013
}
1014

1015
// deleteLightningNode uses an existing database transaction to remove a
1016
// vertex/node from the database according to the node's public key.
1017
func (c *ChannelGraph) deleteLightningNode(nodes kvdb.RwBucket,
1018
        compressedPubKey []byte) error {
73✔
1019

73✔
1020
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
73✔
1021
        if aliases == nil {
73✔
1022
                return ErrGraphNodesNotFound
×
1023
        }
×
1024

1025
        if err := aliases.Delete(compressedPubKey); err != nil {
73✔
1026
                return err
×
1027
        }
×
1028

1029
        // Before we delete the node, we'll fetch its current state so we can
1030
        // determine when its last update was to clear out the node update
1031
        // index.
1032
        node, err := fetchLightningNode(nodes, compressedPubKey)
73✔
1033
        if err != nil {
73✔
1034
                return err
×
1035
        }
×
1036

1037
        if err := nodes.Delete(compressedPubKey); err != nil {
73✔
1038
                return err
×
1039
        }
×
1040

1041
        // Finally, we'll delete the index entry for the node within the
1042
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1043
        // need to track its last update.
1044
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
73✔
1045
        if nodeUpdateIndex == nil {
73✔
1046
                return ErrGraphNodesNotFound
×
1047
        }
×
1048

1049
        // In order to delete the entry, we'll need to reconstruct the key for
1050
        // its last update.
1051
        updateUnix := uint64(node.LastUpdate.Unix())
73✔
1052
        var indexKey [8 + 33]byte
73✔
1053
        byteOrder.PutUint64(indexKey[:8], updateUnix)
73✔
1054
        copy(indexKey[8:], compressedPubKey)
73✔
1055

73✔
1056
        return nodeUpdateIndex.Delete(indexKey[:])
73✔
1057
}
1058

1059
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1060
// undirected edge from the two target nodes are created. The information stored
1061
// denotes the static attributes of the channel, such as the channelID, the keys
1062
// involved in creation of the channel, and the set of features that the channel
1063
// supports. The chanPoint and chanID are used to uniquely identify the edge
1064
// globally within the database.
1065
func (c *ChannelGraph) AddChannelEdge(edge *models.ChannelEdgeInfo,
1066
        op ...batch.SchedulerOption) error {
1,713✔
1067

1,713✔
1068
        var alreadyExists bool
1,713✔
1069
        r := &batch.Request{
1,713✔
1070
                Reset: func() {
3,426✔
1071
                        alreadyExists = false
1,713✔
1072
                },
1,713✔
1073
                Update: func(tx kvdb.RwTx) error {
1,713✔
1074
                        err := c.addChannelEdge(tx, edge)
1,713✔
1075

1,713✔
1076
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,713✔
1077
                        // succeed, but propagate the error via local state.
1,713✔
1078
                        if err == ErrEdgeAlreadyExist {
1,947✔
1079
                                alreadyExists = true
234✔
1080
                                return nil
234✔
1081
                        }
234✔
1082

1083
                        return err
1,479✔
1084
                },
1085
                OnCommit: func(err error) error {
1,713✔
1086
                        switch {
1,713✔
1087
                        case err != nil:
×
1088
                                return err
×
1089
                        case alreadyExists:
234✔
1090
                                return ErrEdgeAlreadyExist
234✔
1091
                        default:
1,479✔
1092
                                c.rejectCache.remove(edge.ChannelID)
1,479✔
1093
                                c.chanCache.remove(edge.ChannelID)
1,479✔
1094
                                return nil
1,479✔
1095
                        }
1096
                },
1097
        }
1098

1099
        for _, f := range op {
1,715✔
1100
                if f == nil {
2✔
1101
                        return fmt.Errorf("nil scheduler option was used")
×
1102
                }
×
1103

1104
                f(r)
2✔
1105
        }
1106

1107
        return c.chanScheduler.Execute(r)
1,713✔
1108
}
1109

1110
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1111
// utilize an existing db transaction.
1112
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1113
        edge *models.ChannelEdgeInfo) error {
1,713✔
1114

1,713✔
1115
        // Construct the channel's primary key which is the 8-byte channel ID.
1,713✔
1116
        var chanKey [8]byte
1,713✔
1117
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,713✔
1118

1,713✔
1119
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,713✔
1120
        if err != nil {
1,713✔
1121
                return err
×
1122
        }
×
1123
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,713✔
1124
        if err != nil {
1,713✔
1125
                return err
×
1126
        }
×
1127
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,713✔
1128
        if err != nil {
1,713✔
1129
                return err
×
1130
        }
×
1131
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,713✔
1132
        if err != nil {
1,713✔
1133
                return err
×
1134
        }
×
1135

1136
        // First, attempt to check if this edge has already been created. If
1137
        // so, then we can exit early as this method is meant to be idempotent.
1138
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,947✔
1139
                return ErrEdgeAlreadyExist
234✔
1140
        }
234✔
1141

1142
        if c.graphCache != nil {
2,768✔
1143
                c.graphCache.AddChannel(edge, nil, nil)
1,289✔
1144
        }
1,289✔
1145

1146
        // Before we insert the channel into the database, we'll ensure that
1147
        // both nodes already exist in the channel graph. If either node
1148
        // doesn't, then we'll insert a "shell" node that just includes its
1149
        // public key, so subsequent validation and queries can work properly.
1150
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
1,479✔
1151
        switch {
1,479✔
1152
        case node1Err == ErrGraphNodeNotFound:
20✔
1153
                node1Shell := models.LightningNode{
20✔
1154
                        PubKeyBytes:          edge.NodeKey1Bytes,
20✔
1155
                        HaveNodeAnnouncement: false,
20✔
1156
                }
20✔
1157
                err := addLightningNode(tx, &node1Shell)
20✔
1158
                if err != nil {
20✔
1159
                        return fmt.Errorf("unable to create shell node "+
×
1160
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1161
                }
×
1162
        case node1Err != nil:
×
1163
                return node1Err
×
1164
        }
1165

1166
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,479✔
1167
        switch {
1,479✔
1168
        case node2Err == ErrGraphNodeNotFound:
63✔
1169
                node2Shell := models.LightningNode{
63✔
1170
                        PubKeyBytes:          edge.NodeKey2Bytes,
63✔
1171
                        HaveNodeAnnouncement: false,
63✔
1172
                }
63✔
1173
                err := addLightningNode(tx, &node2Shell)
63✔
1174
                if err != nil {
63✔
1175
                        return fmt.Errorf("unable to create shell node "+
×
1176
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1177
                }
×
1178
        case node2Err != nil:
×
1179
                return node2Err
×
1180
        }
1181

1182
        // If the edge hasn't been created yet, then we'll first add it to the
1183
        // edge index in order to associate the edge between two nodes and also
1184
        // store the static components of the channel.
1185
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
1,479✔
1186
                return err
×
1187
        }
×
1188

1189
        // Mark edge policies for both sides as unknown. This is to enable
1190
        // efficient incoming channel lookup for a node.
1191
        keys := []*[33]byte{
1,479✔
1192
                &edge.NodeKey1Bytes,
1,479✔
1193
                &edge.NodeKey2Bytes,
1,479✔
1194
        }
1,479✔
1195
        for _, key := range keys {
4,435✔
1196
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,956✔
1197
                if err != nil {
2,956✔
1198
                        return err
×
1199
                }
×
1200
        }
1201

1202
        // Finally we add it to the channel index which maps channel points
1203
        // (outpoints) to the shorter channel ID's.
1204
        var b bytes.Buffer
1,479✔
1205
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,479✔
1206
                return err
×
1207
        }
×
1208
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,479✔
1209
}
1210

1211
// HasChannelEdge returns true if the database knows of a channel edge with the
1212
// passed channel ID, and false otherwise. If an edge with that ID is found
1213
// within the graph, then two time stamps representing the last time the edge
1214
// was updated for both directed edges are returned along with the boolean. If
1215
// it is not found, then the zombie index is checked and its result is returned
1216
// as the second boolean.
1217
func (c *ChannelGraph) HasChannelEdge(
1218
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
211✔
1219

211✔
1220
        var (
211✔
1221
                upd1Time time.Time
211✔
1222
                upd2Time time.Time
211✔
1223
                exists   bool
211✔
1224
                isZombie bool
211✔
1225
        )
211✔
1226

211✔
1227
        // We'll query the cache with the shared lock held to allow multiple
211✔
1228
        // readers to access values in the cache concurrently if they exist.
211✔
1229
        c.cacheMu.RLock()
211✔
1230
        if entry, ok := c.rejectCache.get(chanID); ok {
277✔
1231
                c.cacheMu.RUnlock()
66✔
1232
                upd1Time = time.Unix(entry.upd1Time, 0)
66✔
1233
                upd2Time = time.Unix(entry.upd2Time, 0)
66✔
1234
                exists, isZombie = entry.flags.unpack()
66✔
1235
                return upd1Time, upd2Time, exists, isZombie, nil
66✔
1236
        }
66✔
1237
        c.cacheMu.RUnlock()
147✔
1238

147✔
1239
        c.cacheMu.Lock()
147✔
1240
        defer c.cacheMu.Unlock()
147✔
1241

147✔
1242
        // The item was not found with the shared lock, so we'll acquire the
147✔
1243
        // exclusive lock and check the cache again in case another method added
147✔
1244
        // the entry to the cache while no lock was held.
147✔
1245
        if entry, ok := c.rejectCache.get(chanID); ok {
153✔
1246
                upd1Time = time.Unix(entry.upd1Time, 0)
6✔
1247
                upd2Time = time.Unix(entry.upd2Time, 0)
6✔
1248
                exists, isZombie = entry.flags.unpack()
6✔
1249
                return upd1Time, upd2Time, exists, isZombie, nil
6✔
1250
        }
6✔
1251

1252
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
286✔
1253
                edges := tx.ReadBucket(edgeBucket)
143✔
1254
                if edges == nil {
143✔
1255
                        return ErrGraphNoEdgesFound
×
1256
                }
×
1257
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
143✔
1258
                if edgeIndex == nil {
143✔
1259
                        return ErrGraphNoEdgesFound
×
1260
                }
×
1261

1262
                var channelID [8]byte
143✔
1263
                byteOrder.PutUint64(channelID[:], chanID)
143✔
1264

143✔
1265
                // If the edge doesn't exist, then we'll also check our zombie
143✔
1266
                // index.
143✔
1267
                if edgeIndex.Get(channelID[:]) == nil {
241✔
1268
                        exists = false
98✔
1269
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
98✔
1270
                        if zombieIndex != nil {
196✔
1271
                                isZombie, _, _ = isZombieEdge(
98✔
1272
                                        zombieIndex, chanID,
98✔
1273
                                )
98✔
1274
                        }
98✔
1275

1276
                        return nil
98✔
1277
                }
1278

1279
                exists = true
47✔
1280
                isZombie = false
47✔
1281

47✔
1282
                // If the channel has been found in the graph, then retrieve
47✔
1283
                // the edges itself so we can return the last updated
47✔
1284
                // timestamps.
47✔
1285
                nodes := tx.ReadBucket(nodeBucket)
47✔
1286
                if nodes == nil {
47✔
1287
                        return ErrGraphNodeNotFound
×
1288
                }
×
1289

1290
                e1, e2, err := fetchChanEdgePolicies(
47✔
1291
                        edgeIndex, edges, channelID[:],
47✔
1292
                )
47✔
1293
                if err != nil {
47✔
1294
                        return err
×
1295
                }
×
1296

1297
                // As we may have only one of the edges populated, only set the
1298
                // update time if the edge was found in the database.
1299
                if e1 != nil {
67✔
1300
                        upd1Time = e1.LastUpdate
20✔
1301
                }
20✔
1302
                if e2 != nil {
65✔
1303
                        upd2Time = e2.LastUpdate
18✔
1304
                }
18✔
1305

1306
                return nil
47✔
1307
        }, func() {}); err != nil {
143✔
1308
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1309
        }
×
1310

1311
        c.rejectCache.insert(chanID, rejectCacheEntry{
143✔
1312
                upd1Time: upd1Time.Unix(),
143✔
1313
                upd2Time: upd2Time.Unix(),
143✔
1314
                flags:    packRejectFlags(exists, isZombie),
143✔
1315
        })
143✔
1316

143✔
1317
        return upd1Time, upd2Time, exists, isZombie, nil
143✔
1318
}
1319

1320
// AddEdgeProof sets the proof of an existing edge in the graph database.
1321
func (c *ChannelGraph) AddEdgeProof(chanID lnwire.ShortChannelID,
1322
        proof *models.ChannelAuthProof) error {
3✔
1323

3✔
1324
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1325
        var chanKey [8]byte
3✔
1326
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1327

3✔
1328
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1329
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1330
                if edges == nil {
3✔
1331
                        return ErrEdgeNotFound
×
1332
                }
×
1333

1334
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1335
                if edgeIndex == nil {
3✔
1336
                        return ErrEdgeNotFound
×
1337
                }
×
1338

1339
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1340
                if err != nil {
3✔
NEW
1341
                        return err
×
UNCOV
1342
                }
×
1343

1344
                edge.AuthProof = proof
3✔
1345

3✔
1346
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1347
        }, func() {})
3✔
1348
}
1349

1350
const (
1351
        // pruneTipBytes is the total size of the value which stores a prune
1352
        // entry of the graph in the prune log. The "prune tip" is the last
1353
        // entry in the prune log, and indicates if the channel graph is in
1354
        // sync with the current UTXO state. The structure of the value
1355
        // is: blockHash, taking 32 bytes total.
1356
        pruneTipBytes = 32
1357
)
1358

1359
// PruneGraph prunes newly closed channels from the channel graph in response
1360
// to a new block being solved on the network. Any transactions which spend the
1361
// funding output of any known channels within he graph will be deleted.
1362
// Additionally, the "prune tip", or the last block which has been used to
1363
// prune the graph is stored so callers can ensure the graph is fully in sync
1364
// with the current UTXO state. A slice of channels that have been closed by
1365
// the target block are returned if the function succeeds without error.
1366
func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint,
1367
        blockHash *chainhash.Hash, blockHeight uint32) (
1368
        []*models.ChannelEdgeInfo, error) {
248✔
1369

248✔
1370
        c.cacheMu.Lock()
248✔
1371
        defer c.cacheMu.Unlock()
248✔
1372

248✔
1373
        var chansClosed []*models.ChannelEdgeInfo
248✔
1374

248✔
1375
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
496✔
1376
                // First grab the edges bucket which houses the information
248✔
1377
                // we'd like to delete
248✔
1378
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
248✔
1379
                if err != nil {
248✔
1380
                        return err
×
1381
                }
×
1382

1383
                // Next grab the two edge indexes which will also need to be
1384
                // updated.
1385
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
248✔
1386
                if err != nil {
248✔
1387
                        return err
×
1388
                }
×
1389
                chanIndex, err := edges.CreateBucketIfNotExists(
248✔
1390
                        channelPointBucket,
248✔
1391
                )
248✔
1392
                if err != nil {
248✔
1393
                        return err
×
1394
                }
×
1395
                nodes := tx.ReadWriteBucket(nodeBucket)
248✔
1396
                if nodes == nil {
248✔
1397
                        return ErrSourceNodeNotSet
×
1398
                }
×
1399
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
248✔
1400
                if err != nil {
248✔
1401
                        return err
×
1402
                }
×
1403

1404
                // For each of the outpoints that have been spent within the
1405
                // block, we attempt to delete them from the graph as if that
1406
                // outpoint was a channel, then it has now been closed.
1407
                for _, chanPoint := range spentOutputs {
395✔
1408
                        // TODO(roasbeef): load channel bloom filter, continue
147✔
1409
                        // if NOT if filter
147✔
1410

147✔
1411
                        var opBytes bytes.Buffer
147✔
1412
                        err := WriteOutpoint(&opBytes, chanPoint)
147✔
1413
                        if err != nil {
147✔
1414
                                return err
×
1415
                        }
×
1416

1417
                        // First attempt to see if the channel exists within
1418
                        // the database, if not, then we can exit early.
1419
                        chanID := chanIndex.Get(opBytes.Bytes())
147✔
1420
                        if chanID == nil {
272✔
1421
                                continue
125✔
1422
                        }
1423

1424
                        // However, if it does, then we'll read out the full
1425
                        // version so we can add it to the set of deleted
1426
                        // channels.
1427
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
22✔
1428
                        if err != nil {
22✔
1429
                                return err
×
1430
                        }
×
1431

1432
                        // Attempt to delete the channel, an ErrEdgeNotFound
1433
                        // will be returned if that outpoint isn't known to be
1434
                        // a channel. If no error is returned, then a channel
1435
                        // was successfully pruned.
1436
                        err = c.delChannelEdgeUnsafe(
22✔
1437
                                edges, edgeIndex, chanIndex, zombieIndex,
22✔
1438
                                chanID, false, false,
22✔
1439
                        )
22✔
1440
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
22✔
1441
                                return err
×
1442
                        }
×
1443

1444
                        chansClosed = append(chansClosed, &edgeInfo)
22✔
1445
                }
1446

1447
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
248✔
1448
                if err != nil {
248✔
1449
                        return err
×
1450
                }
×
1451

1452
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
248✔
1453
                        pruneLogBucket,
248✔
1454
                )
248✔
1455
                if err != nil {
248✔
1456
                        return err
×
1457
                }
×
1458

1459
                // With the graph pruned, add a new entry to the prune log,
1460
                // which can be used to check if the graph is fully synced with
1461
                // the current UTXO state.
1462
                var blockHeightBytes [4]byte
248✔
1463
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
248✔
1464

248✔
1465
                var newTip [pruneTipBytes]byte
248✔
1466
                copy(newTip[:], blockHash[:])
248✔
1467

248✔
1468
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
248✔
1469
                if err != nil {
248✔
1470
                        return err
×
1471
                }
×
1472

1473
                // Now that the graph has been pruned, we'll also attempt to
1474
                // prune any nodes that have had a channel closed within the
1475
                // latest block.
1476
                return c.pruneGraphNodes(nodes, edgeIndex)
248✔
1477
        }, func() {
248✔
1478
                chansClosed = nil
248✔
1479
        })
248✔
1480
        if err != nil {
248✔
1481
                return nil, err
×
1482
        }
×
1483

1484
        for _, channel := range chansClosed {
270✔
1485
                c.rejectCache.remove(channel.ChannelID)
22✔
1486
                c.chanCache.remove(channel.ChannelID)
22✔
1487
        }
22✔
1488

1489
        if c.graphCache != nil {
496✔
1490
                log.Debugf("Pruned graph, cache now has %s",
248✔
1491
                        c.graphCache.Stats())
248✔
1492
        }
248✔
1493

1494
        return chansClosed, nil
248✔
1495
}
1496

1497
// PruneGraphNodes is a garbage collection method which attempts to prune out
1498
// any nodes from the channel graph that are currently unconnected. This ensure
1499
// that we only maintain a graph of reachable nodes. In the event that a pruned
1500
// node gains more channels, it will be re-added back to the graph.
1501
func (c *ChannelGraph) PruneGraphNodes() error {
25✔
1502
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
50✔
1503
                nodes := tx.ReadWriteBucket(nodeBucket)
25✔
1504
                if nodes == nil {
25✔
1505
                        return ErrGraphNodesNotFound
×
1506
                }
×
1507
                edges := tx.ReadWriteBucket(edgeBucket)
25✔
1508
                if edges == nil {
25✔
1509
                        return ErrGraphNotFound
×
1510
                }
×
1511
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
25✔
1512
                if edgeIndex == nil {
25✔
1513
                        return ErrGraphNoEdgesFound
×
1514
                }
×
1515

1516
                return c.pruneGraphNodes(nodes, edgeIndex)
25✔
1517
        }, func() {})
25✔
1518
}
1519

1520
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1521
// channel closed within the current block. If the node still has existing
1522
// channels in the graph, this will act as a no-op.
1523
func (c *ChannelGraph) pruneGraphNodes(nodes kvdb.RwBucket,
1524
        edgeIndex kvdb.RwBucket) error {
271✔
1525

271✔
1526
        log.Trace("Pruning nodes from graph with no open channels")
271✔
1527

271✔
1528
        // We'll retrieve the graph's source node to ensure we don't remove it
271✔
1529
        // even if it no longer has any open channels.
271✔
1530
        sourceNode, err := c.sourceNode(nodes)
271✔
1531
        if err != nil {
271✔
1532
                return err
×
1533
        }
×
1534

1535
        // We'll use this map to keep count the number of references to a node
1536
        // in the graph. A node should only be removed once it has no more
1537
        // references in the graph.
1538
        nodeRefCounts := make(map[[33]byte]int)
271✔
1539
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,594✔
1540
                // If this is the source key, then we skip this
1,323✔
1541
                // iteration as the value for this key is a pubKey
1,323✔
1542
                // rather than raw node information.
1,323✔
1543
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,132✔
1544
                        return nil
809✔
1545
                }
809✔
1546

1547
                var nodePub [33]byte
516✔
1548
                copy(nodePub[:], pubKey)
516✔
1549
                nodeRefCounts[nodePub] = 0
516✔
1550

516✔
1551
                return nil
516✔
1552
        })
1553
        if err != nil {
271✔
1554
                return err
×
1555
        }
×
1556

1557
        // To ensure we never delete the source node, we'll start off by
1558
        // bumping its ref count to 1.
1559
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
271✔
1560

271✔
1561
        // Next, we'll run through the edgeIndex which maps a channel ID to the
271✔
1562
        // edge info. We'll use this scan to populate our reference count map
271✔
1563
        // above.
271✔
1564
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
465✔
1565
                // The first 66 bytes of the edge info contain the pubkeys of
194✔
1566
                // the nodes that this edge attaches. We'll extract them, and
194✔
1567
                // add them to the ref count map.
194✔
1568
                var node1, node2 [33]byte
194✔
1569
                copy(node1[:], edgeInfoBytes[:33])
194✔
1570
                copy(node2[:], edgeInfoBytes[33:])
194✔
1571

194✔
1572
                // With the nodes extracted, we'll increase the ref count of
194✔
1573
                // each of the nodes.
194✔
1574
                nodeRefCounts[node1]++
194✔
1575
                nodeRefCounts[node2]++
194✔
1576

194✔
1577
                return nil
194✔
1578
        })
194✔
1579
        if err != nil {
271✔
1580
                return err
×
1581
        }
×
1582

1583
        // Finally, we'll make a second pass over the set of nodes, and delete
1584
        // any nodes that have a ref count of zero.
1585
        var numNodesPruned int
271✔
1586
        for nodePubKey, refCount := range nodeRefCounts {
787✔
1587
                // If the ref count of the node isn't zero, then we can safely
516✔
1588
                // skip it as it still has edges to or from it within the
516✔
1589
                // graph.
516✔
1590
                if refCount != 0 {
964✔
1591
                        continue
448✔
1592
                }
1593

1594
                if c.graphCache != nil {
140✔
1595
                        c.graphCache.RemoveNode(nodePubKey)
70✔
1596
                }
70✔
1597

1598
                // If we reach this point, then there are no longer any edges
1599
                // that connect this node, so we can delete it.
1600
                err := c.deleteLightningNode(nodes, nodePubKey[:])
70✔
1601
                if err != nil {
70✔
1602
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1603
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1604

×
1605
                                log.Warnf("Unable to prune node %x from the "+
×
1606
                                        "graph: %v", nodePubKey, err)
×
1607
                                continue
×
1608
                        }
1609

1610
                        return err
×
1611
                }
1612

1613
                log.Infof("Pruned unconnected node %x from channel graph",
70✔
1614
                        nodePubKey[:])
70✔
1615

70✔
1616
                numNodesPruned++
70✔
1617
        }
1618

1619
        if numNodesPruned > 0 {
325✔
1620
                log.Infof("Pruned %v unconnected nodes from the channel graph",
54✔
1621
                        numNodesPruned)
54✔
1622
        }
54✔
1623

1624
        return nil
271✔
1625
}
1626

1627
// DisconnectBlockAtHeight is used to indicate that the block specified
1628
// by the passed height has been disconnected from the main chain. This
1629
// will "rewind" the graph back to the height below, deleting channels
1630
// that are no longer confirmed from the graph. The prune log will be
1631
// set to the last prune height valid for the remaining chain.
1632
// Channels that were removed from the graph resulting from the
1633
// disconnected block are returned.
1634
func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) (
1635
        []*models.ChannelEdgeInfo, error) {
164✔
1636

164✔
1637
        // Every channel having a ShortChannelID starting at 'height'
164✔
1638
        // will no longer be confirmed.
164✔
1639
        startShortChanID := lnwire.ShortChannelID{
164✔
1640
                BlockHeight: height,
164✔
1641
        }
164✔
1642

164✔
1643
        // Delete everything after this height from the db up until the
164✔
1644
        // SCID alias range.
164✔
1645
        endShortChanID := aliasmgr.StartingAlias
164✔
1646

164✔
1647
        // The block height will be the 3 first bytes of the channel IDs.
164✔
1648
        var chanIDStart [8]byte
164✔
1649
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
164✔
1650
        var chanIDEnd [8]byte
164✔
1651
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
164✔
1652

164✔
1653
        c.cacheMu.Lock()
164✔
1654
        defer c.cacheMu.Unlock()
164✔
1655

164✔
1656
        // Keep track of the channels that are removed from the graph.
164✔
1657
        var removedChans []*models.ChannelEdgeInfo
164✔
1658

164✔
1659
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
328✔
1660
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
164✔
1661
                if err != nil {
164✔
1662
                        return err
×
1663
                }
×
1664
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
164✔
1665
                if err != nil {
164✔
1666
                        return err
×
1667
                }
×
1668
                chanIndex, err := edges.CreateBucketIfNotExists(
164✔
1669
                        channelPointBucket,
164✔
1670
                )
164✔
1671
                if err != nil {
164✔
1672
                        return err
×
1673
                }
×
1674
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
164✔
1675
                if err != nil {
164✔
1676
                        return err
×
1677
                }
×
1678

1679
                // Scan from chanIDStart to chanIDEnd, deleting every
1680
                // found edge.
1681
                // NOTE: we must delete the edges after the cursor loop, since
1682
                // modifying the bucket while traversing is not safe.
1683
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1684
                // so that the StartingAlias itself isn't deleted.
1685
                var keys [][]byte
164✔
1686
                cursor := edgeIndex.ReadWriteCursor()
164✔
1687

164✔
1688
                //nolint:ll
164✔
1689
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
164✔
1690
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
257✔
1691
                        edgeInfoReader := bytes.NewReader(v)
93✔
1692
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
93✔
1693
                        if err != nil {
93✔
1694
                                return err
×
1695
                        }
×
1696

1697
                        keys = append(keys, k)
93✔
1698
                        removedChans = append(removedChans, &edgeInfo)
93✔
1699
                }
1700

1701
                for _, k := range keys {
257✔
1702
                        err = c.delChannelEdgeUnsafe(
93✔
1703
                                edges, edgeIndex, chanIndex, zombieIndex,
93✔
1704
                                k, false, false,
93✔
1705
                        )
93✔
1706
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
93✔
1707
                                return err
×
1708
                        }
×
1709
                }
1710

1711
                // Delete all the entries in the prune log having a height
1712
                // greater or equal to the block disconnected.
1713
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
164✔
1714
                if err != nil {
164✔
1715
                        return err
×
1716
                }
×
1717

1718
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
164✔
1719
                        pruneLogBucket,
164✔
1720
                )
164✔
1721
                if err != nil {
164✔
1722
                        return err
×
1723
                }
×
1724

1725
                var pruneKeyStart [4]byte
164✔
1726
                byteOrder.PutUint32(pruneKeyStart[:], height)
164✔
1727

164✔
1728
                var pruneKeyEnd [4]byte
164✔
1729
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
164✔
1730

164✔
1731
                // To avoid modifying the bucket while traversing, we delete
164✔
1732
                // the keys in a second loop.
164✔
1733
                var pruneKeys [][]byte
164✔
1734
                pruneCursor := pruneBucket.ReadWriteCursor()
164✔
1735
                //nolint:ll
164✔
1736
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
164✔
1737
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
266✔
1738
                        pruneKeys = append(pruneKeys, k)
102✔
1739
                }
102✔
1740

1741
                for _, k := range pruneKeys {
266✔
1742
                        if err := pruneBucket.Delete(k); err != nil {
102✔
1743
                                return err
×
1744
                        }
×
1745
                }
1746

1747
                return nil
164✔
1748
        }, func() {
164✔
1749
                removedChans = nil
164✔
1750
        }); err != nil {
164✔
1751
                return nil, err
×
1752
        }
×
1753

1754
        for _, channel := range removedChans {
257✔
1755
                c.rejectCache.remove(channel.ChannelID)
93✔
1756
                c.chanCache.remove(channel.ChannelID)
93✔
1757
        }
93✔
1758

1759
        return removedChans, nil
164✔
1760
}
1761

1762
// PruneTip returns the block height and hash of the latest block that has been
1763
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1764
// to tell if the graph is currently in sync with the current best known UTXO
1765
// state.
1766
func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error) {
55✔
1767
        var (
55✔
1768
                tipHash   chainhash.Hash
55✔
1769
                tipHeight uint32
55✔
1770
        )
55✔
1771

55✔
1772
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
110✔
1773
                graphMeta := tx.ReadBucket(graphMetaBucket)
55✔
1774
                if graphMeta == nil {
55✔
1775
                        return ErrGraphNotFound
×
1776
                }
×
1777
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
55✔
1778
                if pruneBucket == nil {
55✔
1779
                        return ErrGraphNeverPruned
×
1780
                }
×
1781

1782
                pruneCursor := pruneBucket.ReadCursor()
55✔
1783

55✔
1784
                // The prune key with the largest block height will be our
55✔
1785
                // prune tip.
55✔
1786
                k, v := pruneCursor.Last()
55✔
1787
                if k == nil {
75✔
1788
                        return ErrGraphNeverPruned
20✔
1789
                }
20✔
1790

1791
                // Once we have the prune tip, the value will be the block hash,
1792
                // and the key the block height.
1793
                copy(tipHash[:], v[:])
37✔
1794
                tipHeight = byteOrder.Uint32(k[:])
37✔
1795

37✔
1796
                return nil
37✔
1797
        }, func() {})
55✔
1798
        if err != nil {
75✔
1799
                return nil, 0, err
20✔
1800
        }
20✔
1801

1802
        return &tipHash, tipHeight, nil
37✔
1803
}
1804

1805
// DeleteChannelEdges removes edges with the given channel IDs from the
1806
// database and marks them as zombies. This ensures that we're unable to re-add
1807
// it to our database once again. If an edge does not exist within the
1808
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1809
// true, then when we mark these edges as zombies, we'll set up the keys such
1810
// that we require the node that failed to send the fresh update to be the one
1811
// that resurrects the channel from its zombie state. The markZombie bool
1812
// denotes whether or not to mark the channel as a zombie.
1813
func (c *ChannelGraph) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1814
        chanIDs ...uint64) error {
144✔
1815

144✔
1816
        // TODO(roasbeef): possibly delete from node bucket if node has no more
144✔
1817
        // channels
144✔
1818
        // TODO(roasbeef): don't delete both edges?
144✔
1819

144✔
1820
        c.cacheMu.Lock()
144✔
1821
        defer c.cacheMu.Unlock()
144✔
1822

144✔
1823
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
288✔
1824
                edges := tx.ReadWriteBucket(edgeBucket)
144✔
1825
                if edges == nil {
144✔
1826
                        return ErrEdgeNotFound
×
1827
                }
×
1828
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
144✔
1829
                if edgeIndex == nil {
144✔
1830
                        return ErrEdgeNotFound
×
1831
                }
×
1832
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
144✔
1833
                if chanIndex == nil {
144✔
1834
                        return ErrEdgeNotFound
×
1835
                }
×
1836
                nodes := tx.ReadWriteBucket(nodeBucket)
144✔
1837
                if nodes == nil {
144✔
1838
                        return ErrGraphNodeNotFound
×
1839
                }
×
1840
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
144✔
1841
                if err != nil {
144✔
1842
                        return err
×
1843
                }
×
1844

1845
                var rawChanID [8]byte
144✔
1846
                for _, chanID := range chanIDs {
232✔
1847
                        byteOrder.PutUint64(rawChanID[:], chanID)
88✔
1848
                        err := c.delChannelEdgeUnsafe(
88✔
1849
                                edges, edgeIndex, chanIndex, zombieIndex,
88✔
1850
                                rawChanID[:], markZombie, strictZombiePruning,
88✔
1851
                        )
88✔
1852
                        if err != nil {
149✔
1853
                                return err
61✔
1854
                        }
61✔
1855
                }
1856

1857
                return nil
83✔
1858
        }, func() {})
144✔
1859
        if err != nil {
205✔
1860
                return err
61✔
1861
        }
61✔
1862

1863
        for _, chanID := range chanIDs {
110✔
1864
                c.rejectCache.remove(chanID)
27✔
1865
                c.chanCache.remove(chanID)
27✔
1866
        }
27✔
1867

1868
        return nil
83✔
1869
}
1870

1871
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1872
// passed channel point (outpoint). If the passed channel doesn't exist within
1873
// the database, then ErrEdgeNotFound is returned.
1874
func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1875
        var chanID uint64
3✔
1876
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1877
                var err error
3✔
1878
                chanID, err = getChanID(tx, chanPoint)
3✔
1879
                return err
3✔
1880
        }, func() {
6✔
1881
                chanID = 0
3✔
1882
        }); err != nil {
5✔
1883
                return 0, err
2✔
1884
        }
2✔
1885

1886
        return chanID, nil
3✔
1887
}
1888

1889
// getChanID returns the assigned channel ID for a given channel point.
1890
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1891
        var b bytes.Buffer
3✔
1892
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1893
                return 0, err
×
1894
        }
×
1895

1896
        edges := tx.ReadBucket(edgeBucket)
3✔
1897
        if edges == nil {
3✔
1898
                return 0, ErrGraphNoEdgesFound
×
1899
        }
×
1900
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1901
        if chanIndex == nil {
3✔
1902
                return 0, ErrGraphNoEdgesFound
×
1903
        }
×
1904

1905
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1906
        if chanIDBytes == nil {
5✔
1907
                return 0, ErrEdgeNotFound
2✔
1908
        }
2✔
1909

1910
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1911

3✔
1912
        return chanID, nil
3✔
1913
}
1914

1915
// TODO(roasbeef): allow updates to use Batch?
1916

1917
// HighestChanID returns the "highest" known channel ID in the channel graph.
1918
// This represents the "newest" channel from the PoV of the chain. This method
1919
// can be used by peers to quickly determine if they're graphs are in sync.
1920
func (c *ChannelGraph) HighestChanID() (uint64, error) {
5✔
1921
        var cid uint64
5✔
1922

5✔
1923
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
1924
                edges := tx.ReadBucket(edgeBucket)
5✔
1925
                if edges == nil {
5✔
1926
                        return ErrGraphNoEdgesFound
×
1927
                }
×
1928
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
5✔
1929
                if edgeIndex == nil {
5✔
1930
                        return ErrGraphNoEdgesFound
×
1931
                }
×
1932

1933
                // In order to find the highest chan ID, we'll fetch a cursor
1934
                // and use that to seek to the "end" of our known rage.
1935
                cidCursor := edgeIndex.ReadCursor()
5✔
1936

5✔
1937
                lastChanID, _ := cidCursor.Last()
5✔
1938

5✔
1939
                // If there's no key, then this means that we don't actually
5✔
1940
                // know of any channels, so we'll return a predicable error.
5✔
1941
                if lastChanID == nil {
8✔
1942
                        return ErrGraphNoEdgesFound
3✔
1943
                }
3✔
1944

1945
                // Otherwise, we'll de serialize the channel ID and return it
1946
                // to the caller.
1947
                cid = byteOrder.Uint64(lastChanID)
4✔
1948
                return nil
4✔
1949
        }, func() {
5✔
1950
                cid = 0
5✔
1951
        })
5✔
1952
        if err != nil && err != ErrGraphNoEdgesFound {
5✔
1953
                return 0, err
×
1954
        }
×
1955

1956
        return cid, nil
5✔
1957
}
1958

1959
// ChannelEdge represents the complete set of information for a channel edge in
1960
// the known channel graph. This struct couples the core information of the
1961
// edge as well as each of the known advertised edge policies.
1962
type ChannelEdge struct {
1963
        // Info contains all the static information describing the channel.
1964
        Info *models.ChannelEdgeInfo
1965

1966
        // Policy1 points to the "first" edge policy of the channel containing
1967
        // the dynamic information required to properly route through the edge.
1968
        Policy1 *models.ChannelEdgePolicy
1969

1970
        // Policy2 points to the "second" edge policy of the channel containing
1971
        // the dynamic information required to properly route through the edge.
1972
        Policy2 *models.ChannelEdgePolicy
1973

1974
        // Node1 is "node 1" in the channel. This is the node that would have
1975
        // produced Policy1 if it exists.
1976
        Node1 *models.LightningNode
1977

1978
        // Node2 is "node 2" in the channel. This is the node that would have
1979
        // produced Policy2 if it exists.
1980
        Node2 *models.LightningNode
1981
}
1982

1983
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1984
// one edge that has an update timestamp within the specified horizon.
1985
func (c *ChannelGraph) ChanUpdatesInHorizon(startTime,
1986
        endTime time.Time) ([]ChannelEdge, error) {
143✔
1987

143✔
1988
        // To ensure we don't return duplicate ChannelEdges, we'll use an
143✔
1989
        // additional map to keep track of the edges already seen to prevent
143✔
1990
        // re-adding it.
143✔
1991
        var edgesSeen map[uint64]struct{}
143✔
1992
        var edgesToCache map[uint64]ChannelEdge
143✔
1993
        var edgesInHorizon []ChannelEdge
143✔
1994

143✔
1995
        c.cacheMu.Lock()
143✔
1996
        defer c.cacheMu.Unlock()
143✔
1997

143✔
1998
        var hits int
143✔
1999
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
286✔
2000
                edges := tx.ReadBucket(edgeBucket)
143✔
2001
                if edges == nil {
143✔
2002
                        return ErrGraphNoEdgesFound
×
2003
                }
×
2004
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
143✔
2005
                if edgeIndex == nil {
143✔
2006
                        return ErrGraphNoEdgesFound
×
2007
                }
×
2008
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
143✔
2009
                if edgeUpdateIndex == nil {
143✔
2010
                        return ErrGraphNoEdgesFound
×
2011
                }
×
2012

2013
                nodes := tx.ReadBucket(nodeBucket)
143✔
2014
                if nodes == nil {
143✔
2015
                        return ErrGraphNodesNotFound
×
2016
                }
×
2017

2018
                // We'll now obtain a cursor to perform a range query within
2019
                // the index to find all channels within the horizon.
2020
                updateCursor := edgeUpdateIndex.ReadCursor()
143✔
2021

143✔
2022
                var startTimeBytes, endTimeBytes [8 + 8]byte
143✔
2023
                byteOrder.PutUint64(
143✔
2024
                        startTimeBytes[:8], uint64(startTime.Unix()),
143✔
2025
                )
143✔
2026
                byteOrder.PutUint64(
143✔
2027
                        endTimeBytes[:8], uint64(endTime.Unix()),
143✔
2028
                )
143✔
2029

143✔
2030
                // With our start and end times constructed, we'll step through
143✔
2031
                // the index collecting the info and policy of each update of
143✔
2032
                // each channel that has a last update within the time range.
143✔
2033
                //
143✔
2034
                //nolint:ll
143✔
2035
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
143✔
2036
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
191✔
2037

48✔
2038
                        // We have a new eligible entry, so we'll slice of the
48✔
2039
                        // chan ID so we can query it in the DB.
48✔
2040
                        chanID := indexKey[8:]
48✔
2041

48✔
2042
                        // If we've already retrieved the info and policies for
48✔
2043
                        // this edge, then we can skip it as we don't need to do
48✔
2044
                        // so again.
48✔
2045
                        chanIDInt := byteOrder.Uint64(chanID)
48✔
2046
                        if _, ok := edgesSeen[chanIDInt]; ok {
67✔
2047
                                continue
19✔
2048
                        }
2049

2050
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
40✔
2051
                                hits++
11✔
2052
                                edgesSeen[chanIDInt] = struct{}{}
11✔
2053
                                edgesInHorizon = append(edgesInHorizon, channel)
11✔
2054
                                continue
11✔
2055
                        }
2056

2057
                        // First, we'll fetch the static edge information.
2058
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
20✔
2059
                        if err != nil {
20✔
2060
                                chanID := byteOrder.Uint64(chanID)
×
2061
                                return fmt.Errorf("unable to fetch info for "+
×
2062
                                        "edge with chan_id=%v: %v", chanID, err)
×
2063
                        }
×
2064

2065
                        // With the static information obtained, we'll now
2066
                        // fetch the dynamic policy info.
2067
                        edge1, edge2, err := fetchChanEdgePolicies(
20✔
2068
                                edgeIndex, edges, chanID,
20✔
2069
                        )
20✔
2070
                        if err != nil {
20✔
2071
                                chanID := byteOrder.Uint64(chanID)
×
2072
                                return fmt.Errorf("unable to fetch policies "+
×
2073
                                        "for edge with chan_id=%v: %v", chanID,
×
2074
                                        err)
×
2075
                        }
×
2076

2077
                        node1, err := fetchLightningNode(
20✔
2078
                                nodes, edgeInfo.NodeKey1Bytes[:],
20✔
2079
                        )
20✔
2080
                        if err != nil {
20✔
2081
                                return err
×
2082
                        }
×
2083

2084
                        node2, err := fetchLightningNode(
20✔
2085
                                nodes, edgeInfo.NodeKey2Bytes[:],
20✔
2086
                        )
20✔
2087
                        if err != nil {
20✔
2088
                                return err
×
2089
                        }
×
2090

2091
                        // Finally, we'll collate this edge with the rest of
2092
                        // edges to be returned.
2093
                        edgesSeen[chanIDInt] = struct{}{}
20✔
2094
                        channel := ChannelEdge{
20✔
2095
                                Info:    &edgeInfo,
20✔
2096
                                Policy1: edge1,
20✔
2097
                                Policy2: edge2,
20✔
2098
                                Node1:   &node1,
20✔
2099
                                Node2:   &node2,
20✔
2100
                        }
20✔
2101
                        edgesInHorizon = append(edgesInHorizon, channel)
20✔
2102
                        edgesToCache[chanIDInt] = channel
20✔
2103
                }
2104

2105
                return nil
143✔
2106
        }, func() {
143✔
2107
                edgesSeen = make(map[uint64]struct{})
143✔
2108
                edgesToCache = make(map[uint64]ChannelEdge)
143✔
2109
                edgesInHorizon = nil
143✔
2110
        })
143✔
2111
        switch {
143✔
2112
        case err == ErrGraphNoEdgesFound:
×
2113
                fallthrough
×
2114
        case err == ErrGraphNodesNotFound:
×
2115
                break
×
2116

2117
        case err != nil:
×
2118
                return nil, err
×
2119
        }
2120

2121
        // Insert any edges loaded from disk into the cache.
2122
        for chanid, channel := range edgesToCache {
163✔
2123
                c.chanCache.insert(chanid, channel)
20✔
2124
        }
20✔
2125

2126
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
143✔
2127
                float64(hits)/float64(len(edgesInHorizon)), hits,
143✔
2128
                len(edgesInHorizon))
143✔
2129

143✔
2130
        return edgesInHorizon, nil
143✔
2131
}
2132

2133
// NodeUpdatesInHorizon returns all the known lightning node which have an
2134
// update timestamp within the passed range. This method can be used by two
2135
// nodes to quickly determine if they have the same set of up to date node
2136
// announcements.
2137
func (c *ChannelGraph) NodeUpdatesInHorizon(startTime,
2138
        endTime time.Time) ([]models.LightningNode, error) {
10✔
2139

10✔
2140
        var nodesInHorizon []models.LightningNode
10✔
2141

10✔
2142
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
20✔
2143
                nodes := tx.ReadBucket(nodeBucket)
10✔
2144
                if nodes == nil {
10✔
2145
                        return ErrGraphNodesNotFound
×
2146
                }
×
2147

2148
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
10✔
2149
                if nodeUpdateIndex == nil {
10✔
2150
                        return ErrGraphNodesNotFound
×
2151
                }
×
2152

2153
                // We'll now obtain a cursor to perform a range query within
2154
                // the index to find all node announcements within the horizon.
2155
                updateCursor := nodeUpdateIndex.ReadCursor()
10✔
2156

10✔
2157
                var startTimeBytes, endTimeBytes [8 + 33]byte
10✔
2158
                byteOrder.PutUint64(
10✔
2159
                        startTimeBytes[:8], uint64(startTime.Unix()),
10✔
2160
                )
10✔
2161
                byteOrder.PutUint64(
10✔
2162
                        endTimeBytes[:8], uint64(endTime.Unix()),
10✔
2163
                )
10✔
2164

10✔
2165
                // With our start and end times constructed, we'll step through
10✔
2166
                // the index collecting info for each node within the time
10✔
2167
                // range.
10✔
2168
                //
10✔
2169
                //nolint:ll
10✔
2170
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
10✔
2171
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
41✔
2172

31✔
2173
                        nodePub := indexKey[8:]
31✔
2174
                        node, err := fetchLightningNode(nodes, nodePub)
31✔
2175
                        if err != nil {
31✔
2176
                                return err
×
2177
                        }
×
2178

2179
                        nodesInHorizon = append(nodesInHorizon, node)
31✔
2180
                }
2181

2182
                return nil
10✔
2183
        }, func() {
10✔
2184
                nodesInHorizon = nil
10✔
2185
        })
10✔
2186
        switch {
10✔
2187
        case err == ErrGraphNoEdgesFound:
×
2188
                fallthrough
×
2189
        case err == ErrGraphNodesNotFound:
×
2190
                break
×
2191

2192
        case err != nil:
×
2193
                return nil, err
×
2194
        }
2195

2196
        return nodesInHorizon, nil
10✔
2197
}
2198

2199
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2200
// ID's that we don't know and are not known zombies of the passed set. In other
2201
// words, we perform a set difference of our set of chan ID's and the ones
2202
// passed in. This method can be used by callers to determine the set of
2203
// channels another peer knows of that we don't.
2204
func (c *ChannelGraph) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo,
2205
        isZombieChan func(time.Time, time.Time) bool) ([]uint64, error) {
117✔
2206

117✔
2207
        var newChanIDs []uint64
117✔
2208

117✔
2209
        c.cacheMu.Lock()
117✔
2210
        defer c.cacheMu.Unlock()
117✔
2211

117✔
2212
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
234✔
2213
                edges := tx.ReadBucket(edgeBucket)
117✔
2214
                if edges == nil {
117✔
2215
                        return ErrGraphNoEdgesFound
×
2216
                }
×
2217
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
117✔
2218
                if edgeIndex == nil {
117✔
2219
                        return ErrGraphNoEdgesFound
×
2220
                }
×
2221

2222
                // Fetch the zombie index, it may not exist if no edges have
2223
                // ever been marked as zombies. If the index has been
2224
                // initialized, we will use it later to skip known zombie edges.
2225
                zombieIndex := edges.NestedReadBucket(zombieBucket)
117✔
2226

117✔
2227
                // We'll run through the set of chanIDs and collate only the
117✔
2228
                // set of channel that are unable to be found within our db.
117✔
2229
                var cidBytes [8]byte
117✔
2230
                for _, info := range chansInfo {
224✔
2231
                        scid := info.ShortChannelID.ToUint64()
107✔
2232
                        byteOrder.PutUint64(cidBytes[:], scid)
107✔
2233

107✔
2234
                        // If the edge is already known, skip it.
107✔
2235
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
129✔
2236
                                continue
22✔
2237
                        }
2238

2239
                        // If the edge is a known zombie, skip it.
2240
                        if zombieIndex != nil {
174✔
2241
                                isZombie, _, _ := isZombieEdge(
87✔
2242
                                        zombieIndex, scid,
87✔
2243
                                )
87✔
2244

87✔
2245
                                // TODO(ziggie): Make sure that for the strict
87✔
2246
                                // pruning case we compare the pubkeys and
87✔
2247
                                // whether the right timestamp is not older than
87✔
2248
                                // the `ChannelPruneExpiry`.
87✔
2249
                                //
87✔
2250
                                // NOTE: The timestamp data has no verification
87✔
2251
                                // attached to it in the `ReplyChannelRange` msg
87✔
2252
                                // so we are trusting this data at this point.
87✔
2253
                                // However it is not critical because we are
87✔
2254
                                // just removing the channel from the db when
87✔
2255
                                // the timestamps are more recent. During the
87✔
2256
                                // querying of the gossip msg verification
87✔
2257
                                // happens as usual.
87✔
2258
                                // However we should start punishing peers when
87✔
2259
                                // they don't provide us honest data ?
87✔
2260
                                isStillZombie := isZombieChan(
87✔
2261
                                        info.Node1UpdateTimestamp,
87✔
2262
                                        info.Node2UpdateTimestamp,
87✔
2263
                                )
87✔
2264

87✔
2265
                                switch {
87✔
2266
                                // If the edge is a known zombie and if we
2267
                                // would still consider it a zombie given the
2268
                                // latest update timestamps, then we skip this
2269
                                // channel.
2270
                                case isZombie && isStillZombie:
27✔
2271
                                        continue
27✔
2272

2273
                                // Otherwise, if we have marked it as a zombie
2274
                                // but the latest update timestamps could bring
2275
                                // it back from the dead, then we mark it alive,
2276
                                // and we let it be added to the set of IDs to
2277
                                // query our peer for.
2278
                                case isZombie && !isStillZombie:
20✔
2279
                                        err := c.markEdgeLiveUnsafe(tx, scid)
20✔
2280
                                        if err != nil {
20✔
2281
                                                return err
×
2282
                                        }
×
2283
                                }
2284
                        }
2285

2286
                        newChanIDs = append(newChanIDs, scid)
60✔
2287
                }
2288

2289
                return nil
117✔
2290
        }, func() {
117✔
2291
                newChanIDs = nil
117✔
2292
        })
117✔
2293
        switch {
117✔
2294
        // If we don't know of any edges yet, then we'll return the entire set
2295
        // of chan IDs specified.
2296
        case err == ErrGraphNoEdgesFound:
×
2297
                ogChanIDs := make([]uint64, len(chansInfo))
×
2298
                for i, info := range chansInfo {
×
2299
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2300
                }
×
2301

2302
                return ogChanIDs, nil
×
2303

2304
        case err != nil:
×
2305
                return nil, err
×
2306
        }
2307

2308
        return newChanIDs, nil
117✔
2309
}
2310

2311
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2312
// latest received channel updates for the channel.
2313
type ChannelUpdateInfo struct {
2314
        // ShortChannelID is the SCID identifier of the channel.
2315
        ShortChannelID lnwire.ShortChannelID
2316

2317
        // Node1UpdateTimestamp is the timestamp of the latest received update
2318
        // from the node 1 channel peer. This will be set to zero time if no
2319
        // update has yet been received from this node.
2320
        Node1UpdateTimestamp time.Time
2321

2322
        // Node2UpdateTimestamp is the timestamp of the latest received update
2323
        // from the node 2 channel peer. This will be set to zero time if no
2324
        // update has yet been received from this node.
2325
        Node2UpdateTimestamp time.Time
2326
}
2327

2328
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2329
// timestamps with zero seconds unix timestamp which equals
2330
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2331
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2332
        node2Timestamp time.Time) ChannelUpdateInfo {
220✔
2333

220✔
2334
        chanInfo := ChannelUpdateInfo{
220✔
2335
                ShortChannelID:       scid,
220✔
2336
                Node1UpdateTimestamp: node1Timestamp,
220✔
2337
                Node2UpdateTimestamp: node2Timestamp,
220✔
2338
        }
220✔
2339

220✔
2340
        if node1Timestamp.IsZero() {
430✔
2341
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
210✔
2342
        }
210✔
2343

2344
        if node2Timestamp.IsZero() {
430✔
2345
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
210✔
2346
        }
210✔
2347

2348
        return chanInfo
220✔
2349
}
2350

2351
// BlockChannelRange represents a range of channels for a given block height.
2352
type BlockChannelRange struct {
2353
        // Height is the height of the block all of the channels below were
2354
        // included in.
2355
        Height uint32
2356

2357
        // Channels is the list of channels identified by their short ID
2358
        // representation known to us that were included in the block height
2359
        // above. The list may include channel update timestamp information if
2360
        // requested.
2361
        Channels []ChannelUpdateInfo
2362
}
2363

2364
// FilterChannelRange returns the channel ID's of all known channels which were
2365
// mined in a block height within the passed range. The channel IDs are grouped
2366
// by their common block height. This method can be used to quickly share with a
2367
// peer the set of channels we know of within a particular range to catch them
2368
// up after a period of time offline. If withTimestamps is true then the
2369
// timestamp info of the latest received channel update messages of the channel
2370
// will be included in the response.
2371
func (c *ChannelGraph) FilterChannelRange(startHeight,
2372
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
13✔
2373

13✔
2374
        startChanID := &lnwire.ShortChannelID{
13✔
2375
                BlockHeight: startHeight,
13✔
2376
        }
13✔
2377

13✔
2378
        endChanID := lnwire.ShortChannelID{
13✔
2379
                BlockHeight: endHeight,
13✔
2380
                TxIndex:     math.MaxUint32 & 0x00ffffff,
13✔
2381
                TxPosition:  math.MaxUint16,
13✔
2382
        }
13✔
2383

13✔
2384
        // As we need to perform a range scan, we'll convert the starting and
13✔
2385
        // ending height to their corresponding values when encoded using short
13✔
2386
        // channel ID's.
13✔
2387
        var chanIDStart, chanIDEnd [8]byte
13✔
2388
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
13✔
2389
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
13✔
2390

13✔
2391
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
13✔
2392
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
26✔
2393
                edges := tx.ReadBucket(edgeBucket)
13✔
2394
                if edges == nil {
13✔
2395
                        return ErrGraphNoEdgesFound
×
2396
                }
×
2397
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
13✔
2398
                if edgeIndex == nil {
13✔
2399
                        return ErrGraphNoEdgesFound
×
2400
                }
×
2401

2402
                cursor := edgeIndex.ReadCursor()
13✔
2403

13✔
2404
                // We'll now iterate through the database, and find each
13✔
2405
                // channel ID that resides within the specified range.
13✔
2406
                //
13✔
2407
                //nolint:ll
13✔
2408
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
13✔
2409
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
59✔
2410
                        // Don't send alias SCIDs during gossip sync.
46✔
2411
                        edgeReader := bytes.NewReader(v)
46✔
2412
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
46✔
2413
                        if err != nil {
46✔
2414
                                return err
×
2415
                        }
×
2416

2417
                        if edgeInfo.AuthProof == nil {
48✔
2418
                                continue
2✔
2419
                        }
2420

2421
                        // This channel ID rests within the target range, so
2422
                        // we'll add it to our returned set.
2423
                        rawCid := byteOrder.Uint64(k)
46✔
2424
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
46✔
2425

46✔
2426
                        chanInfo := NewChannelUpdateInfo(
46✔
2427
                                cid, time.Time{}, time.Time{},
46✔
2428
                        )
46✔
2429

46✔
2430
                        if !withTimestamps {
68✔
2431
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2432
                                        channelsPerBlock[cid.BlockHeight],
22✔
2433
                                        chanInfo,
22✔
2434
                                )
22✔
2435

22✔
2436
                                continue
22✔
2437
                        }
2438

2439
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
24✔
2440

24✔
2441
                        rawPolicy := edges.Get(node1Key)
24✔
2442
                        if len(rawPolicy) != 0 {
33✔
2443
                                r := bytes.NewReader(rawPolicy)
9✔
2444

9✔
2445
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2446
                                if err != nil && !errors.Is(
9✔
2447
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2448
                                ) {
9✔
2449

×
2450
                                        return err
×
2451
                                }
×
2452

2453
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2454
                        }
2455

2456
                        rawPolicy = edges.Get(node2Key)
24✔
2457
                        if len(rawPolicy) != 0 {
33✔
2458
                                r := bytes.NewReader(rawPolicy)
9✔
2459

9✔
2460
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2461
                                if err != nil && !errors.Is(
9✔
2462
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2463
                                ) {
9✔
2464

×
2465
                                        return err
×
2466
                                }
×
2467

2468
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
9✔
2469
                        }
2470

2471
                        channelsPerBlock[cid.BlockHeight] = append(
24✔
2472
                                channelsPerBlock[cid.BlockHeight], chanInfo,
24✔
2473
                        )
24✔
2474
                }
2475

2476
                return nil
13✔
2477
        }, func() {
13✔
2478
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
13✔
2479
        })
13✔
2480

2481
        switch {
13✔
2482
        // If we don't know of any channels yet, then there's nothing to
2483
        // filter, so we'll return an empty slice.
2484
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
5✔
2485
                return nil, nil
5✔
2486

2487
        case err != nil:
×
2488
                return nil, err
×
2489
        }
2490

2491
        // Return the channel ranges in ascending block height order.
2492
        blocks := make([]uint32, 0, len(channelsPerBlock))
10✔
2493
        for block := range channelsPerBlock {
34✔
2494
                blocks = append(blocks, block)
24✔
2495
        }
24✔
2496
        sort.Slice(blocks, func(i, j int) bool {
29✔
2497
                return blocks[i] < blocks[j]
19✔
2498
        })
19✔
2499

2500
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
10✔
2501
        for _, block := range blocks {
34✔
2502
                channelRanges = append(channelRanges, BlockChannelRange{
24✔
2503
                        Height:   block,
24✔
2504
                        Channels: channelsPerBlock[block],
24✔
2505
                })
24✔
2506
        }
24✔
2507

2508
        return channelRanges, nil
10✔
2509
}
2510

2511
// FetchChanInfos returns the set of channel edges that correspond to the passed
2512
// channel ID's. If an edge is the query is unknown to the database, it will
2513
// skipped and the result will contain only those edges that exist at the time
2514
// of the query. This can be used to respond to peer queries that are seeking to
2515
// fill in gaps in their view of the channel graph.
2516
func (c *ChannelGraph) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
5✔
2517
        return c.fetchChanInfos(nil, chanIDs)
5✔
2518
}
5✔
2519

2520
// fetchChanInfos returns the set of channel edges that correspond to the passed
2521
// channel ID's. If an edge is the query is unknown to the database, it will
2522
// skipped and the result will contain only those edges that exist at the time
2523
// of the query. This can be used to respond to peer queries that are seeking to
2524
// fill in gaps in their view of the channel graph.
2525
//
2526
// NOTE: An optional transaction may be provided. If none is provided, then a
2527
// new one will be created.
2528
func (c *ChannelGraph) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2529
        []ChannelEdge, error) {
26✔
2530
        // TODO(roasbeef): sort cids?
26✔
2531

26✔
2532
        var (
26✔
2533
                chanEdges []ChannelEdge
26✔
2534
                cidBytes  [8]byte
26✔
2535
        )
26✔
2536

26✔
2537
        fetchChanInfos := func(tx kvdb.RTx) error {
52✔
2538
                edges := tx.ReadBucket(edgeBucket)
26✔
2539
                if edges == nil {
26✔
2540
                        return ErrGraphNoEdgesFound
×
2541
                }
×
2542
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
26✔
2543
                if edgeIndex == nil {
26✔
2544
                        return ErrGraphNoEdgesFound
×
2545
                }
×
2546
                nodes := tx.ReadBucket(nodeBucket)
26✔
2547
                if nodes == nil {
26✔
2548
                        return ErrGraphNotFound
×
2549
                }
×
2550

2551
                for _, cid := range chanIDs {
59✔
2552
                        byteOrder.PutUint64(cidBytes[:], cid)
33✔
2553

33✔
2554
                        // First, we'll fetch the static edge information. If
33✔
2555
                        // the edge is unknown, we will skip the edge and
33✔
2556
                        // continue gathering all known edges.
33✔
2557
                        edgeInfo, err := fetchChanEdgeInfo(
33✔
2558
                                edgeIndex, cidBytes[:],
33✔
2559
                        )
33✔
2560
                        switch {
33✔
2561
                        case errors.Is(err, ErrEdgeNotFound):
23✔
2562
                                continue
23✔
2563
                        case err != nil:
×
2564
                                return err
×
2565
                        }
2566

2567
                        // With the static information obtained, we'll now
2568
                        // fetch the dynamic policy info.
2569
                        edge1, edge2, err := fetchChanEdgePolicies(
10✔
2570
                                edgeIndex, edges, cidBytes[:],
10✔
2571
                        )
10✔
2572
                        if err != nil {
10✔
2573
                                return err
×
2574
                        }
×
2575

2576
                        node1, err := fetchLightningNode(
10✔
2577
                                nodes, edgeInfo.NodeKey1Bytes[:],
10✔
2578
                        )
10✔
2579
                        if err != nil {
10✔
2580
                                return err
×
2581
                        }
×
2582

2583
                        node2, err := fetchLightningNode(
10✔
2584
                                nodes, edgeInfo.NodeKey2Bytes[:],
10✔
2585
                        )
10✔
2586
                        if err != nil {
10✔
2587
                                return err
×
2588
                        }
×
2589

2590
                        chanEdges = append(chanEdges, ChannelEdge{
10✔
2591
                                Info:    &edgeInfo,
10✔
2592
                                Policy1: edge1,
10✔
2593
                                Policy2: edge2,
10✔
2594
                                Node1:   &node1,
10✔
2595
                                Node2:   &node2,
10✔
2596
                        })
10✔
2597
                }
2598
                return nil
26✔
2599
        }
2600

2601
        if tx == nil {
32✔
2602
                err := kvdb.View(c.db, fetchChanInfos, func() {
12✔
2603
                        chanEdges = nil
6✔
2604
                })
6✔
2605
                if err != nil {
6✔
2606
                        return nil, err
×
2607
                }
×
2608

2609
                return chanEdges, nil
6✔
2610
        }
2611

2612
        err := fetchChanInfos(tx)
20✔
2613
        if err != nil {
20✔
2614
                return nil, err
×
2615
        }
×
2616

2617
        return chanEdges, nil
20✔
2618
}
2619

2620
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2621
        edge1, edge2 *models.ChannelEdgePolicy) error {
138✔
2622

138✔
2623
        // First, we'll fetch the edge update index bucket which currently
138✔
2624
        // stores an entry for the channel we're about to delete.
138✔
2625
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
138✔
2626
        if updateIndex == nil {
138✔
2627
                // No edges in bucket, return early.
×
2628
                return nil
×
2629
        }
×
2630

2631
        // Now that we have the bucket, we'll attempt to construct a template
2632
        // for the index key: updateTime || chanid.
2633
        var indexKey [8 + 8]byte
138✔
2634
        byteOrder.PutUint64(indexKey[8:], chanID)
138✔
2635

138✔
2636
        // With the template constructed, we'll attempt to delete an entry that
138✔
2637
        // would have been created by both edges: we'll alternate the update
138✔
2638
        // times, as one may had overridden the other.
138✔
2639
        if edge1 != nil {
150✔
2640
                byteOrder.PutUint64(
12✔
2641
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
12✔
2642
                )
12✔
2643
                if err := updateIndex.Delete(indexKey[:]); err != nil {
12✔
2644
                        return err
×
2645
                }
×
2646
        }
2647

2648
        // We'll also attempt to delete the entry that may have been created by
2649
        // the second edge.
2650
        if edge2 != nil {
152✔
2651
                byteOrder.PutUint64(
14✔
2652
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
14✔
2653
                )
14✔
2654
                if err := updateIndex.Delete(indexKey[:]); err != nil {
14✔
2655
                        return err
×
2656
                }
×
2657
        }
2658

2659
        return nil
138✔
2660
}
2661

2662
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2663
// cache. It then goes on to delete any policy info and edge info for this
2664
// channel from the DB and finally, if isZombie is true, it will add an entry
2665
// for this channel in the zombie index.
2666
//
2667
// NOTE: this method MUST only be called if the cacheMu has already been
2668
// acquired.
2669
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2670
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2671
        strictZombie bool) error {
199✔
2672

199✔
2673
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
199✔
2674
        if err != nil {
260✔
2675
                return err
61✔
2676
        }
61✔
2677

2678
        if c.graphCache != nil {
276✔
2679
                c.graphCache.RemoveChannel(
138✔
2680
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
138✔
2681
                        edgeInfo.ChannelID,
138✔
2682
                )
138✔
2683
        }
138✔
2684

2685
        // We'll also remove the entry in the edge update index bucket before
2686
        // we delete the edges themselves so we can access their last update
2687
        // times.
2688
        cid := byteOrder.Uint64(chanID)
138✔
2689
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
138✔
2690
        if err != nil {
138✔
2691
                return err
×
2692
        }
×
2693
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
138✔
2694
        if err != nil {
138✔
2695
                return err
×
2696
        }
×
2697

2698
        // The edge key is of the format pubKey || chanID. First we construct
2699
        // the latter half, populating the channel ID.
2700
        var edgeKey [33 + 8]byte
138✔
2701
        copy(edgeKey[33:], chanID)
138✔
2702

138✔
2703
        // With the latter half constructed, copy over the first public key to
138✔
2704
        // delete the edge in this direction, then the second to delete the
138✔
2705
        // edge in the opposite direction.
138✔
2706
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
138✔
2707
        if edges.Get(edgeKey[:]) != nil {
276✔
2708
                if err := edges.Delete(edgeKey[:]); err != nil {
138✔
2709
                        return err
×
2710
                }
×
2711
        }
2712
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
138✔
2713
        if edges.Get(edgeKey[:]) != nil {
276✔
2714
                if err := edges.Delete(edgeKey[:]); err != nil {
138✔
2715
                        return err
×
2716
                }
×
2717
        }
2718

2719
        // As part of deleting the edge we also remove all disabled entries
2720
        // from the edgePolicyDisabledIndex bucket. We do that for both
2721
        // directions.
2722
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
138✔
2723
        if err != nil {
138✔
2724
                return err
×
2725
        }
×
2726
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
138✔
2727
        if err != nil {
138✔
2728
                return err
×
2729
        }
×
2730

2731
        // With the edge data deleted, we can purge the information from the two
2732
        // edge indexes.
2733
        if err := edgeIndex.Delete(chanID); err != nil {
138✔
2734
                return err
×
2735
        }
×
2736
        var b bytes.Buffer
138✔
2737
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
138✔
2738
                return err
×
2739
        }
×
2740
        if err := chanIndex.Delete(b.Bytes()); err != nil {
138✔
2741
                return err
×
2742
        }
×
2743

2744
        // Finally, we'll mark the edge as a zombie within our index if it's
2745
        // being removed due to the channel becoming a zombie. We do this to
2746
        // ensure we don't store unnecessary data for spent channels.
2747
        if !isZombie {
252✔
2748
                return nil
114✔
2749
        }
114✔
2750

2751
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
26✔
2752
        if strictZombie {
30✔
2753
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
4✔
2754
        }
4✔
2755

2756
        return markEdgeZombie(
26✔
2757
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
26✔
2758
        )
26✔
2759
}
2760

2761
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2762
// particular pair of channel policies. The return values are one of:
2763
//  1. (pubkey1, pubkey2)
2764
//  2. (pubkey1, blank)
2765
//  3. (blank, pubkey2)
2766
//
2767
// A blank pubkey means that corresponding node will be unable to resurrect a
2768
// channel on its own. For example, node1 may continue to publish recent
2769
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2770
// we don't want another fresh update from node1 to resurrect, as the edge can
2771
// only become live once node2 finally sends something recent.
2772
//
2773
// In the case where we have neither update, we allow either party to resurrect
2774
// the channel. If the channel were to be marked zombie again, it would be
2775
// marked with the correct lagging channel since we received an update from only
2776
// one side.
2777
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2778
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
4✔
2779

4✔
2780
        switch {
4✔
2781
        // If we don't have either edge policy, we'll return both pubkeys so
2782
        // that the channel can be resurrected by either party.
2783
        case e1 == nil && e2 == nil:
1✔
2784
                return info.NodeKey1Bytes, info.NodeKey2Bytes
1✔
2785

2786
        // If we're missing edge1, or if both edges are present but edge1 is
2787
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2788
        // means that only an update from edge1 will be able to resurrect the
2789
        // channel.
2790
        case e1 == nil || (e2 != nil && e1.LastUpdate.Before(e2.LastUpdate)):
1✔
2791
                return info.NodeKey1Bytes, [33]byte{}
1✔
2792

2793
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2794
        // return a blank pubkey for edge1. In this case, only an update from
2795
        // edge2 can resurect the channel.
2796
        default:
2✔
2797
                return [33]byte{}, info.NodeKey2Bytes
2✔
2798
        }
2799
}
2800

2801
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2802
// within the database for the referenced channel. The `flags` attribute within
2803
// the ChannelEdgePolicy determines which of the directed edges are being
2804
// updated. If the flag is 1, then the first node's information is being
2805
// updated, otherwise it's the second node's information. The node ordering is
2806
// determined by the lexicographical ordering of the identity public keys of the
2807
// nodes on either side of the channel.
2808
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2809
        op ...batch.SchedulerOption) error {
2,663✔
2810

2,663✔
2811
        var (
2,663✔
2812
                isUpdate1    bool
2,663✔
2813
                edgeNotFound bool
2,663✔
2814
        )
2,663✔
2815

2,663✔
2816
        r := &batch.Request{
2,663✔
2817
                Reset: func() {
5,326✔
2818
                        isUpdate1 = false
2,663✔
2819
                        edgeNotFound = false
2,663✔
2820
                },
2,663✔
2821
                Update: func(tx kvdb.RwTx) error {
2,663✔
2822
                        var err error
2,663✔
2823
                        isUpdate1, err = updateEdgePolicy(
2,663✔
2824
                                tx, edge, c.graphCache,
2,663✔
2825
                        )
2,663✔
2826

2,663✔
2827
                        if err != nil {
2,666✔
2828
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
3✔
2829
                        }
3✔
2830

2831
                        // Silence ErrEdgeNotFound so that the batch can
2832
                        // succeed, but propagate the error via local state.
2833
                        if errors.Is(err, ErrEdgeNotFound) {
2,666✔
2834
                                edgeNotFound = true
3✔
2835
                                return nil
3✔
2836
                        }
3✔
2837

2838
                        return err
2,660✔
2839
                },
2840
                OnCommit: func(err error) error {
2,663✔
2841
                        switch {
2,663✔
2842
                        case err != nil:
×
2843
                                return err
×
2844
                        case edgeNotFound:
3✔
2845
                                return ErrEdgeNotFound
3✔
2846
                        default:
2,660✔
2847
                                c.updateEdgeCache(edge, isUpdate1)
2,660✔
2848
                                return nil
2,660✔
2849
                        }
2850
                },
2851
        }
2852

2853
        for _, f := range op {
2,665✔
2854
                f(r)
2✔
2855
        }
2✔
2856

2857
        return c.chanScheduler.Execute(r)
2,663✔
2858
}
2859

2860
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2861
        isUpdate1 bool) {
2,660✔
2862

2,660✔
2863
        // If an entry for this channel is found in reject cache, we'll modify
2,660✔
2864
        // the entry with the updated timestamp for the direction that was just
2,660✔
2865
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,660✔
2866
        // during the next query for this edge.
2,660✔
2867
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,667✔
2868
                if isUpdate1 {
12✔
2869
                        entry.upd1Time = e.LastUpdate.Unix()
5✔
2870
                } else {
9✔
2871
                        entry.upd2Time = e.LastUpdate.Unix()
4✔
2872
                }
4✔
2873
                c.rejectCache.insert(e.ChannelID, entry)
7✔
2874
        }
2875

2876
        // If an entry for this channel is found in channel cache, we'll modify
2877
        // the entry with the updated policy for the direction that was just
2878
        // written. If the edge doesn't exist, we'll defer loading the info and
2879
        // policies and lazily read from disk during the next query.
2880
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,662✔
2881
                if isUpdate1 {
4✔
2882
                        channel.Policy1 = e
2✔
2883
                } else {
4✔
2884
                        channel.Policy2 = e
2✔
2885
                }
2✔
2886
                c.chanCache.insert(e.ChannelID, channel)
2✔
2887
        }
2888
}
2889

2890
// updateEdgePolicy attempts to update an edge's policy within the relevant
2891
// buckets using an existing database transaction. The returned boolean will be
2892
// true if the updated policy belongs to node1, and false if the policy belonged
2893
// to node2.
2894
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2895
        graphCache *GraphCache) (bool, error) {
2,663✔
2896

2,663✔
2897
        edges := tx.ReadWriteBucket(edgeBucket)
2,663✔
2898
        if edges == nil {
2,663✔
2899
                return false, ErrEdgeNotFound
×
2900
        }
×
2901
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,663✔
2902
        if edgeIndex == nil {
2,663✔
2903
                return false, ErrEdgeNotFound
×
2904
        }
×
2905

2906
        // Create the channelID key be converting the channel ID
2907
        // integer into a byte slice.
2908
        var chanID [8]byte
2,663✔
2909
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,663✔
2910

2,663✔
2911
        // With the channel ID, we then fetch the value storing the two
2,663✔
2912
        // nodes which connect this channel edge.
2,663✔
2913
        nodeInfo := edgeIndex.Get(chanID[:])
2,663✔
2914
        if nodeInfo == nil {
2,666✔
2915
                return false, ErrEdgeNotFound
3✔
2916
        }
3✔
2917

2918
        // Depending on the flags value passed above, either the first
2919
        // or second edge policy is being updated.
2920
        var fromNode, toNode []byte
2,660✔
2921
        var isUpdate1 bool
2,660✔
2922
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,994✔
2923
                fromNode = nodeInfo[:33]
1,334✔
2924
                toNode = nodeInfo[33:66]
1,334✔
2925
                isUpdate1 = true
1,334✔
2926
        } else {
2,662✔
2927
                fromNode = nodeInfo[33:66]
1,328✔
2928
                toNode = nodeInfo[:33]
1,328✔
2929
                isUpdate1 = false
1,328✔
2930
        }
1,328✔
2931

2932
        // Finally, with the direction of the edge being updated
2933
        // identified, we update the on-disk edge representation.
2934
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,660✔
2935
        if err != nil {
2,660✔
2936
                return false, err
×
2937
        }
×
2938

2939
        var (
2,660✔
2940
                fromNodePubKey route.Vertex
2,660✔
2941
                toNodePubKey   route.Vertex
2,660✔
2942
        )
2,660✔
2943
        copy(fromNodePubKey[:], fromNode)
2,660✔
2944
        copy(toNodePubKey[:], toNode)
2,660✔
2945

2,660✔
2946
        if graphCache != nil {
4,934✔
2947
                graphCache.UpdatePolicy(
2,274✔
2948
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,274✔
2949
                )
2,274✔
2950
        }
2,274✔
2951

2952
        return isUpdate1, nil
2,660✔
2953
}
2954

2955
// isPublic determines whether the node is seen as public within the graph from
2956
// the source node's point of view. An existing database transaction can also be
2957
// specified.
2958
func (c *ChannelGraph) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2959
        sourcePubKey []byte) (bool, error) {
15✔
2960

15✔
2961
        // In order to determine whether this node is publicly advertised within
15✔
2962
        // the graph, we'll need to look at all of its edges and check whether
15✔
2963
        // they extend to any other node than the source node. errDone will be
15✔
2964
        // used to terminate the check early.
15✔
2965
        nodeIsPublic := false
15✔
2966
        errDone := errors.New("done")
15✔
2967
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
15✔
2968
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
15✔
2969
                _ *models.ChannelEdgePolicy) error {
27✔
2970

12✔
2971
                // If this edge doesn't extend to the source node, we'll
12✔
2972
                // terminate our search as we can now conclude that the node is
12✔
2973
                // publicly advertised within the graph due to the local node
12✔
2974
                // knowing of the current edge.
12✔
2975
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
12✔
2976
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
17✔
2977

5✔
2978
                        nodeIsPublic = true
5✔
2979
                        return errDone
5✔
2980
                }
5✔
2981

2982
                // Since the edge _does_ extend to the source node, we'll also
2983
                // need to ensure that this is a public edge.
2984
                if info.AuthProof != nil {
17✔
2985
                        nodeIsPublic = true
8✔
2986
                        return errDone
8✔
2987
                }
8✔
2988

2989
                // Otherwise, we'll continue our search.
2990
                return nil
3✔
2991
        })
2992
        if err != nil && err != errDone {
15✔
2993
                return false, err
×
2994
        }
×
2995

2996
        return nodeIsPublic, nil
15✔
2997
}
2998

2999
// FetchLightningNodeTx attempts to look up a target node by its identity
3000
// public key. If the node isn't found in the database, then
3001
// ErrGraphNodeNotFound is returned. An optional transaction may be provided.
3002
// If none is provided, then a new one will be created.
3003
func (c *ChannelGraph) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
3004
        *models.LightningNode, error) {
3,632✔
3005

3,632✔
3006
        return c.fetchLightningNode(tx, nodePub)
3,632✔
3007
}
3,632✔
3008

3009
// FetchLightningNode attempts to look up a target node by its identity public
3010
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3011
// returned.
3012
func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (
3013
        *models.LightningNode, error) {
154✔
3014

154✔
3015
        return c.fetchLightningNode(nil, nodePub)
154✔
3016
}
154✔
3017

3018
// fetchLightningNode attempts to look up a target node by its identity public
3019
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3020
// returned. An optional transaction may be provided. If none is provided, then
3021
// a new one will be created.
3022
func (c *ChannelGraph) fetchLightningNode(tx kvdb.RTx,
3023
        nodePub route.Vertex) (*models.LightningNode, error) {
3,784✔
3024

3,784✔
3025
        var node *models.LightningNode
3,784✔
3026
        fetch := func(tx kvdb.RTx) error {
7,568✔
3027
                // First grab the nodes bucket which stores the mapping from
3,784✔
3028
                // pubKey to node information.
3,784✔
3029
                nodes := tx.ReadBucket(nodeBucket)
3,784✔
3030
                if nodes == nil {
3,784✔
3031
                        return ErrGraphNotFound
×
3032
                }
×
3033

3034
                // If a key for this serialized public key isn't found, then
3035
                // the target node doesn't exist within the database.
3036
                nodeBytes := nodes.Get(nodePub[:])
3,784✔
3037
                if nodeBytes == nil {
3,800✔
3038
                        return ErrGraphNodeNotFound
16✔
3039
                }
16✔
3040

3041
                // If the node is found, then we can de deserialize the node
3042
                // information to return to the user.
3043
                nodeReader := bytes.NewReader(nodeBytes)
3,770✔
3044
                n, err := deserializeLightningNode(nodeReader)
3,770✔
3045
                if err != nil {
3,770✔
3046
                        return err
×
3047
                }
×
3048

3049
                node = &n
3,770✔
3050

3,770✔
3051
                return nil
3,770✔
3052
        }
3053

3054
        if tx == nil {
3,941✔
3055
                err := kvdb.View(
157✔
3056
                        c.db, fetch, func() {
314✔
3057
                                node = nil
157✔
3058
                        },
157✔
3059
                )
3060
                if err != nil {
162✔
3061
                        return nil, err
5✔
3062
                }
5✔
3063

3064
                return node, nil
154✔
3065
        }
3066

3067
        err := fetch(tx)
3,627✔
3068
        if err != nil {
3,638✔
3069
                return nil, err
11✔
3070
        }
11✔
3071

3072
        return node, nil
3,616✔
3073
}
3074

3075
// HasLightningNode determines if the graph has a vertex identified by the
3076
// target node identity public key. If the node exists in the database, a
3077
// timestamp of when the data for the node was lasted updated is returned along
3078
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3079
// boolean.
3080
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3081
        error) {
18✔
3082

18✔
3083
        var (
18✔
3084
                updateTime time.Time
18✔
3085
                exists     bool
18✔
3086
        )
18✔
3087

18✔
3088
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
36✔
3089
                // First grab the nodes bucket which stores the mapping from
18✔
3090
                // pubKey to node information.
18✔
3091
                nodes := tx.ReadBucket(nodeBucket)
18✔
3092
                if nodes == nil {
18✔
3093
                        return ErrGraphNotFound
×
3094
                }
×
3095

3096
                // If a key for this serialized public key isn't found, we can
3097
                // exit early.
3098
                nodeBytes := nodes.Get(nodePub[:])
18✔
3099
                if nodeBytes == nil {
23✔
3100
                        exists = false
5✔
3101
                        return nil
5✔
3102
                }
5✔
3103

3104
                // Otherwise we continue on to obtain the time stamp
3105
                // representing the last time the data for this node was
3106
                // updated.
3107
                nodeReader := bytes.NewReader(nodeBytes)
15✔
3108
                node, err := deserializeLightningNode(nodeReader)
15✔
3109
                if err != nil {
15✔
3110
                        return err
×
3111
                }
×
3112

3113
                exists = true
15✔
3114
                updateTime = node.LastUpdate
15✔
3115
                return nil
15✔
3116
        }, func() {
18✔
3117
                updateTime = time.Time{}
18✔
3118
                exists = false
18✔
3119
        })
18✔
3120
        if err != nil {
18✔
3121
                return time.Time{}, exists, err
×
3122
        }
×
3123

3124
        return updateTime, exists, nil
18✔
3125
}
3126

3127
// nodeTraversal is used to traverse all channels of a node given by its
3128
// public key and passes channel information into the specified callback.
3129
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3130
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3131
                *models.ChannelEdgePolicy) error) error {
1,268✔
3132

1,268✔
3133
        traversal := func(tx kvdb.RTx) error {
2,536✔
3134
                edges := tx.ReadBucket(edgeBucket)
1,268✔
3135
                if edges == nil {
1,268✔
3136
                        return ErrGraphNotFound
×
3137
                }
×
3138
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,268✔
3139
                if edgeIndex == nil {
1,268✔
3140
                        return ErrGraphNoEdgesFound
×
3141
                }
×
3142

3143
                // In order to reach all the edges for this node, we take
3144
                // advantage of the construction of the key-space within the
3145
                // edge bucket. The keys are stored in the form: pubKey ||
3146
                // chanID. Therefore, starting from a chanID of zero, we can
3147
                // scan forward in the bucket, grabbing all the edges for the
3148
                // node. Once the prefix no longer matches, then we know we're
3149
                // done.
3150
                var nodeStart [33 + 8]byte
1,268✔
3151
                copy(nodeStart[:], nodePub)
1,268✔
3152
                copy(nodeStart[33:], chanStart[:])
1,268✔
3153

1,268✔
3154
                // Starting from the key pubKey || 0, we seek forward in the
1,268✔
3155
                // bucket until the retrieved key no longer has the public key
1,268✔
3156
                // as its prefix. This indicates that we've stepped over into
1,268✔
3157
                // another node's edges, so we can terminate our scan.
1,268✔
3158
                edgeCursor := edges.ReadCursor()
1,268✔
3159
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
5,110✔
3160
                        // If the prefix still matches, the channel id is
3,842✔
3161
                        // returned in nodeEdge. Channel id is used to lookup
3,842✔
3162
                        // the node at the other end of the channel and both
3,842✔
3163
                        // edge policies.
3,842✔
3164
                        chanID := nodeEdge[33:]
3,842✔
3165
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,842✔
3166
                        if err != nil {
3,842✔
3167
                                return err
×
3168
                        }
×
3169

3170
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,842✔
3171
                                edges, chanID, nodePub,
3,842✔
3172
                        )
3,842✔
3173
                        if err != nil {
3,842✔
3174
                                return err
×
3175
                        }
×
3176

3177
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,842✔
3178
                        if err != nil {
3,842✔
3179
                                return err
×
3180
                        }
×
3181

3182
                        incomingPolicy, err := fetchChanEdgePolicy(
3,842✔
3183
                                edges, chanID, otherNode[:],
3,842✔
3184
                        )
3,842✔
3185
                        if err != nil {
3,842✔
3186
                                return err
×
3187
                        }
×
3188

3189
                        // Finally, we execute the callback.
3190
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,842✔
3191
                        if err != nil {
3,853✔
3192
                                return err
11✔
3193
                        }
11✔
3194
                }
3195

3196
                return nil
1,259✔
3197
        }
3198

3199
        // If no transaction was provided, then we'll create a new transaction
3200
        // to execute the transaction within.
3201
        if tx == nil {
1,279✔
3202
                return kvdb.View(db, traversal, func() {})
22✔
3203
        }
3204

3205
        // Otherwise, we re-use the existing transaction to execute the graph
3206
        // traversal.
3207
        return traversal(tx)
1,259✔
3208
}
3209

3210
// ForEachNodeChannel iterates through all channels of the given node,
3211
// executing the passed callback with an edge info structure and the policies
3212
// of each end of the channel. The first edge policy is the outgoing edge *to*
3213
// the connecting node, while the second is the incoming edge *from* the
3214
// connecting node. If the callback returns an error, then the iteration is
3215
// halted with the error propagated back up to the caller.
3216
//
3217
// Unknown policies are passed into the callback as nil values.
3218
func (c *ChannelGraph) ForEachNodeChannel(nodePub route.Vertex,
3219
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3220
                *models.ChannelEdgePolicy) error) error {
8✔
3221

8✔
3222
        return nodeTraversal(nil, nodePub[:], c.db, cb)
8✔
3223
}
8✔
3224

3225
// ForEachNodeChannelTx iterates through all channels of the given node,
3226
// executing the passed callback with an edge info structure and the policies
3227
// of each end of the channel. The first edge policy is the outgoing edge *to*
3228
// the connecting node, while the second is the incoming edge *from* the
3229
// connecting node. If the callback returns an error, then the iteration is
3230
// halted with the error propagated back up to the caller.
3231
//
3232
// Unknown policies are passed into the callback as nil values.
3233
//
3234
// If the caller wishes to re-use an existing boltdb transaction, then it
3235
// should be passed as the first argument.  Otherwise, the first argument should
3236
// be nil and a fresh transaction will be created to execute the graph
3237
// traversal.
3238
func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx,
3239
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3240
                *models.ChannelEdgePolicy,
3241
                *models.ChannelEdgePolicy) error) error {
1,020✔
3242

1,020✔
3243
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,020✔
3244
}
1,020✔
3245

3246
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3247
// the target node in the channel. This is useful when one knows the pubkey of
3248
// one of the nodes, and wishes to obtain the full LightningNode for the other
3249
// end of the channel.
3250
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3251
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3252
        *models.LightningNode, error) {
2✔
3253

2✔
3254
        // Ensure that the node passed in is actually a member of the channel.
2✔
3255
        var targetNodeBytes [33]byte
2✔
3256
        switch {
2✔
3257
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
2✔
3258
                targetNodeBytes = channel.NodeKey2Bytes
2✔
3259
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
2✔
3260
                targetNodeBytes = channel.NodeKey1Bytes
2✔
3261
        default:
×
3262
                return nil, fmt.Errorf("node not participating in this channel")
×
3263
        }
3264

3265
        var targetNode *models.LightningNode
2✔
3266
        fetchNodeFunc := func(tx kvdb.RTx) error {
4✔
3267
                // First grab the nodes bucket which stores the mapping from
2✔
3268
                // pubKey to node information.
2✔
3269
                nodes := tx.ReadBucket(nodeBucket)
2✔
3270
                if nodes == nil {
2✔
3271
                        return ErrGraphNotFound
×
3272
                }
×
3273

3274
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
2✔
3275
                if err != nil {
2✔
3276
                        return err
×
3277
                }
×
3278

3279
                targetNode = &node
2✔
3280

2✔
3281
                return nil
2✔
3282
        }
3283

3284
        // If the transaction is nil, then we'll need to create a new one,
3285
        // otherwise we can use the existing db transaction.
3286
        var err error
2✔
3287
        if tx == nil {
2✔
3288
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3289
                        targetNode = nil
×
3290
                })
×
3291
        } else {
2✔
3292
                err = fetchNodeFunc(tx)
2✔
3293
        }
2✔
3294

3295
        return targetNode, err
2✔
3296
}
3297

3298
// computeEdgePolicyKeys is a helper function that can be used to compute the
3299
// keys used to index the channel edge policy info for the two nodes of the
3300
// edge. The keys for node 1 and node 2 are returned respectively.
3301
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
24✔
3302
        var (
24✔
3303
                node1Key [33 + 8]byte
24✔
3304
                node2Key [33 + 8]byte
24✔
3305
        )
24✔
3306

24✔
3307
        copy(node1Key[:], info.NodeKey1Bytes[:])
24✔
3308
        copy(node2Key[:], info.NodeKey2Bytes[:])
24✔
3309

24✔
3310
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
24✔
3311
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
24✔
3312

24✔
3313
        return node1Key[:], node2Key[:]
24✔
3314
}
24✔
3315

3316
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3317
// the channel identified by the funding outpoint. If the channel can't be
3318
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3319
// information for the channel itself is returned as well as two structs that
3320
// contain the routing policies for the channel in either direction.
3321
func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3322
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3323
        *models.ChannelEdgePolicy, error) {
13✔
3324

13✔
3325
        var (
13✔
3326
                edgeInfo *models.ChannelEdgeInfo
13✔
3327
                policy1  *models.ChannelEdgePolicy
13✔
3328
                policy2  *models.ChannelEdgePolicy
13✔
3329
        )
13✔
3330

13✔
3331
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
26✔
3332
                // First, grab the node bucket. This will be used to populate
13✔
3333
                // the Node pointers in each edge read from disk.
13✔
3334
                nodes := tx.ReadBucket(nodeBucket)
13✔
3335
                if nodes == nil {
13✔
3336
                        return ErrGraphNotFound
×
3337
                }
×
3338

3339
                // Next, grab the edge bucket which stores the edges, and also
3340
                // the index itself so we can group the directed edges together
3341
                // logically.
3342
                edges := tx.ReadBucket(edgeBucket)
13✔
3343
                if edges == nil {
13✔
3344
                        return ErrGraphNoEdgesFound
×
3345
                }
×
3346
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
13✔
3347
                if edgeIndex == nil {
13✔
3348
                        return ErrGraphNoEdgesFound
×
3349
                }
×
3350

3351
                // If the channel's outpoint doesn't exist within the outpoint
3352
                // index, then the edge does not exist.
3353
                chanIndex := edges.NestedReadBucket(channelPointBucket)
13✔
3354
                if chanIndex == nil {
13✔
3355
                        return ErrGraphNoEdgesFound
×
3356
                }
×
3357
                var b bytes.Buffer
13✔
3358
                if err := WriteOutpoint(&b, op); err != nil {
13✔
3359
                        return err
×
3360
                }
×
3361
                chanID := chanIndex.Get(b.Bytes())
13✔
3362
                if chanID == nil {
25✔
3363
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
12✔
3364
                }
12✔
3365

3366
                // If the channel is found to exists, then we'll first retrieve
3367
                // the general information for the channel.
3368
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3369
                if err != nil {
3✔
3370
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3371
                }
×
3372
                edgeInfo = &edge
3✔
3373

3✔
3374
                // Once we have the information about the channels' parameters,
3✔
3375
                // we'll fetch the routing policies for each for the directed
3✔
3376
                // edges.
3✔
3377
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3378
                if err != nil {
3✔
3379
                        return fmt.Errorf("failed to find policy: %w", err)
×
3380
                }
×
3381

3382
                policy1 = e1
3✔
3383
                policy2 = e2
3✔
3384
                return nil
3✔
3385
        }, func() {
13✔
3386
                edgeInfo = nil
13✔
3387
                policy1 = nil
13✔
3388
                policy2 = nil
13✔
3389
        })
13✔
3390
        if err != nil {
25✔
3391
                return nil, nil, nil, err
12✔
3392
        }
12✔
3393

3394
        return edgeInfo, policy1, policy2, nil
3✔
3395
}
3396

3397
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3398
// channel identified by the channel ID. If the channel can't be found, then
3399
// ErrEdgeNotFound is returned. A struct which houses the general information
3400
// for the channel itself is returned as well as two structs that contain the
3401
// routing policies for the channel in either direction.
3402
//
3403
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3404
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3405
// the ChannelEdgeInfo will only include the public keys of each node.
3406
func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64) (
3407
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3408
        *models.ChannelEdgePolicy, error) {
26✔
3409

26✔
3410
        var (
26✔
3411
                edgeInfo  *models.ChannelEdgeInfo
26✔
3412
                policy1   *models.ChannelEdgePolicy
26✔
3413
                policy2   *models.ChannelEdgePolicy
26✔
3414
                channelID [8]byte
26✔
3415
        )
26✔
3416

26✔
3417
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
52✔
3418
                // First, grab the node bucket. This will be used to populate
26✔
3419
                // the Node pointers in each edge read from disk.
26✔
3420
                nodes := tx.ReadBucket(nodeBucket)
26✔
3421
                if nodes == nil {
26✔
3422
                        return ErrGraphNotFound
×
3423
                }
×
3424

3425
                // Next, grab the edge bucket which stores the edges, and also
3426
                // the index itself so we can group the directed edges together
3427
                // logically.
3428
                edges := tx.ReadBucket(edgeBucket)
26✔
3429
                if edges == nil {
26✔
3430
                        return ErrGraphNoEdgesFound
×
3431
                }
×
3432
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
26✔
3433
                if edgeIndex == nil {
26✔
3434
                        return ErrGraphNoEdgesFound
×
3435
                }
×
3436

3437
                byteOrder.PutUint64(channelID[:], chanID)
26✔
3438

26✔
3439
                // Now, attempt to fetch edge.
26✔
3440
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
26✔
3441

26✔
3442
                // If it doesn't exist, we'll quickly check our zombie index to
26✔
3443
                // see if we've previously marked it as so.
26✔
3444
                if errors.Is(err, ErrEdgeNotFound) {
29✔
3445
                        // If the zombie index doesn't exist, or the edge is not
3✔
3446
                        // marked as a zombie within it, then we'll return the
3✔
3447
                        // original ErrEdgeNotFound error.
3✔
3448
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3449
                        if zombieIndex == nil {
3✔
3450
                                return ErrEdgeNotFound
×
3451
                        }
×
3452

3453
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3454
                                zombieIndex, chanID,
3✔
3455
                        )
3✔
3456
                        if !isZombie {
5✔
3457
                                return ErrEdgeNotFound
2✔
3458
                        }
2✔
3459

3460
                        // Otherwise, the edge is marked as a zombie, so we'll
3461
                        // populate the edge info with the public keys of each
3462
                        // party as this is the only information we have about
3463
                        // it and return an error signaling so.
3464
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3465
                                NodeKey1Bytes: pubKey1,
3✔
3466
                                NodeKey2Bytes: pubKey2,
3✔
3467
                        }
3✔
3468
                        return ErrZombieEdge
3✔
3469
                }
3470

3471
                // Otherwise, we'll just return the error if any.
3472
                if err != nil {
25✔
3473
                        return err
×
3474
                }
×
3475

3476
                edgeInfo = &edge
25✔
3477

25✔
3478
                // Then we'll attempt to fetch the accompanying policies of this
25✔
3479
                // edge.
25✔
3480
                e1, e2, err := fetchChanEdgePolicies(
25✔
3481
                        edgeIndex, edges, channelID[:],
25✔
3482
                )
25✔
3483
                if err != nil {
25✔
3484
                        return err
×
3485
                }
×
3486

3487
                policy1 = e1
25✔
3488
                policy2 = e2
25✔
3489
                return nil
25✔
3490
        }, func() {
26✔
3491
                edgeInfo = nil
26✔
3492
                policy1 = nil
26✔
3493
                policy2 = nil
26✔
3494
        })
26✔
3495
        if err == ErrZombieEdge {
29✔
3496
                return edgeInfo, nil, nil, err
3✔
3497
        }
3✔
3498
        if err != nil {
27✔
3499
                return nil, nil, nil, err
2✔
3500
        }
2✔
3501

3502
        return edgeInfo, policy1, policy2, nil
25✔
3503
}
3504

3505
// IsPublicNode is a helper method that determines whether the node with the
3506
// given public key is seen as a public node in the graph from the graph's
3507
// source node's point of view.
3508
func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) {
15✔
3509
        var nodeIsPublic bool
15✔
3510
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
30✔
3511
                nodes := tx.ReadBucket(nodeBucket)
15✔
3512
                if nodes == nil {
15✔
3513
                        return ErrGraphNodesNotFound
×
3514
                }
×
3515
                ourPubKey := nodes.Get(sourceKey)
15✔
3516
                if ourPubKey == nil {
15✔
3517
                        return ErrSourceNodeNotSet
×
3518
                }
×
3519
                node, err := fetchLightningNode(nodes, pubKey[:])
15✔
3520
                if err != nil {
15✔
3521
                        return err
×
3522
                }
×
3523

3524
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
15✔
3525
                return err
15✔
3526
        }, func() {
15✔
3527
                nodeIsPublic = false
15✔
3528
        })
15✔
3529
        if err != nil {
15✔
3530
                return false, err
×
3531
        }
×
3532

3533
        return nodeIsPublic, nil
15✔
3534
}
3535

3536
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3537
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
48✔
3538
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
48✔
3539
        if err != nil {
48✔
3540
                return nil, err
×
3541
        }
×
3542

3543
        // With the witness script generated, we'll now turn it into a p2wsh
3544
        // script:
3545
        //  * OP_0 <sha256(script)>
3546
        bldr := txscript.NewScriptBuilder(
48✔
3547
                txscript.WithScriptAllocSize(input.P2WSHSize),
48✔
3548
        )
48✔
3549
        bldr.AddOp(txscript.OP_0)
48✔
3550
        scriptHash := sha256.Sum256(witnessScript)
48✔
3551
        bldr.AddData(scriptHash[:])
48✔
3552

48✔
3553
        return bldr.Script()
48✔
3554
}
3555

3556
// EdgePoint couples the outpoint of a channel with the funding script that it
3557
// creates. The FilteredChainView will use this to watch for spends of this
3558
// edge point on chain. We require both of these values as depending on the
3559
// concrete implementation, either the pkScript, or the out point will be used.
3560
type EdgePoint struct {
3561
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3562
        FundingPkScript []byte
3563

3564
        // OutPoint is the outpoint of the target channel.
3565
        OutPoint wire.OutPoint
3566
}
3567

3568
// String returns a human readable version of the target EdgePoint. We return
3569
// the outpoint directly as it is enough to uniquely identify the edge point.
3570
func (e *EdgePoint) String() string {
×
3571
        return e.OutPoint.String()
×
3572
}
×
3573

3574
// ChannelView returns the verifiable edge information for each active channel
3575
// within the known channel graph. The set of UTXO's (along with their scripts)
3576
// returned are the ones that need to be watched on chain to detect channel
3577
// closes on the resident blockchain.
3578
func (c *ChannelGraph) ChannelView() ([]EdgePoint, error) {
24✔
3579
        var edgePoints []EdgePoint
24✔
3580
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
48✔
3581
                // We're going to iterate over the entire channel index, so
24✔
3582
                // we'll need to fetch the edgeBucket to get to the index as
24✔
3583
                // it's a sub-bucket.
24✔
3584
                edges := tx.ReadBucket(edgeBucket)
24✔
3585
                if edges == nil {
24✔
3586
                        return ErrGraphNoEdgesFound
×
3587
                }
×
3588
                chanIndex := edges.NestedReadBucket(channelPointBucket)
24✔
3589
                if chanIndex == nil {
24✔
3590
                        return ErrGraphNoEdgesFound
×
3591
                }
×
3592
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
24✔
3593
                if edgeIndex == nil {
24✔
3594
                        return ErrGraphNoEdgesFound
×
3595
                }
×
3596

3597
                // Once we have the proper bucket, we'll range over each key
3598
                // (which is the channel point for the channel) and decode it,
3599
                // accumulating each entry.
3600
                return chanIndex.ForEach(
24✔
3601
                        func(chanPointBytes, chanID []byte) error {
68✔
3602
                                chanPointReader := bytes.NewReader(
44✔
3603
                                        chanPointBytes,
44✔
3604
                                )
44✔
3605

44✔
3606
                                var chanPoint wire.OutPoint
44✔
3607
                                err := ReadOutpoint(chanPointReader, &chanPoint)
44✔
3608
                                if err != nil {
44✔
3609
                                        return err
×
3610
                                }
×
3611

3612
                                edgeInfo, err := fetchChanEdgeInfo(
44✔
3613
                                        edgeIndex, chanID,
44✔
3614
                                )
44✔
3615
                                if err != nil {
44✔
3616
                                        return err
×
3617
                                }
×
3618

3619
                                pkScript, err := genMultiSigP2WSH(
44✔
3620
                                        edgeInfo.BitcoinKey1Bytes[:],
44✔
3621
                                        edgeInfo.BitcoinKey2Bytes[:],
44✔
3622
                                )
44✔
3623
                                if err != nil {
44✔
3624
                                        return err
×
3625
                                }
×
3626

3627
                                edgePoints = append(edgePoints, EdgePoint{
44✔
3628
                                        FundingPkScript: pkScript,
44✔
3629
                                        OutPoint:        chanPoint,
44✔
3630
                                })
44✔
3631

44✔
3632
                                return nil
44✔
3633
                        },
3634
                )
3635
        }, func() {
24✔
3636
                edgePoints = nil
24✔
3637
        }); err != nil {
24✔
3638
                return nil, err
×
3639
        }
×
3640

3641
        return edgePoints, nil
24✔
3642
}
3643

3644
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3645
// zombie. This method is used on an ad-hoc basis, when channels need to be
3646
// marked as zombies outside the normal pruning cycle.
3647
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3648
        pubKey1, pubKey2 [33]byte) error {
128✔
3649

128✔
3650
        c.cacheMu.Lock()
128✔
3651
        defer c.cacheMu.Unlock()
128✔
3652

128✔
3653
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
256✔
3654
                edges := tx.ReadWriteBucket(edgeBucket)
128✔
3655
                if edges == nil {
128✔
3656
                        return ErrGraphNoEdgesFound
×
3657
                }
×
3658
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
128✔
3659
                if err != nil {
128✔
3660
                        return fmt.Errorf("unable to create zombie "+
×
3661
                                "bucket: %w", err)
×
3662
                }
×
3663

3664
                if c.graphCache != nil {
256✔
3665
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
128✔
3666
                }
128✔
3667

3668
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
128✔
3669
        })
3670
        if err != nil {
128✔
3671
                return err
×
3672
        }
×
3673

3674
        c.rejectCache.remove(chanID)
128✔
3675
        c.chanCache.remove(chanID)
128✔
3676

128✔
3677
        return nil
128✔
3678
}
3679

3680
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3681
// keys should represent the node public keys of the two parties involved in the
3682
// edge.
3683
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3684
        pubKey2 [33]byte) error {
154✔
3685

154✔
3686
        var k [8]byte
154✔
3687
        byteOrder.PutUint64(k[:], chanID)
154✔
3688

154✔
3689
        var v [66]byte
154✔
3690
        copy(v[:33], pubKey1[:])
154✔
3691
        copy(v[33:], pubKey2[:])
154✔
3692

154✔
3693
        return zombieIndex.Put(k[:], v[:])
154✔
3694
}
154✔
3695

3696
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3697
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
2✔
3698
        c.cacheMu.Lock()
2✔
3699
        defer c.cacheMu.Unlock()
2✔
3700

2✔
3701
        return c.markEdgeLiveUnsafe(nil, chanID)
2✔
3702
}
2✔
3703

3704
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3705
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3706
// case a new transaction will be created.
3707
//
3708
// NOTE: this method MUST only be called if the cacheMu has already been
3709
// acquired.
3710
func (c *ChannelGraph) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
22✔
3711
        dbFn := func(tx kvdb.RwTx) error {
44✔
3712
                edges := tx.ReadWriteBucket(edgeBucket)
22✔
3713
                if edges == nil {
22✔
3714
                        return ErrGraphNoEdgesFound
×
3715
                }
×
3716
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
22✔
3717
                if zombieIndex == nil {
22✔
3718
                        return nil
×
3719
                }
×
3720

3721
                var k [8]byte
22✔
3722
                byteOrder.PutUint64(k[:], chanID)
22✔
3723

22✔
3724
                if len(zombieIndex.Get(k[:])) == 0 {
23✔
3725
                        return ErrZombieEdgeNotFound
1✔
3726
                }
1✔
3727

3728
                return zombieIndex.Delete(k[:])
21✔
3729
        }
3730

3731
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3732
        // the existing transaction
3733
        var err error
22✔
3734
        if tx == nil {
24✔
3735
                err = kvdb.Update(c.db, dbFn, func() {})
4✔
3736
        } else {
20✔
3737
                err = dbFn(tx)
20✔
3738
        }
20✔
3739
        if err != nil {
23✔
3740
                return err
1✔
3741
        }
1✔
3742

3743
        c.rejectCache.remove(chanID)
21✔
3744
        c.chanCache.remove(chanID)
21✔
3745

21✔
3746
        // We need to add the channel back into our graph cache, otherwise we
21✔
3747
        // won't use it for path finding.
21✔
3748
        if c.graphCache != nil {
42✔
3749
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
21✔
3750
                if err != nil {
21✔
3751
                        return err
×
3752
                }
×
3753

3754
                for _, edgeInfo := range edgeInfos {
21✔
3755
                        c.graphCache.AddChannel(
×
3756
                                edgeInfo.Info, edgeInfo.Policy1,
×
3757
                                edgeInfo.Policy2,
×
3758
                        )
×
3759
                }
×
3760
        }
3761

3762
        return nil
21✔
3763
}
3764

3765
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3766
// zombie, then the two node public keys corresponding to this edge are also
3767
// returned.
3768
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3769
        var (
5✔
3770
                isZombie         bool
5✔
3771
                pubKey1, pubKey2 [33]byte
5✔
3772
        )
5✔
3773

5✔
3774
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3775
                edges := tx.ReadBucket(edgeBucket)
5✔
3776
                if edges == nil {
5✔
3777
                        return ErrGraphNoEdgesFound
×
3778
                }
×
3779
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3780
                if zombieIndex == nil {
5✔
3781
                        return nil
×
3782
                }
×
3783

3784
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3785
                return nil
5✔
3786
        }, func() {
5✔
3787
                isZombie = false
5✔
3788
                pubKey1 = [33]byte{}
5✔
3789
                pubKey2 = [33]byte{}
5✔
3790
        })
5✔
3791
        if err != nil {
5✔
3792
                return false, [33]byte{}, [33]byte{}
×
3793
        }
×
3794

3795
        return isZombie, pubKey1, pubKey2
5✔
3796
}
3797

3798
// isZombieEdge returns whether an entry exists for the given channel in the
3799
// zombie index. If an entry exists, then the two node public keys corresponding
3800
// to this edge are also returned.
3801
func isZombieEdge(zombieIndex kvdb.RBucket,
3802
        chanID uint64) (bool, [33]byte, [33]byte) {
189✔
3803

189✔
3804
        var k [8]byte
189✔
3805
        byteOrder.PutUint64(k[:], chanID)
189✔
3806

189✔
3807
        v := zombieIndex.Get(k[:])
189✔
3808
        if v == nil {
289✔
3809
                return false, [33]byte{}, [33]byte{}
100✔
3810
        }
100✔
3811

3812
        var pubKey1, pubKey2 [33]byte
91✔
3813
        copy(pubKey1[:], v[:33])
91✔
3814
        copy(pubKey2[:], v[33:])
91✔
3815

91✔
3816
        return true, pubKey1, pubKey2
91✔
3817
}
3818

3819
// NumZombies returns the current number of zombie channels in the graph.
3820
func (c *ChannelGraph) NumZombies() (uint64, error) {
4✔
3821
        var numZombies uint64
4✔
3822
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3823
                edges := tx.ReadBucket(edgeBucket)
4✔
3824
                if edges == nil {
4✔
3825
                        return nil
×
3826
                }
×
3827
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3828
                if zombieIndex == nil {
4✔
3829
                        return nil
×
3830
                }
×
3831

3832
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3833
                        numZombies++
2✔
3834
                        return nil
2✔
3835
                })
2✔
3836
        }, func() {
4✔
3837
                numZombies = 0
4✔
3838
        })
4✔
3839
        if err != nil {
4✔
3840
                return 0, err
×
3841
        }
×
3842

3843
        return numZombies, nil
4✔
3844
}
3845

3846
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3847
// that we can ignore channel announcements that we know to be closed without
3848
// having to validate them and fetch a block.
3849
func (c *ChannelGraph) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3850
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3851
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3852
                if err != nil {
1✔
3853
                        return err
×
3854
                }
×
3855

3856
                var k [8]byte
1✔
3857
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3858

1✔
3859
                return closedScids.Put(k[:], []byte{})
1✔
3860
        }, func() {})
1✔
3861
}
3862

3863
// IsClosedScid checks whether a channel identified by the passed in scid is
3864
// closed. This helps avoid having to perform expensive validation checks.
3865
// TODO: Add an LRU cache to cut down on disc reads.
3866
func (c *ChannelGraph) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
4✔
3867
        var isClosed bool
4✔
3868
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3869
                closedScids := tx.ReadBucket(closedScidBucket)
4✔
3870
                if closedScids == nil {
4✔
3871
                        return ErrClosedScidsNotFound
×
3872
                }
×
3873

3874
                var k [8]byte
4✔
3875
                byteOrder.PutUint64(k[:], scid.ToUint64())
4✔
3876

4✔
3877
                if closedScids.Get(k[:]) != nil {
5✔
3878
                        isClosed = true
1✔
3879
                        return nil
1✔
3880
                }
1✔
3881

3882
                return nil
3✔
3883
        }, func() {
4✔
3884
                isClosed = false
4✔
3885
        })
4✔
3886
        if err != nil {
4✔
3887
                return false, err
×
3888
        }
×
3889

3890
        return isClosed, nil
4✔
3891
}
3892

3893
// GraphSession will provide the call-back with access to a NodeTraverser
3894
// instance which can be used to perform queries against the channel graph. If
3895
// the graph cache is not enabled, then the call-back will  be provided with
3896
// access to the graph via a consistent read-only transaction.
3897
func (c *ChannelGraph) GraphSession(cb func(graph NodeTraverser) error) error {
135✔
3898
        var (
135✔
3899
                tx     kvdb.RTx
135✔
3900
                err    error
135✔
3901
                commit = func() {}
216✔
3902
        )
3903
        if c.graphCache == nil {
189✔
3904
                tx, err = c.db.BeginReadTx()
54✔
3905
                if err != nil {
54✔
3906
                        return err
×
3907
                }
×
3908

3909
                commit = func() {
108✔
3910
                        if err := tx.Rollback(); err != nil {
54✔
3911
                                log.Errorf("Unable to rollback tx: %v", err)
×
3912
                        }
×
3913
                }
3914
        }
3915
        defer commit()
135✔
3916

135✔
3917
        return cb(&nodeTraverserSession{
135✔
3918
                db: c,
135✔
3919
                tx: tx,
135✔
3920
        })
135✔
3921
}
3922

3923
// nodeTraverserSession implements the NodeTraverser interface but with a
3924
// backing read only transaction for a consistent view of the graph in the case
3925
// where the graph Cache has not been enabled.
3926
type nodeTraverserSession struct {
3927
        tx kvdb.RTx
3928
        db *ChannelGraph
3929
}
3930

3931
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3932
// node.
3933
//
3934
// NOTE: Part of the NodeTraverser interface.
3935
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3936
        cb func(channel *DirectedChannel) error) error {
591✔
3937

591✔
3938
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
591✔
3939
}
591✔
3940

3941
// FetchNodeFeatures returns the features of the given node. If the node is
3942
// unknown, assume no additional features are supported.
3943
//
3944
// NOTE: Part of the NodeTraverser interface.
3945
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
3946
        *lnwire.FeatureVector, error) {
622✔
3947

622✔
3948
        return c.db.fetchNodeFeatures(c.tx, nodePub)
622✔
3949
}
622✔
3950

3951
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3952
        updateIndex kvdb.RwBucket, node *models.LightningNode) error {
998✔
3953

998✔
3954
        var (
998✔
3955
                scratch [16]byte
998✔
3956
                b       bytes.Buffer
998✔
3957
        )
998✔
3958

998✔
3959
        pub, err := node.PubKey()
998✔
3960
        if err != nil {
998✔
3961
                return err
×
3962
        }
×
3963
        nodePub := pub.SerializeCompressed()
998✔
3964

998✔
3965
        // If the node has the update time set, write it, else write 0.
998✔
3966
        updateUnix := uint64(0)
998✔
3967
        if node.LastUpdate.Unix() > 0 {
1,863✔
3968
                updateUnix = uint64(node.LastUpdate.Unix())
865✔
3969
        }
865✔
3970

3971
        byteOrder.PutUint64(scratch[:8], updateUnix)
998✔
3972
        if _, err := b.Write(scratch[:8]); err != nil {
998✔
3973
                return err
×
3974
        }
×
3975

3976
        if _, err := b.Write(nodePub); err != nil {
998✔
3977
                return err
×
3978
        }
×
3979

3980
        // If we got a node announcement for this node, we will have the rest
3981
        // of the data available. If not we don't have more data to write.
3982
        if !node.HaveNodeAnnouncement {
1,080✔
3983
                // Write HaveNodeAnnouncement=0.
82✔
3984
                byteOrder.PutUint16(scratch[:2], 0)
82✔
3985
                if _, err := b.Write(scratch[:2]); err != nil {
82✔
3986
                        return err
×
3987
                }
×
3988

3989
                return nodeBucket.Put(nodePub, b.Bytes())
82✔
3990
        }
3991

3992
        // Write HaveNodeAnnouncement=1.
3993
        byteOrder.PutUint16(scratch[:2], 1)
918✔
3994
        if _, err := b.Write(scratch[:2]); err != nil {
918✔
3995
                return err
×
3996
        }
×
3997

3998
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
918✔
3999
                return err
×
4000
        }
×
4001
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
918✔
4002
                return err
×
4003
        }
×
4004
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
918✔
4005
                return err
×
4006
        }
×
4007

4008
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
918✔
4009
                return err
×
4010
        }
×
4011

4012
        if err := node.Features.Encode(&b); err != nil {
918✔
4013
                return err
×
4014
        }
×
4015

4016
        numAddresses := uint16(len(node.Addresses))
918✔
4017
        byteOrder.PutUint16(scratch[:2], numAddresses)
918✔
4018
        if _, err := b.Write(scratch[:2]); err != nil {
918✔
4019
                return err
×
4020
        }
×
4021

4022
        for _, address := range node.Addresses {
2,064✔
4023
                if err := SerializeAddr(&b, address); err != nil {
1,146✔
4024
                        return err
×
4025
                }
×
4026
        }
4027

4028
        sigLen := len(node.AuthSigBytes)
918✔
4029
        if sigLen > 80 {
918✔
4030
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4031
                        sigLen)
×
4032
        }
×
4033

4034
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
918✔
4035
        if err != nil {
918✔
4036
                return err
×
4037
        }
×
4038

4039
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
918✔
4040
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4041
        }
×
4042
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
918✔
4043
        if err != nil {
918✔
4044
                return err
×
4045
        }
×
4046

4047
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
918✔
4048
                return err
×
4049
        }
×
4050

4051
        // With the alias bucket updated, we'll now update the index that
4052
        // tracks the time series of node updates.
4053
        var indexKey [8 + 33]byte
918✔
4054
        byteOrder.PutUint64(indexKey[:8], updateUnix)
918✔
4055
        copy(indexKey[8:], nodePub)
918✔
4056

918✔
4057
        // If there was already an old index entry for this node, then we'll
918✔
4058
        // delete the old one before we write the new entry.
918✔
4059
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,024✔
4060
                // Extract out the old update time to we can reconstruct the
106✔
4061
                // prior index key to delete it from the index.
106✔
4062
                oldUpdateTime := nodeBytes[:8]
106✔
4063

106✔
4064
                var oldIndexKey [8 + 33]byte
106✔
4065
                copy(oldIndexKey[:8], oldUpdateTime)
106✔
4066
                copy(oldIndexKey[8:], nodePub)
106✔
4067

106✔
4068
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
106✔
4069
                        return err
×
4070
                }
×
4071
        }
4072

4073
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
918✔
4074
                return err
×
4075
        }
×
4076

4077
        return nodeBucket.Put(nodePub, b.Bytes())
918✔
4078
}
4079

4080
func fetchLightningNode(nodeBucket kvdb.RBucket,
4081
        nodePub []byte) (models.LightningNode, error) {
3,620✔
4082

3,620✔
4083
        nodeBytes := nodeBucket.Get(nodePub)
3,620✔
4084
        if nodeBytes == nil {
3,701✔
4085
                return models.LightningNode{}, ErrGraphNodeNotFound
81✔
4086
        }
81✔
4087

4088
        nodeReader := bytes.NewReader(nodeBytes)
3,541✔
4089
        return deserializeLightningNode(nodeReader)
3,541✔
4090
}
4091

4092
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4093
        *lnwire.FeatureVector, error) {
122✔
4094

122✔
4095
        var (
122✔
4096
                pubKey      route.Vertex
122✔
4097
                features    = lnwire.EmptyFeatureVector()
122✔
4098
                nodeScratch [8]byte
122✔
4099
        )
122✔
4100

122✔
4101
        // Skip ahead:
122✔
4102
        // - LastUpdate (8 bytes)
122✔
4103
        if _, err := r.Read(nodeScratch[:]); err != nil {
122✔
4104
                return pubKey, nil, err
×
4105
        }
×
4106

4107
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
122✔
4108
                return pubKey, nil, err
×
4109
        }
×
4110

4111
        // Read the node announcement flag.
4112
        if _, err := r.Read(nodeScratch[:2]); err != nil {
122✔
4113
                return pubKey, nil, err
×
4114
        }
×
4115
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
122✔
4116

122✔
4117
        // The rest of the data is optional, and will only be there if we got a
122✔
4118
        // node announcement for this node.
122✔
4119
        if hasNodeAnn == 0 {
124✔
4120
                return pubKey, features, nil
2✔
4121
        }
2✔
4122

4123
        // We did get a node announcement for this node, so we'll have the rest
4124
        // of the data available.
4125
        var rgb uint8
122✔
4126
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
122✔
4127
                return pubKey, nil, err
×
4128
        }
×
4129
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
122✔
4130
                return pubKey, nil, err
×
4131
        }
×
4132
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
122✔
4133
                return pubKey, nil, err
×
4134
        }
×
4135

4136
        if _, err := wire.ReadVarString(r, 0); err != nil {
122✔
4137
                return pubKey, nil, err
×
4138
        }
×
4139

4140
        if err := features.Decode(r); err != nil {
122✔
4141
                return pubKey, nil, err
×
4142
        }
×
4143

4144
        return pubKey, features, nil
122✔
4145
}
4146

4147
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,500✔
4148
        var (
8,500✔
4149
                node    models.LightningNode
8,500✔
4150
                scratch [8]byte
8,500✔
4151
                err     error
8,500✔
4152
        )
8,500✔
4153

8,500✔
4154
        // Always populate a feature vector, even if we don't have a node
8,500✔
4155
        // announcement and short circuit below.
8,500✔
4156
        node.Features = lnwire.EmptyFeatureVector()
8,500✔
4157

8,500✔
4158
        if _, err := r.Read(scratch[:]); err != nil {
8,500✔
4159
                return models.LightningNode{}, err
×
4160
        }
×
4161

4162
        unix := int64(byteOrder.Uint64(scratch[:]))
8,500✔
4163
        node.LastUpdate = time.Unix(unix, 0)
8,500✔
4164

8,500✔
4165
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,500✔
4166
                return models.LightningNode{}, err
×
4167
        }
×
4168

4169
        if _, err := r.Read(scratch[:2]); err != nil {
8,500✔
4170
                return models.LightningNode{}, err
×
4171
        }
×
4172

4173
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,500✔
4174
        if hasNodeAnn == 1 {
16,867✔
4175
                node.HaveNodeAnnouncement = true
8,367✔
4176
        } else {
8,502✔
4177
                node.HaveNodeAnnouncement = false
135✔
4178
        }
135✔
4179

4180
        // The rest of the data is optional, and will only be there if we got a
4181
        // node announcement for this node.
4182
        if !node.HaveNodeAnnouncement {
8,635✔
4183
                return node, nil
135✔
4184
        }
135✔
4185

4186
        // We did get a node announcement for this node, so we'll have the rest
4187
        // of the data available.
4188
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,367✔
4189
                return models.LightningNode{}, err
×
4190
        }
×
4191
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,367✔
4192
                return models.LightningNode{}, err
×
4193
        }
×
4194
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,367✔
4195
                return models.LightningNode{}, err
×
4196
        }
×
4197

4198
        node.Alias, err = wire.ReadVarString(r, 0)
8,367✔
4199
        if err != nil {
8,367✔
4200
                return models.LightningNode{}, err
×
4201
        }
×
4202

4203
        err = node.Features.Decode(r)
8,367✔
4204
        if err != nil {
8,367✔
4205
                return models.LightningNode{}, err
×
4206
        }
×
4207

4208
        if _, err := r.Read(scratch[:2]); err != nil {
8,367✔
4209
                return models.LightningNode{}, err
×
4210
        }
×
4211
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,367✔
4212

8,367✔
4213
        var addresses []net.Addr
8,367✔
4214
        for i := 0; i < numAddresses; i++ {
18,968✔
4215
                address, err := DeserializeAddr(r)
10,601✔
4216
                if err != nil {
10,601✔
4217
                        return models.LightningNode{}, err
×
4218
                }
×
4219
                addresses = append(addresses, address)
10,601✔
4220
        }
4221
        node.Addresses = addresses
8,367✔
4222

8,367✔
4223
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,367✔
4224
        if err != nil {
8,367✔
4225
                return models.LightningNode{}, err
×
4226
        }
×
4227

4228
        // We'll try and see if there are any opaque bytes left, if not, then
4229
        // we'll ignore the EOF error and return the node as is.
4230
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,367✔
4231
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,367✔
4232
        )
8,367✔
4233
        switch {
8,367✔
4234
        case err == io.ErrUnexpectedEOF:
×
4235
        case err == io.EOF:
×
4236
        case err != nil:
×
4237
                return models.LightningNode{}, err
×
4238
        }
4239

4240
        return node, nil
8,367✔
4241
}
4242

4243
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4244
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,480✔
4245

1,480✔
4246
        var b bytes.Buffer
1,480✔
4247

1,480✔
4248
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,480✔
4249
                return err
×
4250
        }
×
4251
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,480✔
4252
                return err
×
4253
        }
×
4254
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,480✔
4255
                return err
×
4256
        }
×
4257
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,480✔
4258
                return err
×
4259
        }
×
4260

4261
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,480✔
4262
                return err
×
4263
        }
×
4264

4265
        authProof := edgeInfo.AuthProof
1,480✔
4266
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,480✔
4267
        if authProof != nil {
2,877✔
4268
                nodeSig1 = authProof.NodeSig1Bytes
1,397✔
4269
                nodeSig2 = authProof.NodeSig2Bytes
1,397✔
4270
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,397✔
4271
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,397✔
4272
        }
1,397✔
4273

4274
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,480✔
4275
                return err
×
4276
        }
×
4277
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,480✔
4278
                return err
×
4279
        }
×
4280
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,480✔
4281
                return err
×
4282
        }
×
4283
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,480✔
4284
                return err
×
4285
        }
×
4286

4287
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,480✔
4288
                return err
×
4289
        }
×
4290
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,480✔
4291
        if err != nil {
1,480✔
4292
                return err
×
4293
        }
×
4294
        if _, err := b.Write(chanID[:]); err != nil {
1,480✔
4295
                return err
×
4296
        }
×
4297
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,480✔
4298
                return err
×
4299
        }
×
4300

4301
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,480✔
4302
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4303
        }
×
4304
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,480✔
4305
        if err != nil {
1,480✔
4306
                return err
×
4307
        }
×
4308

4309
        return edgeIndex.Put(chanID[:], b.Bytes())
1,480✔
4310
}
4311

4312
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4313
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,176✔
4314

4,176✔
4315
        edgeInfoBytes := edgeIndex.Get(chanID)
4,176✔
4316
        if edgeInfoBytes == nil {
4,263✔
4317
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
87✔
4318
        }
87✔
4319

4320
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,091✔
4321
        return deserializeChanEdgeInfo(edgeInfoReader)
4,091✔
4322
}
4323

4324
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,721✔
4325
        var (
4,721✔
4326
                err      error
4,721✔
4327
                edgeInfo models.ChannelEdgeInfo
4,721✔
4328
        )
4,721✔
4329

4,721✔
4330
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,721✔
4331
                return models.ChannelEdgeInfo{}, err
×
4332
        }
×
4333
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,721✔
4334
                return models.ChannelEdgeInfo{}, err
×
4335
        }
×
4336
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,721✔
4337
                return models.ChannelEdgeInfo{}, err
×
4338
        }
×
4339
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,721✔
4340
                return models.ChannelEdgeInfo{}, err
×
4341
        }
×
4342

4343
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,721✔
4344
        if err != nil {
4,721✔
4345
                return models.ChannelEdgeInfo{}, err
×
4346
        }
×
4347

4348
        proof := &models.ChannelAuthProof{}
4,721✔
4349

4,721✔
4350
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,721✔
4351
        if err != nil {
4,721✔
4352
                return models.ChannelEdgeInfo{}, err
×
4353
        }
×
4354
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,721✔
4355
        if err != nil {
4,721✔
4356
                return models.ChannelEdgeInfo{}, err
×
4357
        }
×
4358
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,721✔
4359
        if err != nil {
4,721✔
4360
                return models.ChannelEdgeInfo{}, err
×
4361
        }
×
4362
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,721✔
4363
        if err != nil {
4,721✔
4364
                return models.ChannelEdgeInfo{}, err
×
4365
        }
×
4366

4367
        if !proof.IsEmpty() {
6,493✔
4368
                edgeInfo.AuthProof = proof
1,772✔
4369
        }
1,772✔
4370

4371
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,721✔
4372
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,721✔
4373
                return models.ChannelEdgeInfo{}, err
×
4374
        }
×
4375
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,721✔
4376
                return models.ChannelEdgeInfo{}, err
×
4377
        }
×
4378
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,721✔
4379
                return models.ChannelEdgeInfo{}, err
×
4380
        }
×
4381

4382
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,721✔
4383
                return models.ChannelEdgeInfo{}, err
×
4384
        }
×
4385

4386
        // We'll try and see if there are any opaque bytes left, if not, then
4387
        // we'll ignore the EOF error and return the edge as is.
4388
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,721✔
4389
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,721✔
4390
        )
4,721✔
4391
        switch {
4,721✔
4392
        case err == io.ErrUnexpectedEOF:
×
4393
        case err == io.EOF:
×
4394
        case err != nil:
×
4395
                return models.ChannelEdgeInfo{}, err
×
4396
        }
4397

4398
        return edgeInfo, nil
4,721✔
4399
}
4400

4401
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4402
        from, to []byte) error {
2,660✔
4403

2,660✔
4404
        var edgeKey [33 + 8]byte
2,660✔
4405
        copy(edgeKey[:], from)
2,660✔
4406
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,660✔
4407

2,660✔
4408
        var b bytes.Buffer
2,660✔
4409
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,660✔
4410
                return err
×
4411
        }
×
4412

4413
        // Before we write out the new edge, we'll create a new entry in the
4414
        // update index in order to keep it fresh.
4415
        updateUnix := uint64(edge.LastUpdate.Unix())
2,660✔
4416
        var indexKey [8 + 8]byte
2,660✔
4417
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,660✔
4418
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,660✔
4419

2,660✔
4420
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,660✔
4421
        if err != nil {
2,660✔
4422
                return err
×
4423
        }
×
4424

4425
        // If there was already an entry for this edge, then we'll need to
4426
        // delete the old one to ensure we don't leave around any after-images.
4427
        // An unknown policy value does not have a update time recorded, so
4428
        // it also does not need to be removed.
4429
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
2,660✔
4430
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,686✔
4431

26✔
4432
                // In order to delete the old entry, we'll need to obtain the
26✔
4433
                // *prior* update time in order to delete it. To do this, we'll
26✔
4434
                // need to deserialize the existing policy within the database
26✔
4435
                // (now outdated by the new one), and delete its corresponding
26✔
4436
                // entry within the update index. We'll ignore any
26✔
4437
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
26✔
4438
                // the channel ID and update time to delete the entry.
26✔
4439
                // TODO(halseth): get rid of these invalid policies in a
26✔
4440
                // migration.
26✔
4441
                oldEdgePolicy, err := deserializeChanEdgePolicy(
26✔
4442
                        bytes.NewReader(edgeBytes),
26✔
4443
                )
26✔
4444
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
26✔
4445
                        return err
×
4446
                }
×
4447

4448
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
26✔
4449

26✔
4450
                var oldIndexKey [8 + 8]byte
26✔
4451
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
26✔
4452
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
26✔
4453

26✔
4454
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
26✔
4455
                        return err
×
4456
                }
×
4457
        }
4458

4459
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,660✔
4460
                return err
×
4461
        }
×
4462

4463
        err = updateEdgePolicyDisabledIndex(
2,660✔
4464
                edges, edge.ChannelID,
2,660✔
4465
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,660✔
4466
                edge.IsDisabled(),
2,660✔
4467
        )
2,660✔
4468
        if err != nil {
2,660✔
4469
                return err
×
4470
        }
×
4471

4472
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,660✔
4473
}
4474

4475
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4476
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4477
// one.
4478
// The direction represents the direction of the edge and disabled is used for
4479
// deciding whether to remove or add an entry to the bucket.
4480
// In general a channel is disabled if two entries for the same chanID exist
4481
// in this bucket.
4482
// Maintaining the bucket this way allows a fast retrieval of disabled
4483
// channels, for example when prune is needed.
4484
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4485
        direction bool, disabled bool) error {
2,932✔
4486

2,932✔
4487
        var disabledEdgeKey [8 + 1]byte
2,932✔
4488
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,932✔
4489
        if direction {
4,396✔
4490
                disabledEdgeKey[8] = 1
1,464✔
4491
        }
1,464✔
4492

4493
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,932✔
4494
                disabledEdgePolicyBucket,
2,932✔
4495
        )
2,932✔
4496
        if err != nil {
2,932✔
4497
                return err
×
4498
        }
×
4499

4500
        if disabled {
2,960✔
4501
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
28✔
4502
        }
28✔
4503

4504
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,906✔
4505
}
4506

4507
// putChanEdgePolicyUnknown marks the edge policy as unknown
4508
// in the edges bucket.
4509
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4510
        from []byte) error {
2,956✔
4511

2,956✔
4512
        var edgeKey [33 + 8]byte
2,956✔
4513
        copy(edgeKey[:], from)
2,956✔
4514
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,956✔
4515

2,956✔
4516
        if edges.Get(edgeKey[:]) != nil {
2,956✔
4517
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4518
                        " when there is already a policy present", channelID)
×
4519
        }
×
4520

4521
        return edges.Put(edgeKey[:], unknownPolicy)
2,956✔
4522
}
4523

4524
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4525
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,144✔
4526

8,144✔
4527
        var edgeKey [33 + 8]byte
8,144✔
4528
        copy(edgeKey[:], nodePub)
8,144✔
4529
        copy(edgeKey[33:], chanID[:])
8,144✔
4530

8,144✔
4531
        edgeBytes := edges.Get(edgeKey[:])
8,144✔
4532
        if edgeBytes == nil {
8,144✔
4533
                return nil, ErrEdgeNotFound
×
4534
        }
×
4535

4536
        // No need to deserialize unknown policy.
4537
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,491✔
4538
                return nil, nil
347✔
4539
        }
347✔
4540

4541
        edgeReader := bytes.NewReader(edgeBytes)
7,799✔
4542

7,799✔
4543
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,799✔
4544
        switch {
7,799✔
4545
        // If the db policy was missing an expected optional field, we return
4546
        // nil as if the policy was unknown.
4547
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4548
                return nil, nil
1✔
4549

4550
        case err != nil:
×
4551
                return nil, err
×
4552
        }
4553

4554
        return ep, nil
7,798✔
4555
}
4556

4557
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4558
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4559
        error) {
233✔
4560

233✔
4561
        edgeInfo := edgeIndex.Get(chanID)
233✔
4562
        if edgeInfo == nil {
233✔
4563
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4564
                        chanID)
×
4565
        }
×
4566

4567
        // The first node is contained within the first half of the edge
4568
        // information. We only propagate the error here and below if it's
4569
        // something other than edge non-existence.
4570
        node1Pub := edgeInfo[:33]
233✔
4571
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
233✔
4572
        if err != nil {
233✔
4573
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4574
                        node1Pub)
×
4575
        }
×
4576

4577
        // Similarly, the second node is contained within the latter
4578
        // half of the edge information.
4579
        node2Pub := edgeInfo[33:66]
233✔
4580
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
233✔
4581
        if err != nil {
233✔
4582
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4583
                        node2Pub)
×
4584
        }
×
4585

4586
        return edge1, edge2, nil
233✔
4587
}
4588

4589
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4590
        to []byte) error {
2,662✔
4591

2,662✔
4592
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,662✔
4593
        if err != nil {
2,662✔
4594
                return err
×
4595
        }
×
4596

4597
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,662✔
4598
                return err
×
4599
        }
×
4600

4601
        var scratch [8]byte
2,662✔
4602
        updateUnix := uint64(edge.LastUpdate.Unix())
2,662✔
4603
        byteOrder.PutUint64(scratch[:], updateUnix)
2,662✔
4604
        if _, err := w.Write(scratch[:]); err != nil {
2,662✔
4605
                return err
×
4606
        }
×
4607

4608
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,662✔
4609
                return err
×
4610
        }
×
4611
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,662✔
4612
                return err
×
4613
        }
×
4614
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,662✔
4615
                return err
×
4616
        }
×
4617
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,662✔
4618
                return err
×
4619
        }
×
4620
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,662✔
4621
        if err != nil {
2,662✔
4622
                return err
×
4623
        }
×
4624
        err = binary.Write(
2,662✔
4625
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,662✔
4626
        )
2,662✔
4627
        if err != nil {
2,662✔
4628
                return err
×
4629
        }
×
4630

4631
        if _, err := w.Write(to); err != nil {
2,662✔
4632
                return err
×
4633
        }
×
4634

4635
        // If the max_htlc field is present, we write it. To be compatible with
4636
        // older versions that wasn't aware of this field, we write it as part
4637
        // of the opaque data.
4638
        // TODO(halseth): clean up when moving to TLV.
4639
        var opaqueBuf bytes.Buffer
2,662✔
4640
        if edge.MessageFlags.HasMaxHtlc() {
4,942✔
4641
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,280✔
4642
                if err != nil {
2,280✔
4643
                        return err
×
4644
                }
×
4645
        }
4646

4647
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,662✔
4648
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4649
        }
×
4650
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,662✔
4651
                return err
×
4652
        }
×
4653

4654
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,662✔
4655
                return err
×
4656
        }
×
4657
        return nil
2,662✔
4658
}
4659

4660
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,824✔
4661
        // Deserialize the policy. Note that in case an optional field is not
7,824✔
4662
        // found, both an error and a populated policy object are returned.
7,824✔
4663
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,824✔
4664
        if deserializeErr != nil &&
7,824✔
4665
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,824✔
4666

×
4667
                return nil, deserializeErr
×
4668
        }
×
4669

4670
        return edge, deserializeErr
7,824✔
4671
}
4672

4673
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4674
        error) {
8,828✔
4675

8,828✔
4676
        edge := &models.ChannelEdgePolicy{}
8,828✔
4677

8,828✔
4678
        var err error
8,828✔
4679
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,828✔
4680
        if err != nil {
8,828✔
4681
                return nil, err
×
4682
        }
×
4683

4684
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,828✔
4685
                return nil, err
×
4686
        }
×
4687

4688
        var scratch [8]byte
8,828✔
4689
        if _, err := r.Read(scratch[:]); err != nil {
8,828✔
4690
                return nil, err
×
4691
        }
×
4692
        unix := int64(byteOrder.Uint64(scratch[:]))
8,828✔
4693
        edge.LastUpdate = time.Unix(unix, 0)
8,828✔
4694

8,828✔
4695
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,828✔
4696
                return nil, err
×
4697
        }
×
4698
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,828✔
4699
                return nil, err
×
4700
        }
×
4701
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,828✔
4702
                return nil, err
×
4703
        }
×
4704

4705
        var n uint64
8,828✔
4706
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,828✔
4707
                return nil, err
×
4708
        }
×
4709
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,828✔
4710

8,828✔
4711
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,828✔
4712
                return nil, err
×
4713
        }
×
4714
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,828✔
4715

8,828✔
4716
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,828✔
4717
                return nil, err
×
4718
        }
×
4719
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,828✔
4720

8,828✔
4721
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,828✔
4722
                return nil, err
×
4723
        }
×
4724

4725
        // We'll try and see if there are any opaque bytes left, if not, then
4726
        // we'll ignore the EOF error and return the edge as is.
4727
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,828✔
4728
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,828✔
4729
        )
8,828✔
4730
        switch {
8,828✔
4731
        case err == io.ErrUnexpectedEOF:
×
4732
        case err == io.EOF:
3✔
4733
        case err != nil:
×
4734
                return nil, err
×
4735
        }
4736

4737
        // See if optional fields are present.
4738
        if edge.MessageFlags.HasMaxHtlc() {
17,285✔
4739
                // The max_htlc field should be at the beginning of the opaque
8,457✔
4740
                // bytes.
8,457✔
4741
                opq := edge.ExtraOpaqueData
8,457✔
4742

8,457✔
4743
                // If the max_htlc field is not present, it might be old data
8,457✔
4744
                // stored before this field was validated. We'll return the
8,457✔
4745
                // edge along with an error.
8,457✔
4746
                if len(opq) < 8 {
8,460✔
4747
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4748
                }
3✔
4749

4750
                maxHtlc := byteOrder.Uint64(opq[:8])
8,454✔
4751
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,454✔
4752

8,454✔
4753
                // Exclude the parsed field from the rest of the opaque data.
8,454✔
4754
                edge.ExtraOpaqueData = opq[8:]
8,454✔
4755
        }
4756

4757
        return edge, nil
8,825✔
4758
}
4759

4760
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4761
// ChannelGraph and a kvdb.RTx.
4762
type chanGraphNodeTx struct {
4763
        tx   kvdb.RTx
4764
        db   *ChannelGraph
4765
        node *models.LightningNode
4766
}
4767

4768
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4769
// interface.
4770
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4771

4772
func newChanGraphNodeTx(tx kvdb.RTx, db *ChannelGraph,
4773
        node *models.LightningNode) *chanGraphNodeTx {
3,916✔
4774

3,916✔
4775
        return &chanGraphNodeTx{
3,916✔
4776
                tx:   tx,
3,916✔
4777
                db:   db,
3,916✔
4778
                node: node,
3,916✔
4779
        }
3,916✔
4780
}
3,916✔
4781

4782
// Node returns the raw information of the node.
4783
//
4784
// NOTE: This is a part of the NodeRTx interface.
4785
func (c *chanGraphNodeTx) Node() *models.LightningNode {
4,841✔
4786
        return c.node
4,841✔
4787
}
4,841✔
4788

4789
// FetchNode fetches the node with the given pub key under the same transaction
4790
// used to fetch the current node. The returned node is also a NodeRTx and any
4791
// operations on that NodeRTx will also be done under the same transaction.
4792
//
4793
// NOTE: This is a part of the NodeRTx interface.
4794
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
2,944✔
4795
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
2,944✔
4796
        if err != nil {
2,944✔
4797
                return nil, err
×
4798
        }
×
4799

4800
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4801
}
4802

4803
// ForEachChannel can be used to iterate over the node's channels under
4804
// the same transaction used to fetch the node.
4805
//
4806
// NOTE: This is a part of the NodeRTx interface.
4807
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4808
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4809

965✔
4810
        return c.db.ForEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4811
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4812
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4813

2,944✔
4814
                        return f(info, policy1, policy2)
2,944✔
4815
                },
2,944✔
4816
        )
4817
}
4818

4819
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4820
// purposes.
4821
func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph,
4822
        error) {
40✔
4823

40✔
4824
        opts := DefaultOptions()
40✔
4825
        for _, modifier := range modifiers {
40✔
4826
                modifier(opts)
×
4827
        }
×
4828

4829
        // Next, create channelgraph for the first time.
4830
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
40✔
4831
        if err != nil {
40✔
4832
                backendCleanup()
×
4833
                return nil, err
×
4834
        }
×
4835

4836
        graph, err := NewChannelGraph(backend)
40✔
4837
        if err != nil {
40✔
4838
                backendCleanup()
×
4839
                return nil, err
×
4840
        }
×
4841

4842
        t.Cleanup(func() {
80✔
4843
                _ = backend.Close()
40✔
4844
                backendCleanup()
40✔
4845
        })
40✔
4846

4847
        return graph, nil
40✔
4848
}
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