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

lightningnetwork / lnd / 13393430089

18 Feb 2025 02:54PM UTC coverage: 58.804% (+0.02%) from 58.787%
13393430089

push

github

web-flow
Merge pull request #9513 from ellemouton/graph5

graph+routing: refactor to remove `graphsession`

72 of 78 new or added lines in 7 files covered. (92.31%)

41 existing lines in 12 files now uncovered.

136126 of 231492 relevant lines covered (58.8%)

19339.97 hits per line

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

77.35
/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) {
176✔
202

176✔
203
        opts := DefaultOptions()
176✔
204
        for _, o := range options {
281✔
205
                o(opts)
105✔
206
        }
105✔
207

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

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

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

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

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

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

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

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

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

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

260
        return g, nil
176✔
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) {
147✔
273

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

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

584✔
285
                        return nil
584✔
286
                }
584✔
287

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

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

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

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

993✔
307
                switch {
993✔
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
993✔
318

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

325
        return channelMap, nil
147✔
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 {
176✔
360
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
352✔
361
                for _, tlb := range graphTopLevelBuckets {
871✔
362
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
695✔
363
                                return err
×
364
                        }
×
365
                }
366

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

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

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

403
        return nil
176✔
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) {
4✔
413

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

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

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

429
        return true, node.Addresses, nil
4✔
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 {
147✔
443

147✔
444
        return c.db.View(func(tx kvdb.RTx) error {
294✔
445
                edges := tx.ReadBucket(edgeBucket)
147✔
446
                if edges == nil {
147✔
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)
147✔
453
                if err != nil {
147✔
454
                        return err
×
455
                }
×
456

457
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
147✔
458
                if edgeIndex == nil {
147✔
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(
147✔
465
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
645✔
466
                                var chanID [8]byte
498✔
467
                                copy(chanID[:], k)
498✔
468

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

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

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

498✔
487
                                return cb(&info, policy1, policy2)
498✔
488
                        },
489
                )
490
        }, func() {})
147✔
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 {
706✔
502

706✔
503
        if c.graphCache != nil {
1,170✔
504
                return c.graphCache.ForEachChannel(node, cb)
464✔
505
        }
464✔
506

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

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

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

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

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

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

550
                return cb(directedChannel)
498✔
551
        }
552
        return nodeTraversal(tx, node[:], c.db, dbCallback)
245✔
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,142✔
560

1,142✔
561
        if c.graphCache != nil {
1,598✔
562
                return c.graphCache.GetFeatures(node), nil
456✔
563
        }
456✔
564

565
        // Fallback that uses the database.
566
        targetNode, err := c.FetchLightningNodeTx(tx, node)
689✔
567
        switch err {
689✔
568
        // If the node exists and has features, return them directly.
569
        case nil:
678✔
570
                return targetNode.Features, nil
678✔
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 {
114✔
595

114✔
596
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
114✔
597
}
114✔
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) {
90✔
607

90✔
608
        return c.fetchNodeFeatures(nil, nodePub)
90✔
609
}
90✔
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 {
123✔
743
        return c.forEachNode(func(tx kvdb.RTx,
123✔
744
                node *models.LightningNode) error {
1,096✔
745

973✔
746
                return cb(newChanGraphNodeTx(tx, c, node))
973✔
747
        })
973✔
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 {
132✔
759

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

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

776
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
777
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
778
                        if err != nil {
1,181✔
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,181✔
785
                })
786
        }
787

788
        return kvdb.View(c.db, traversal, func() {})
264✔
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 {
144✔
797

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

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

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

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

828
        return kvdb.View(c.db, traversal, func() {})
288✔
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) {
234✔
836
        var source *models.LightningNode
234✔
837
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
468✔
838
                // First grab the nodes bucket which stores the mapping from
234✔
839
                // pubKey to node information.
234✔
840
                nodes := tx.ReadBucket(nodeBucket)
234✔
841
                if nodes == nil {
234✔
842
                        return ErrGraphNotFound
×
843
                }
×
844

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

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

859
        return source, nil
233✔
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) {
499✔
868

499✔
869
        selfPub := nodes.Get(sourceKey)
499✔
870
        if selfPub == nil {
500✔
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)
498✔
877
        if err != nil {
498✔
878
                return nil, err
×
879
        }
×
880

881
        return &node, nil
498✔
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 {
120✔
888
        nodePubBytes := node.PubKeyBytes[:]
120✔
889

120✔
890
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
240✔
891
                // First grab the nodes bucket which stores the mapping from
120✔
892
                // pubKey to node information.
120✔
893
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
120✔
894
                if err != nil {
120✔
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 {
120✔
901
                        return err
×
902
                }
×
903

904
                // Finally, we commit the information of the lightning node
905
                // itself.
906
                return addLightningNode(tx, node)
120✔
907
        }, func() {})
120✔
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 {
803✔
920

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

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

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

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

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

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

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

958
        return putLightningNode(nodes, aliases, updateIndex, node)
999✔
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) {
5✔
964
        var alias string
5✔
965

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

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

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

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

994
        return alias, nil
4✔
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 {
74✔
1019

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

1025
        if err := aliases.Delete(compressedPubKey); err != nil {
74✔
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)
74✔
1033
        if err != nil {
74✔
1034
                return err
×
1035
        }
×
1036

1037
        if err := nodes.Delete(compressedPubKey); err != nil {
74✔
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)
74✔
1045
        if nodeUpdateIndex == nil {
74✔
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())
74✔
1052
        var indexKey [8 + 33]byte
74✔
1053
        byteOrder.PutUint64(indexKey[:8], updateUnix)
74✔
1054
        copy(indexKey[8:], compressedPubKey)
74✔
1055

74✔
1056
        return nodeUpdateIndex.Delete(indexKey[:])
74✔
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,727✔
1067

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

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

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

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

1104
                f(r)
3✔
1105
        }
1106

1107
        return c.chanScheduler.Execute(r)
1,727✔
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,727✔
1114

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

1,727✔
1119
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,727✔
1120
        if err != nil {
1,727✔
1121
                return err
×
1122
        }
×
1123
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,727✔
1124
        if err != nil {
1,727✔
1125
                return err
×
1126
        }
×
1127
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,727✔
1128
        if err != nil {
1,727✔
1129
                return err
×
1130
        }
×
1131
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,727✔
1132
        if err != nil {
1,727✔
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,961✔
1139
                return ErrEdgeAlreadyExist
234✔
1140
        }
234✔
1141

1142
        if c.graphCache != nil {
2,796✔
1143
                c.graphCache.AddChannel(edge, nil, nil)
1,303✔
1144
        }
1,303✔
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,493✔
1151
        switch {
1,493✔
1152
        case node1Err == ErrGraphNodeNotFound:
21✔
1153
                node1Shell := models.LightningNode{
21✔
1154
                        PubKeyBytes:          edge.NodeKey1Bytes,
21✔
1155
                        HaveNodeAnnouncement: false,
21✔
1156
                }
21✔
1157
                err := addLightningNode(tx, &node1Shell)
21✔
1158
                if err != nil {
21✔
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,493✔
1167
        switch {
1,493✔
1168
        case node2Err == ErrGraphNodeNotFound:
64✔
1169
                node2Shell := models.LightningNode{
64✔
1170
                        PubKeyBytes:          edge.NodeKey2Bytes,
64✔
1171
                        HaveNodeAnnouncement: false,
64✔
1172
                }
64✔
1173
                err := addLightningNode(tx, &node2Shell)
64✔
1174
                if err != nil {
64✔
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,493✔
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,493✔
1192
                &edge.NodeKey1Bytes,
1,493✔
1193
                &edge.NodeKey2Bytes,
1,493✔
1194
        }
1,493✔
1195
        for _, key := range keys {
4,476✔
1196
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,983✔
1197
                if err != nil {
2,983✔
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,493✔
1205
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,493✔
1206
                return err
×
1207
        }
×
1208
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,493✔
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) {
215✔
1219

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

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

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

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

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

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

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

1276
                        return nil
93✔
1277
                }
1278

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

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

1290
                e1, e2, err := fetchChanEdgePolicies(
51✔
1291
                        edgeIndex, edges, channelID[:],
51✔
1292
                )
51✔
1293
                if err != nil {
51✔
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 {
72✔
1300
                        upd1Time = e1.LastUpdate
21✔
1301
                }
21✔
1302
                if e2 != nil {
70✔
1303
                        upd2Time = e2.LastUpdate
19✔
1304
                }
19✔
1305

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

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

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

1320
// UpdateChannelEdge retrieves and update edge of the graph database. Method
1321
// only reserved for updating an edge info after its already been created.
1322
// In order to maintain this constraints, we return an error in the scenario
1323
// that an edge info hasn't yet been created yet, but someone attempts to update
1324
// it.
1325
func (c *ChannelGraph) UpdateChannelEdge(edge *models.ChannelEdgeInfo) error {
4✔
1326
        // Construct the channel's primary key which is the 8-byte channel ID.
4✔
1327
        var chanKey [8]byte
4✔
1328
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
4✔
1329

4✔
1330
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
8✔
1331
                edges := tx.ReadWriteBucket(edgeBucket)
4✔
1332
                if edge == nil {
4✔
1333
                        return ErrEdgeNotFound
×
1334
                }
×
1335

1336
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
4✔
1337
                if edgeIndex == nil {
4✔
1338
                        return ErrEdgeNotFound
×
1339
                }
×
1340

1341
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
4✔
1342
                        return ErrEdgeNotFound
×
1343
                }
×
1344

1345
                if c.graphCache != nil {
8✔
1346
                        c.graphCache.UpdateChannel(edge)
4✔
1347
                }
4✔
1348

1349
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
4✔
1350
        }, func() {})
4✔
1351
}
1352

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

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

245✔
1373
        c.cacheMu.Lock()
245✔
1374
        defer c.cacheMu.Unlock()
245✔
1375

245✔
1376
        var chansClosed []*models.ChannelEdgeInfo
245✔
1377

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

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

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

142✔
1414
                        var opBytes bytes.Buffer
142✔
1415
                        err := WriteOutpoint(&opBytes, chanPoint)
142✔
1416
                        if err != nil {
142✔
1417
                                return err
×
1418
                        }
×
1419

1420
                        // First attempt to see if the channel exists within
1421
                        // the database, if not, then we can exit early.
1422
                        chanID := chanIndex.Get(opBytes.Bytes())
142✔
1423
                        if chanID == nil {
262✔
1424
                                continue
120✔
1425
                        }
1426

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

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

1447
                        chansClosed = append(chansClosed, &edgeInfo)
22✔
1448
                }
1449

1450
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
245✔
1451
                if err != nil {
245✔
1452
                        return err
×
1453
                }
×
1454

1455
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
245✔
1456
                        pruneLogBucket,
245✔
1457
                )
245✔
1458
                if err != nil {
245✔
1459
                        return err
×
1460
                }
×
1461

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

245✔
1468
                var newTip [pruneTipBytes]byte
245✔
1469
                copy(newTip[:], blockHash[:])
245✔
1470

245✔
1471
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
245✔
1472
                if err != nil {
245✔
1473
                        return err
×
1474
                }
×
1475

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

1487
        for _, channel := range chansClosed {
267✔
1488
                c.rejectCache.remove(channel.ChannelID)
22✔
1489
                c.chanCache.remove(channel.ChannelID)
22✔
1490
        }
22✔
1491

1492
        if c.graphCache != nil {
490✔
1493
                log.Debugf("Pruned graph, cache now has %s",
245✔
1494
                        c.graphCache.Stats())
245✔
1495
        }
245✔
1496

1497
        return chansClosed, nil
245✔
1498
}
1499

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

1519
                return c.pruneGraphNodes(nodes, edgeIndex)
26✔
1520
        }, func() {})
26✔
1521
}
1522

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

268✔
1529
        log.Trace("Pruning nodes from graph with no open channels")
268✔
1530

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

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

1550
                var nodePub [33]byte
507✔
1551
                copy(nodePub[:], pubKey)
507✔
1552
                nodeRefCounts[nodePub] = 0
507✔
1553

507✔
1554
                return nil
507✔
1555
        })
1556
        if err != nil {
268✔
1557
                return err
×
1558
        }
×
1559

1560
        // To ensure we never delete the source node, we'll start off by
1561
        // bumping its ref count to 1.
1562
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
268✔
1563

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

190✔
1575
                // With the nodes extracted, we'll increase the ref count of
190✔
1576
                // each of the nodes.
190✔
1577
                nodeRefCounts[node1]++
190✔
1578
                nodeRefCounts[node2]++
190✔
1579

190✔
1580
                return nil
190✔
1581
        })
190✔
1582
        if err != nil {
268✔
1583
                return err
×
1584
        }
×
1585

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

1597
                if c.graphCache != nil {
142✔
1598
                        c.graphCache.RemoveNode(nodePubKey)
71✔
1599
                }
71✔
1600

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

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

1613
                        return err
×
1614
                }
1615

1616
                log.Infof("Pruned unconnected node %x from channel graph",
71✔
1617
                        nodePubKey[:])
71✔
1618

71✔
1619
                numNodesPruned++
71✔
1620
        }
1621

1622
        if numNodesPruned > 0 {
323✔
1623
                log.Infof("Pruned %v unconnected nodes from the channel graph",
55✔
1624
                        numNodesPruned)
55✔
1625
        }
55✔
1626

1627
        return nil
268✔
1628
}
1629

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

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

164✔
1646
        // Delete everything after this height from the db up until the
164✔
1647
        // SCID alias range.
164✔
1648
        endShortChanID := aliasmgr.StartingAlias
164✔
1649

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

164✔
1656
        c.cacheMu.Lock()
164✔
1657
        defer c.cacheMu.Unlock()
164✔
1658

164✔
1659
        // Keep track of the channels that are removed from the graph.
164✔
1660
        var removedChans []*models.ChannelEdgeInfo
164✔
1661

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

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

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

1700
                        keys = append(keys, k)
107✔
1701
                        removedChans = append(removedChans, &edgeInfo)
107✔
1702
                }
1703

1704
                for _, k := range keys {
271✔
1705
                        err = c.delChannelEdgeUnsafe(
107✔
1706
                                edges, edgeIndex, chanIndex, zombieIndex,
107✔
1707
                                k, false, false,
107✔
1708
                        )
107✔
1709
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
107✔
1710
                                return err
×
1711
                        }
×
1712
                }
1713

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

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

1728
                var pruneKeyStart [4]byte
164✔
1729
                byteOrder.PutUint32(pruneKeyStart[:], height)
164✔
1730

164✔
1731
                var pruneKeyEnd [4]byte
164✔
1732
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
164✔
1733

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

1744
                for _, k := range pruneKeys {
260✔
1745
                        if err := pruneBucket.Delete(k); err != nil {
96✔
1746
                                return err
×
1747
                        }
×
1748
                }
1749

1750
                return nil
164✔
1751
        }, func() {
164✔
1752
                removedChans = nil
164✔
1753
        }); err != nil {
164✔
1754
                return nil, err
×
1755
        }
×
1756

1757
        for _, channel := range removedChans {
271✔
1758
                c.rejectCache.remove(channel.ChannelID)
107✔
1759
                c.chanCache.remove(channel.ChannelID)
107✔
1760
        }
107✔
1761

1762
        return removedChans, nil
164✔
1763
}
1764

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

56✔
1775
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
112✔
1776
                graphMeta := tx.ReadBucket(graphMetaBucket)
56✔
1777
                if graphMeta == nil {
56✔
1778
                        return ErrGraphNotFound
×
1779
                }
×
1780
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
56✔
1781
                if pruneBucket == nil {
56✔
1782
                        return ErrGraphNeverPruned
×
1783
                }
×
1784

1785
                pruneCursor := pruneBucket.ReadCursor()
56✔
1786

56✔
1787
                // The prune key with the largest block height will be our
56✔
1788
                // prune tip.
56✔
1789
                k, v := pruneCursor.Last()
56✔
1790
                if k == nil {
77✔
1791
                        return ErrGraphNeverPruned
21✔
1792
                }
21✔
1793

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

38✔
1799
                return nil
38✔
1800
        }, func() {})
56✔
1801
        if err != nil {
77✔
1802
                return nil, 0, err
21✔
1803
        }
21✔
1804

1805
        return &tipHash, tipHeight, nil
38✔
1806
}
1807

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

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

144✔
1823
        c.cacheMu.Lock()
144✔
1824
        defer c.cacheMu.Unlock()
144✔
1825

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

1848
                var rawChanID [8]byte
144✔
1849
                for _, chanID := range chanIDs {
228✔
1850
                        byteOrder.PutUint64(rawChanID[:], chanID)
84✔
1851
                        err := c.delChannelEdgeUnsafe(
84✔
1852
                                edges, edgeIndex, chanIndex, zombieIndex,
84✔
1853
                                rawChanID[:], markZombie, strictZombiePruning,
84✔
1854
                        )
84✔
1855
                        if err != nil {
140✔
1856
                                return err
56✔
1857
                        }
56✔
1858
                }
1859

1860
                return nil
88✔
1861
        }, func() {})
144✔
1862
        if err != nil {
200✔
1863
                return err
56✔
1864
        }
56✔
1865

1866
        for _, chanID := range chanIDs {
115✔
1867
                c.rejectCache.remove(chanID)
27✔
1868
                c.chanCache.remove(chanID)
27✔
1869
        }
27✔
1870

1871
        return nil
88✔
1872
}
1873

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

1889
        return chanID, nil
4✔
1890
}
1891

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

1899
        edges := tx.ReadBucket(edgeBucket)
4✔
1900
        if edges == nil {
4✔
1901
                return 0, ErrGraphNoEdgesFound
×
1902
        }
×
1903
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1904
        if chanIndex == nil {
4✔
1905
                return 0, ErrGraphNoEdgesFound
×
1906
        }
×
1907

1908
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1909
        if chanIDBytes == nil {
7✔
1910
                return 0, ErrEdgeNotFound
3✔
1911
        }
3✔
1912

1913
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1914

4✔
1915
        return chanID, nil
4✔
1916
}
1917

1918
// TODO(roasbeef): allow updates to use Batch?
1919

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

6✔
1926
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
1927
                edges := tx.ReadBucket(edgeBucket)
6✔
1928
                if edges == nil {
6✔
1929
                        return ErrGraphNoEdgesFound
×
1930
                }
×
1931
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
6✔
1932
                if edgeIndex == nil {
6✔
1933
                        return ErrGraphNoEdgesFound
×
1934
                }
×
1935

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

6✔
1940
                lastChanID, _ := cidCursor.Last()
6✔
1941

6✔
1942
                // If there's no key, then this means that we don't actually
6✔
1943
                // know of any channels, so we'll return a predicable error.
6✔
1944
                if lastChanID == nil {
10✔
1945
                        return ErrGraphNoEdgesFound
4✔
1946
                }
4✔
1947

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

1959
        return cid, nil
6✔
1960
}
1961

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

1969
        // Policy1 points to the "first" edge policy of the channel containing
1970
        // the dynamic information required to properly route through the edge.
1971
        Policy1 *models.ChannelEdgePolicy
1972

1973
        // Policy2 points to the "second" edge policy of the channel containing
1974
        // the dynamic information required to properly route through the edge.
1975
        Policy2 *models.ChannelEdgePolicy
1976

1977
        // Node1 is "node 1" in the channel. This is the node that would have
1978
        // produced Policy1 if it exists.
1979
        Node1 *models.LightningNode
1980

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

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

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

138✔
1998
        c.cacheMu.Lock()
138✔
1999
        defer c.cacheMu.Unlock()
138✔
2000

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

2016
                nodes := tx.ReadBucket(nodeBucket)
138✔
2017
                if nodes == nil {
138✔
2018
                        return ErrGraphNodesNotFound
×
2019
                }
×
2020

2021
                // We'll now obtain a cursor to perform a range query within
2022
                // the index to find all channels within the horizon.
2023
                updateCursor := edgeUpdateIndex.ReadCursor()
138✔
2024

138✔
2025
                var startTimeBytes, endTimeBytes [8 + 8]byte
138✔
2026
                byteOrder.PutUint64(
138✔
2027
                        startTimeBytes[:8], uint64(startTime.Unix()),
138✔
2028
                )
138✔
2029
                byteOrder.PutUint64(
138✔
2030
                        endTimeBytes[:8], uint64(endTime.Unix()),
138✔
2031
                )
138✔
2032

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

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

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

2053
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
42✔
2054
                                hits++
12✔
2055
                                edgesSeen[chanIDInt] = struct{}{}
12✔
2056
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
2057
                                continue
12✔
2058
                        }
2059

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

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

2080
                        node1, err := fetchLightningNode(
21✔
2081
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
2082
                        )
21✔
2083
                        if err != nil {
21✔
2084
                                return err
×
2085
                        }
×
2086

2087
                        node2, err := fetchLightningNode(
21✔
2088
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
2089
                        )
21✔
2090
                        if err != nil {
21✔
2091
                                return err
×
2092
                        }
×
2093

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

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

2120
        case err != nil:
×
2121
                return nil, err
×
2122
        }
2123

2124
        // Insert any edges loaded from disk into the cache.
2125
        for chanid, channel := range edgesToCache {
159✔
2126
                c.chanCache.insert(chanid, channel)
21✔
2127
        }
21✔
2128

2129
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
138✔
2130
                float64(hits)/float64(len(edgesInHorizon)), hits,
138✔
2131
                len(edgesInHorizon))
138✔
2132

138✔
2133
        return edgesInHorizon, nil
138✔
2134
}
2135

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

11✔
2143
        var nodesInHorizon []models.LightningNode
11✔
2144

11✔
2145
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2146
                nodes := tx.ReadBucket(nodeBucket)
11✔
2147
                if nodes == nil {
11✔
2148
                        return ErrGraphNodesNotFound
×
2149
                }
×
2150

2151
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2152
                if nodeUpdateIndex == nil {
11✔
2153
                        return ErrGraphNodesNotFound
×
2154
                }
×
2155

2156
                // We'll now obtain a cursor to perform a range query within
2157
                // the index to find all node announcements within the horizon.
2158
                updateCursor := nodeUpdateIndex.ReadCursor()
11✔
2159

11✔
2160
                var startTimeBytes, endTimeBytes [8 + 33]byte
11✔
2161
                byteOrder.PutUint64(
11✔
2162
                        startTimeBytes[:8], uint64(startTime.Unix()),
11✔
2163
                )
11✔
2164
                byteOrder.PutUint64(
11✔
2165
                        endTimeBytes[:8], uint64(endTime.Unix()),
11✔
2166
                )
11✔
2167

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

32✔
2176
                        nodePub := indexKey[8:]
32✔
2177
                        node, err := fetchLightningNode(nodes, nodePub)
32✔
2178
                        if err != nil {
32✔
2179
                                return err
×
2180
                        }
×
2181

2182
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2183
                }
2184

2185
                return nil
11✔
2186
        }, func() {
11✔
2187
                nodesInHorizon = nil
11✔
2188
        })
11✔
2189
        switch {
11✔
2190
        case err == ErrGraphNoEdgesFound:
×
2191
                fallthrough
×
2192
        case err == ErrGraphNodesNotFound:
×
2193
                break
×
2194

2195
        case err != nil:
×
2196
                return nil, err
×
2197
        }
2198

2199
        return nodesInHorizon, nil
11✔
2200
}
2201

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

125✔
2210
        var newChanIDs []uint64
125✔
2211

125✔
2212
        c.cacheMu.Lock()
125✔
2213
        defer c.cacheMu.Unlock()
125✔
2214

125✔
2215
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
250✔
2216
                edges := tx.ReadBucket(edgeBucket)
125✔
2217
                if edges == nil {
125✔
2218
                        return ErrGraphNoEdgesFound
×
2219
                }
×
2220
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
125✔
2221
                if edgeIndex == nil {
125✔
2222
                        return ErrGraphNoEdgesFound
×
2223
                }
×
2224

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

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

143✔
2237
                        // If the edge is already known, skip it.
143✔
2238
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
165✔
2239
                                continue
22✔
2240
                        }
2241

2242
                        // If the edge is a known zombie, skip it.
2243
                        if zombieIndex != nil {
248✔
2244
                                isZombie, _, _ := isZombieEdge(
124✔
2245
                                        zombieIndex, scid,
124✔
2246
                                )
124✔
2247

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

124✔
2268
                                switch {
124✔
2269
                                // If the edge is a known zombie and if we
2270
                                // would still consider it a zombie given the
2271
                                // latest update timestamps, then we skip this
2272
                                // channel.
2273
                                case isZombie && isStillZombie:
28✔
2274
                                        continue
28✔
2275

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

2289
                        newChanIDs = append(newChanIDs, scid)
96✔
2290
                }
2291

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

2305
                return ogChanIDs, nil
×
2306

2307
        case err != nil:
×
2308
                return nil, err
×
2309
        }
2310

2311
        return newChanIDs, nil
125✔
2312
}
2313

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

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

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

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

221✔
2337
        chanInfo := ChannelUpdateInfo{
221✔
2338
                ShortChannelID:       scid,
221✔
2339
                Node1UpdateTimestamp: node1Timestamp,
221✔
2340
                Node2UpdateTimestamp: node2Timestamp,
221✔
2341
        }
221✔
2342

221✔
2343
        if node1Timestamp.IsZero() {
432✔
2344
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
211✔
2345
        }
211✔
2346

2347
        if node2Timestamp.IsZero() {
432✔
2348
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
211✔
2349
        }
211✔
2350

2351
        return chanInfo
221✔
2352
}
2353

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

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

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

14✔
2377
        startChanID := &lnwire.ShortChannelID{
14✔
2378
                BlockHeight: startHeight,
14✔
2379
        }
14✔
2380

14✔
2381
        endChanID := lnwire.ShortChannelID{
14✔
2382
                BlockHeight: endHeight,
14✔
2383
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2384
                TxPosition:  math.MaxUint16,
14✔
2385
        }
14✔
2386

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

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

2405
                cursor := edgeIndex.ReadCursor()
14✔
2406

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

2420
                        if edgeInfo.AuthProof == nil {
50✔
2421
                                continue
3✔
2422
                        }
2423

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

47✔
2429
                        chanInfo := NewChannelUpdateInfo(
47✔
2430
                                cid, time.Time{}, time.Time{},
47✔
2431
                        )
47✔
2432

47✔
2433
                        if !withTimestamps {
69✔
2434
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2435
                                        channelsPerBlock[cid.BlockHeight],
22✔
2436
                                        chanInfo,
22✔
2437
                                )
22✔
2438

22✔
2439
                                continue
22✔
2440
                        }
2441

2442
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2443

25✔
2444
                        rawPolicy := edges.Get(node1Key)
25✔
2445
                        if len(rawPolicy) != 0 {
34✔
2446
                                r := bytes.NewReader(rawPolicy)
9✔
2447

9✔
2448
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2449
                                if err != nil && !errors.Is(
9✔
2450
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2451
                                ) {
9✔
2452

×
2453
                                        return err
×
2454
                                }
×
2455

2456
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2457
                        }
2458

2459
                        rawPolicy = edges.Get(node2Key)
25✔
2460
                        if len(rawPolicy) != 0 {
39✔
2461
                                r := bytes.NewReader(rawPolicy)
14✔
2462

14✔
2463
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2464
                                if err != nil && !errors.Is(
14✔
2465
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2466
                                ) {
14✔
2467

×
2468
                                        return err
×
2469
                                }
×
2470

2471
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2472
                        }
2473

2474
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2475
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2476
                        )
25✔
2477
                }
2478

2479
                return nil
14✔
2480
        }, func() {
14✔
2481
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2482
        })
14✔
2483

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

2490
        case err != nil:
×
2491
                return nil, err
×
2492
        }
2493

2494
        // Return the channel ranges in ascending block height order.
2495
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2496
        for block := range channelsPerBlock {
36✔
2497
                blocks = append(blocks, block)
25✔
2498
        }
25✔
2499
        sort.Slice(blocks, func(i, j int) bool {
40✔
2500
                return blocks[i] < blocks[j]
29✔
2501
        })
29✔
2502

2503
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2504
        for _, block := range blocks {
36✔
2505
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2506
                        Height:   block,
25✔
2507
                        Channels: channelsPerBlock[block],
25✔
2508
                })
25✔
2509
        }
25✔
2510

2511
        return channelRanges, nil
11✔
2512
}
2513

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

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

28✔
2535
        var (
28✔
2536
                chanEdges []ChannelEdge
28✔
2537
                cidBytes  [8]byte
28✔
2538
        )
28✔
2539

28✔
2540
        fetchChanInfos := func(tx kvdb.RTx) error {
56✔
2541
                edges := tx.ReadBucket(edgeBucket)
28✔
2542
                if edges == nil {
28✔
2543
                        return ErrGraphNoEdgesFound
×
2544
                }
×
2545
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
28✔
2546
                if edgeIndex == nil {
28✔
2547
                        return ErrGraphNoEdgesFound
×
2548
                }
×
2549
                nodes := tx.ReadBucket(nodeBucket)
28✔
2550
                if nodes == nil {
28✔
2551
                        return ErrGraphNotFound
×
2552
                }
×
2553

2554
                for _, cid := range chanIDs {
63✔
2555
                        byteOrder.PutUint64(cidBytes[:], cid)
35✔
2556

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

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

2579
                        node1, err := fetchLightningNode(
11✔
2580
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2581
                        )
11✔
2582
                        if err != nil {
11✔
2583
                                return err
×
2584
                        }
×
2585

2586
                        node2, err := fetchLightningNode(
11✔
2587
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2588
                        )
11✔
2589
                        if err != nil {
11✔
2590
                                return err
×
2591
                        }
×
2592

2593
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2594
                                Info:    &edgeInfo,
11✔
2595
                                Policy1: edge1,
11✔
2596
                                Policy2: edge2,
11✔
2597
                                Node1:   &node1,
11✔
2598
                                Node2:   &node2,
11✔
2599
                        })
11✔
2600
                }
2601
                return nil
28✔
2602
        }
2603

2604
        if tx == nil {
35✔
2605
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2606
                        chanEdges = nil
7✔
2607
                })
7✔
2608
                if err != nil {
7✔
2609
                        return nil, err
×
2610
                }
×
2611

2612
                return chanEdges, nil
7✔
2613
        }
2614

2615
        err := fetchChanInfos(tx)
21✔
2616
        if err != nil {
21✔
2617
                return nil, err
×
2618
        }
×
2619

2620
        return chanEdges, nil
21✔
2621
}
2622

2623
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2624
        edge1, edge2 *models.ChannelEdgePolicy) error {
152✔
2625

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

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

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

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

2662
        return nil
152✔
2663
}
2664

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

208✔
2676
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
208✔
2677
        if err != nil {
264✔
2678
                return err
56✔
2679
        }
56✔
2680

2681
        if c.graphCache != nil {
304✔
2682
                c.graphCache.RemoveChannel(
152✔
2683
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
152✔
2684
                        edgeInfo.ChannelID,
152✔
2685
                )
152✔
2686
        }
152✔
2687

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

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

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

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

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

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

2754
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
26✔
2755
        if strictZombie {
29✔
2756
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2757
        }
3✔
2758

2759
        return markEdgeZombie(
26✔
2760
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
26✔
2761
        )
26✔
2762
}
2763

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

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

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

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

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

2,666✔
2814
        var (
2,666✔
2815
                isUpdate1    bool
2,666✔
2816
                edgeNotFound bool
2,666✔
2817
        )
2,666✔
2818

2,666✔
2819
        r := &batch.Request{
2,666✔
2820
                Reset: func() {
5,332✔
2821
                        isUpdate1 = false
2,666✔
2822
                        edgeNotFound = false
2,666✔
2823
                },
2,666✔
2824
                Update: func(tx kvdb.RwTx) error {
2,666✔
2825
                        var err error
2,666✔
2826
                        isUpdate1, err = updateEdgePolicy(
2,666✔
2827
                                tx, edge, c.graphCache,
2,666✔
2828
                        )
2,666✔
2829

2,666✔
2830
                        if err != nil {
2,669✔
2831
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
3✔
2832
                        }
3✔
2833

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

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

2856
        for _, f := range op {
2,669✔
2857
                f(r)
3✔
2858
        }
3✔
2859

2860
        return c.chanScheduler.Execute(r)
2,666✔
2861
}
2862

2863
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2864
        isUpdate1 bool) {
2,663✔
2865

2,663✔
2866
        // If an entry for this channel is found in reject cache, we'll modify
2,663✔
2867
        // the entry with the updated timestamp for the direction that was just
2,663✔
2868
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,663✔
2869
        // during the next query for this edge.
2,663✔
2870
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,671✔
2871
                if isUpdate1 {
14✔
2872
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2873
                } else {
11✔
2874
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2875
                }
5✔
2876
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2877
        }
2878

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

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

2,666✔
2900
        edges := tx.ReadWriteBucket(edgeBucket)
2,666✔
2901
        if edges == nil {
2,666✔
2902
                return false, ErrEdgeNotFound
×
2903
        }
×
2904
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,666✔
2905
        if edgeIndex == nil {
2,666✔
2906
                return false, ErrEdgeNotFound
×
2907
        }
×
2908

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

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

2921
        // Depending on the flags value passed above, either the first
2922
        // or second edge policy is being updated.
2923
        var fromNode, toNode []byte
2,663✔
2924
        var isUpdate1 bool
2,663✔
2925
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,000✔
2926
                fromNode = nodeInfo[:33]
1,337✔
2927
                toNode = nodeInfo[33:66]
1,337✔
2928
                isUpdate1 = true
1,337✔
2929
        } else {
2,666✔
2930
                fromNode = nodeInfo[33:66]
1,329✔
2931
                toNode = nodeInfo[:33]
1,329✔
2932
                isUpdate1 = false
1,329✔
2933
        }
1,329✔
2934

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

2942
        var (
2,663✔
2943
                fromNodePubKey route.Vertex
2,663✔
2944
                toNodePubKey   route.Vertex
2,663✔
2945
        )
2,663✔
2946
        copy(fromNodePubKey[:], fromNode)
2,663✔
2947
        copy(toNodePubKey[:], toNode)
2,663✔
2948

2,663✔
2949
        if graphCache != nil {
4,940✔
2950
                graphCache.UpdatePolicy(
2,277✔
2951
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,277✔
2952
                )
2,277✔
2953
        }
2,277✔
2954

2955
        return isUpdate1, nil
2,663✔
2956
}
2957

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

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

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

6✔
2981
                        nodeIsPublic = true
6✔
2982
                        return errDone
6✔
2983
                }
6✔
2984

2985
                // Since the edge _does_ extend to the source node, we'll also
2986
                // need to ensure that this is a public edge.
2987
                if info.AuthProof != nil {
19✔
2988
                        nodeIsPublic = true
9✔
2989
                        return errDone
9✔
2990
                }
9✔
2991

2992
                // Otherwise, we'll continue our search.
2993
                return nil
4✔
2994
        })
2995
        if err != nil && err != errDone {
16✔
2996
                return false, err
×
2997
        }
×
2998

2999
        return nodeIsPublic, nil
16✔
3000
}
3001

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

3,633✔
3009
        return c.fetchLightningNode(tx, nodePub)
3,633✔
3010
}
3,633✔
3011

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

155✔
3018
        return c.fetchLightningNode(nil, nodePub)
155✔
3019
}
155✔
3020

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

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

3037
                // If a key for this serialized public key isn't found, then
3038
                // the target node doesn't exist within the database.
3039
                nodeBytes := nodes.Get(nodePub[:])
3,785✔
3040
                if nodeBytes == nil {
3,802✔
3041
                        return ErrGraphNodeNotFound
17✔
3042
                }
17✔
3043

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

3052
                node = &n
3,771✔
3053

3,771✔
3054
                return nil
3,771✔
3055
        }
3056

3057
        if tx == nil {
3,943✔
3058
                err := kvdb.View(
158✔
3059
                        c.db, fetch, func() {
316✔
3060
                                node = nil
158✔
3061
                        },
158✔
3062
                )
3063
                if err != nil {
164✔
3064
                        return nil, err
6✔
3065
                }
6✔
3066

3067
                return node, nil
155✔
3068
        }
3069

3070
        err := fetch(tx)
3,627✔
3071
        if err != nil {
3,638✔
3072
                return nil, err
11✔
3073
        }
11✔
3074

3075
        return node, nil
3,616✔
3076
}
3077

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

19✔
3086
        var (
19✔
3087
                updateTime time.Time
19✔
3088
                exists     bool
19✔
3089
        )
19✔
3090

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

3099
                // If a key for this serialized public key isn't found, we can
3100
                // exit early.
3101
                nodeBytes := nodes.Get(nodePub[:])
19✔
3102
                if nodeBytes == nil {
25✔
3103
                        exists = false
6✔
3104
                        return nil
6✔
3105
                }
6✔
3106

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

3116
                exists = true
16✔
3117
                updateTime = node.LastUpdate
16✔
3118
                return nil
16✔
3119
        }, func() {
19✔
3120
                updateTime = time.Time{}
19✔
3121
                exists = false
19✔
3122
        })
19✔
3123
        if err != nil {
19✔
3124
                return time.Time{}, exists, err
×
3125
        }
×
3126

3127
        return updateTime, exists, nil
19✔
3128
}
3129

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

1,269✔
3136
        traversal := func(tx kvdb.RTx) error {
2,538✔
3137
                edges := tx.ReadBucket(edgeBucket)
1,269✔
3138
                if edges == nil {
1,269✔
3139
                        return ErrGraphNotFound
×
3140
                }
×
3141
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,269✔
3142
                if edgeIndex == nil {
1,269✔
3143
                        return ErrGraphNoEdgesFound
×
3144
                }
×
3145

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

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

3173
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,843✔
3174
                                edges, chanID, nodePub,
3,843✔
3175
                        )
3,843✔
3176
                        if err != nil {
3,843✔
3177
                                return err
×
3178
                        }
×
3179

3180
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,843✔
3181
                        if err != nil {
3,843✔
3182
                                return err
×
3183
                        }
×
3184

3185
                        incomingPolicy, err := fetchChanEdgePolicy(
3,843✔
3186
                                edges, chanID, otherNode[:],
3,843✔
3187
                        )
3,843✔
3188
                        if err != nil {
3,843✔
3189
                                return err
×
3190
                        }
×
3191

3192
                        // Finally, we execute the callback.
3193
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,843✔
3194
                        if err != nil {
3,855✔
3195
                                return err
12✔
3196
                        }
12✔
3197
                }
3198

3199
                return nil
1,260✔
3200
        }
3201

3202
        // If no transaction was provided, then we'll create a new transaction
3203
        // to execute the transaction within.
3204
        if tx == nil {
1,281✔
3205
                return kvdb.View(db, traversal, func() {})
24✔
3206
        }
3207

3208
        // Otherwise, we re-use the existing transaction to execute the graph
3209
        // traversal.
3210
        return traversal(tx)
1,260✔
3211
}
3212

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

9✔
3225
        return nodeTraversal(nil, nodePub[:], c.db, cb)
9✔
3226
}
9✔
3227

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

1,021✔
3246
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,021✔
3247
}
1,021✔
3248

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

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

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

3277
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3278
                if err != nil {
3✔
3279
                        return err
×
3280
                }
×
3281

3282
                targetNode = &node
3✔
3283

3✔
3284
                return nil
3✔
3285
        }
3286

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

3298
        return targetNode, err
3✔
3299
}
3300

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

25✔
3310
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3311
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3312

25✔
3313
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3314
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3315

25✔
3316
        return node1Key[:], node2Key[:]
25✔
3317
}
25✔
3318

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

14✔
3328
        var (
14✔
3329
                edgeInfo *models.ChannelEdgeInfo
14✔
3330
                policy1  *models.ChannelEdgePolicy
14✔
3331
                policy2  *models.ChannelEdgePolicy
14✔
3332
        )
14✔
3333

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

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

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

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

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

3385
                policy1 = e1
4✔
3386
                policy2 = e2
4✔
3387
                return nil
4✔
3388
        }, func() {
14✔
3389
                edgeInfo = nil
14✔
3390
                policy1 = nil
14✔
3391
                policy2 = nil
14✔
3392
        })
14✔
3393
        if err != nil {
27✔
3394
                return nil, nil, nil, err
13✔
3395
        }
13✔
3396

3397
        return edgeInfo, policy1, policy2, nil
4✔
3398
}
3399

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

28✔
3413
        var (
28✔
3414
                edgeInfo  *models.ChannelEdgeInfo
28✔
3415
                policy1   *models.ChannelEdgePolicy
28✔
3416
                policy2   *models.ChannelEdgePolicy
28✔
3417
                channelID [8]byte
28✔
3418
        )
28✔
3419

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

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

3440
                byteOrder.PutUint64(channelID[:], chanID)
28✔
3441

28✔
3442
                // Now, attempt to fetch edge.
28✔
3443
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
28✔
3444

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

3456
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3457
                                zombieIndex, chanID,
4✔
3458
                        )
4✔
3459
                        if !isZombie {
7✔
3460
                                return ErrEdgeNotFound
3✔
3461
                        }
3✔
3462

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

3474
                // Otherwise, we'll just return the error if any.
3475
                if err != nil {
27✔
3476
                        return err
×
3477
                }
×
3478

3479
                edgeInfo = &edge
27✔
3480

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

3490
                policy1 = e1
27✔
3491
                policy2 = e2
27✔
3492
                return nil
27✔
3493
        }, func() {
28✔
3494
                edgeInfo = nil
28✔
3495
                policy1 = nil
28✔
3496
                policy2 = nil
28✔
3497
        })
28✔
3498
        if err == ErrZombieEdge {
32✔
3499
                return edgeInfo, nil, nil, err
4✔
3500
        }
4✔
3501
        if err != nil {
30✔
3502
                return nil, nil, nil, err
3✔
3503
        }
3✔
3504

3505
        return edgeInfo, policy1, policy2, nil
27✔
3506
}
3507

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

3527
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3528
                return err
16✔
3529
        }, func() {
16✔
3530
                nodeIsPublic = false
16✔
3531
        })
16✔
3532
        if err != nil {
16✔
3533
                return false, err
×
3534
        }
×
3535

3536
        return nodeIsPublic, nil
16✔
3537
}
3538

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

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

49✔
3556
        return bldr.Script()
49✔
3557
}
3558

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

3567
        // OutPoint is the outpoint of the target channel.
3568
        OutPoint wire.OutPoint
3569
}
3570

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

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

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

45✔
3609
                                var chanPoint wire.OutPoint
45✔
3610
                                err := ReadOutpoint(chanPointReader, &chanPoint)
45✔
3611
                                if err != nil {
45✔
3612
                                        return err
×
3613
                                }
×
3614

3615
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3616
                                        edgeIndex, chanID,
45✔
3617
                                )
45✔
3618
                                if err != nil {
45✔
3619
                                        return err
×
3620
                                }
×
3621

3622
                                pkScript, err := genMultiSigP2WSH(
45✔
3623
                                        edgeInfo.BitcoinKey1Bytes[:],
45✔
3624
                                        edgeInfo.BitcoinKey2Bytes[:],
45✔
3625
                                )
45✔
3626
                                if err != nil {
45✔
3627
                                        return err
×
3628
                                }
×
3629

3630
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3631
                                        FundingPkScript: pkScript,
45✔
3632
                                        OutPoint:        chanPoint,
45✔
3633
                                })
45✔
3634

45✔
3635
                                return nil
45✔
3636
                        },
3637
                )
3638
        }, func() {
25✔
3639
                edgePoints = nil
25✔
3640
        }); err != nil {
25✔
3641
                return nil, err
×
3642
        }
×
3643

3644
        return edgePoints, nil
25✔
3645
}
3646

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

116✔
3653
        c.cacheMu.Lock()
116✔
3654
        defer c.cacheMu.Unlock()
116✔
3655

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

3667
                if c.graphCache != nil {
232✔
3668
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
116✔
3669
                }
116✔
3670

3671
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
116✔
3672
        })
3673
        if err != nil {
116✔
3674
                return err
×
3675
        }
×
3676

3677
        c.rejectCache.remove(chanID)
116✔
3678
        c.chanCache.remove(chanID)
116✔
3679

116✔
3680
        return nil
116✔
3681
}
3682

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

142✔
3689
        var k [8]byte
142✔
3690
        byteOrder.PutUint64(k[:], chanID)
142✔
3691

142✔
3692
        var v [66]byte
142✔
3693
        copy(v[:33], pubKey1[:])
142✔
3694
        copy(v[33:], pubKey2[:])
142✔
3695

142✔
3696
        return zombieIndex.Put(k[:], v[:])
142✔
3697
}
142✔
3698

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

2✔
3704
        return c.markEdgeLiveUnsafe(nil, chanID)
2✔
3705
}
2✔
3706

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

3724
                var k [8]byte
23✔
3725
                byteOrder.PutUint64(k[:], chanID)
23✔
3726

23✔
3727
                if len(zombieIndex.Get(k[:])) == 0 {
24✔
3728
                        return ErrZombieEdgeNotFound
1✔
3729
                }
1✔
3730

3731
                return zombieIndex.Delete(k[:])
22✔
3732
        }
3733

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

3746
        c.rejectCache.remove(chanID)
22✔
3747
        c.chanCache.remove(chanID)
22✔
3748

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

3757
                for _, edgeInfo := range edgeInfos {
22✔
3758
                        c.graphCache.AddChannel(
×
3759
                                edgeInfo.Info, edgeInfo.Policy1,
×
3760
                                edgeInfo.Policy2,
×
3761
                        )
×
3762
                }
×
3763
        }
3764

3765
        return nil
22✔
3766
}
3767

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

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

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

3798
        return isZombie, pubKey1, pubKey2
5✔
3799
}
3800

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

220✔
3807
        var k [8]byte
220✔
3808
        byteOrder.PutUint64(k[:], chanID)
220✔
3809

220✔
3810
        v := zombieIndex.Get(k[:])
220✔
3811
        if v == nil {
356✔
3812
                return false, [33]byte{}, [33]byte{}
136✔
3813
        }
136✔
3814

3815
        var pubKey1, pubKey2 [33]byte
87✔
3816
        copy(pubKey1[:], v[:33])
87✔
3817
        copy(pubKey2[:], v[33:])
87✔
3818

87✔
3819
        return true, pubKey1, pubKey2
87✔
3820
}
3821

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

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

3846
        return numZombies, nil
4✔
3847
}
3848

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

3859
                var k [8]byte
1✔
3860
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3861

1✔
3862
                return closedScids.Put(k[:], []byte{})
1✔
3863
        }, func() {})
1✔
3864
}
3865

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

3877
                var k [8]byte
5✔
3878
                byteOrder.PutUint64(k[:], scid.ToUint64())
5✔
3879

5✔
3880
                if closedScids.Get(k[:]) != nil {
6✔
3881
                        isClosed = true
1✔
3882
                        return nil
1✔
3883
                }
1✔
3884

3885
                return nil
4✔
3886
        }, func() {
5✔
3887
                isClosed = false
5✔
3888
        })
5✔
3889
        if err != nil {
5✔
3890
                return false, err
×
3891
        }
×
3892

3893
        return isClosed, nil
5✔
3894
}
3895

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

3912
                commit = func() {
108✔
3913
                        if err := tx.Rollback(); err != nil {
54✔
NEW
3914
                                log.Errorf("Unable to rollback tx: %v", err)
×
NEW
3915
                        }
×
3916
                }
3917
        }
3918
        defer commit()
136✔
3919

136✔
3920
        return cb(&nodeTraverserSession{
136✔
3921
                db: c,
136✔
3922
                tx: tx,
136✔
3923
        })
136✔
3924
}
3925

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

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

592✔
3941
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
592✔
3942
}
592✔
3943

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

623✔
3951
        return c.db.fetchNodeFeatures(c.tx, nodePub)
623✔
3952
}
623✔
3953

3954
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3955
        updateIndex kvdb.RwBucket, node *models.LightningNode) error {
999✔
3956

999✔
3957
        var (
999✔
3958
                scratch [16]byte
999✔
3959
                b       bytes.Buffer
999✔
3960
        )
999✔
3961

999✔
3962
        pub, err := node.PubKey()
999✔
3963
        if err != nil {
999✔
3964
                return err
×
3965
        }
×
3966
        nodePub := pub.SerializeCompressed()
999✔
3967

999✔
3968
        // If the node has the update time set, write it, else write 0.
999✔
3969
        updateUnix := uint64(0)
999✔
3970
        if node.LastUpdate.Unix() > 0 {
1,865✔
3971
                updateUnix = uint64(node.LastUpdate.Unix())
866✔
3972
        }
866✔
3973

3974
        byteOrder.PutUint64(scratch[:8], updateUnix)
999✔
3975
        if _, err := b.Write(scratch[:8]); err != nil {
999✔
3976
                return err
×
3977
        }
×
3978

3979
        if _, err := b.Write(nodePub); err != nil {
999✔
3980
                return err
×
3981
        }
×
3982

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

3992
                return nodeBucket.Put(nodePub, b.Bytes())
83✔
3993
        }
3994

3995
        // Write HaveNodeAnnouncement=1.
3996
        byteOrder.PutUint16(scratch[:2], 1)
919✔
3997
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
3998
                return err
×
3999
        }
×
4000

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

4011
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
919✔
4012
                return err
×
4013
        }
×
4014

4015
        if err := node.Features.Encode(&b); err != nil {
919✔
4016
                return err
×
4017
        }
×
4018

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

4025
        for _, address := range node.Addresses {
2,066✔
4026
                if err := SerializeAddr(&b, address); err != nil {
1,147✔
4027
                        return err
×
4028
                }
×
4029
        }
4030

4031
        sigLen := len(node.AuthSigBytes)
919✔
4032
        if sigLen > 80 {
919✔
4033
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4034
                        sigLen)
×
4035
        }
×
4036

4037
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
919✔
4038
        if err != nil {
919✔
4039
                return err
×
4040
        }
×
4041

4042
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
919✔
4043
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4044
        }
×
4045
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
919✔
4046
        if err != nil {
919✔
4047
                return err
×
4048
        }
×
4049

4050
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
919✔
4051
                return err
×
4052
        }
×
4053

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

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

107✔
4067
                var oldIndexKey [8 + 33]byte
107✔
4068
                copy(oldIndexKey[:8], oldUpdateTime)
107✔
4069
                copy(oldIndexKey[8:], nodePub)
107✔
4070

107✔
4071
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
107✔
4072
                        return err
×
4073
                }
×
4074
        }
4075

4076
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
919✔
4077
                return err
×
4078
        }
×
4079

4080
        return nodeBucket.Put(nodePub, b.Bytes())
919✔
4081
}
4082

4083
func fetchLightningNode(nodeBucket kvdb.RBucket,
4084
        nodePub []byte) (models.LightningNode, error) {
3,643✔
4085

3,643✔
4086
        nodeBytes := nodeBucket.Get(nodePub)
3,643✔
4087
        if nodeBytes == nil {
3,725✔
4088
                return models.LightningNode{}, ErrGraphNodeNotFound
82✔
4089
        }
82✔
4090

4091
        nodeReader := bytes.NewReader(nodeBytes)
3,564✔
4092
        return deserializeLightningNode(nodeReader)
3,564✔
4093
}
4094

4095
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4096
        *lnwire.FeatureVector, error) {
123✔
4097

123✔
4098
        var (
123✔
4099
                pubKey      route.Vertex
123✔
4100
                features    = lnwire.EmptyFeatureVector()
123✔
4101
                nodeScratch [8]byte
123✔
4102
        )
123✔
4103

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

4110
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
123✔
4111
                return pubKey, nil, err
×
4112
        }
×
4113

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

123✔
4120
        // The rest of the data is optional, and will only be there if we got a
123✔
4121
        // node announcement for this node.
123✔
4122
        if hasNodeAnn == 0 {
126✔
4123
                return pubKey, features, nil
3✔
4124
        }
3✔
4125

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

4139
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4140
                return pubKey, nil, err
×
4141
        }
×
4142

4143
        if err := features.Decode(r); err != nil {
123✔
4144
                return pubKey, nil, err
×
4145
        }
×
4146

4147
        return pubKey, features, nil
123✔
4148
}
4149

4150
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,523✔
4151
        var (
8,523✔
4152
                node    models.LightningNode
8,523✔
4153
                scratch [8]byte
8,523✔
4154
                err     error
8,523✔
4155
        )
8,523✔
4156

8,523✔
4157
        // Always populate a feature vector, even if we don't have a node
8,523✔
4158
        // announcement and short circuit below.
8,523✔
4159
        node.Features = lnwire.EmptyFeatureVector()
8,523✔
4160

8,523✔
4161
        if _, err := r.Read(scratch[:]); err != nil {
8,523✔
4162
                return models.LightningNode{}, err
×
4163
        }
×
4164

4165
        unix := int64(byteOrder.Uint64(scratch[:]))
8,523✔
4166
        node.LastUpdate = time.Unix(unix, 0)
8,523✔
4167

8,523✔
4168
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,523✔
4169
                return models.LightningNode{}, err
×
4170
        }
×
4171

4172
        if _, err := r.Read(scratch[:2]); err != nil {
8,523✔
4173
                return models.LightningNode{}, err
×
4174
        }
×
4175

4176
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,523✔
4177
        if hasNodeAnn == 1 {
16,897✔
4178
                node.HaveNodeAnnouncement = true
8,374✔
4179
        } else {
8,526✔
4180
                node.HaveNodeAnnouncement = false
152✔
4181
        }
152✔
4182

4183
        // The rest of the data is optional, and will only be there if we got a
4184
        // node announcement for this node.
4185
        if !node.HaveNodeAnnouncement {
8,675✔
4186
                return node, nil
152✔
4187
        }
152✔
4188

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

4201
        node.Alias, err = wire.ReadVarString(r, 0)
8,374✔
4202
        if err != nil {
8,374✔
4203
                return models.LightningNode{}, err
×
4204
        }
×
4205

4206
        err = node.Features.Decode(r)
8,374✔
4207
        if err != nil {
8,374✔
4208
                return models.LightningNode{}, err
×
4209
        }
×
4210

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

8,374✔
4216
        var addresses []net.Addr
8,374✔
4217
        for i := 0; i < numAddresses; i++ {
18,988✔
4218
                address, err := DeserializeAddr(r)
10,614✔
4219
                if err != nil {
10,614✔
4220
                        return models.LightningNode{}, err
×
4221
                }
×
4222
                addresses = append(addresses, address)
10,614✔
4223
        }
4224
        node.Addresses = addresses
8,374✔
4225

8,374✔
4226
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,374✔
4227
        if err != nil {
8,374✔
4228
                return models.LightningNode{}, err
×
4229
        }
×
4230

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

4243
        return node, nil
8,374✔
4244
}
4245

4246
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4247
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,494✔
4248

1,494✔
4249
        var b bytes.Buffer
1,494✔
4250

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

4264
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,494✔
4265
                return err
×
4266
        }
×
4267

4268
        authProof := edgeInfo.AuthProof
1,494✔
4269
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,494✔
4270
        if authProof != nil {
2,905✔
4271
                nodeSig1 = authProof.NodeSig1Bytes
1,411✔
4272
                nodeSig2 = authProof.NodeSig2Bytes
1,411✔
4273
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,411✔
4274
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,411✔
4275
        }
1,411✔
4276

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

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

4304
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,494✔
4305
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4306
        }
×
4307
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,494✔
4308
        if err != nil {
1,494✔
4309
                return err
×
4310
        }
×
4311

4312
        return edgeIndex.Put(chanID[:], b.Bytes())
1,494✔
4313
}
4314

4315
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4316
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,185✔
4317

4,185✔
4318
        edgeInfoBytes := edgeIndex.Get(chanID)
4,185✔
4319
        if edgeInfoBytes == nil {
4,269✔
4320
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
84✔
4321
        }
84✔
4322

4323
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,104✔
4324
        return deserializeChanEdgeInfo(edgeInfoReader)
4,104✔
4325
}
4326

4327
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,748✔
4328
        var (
4,748✔
4329
                err      error
4,748✔
4330
                edgeInfo models.ChannelEdgeInfo
4,748✔
4331
        )
4,748✔
4332

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

4346
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,748✔
4347
        if err != nil {
4,748✔
4348
                return models.ChannelEdgeInfo{}, err
×
4349
        }
×
4350

4351
        proof := &models.ChannelAuthProof{}
4,748✔
4352

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

4370
        if !proof.IsEmpty() {
6,547✔
4371
                edgeInfo.AuthProof = proof
1,799✔
4372
        }
1,799✔
4373

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

4385
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,748✔
4386
                return models.ChannelEdgeInfo{}, err
×
4387
        }
×
4388

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

4401
        return edgeInfo, nil
4,748✔
4402
}
4403

4404
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4405
        from, to []byte) error {
2,663✔
4406

2,663✔
4407
        var edgeKey [33 + 8]byte
2,663✔
4408
        copy(edgeKey[:], from)
2,663✔
4409
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,663✔
4410

2,663✔
4411
        var b bytes.Buffer
2,663✔
4412
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,663✔
4413
                return err
×
4414
        }
×
4415

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

2,663✔
4423
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,663✔
4424
        if err != nil {
2,663✔
4425
                return err
×
4426
        }
×
4427

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

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

4451
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
27✔
4452

27✔
4453
                var oldIndexKey [8 + 8]byte
27✔
4454
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
27✔
4455
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
27✔
4456

27✔
4457
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
27✔
4458
                        return err
×
4459
                }
×
4460
        }
4461

4462
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,663✔
4463
                return err
×
4464
        }
×
4465

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

4475
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,663✔
4476
}
4477

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

2,961✔
4490
        var disabledEdgeKey [8 + 1]byte
2,961✔
4491
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,961✔
4492
        if direction {
4,439✔
4493
                disabledEdgeKey[8] = 1
1,478✔
4494
        }
1,478✔
4495

4496
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,961✔
4497
                disabledEdgePolicyBucket,
2,961✔
4498
        )
2,961✔
4499
        if err != nil {
2,961✔
4500
                return err
×
4501
        }
×
4502

4503
        if disabled {
2,990✔
4504
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4505
        }
29✔
4506

4507
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,935✔
4508
}
4509

4510
// putChanEdgePolicyUnknown marks the edge policy as unknown
4511
// in the edges bucket.
4512
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4513
        from []byte) error {
2,983✔
4514

2,983✔
4515
        var edgeKey [33 + 8]byte
2,983✔
4516
        copy(edgeKey[:], from)
2,983✔
4517
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,983✔
4518

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

4524
        return edges.Put(edgeKey[:], unknownPolicy)
2,983✔
4525
}
4526

4527
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4528
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,179✔
4529

8,179✔
4530
        var edgeKey [33 + 8]byte
8,179✔
4531
        copy(edgeKey[:], nodePub)
8,179✔
4532
        copy(edgeKey[33:], chanID[:])
8,179✔
4533

8,179✔
4534
        edgeBytes := edges.Get(edgeKey[:])
8,179✔
4535
        if edgeBytes == nil {
8,179✔
4536
                return nil, ErrEdgeNotFound
×
4537
        }
×
4538

4539
        // No need to deserialize unknown policy.
4540
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,561✔
4541
                return nil, nil
382✔
4542
        }
382✔
4543

4544
        edgeReader := bytes.NewReader(edgeBytes)
7,800✔
4545

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

4553
        case err != nil:
×
4554
                return nil, err
×
4555
        }
4556

4557
        return ep, nil
7,799✔
4558
}
4559

4560
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4561
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4562
        error) {
251✔
4563

251✔
4564
        edgeInfo := edgeIndex.Get(chanID)
251✔
4565
        if edgeInfo == nil {
251✔
4566
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4567
                        chanID)
×
4568
        }
×
4569

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

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

4589
        return edge1, edge2, nil
251✔
4590
}
4591

4592
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4593
        to []byte) error {
2,665✔
4594

2,665✔
4595
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,665✔
4596
        if err != nil {
2,665✔
4597
                return err
×
4598
        }
×
4599

4600
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,665✔
4601
                return err
×
4602
        }
×
4603

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

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

4634
        if _, err := w.Write(to); err != nil {
2,665✔
4635
                return err
×
4636
        }
×
4637

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

4650
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,665✔
4651
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4652
        }
×
4653
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,665✔
4654
                return err
×
4655
        }
×
4656

4657
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,665✔
4658
                return err
×
4659
        }
×
4660
        return nil
2,665✔
4661
}
4662

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

×
4670
                return nil, deserializeErr
×
4671
        }
×
4672

4673
        return edge, deserializeErr
7,825✔
4674
}
4675

4676
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4677
        error) {
8,832✔
4678

8,832✔
4679
        edge := &models.ChannelEdgePolicy{}
8,832✔
4680

8,832✔
4681
        var err error
8,832✔
4682
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,832✔
4683
        if err != nil {
8,832✔
4684
                return nil, err
×
4685
        }
×
4686

4687
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,832✔
4688
                return nil, err
×
4689
        }
×
4690

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

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

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

8,832✔
4714
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,832✔
4715
                return nil, err
×
4716
        }
×
4717
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,832✔
4718

8,832✔
4719
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,832✔
4720
                return nil, err
×
4721
        }
×
4722
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,832✔
4723

8,832✔
4724
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,832✔
4725
                return nil, err
×
4726
        }
×
4727

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

4740
        // See if optional fields are present.
4741
        if edge.MessageFlags.HasMaxHtlc() {
17,290✔
4742
                // The max_htlc field should be at the beginning of the opaque
8,458✔
4743
                // bytes.
8,458✔
4744
                opq := edge.ExtraOpaqueData
8,458✔
4745

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

4753
                maxHtlc := byteOrder.Uint64(opq[:8])
8,455✔
4754
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,455✔
4755

8,455✔
4756
                // Exclude the parsed field from the rest of the opaque data.
8,455✔
4757
                edge.ExtraOpaqueData = opq[8:]
8,455✔
4758
        }
4759

4760
        return edge, nil
8,829✔
4761
}
4762

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

4771
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4772
// interface.
4773
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4774

4775
func newChanGraphNodeTx(tx kvdb.RTx, db *ChannelGraph,
4776
        node *models.LightningNode) *chanGraphNodeTx {
3,917✔
4777

3,917✔
4778
        return &chanGraphNodeTx{
3,917✔
4779
                tx:   tx,
3,917✔
4780
                db:   db,
3,917✔
4781
                node: node,
3,917✔
4782
        }
3,917✔
4783
}
3,917✔
4784

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

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

4803
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4804
}
4805

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

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

2,944✔
4817
                        return f(info, policy1, policy2)
2,944✔
4818
                },
2,944✔
4819
        )
4820
}
4821

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

40✔
4827
        opts := DefaultOptions()
40✔
4828
        for _, modifier := range modifiers {
40✔
4829
                modifier(opts)
×
4830
        }
×
4831

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

4839
        graph, err := NewChannelGraph(backend)
40✔
4840
        if err != nil {
40✔
4841
                backendCleanup()
×
4842
                return nil, err
×
4843
        }
×
4844

4845
        t.Cleanup(func() {
80✔
4846
                _ = backend.Close()
40✔
4847
                backendCleanup()
40✔
4848
        })
40✔
4849

4850
        return graph, nil
40✔
4851
}
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