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

lightningnetwork / lnd / 13518248739

25 Feb 2025 09:45AM UTC coverage: 58.808% (-0.007%) from 58.815%
13518248739

Pull #9552

github

ellemouton
graph/db: move cache write for UpdateEdgePolicy

To the ChannelGraph.
Pull Request #9552: graph: extract cache from CRUD [5]

78 of 89 new or added lines in 2 files covered. (87.64%)

268 existing lines in 16 files now uncovered.

136336 of 231832 relevant lines covered (58.81%)

19292.34 hits per line

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

75.74
/graph/db/kv_store.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/btcsuite/btcwallet/walletdb"
22
        "github.com/lightningnetwork/lnd/aliasmgr"
23
        "github.com/lightningnetwork/lnd/batch"
24
        "github.com/lightningnetwork/lnd/graph/db/models"
25
        "github.com/lightningnetwork/lnd/input"
26
        "github.com/lightningnetwork/lnd/kvdb"
27
        "github.com/lightningnetwork/lnd/lnwire"
28
        "github.com/lightningnetwork/lnd/routing/route"
29
)
30

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

199
// NewKVStore allocates a new KVStore backed by a DB instance. The
200
// returned instance has its own unique reject cache and channel cache.
201
func NewKVStore(db kvdb.Backend, options ...KVStoreOptionModifier) (*KVStore,
202
        error) {
177✔
203

177✔
204
        opts := DefaultOptions()
177✔
205
        for _, o := range options {
180✔
206
                o(opts)
3✔
207
        }
3✔
208

209
        if !opts.NoMigration {
354✔
210
                if err := initKVStore(db); err != nil {
177✔
211
                        return nil, err
×
212
                }
×
213
        }
214

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

177✔
227
        return g, nil
177✔
228
}
229

230
// setGraphCache sets the KVStore's graphCache.
231
//
232
// NOTE: this is temporary and will only be called from the ChannelGraph's
233
// constructor before the KVStore methods are available to be called. This will
234
// be removed once the graph cache is fully owned by the ChannelGraph.
235
func (c *KVStore) setGraphCache(cache *GraphCache) {
144✔
236
        c.graphCache = cache
144✔
237
}
144✔
238

239
// channelMapKey is the key structure used for storing channel edge policies.
240
type channelMapKey struct {
241
        nodeKey route.Vertex
242
        chanID  [8]byte
243
}
244

245
// getChannelMap loads all channel edge policies from the database and stores
246
// them in a map.
247
func (c *KVStore) getChannelMap(edges kvdb.RBucket) (
248
        map[channelMapKey]*models.ChannelEdgePolicy, error) {
148✔
249

148✔
250
        // Create a map to store all channel edge policies.
148✔
251
        channelMap := make(map[channelMapKey]*models.ChannelEdgePolicy)
148✔
252

148✔
253
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
1,726✔
254
                // Skip embedded buckets.
1,578✔
255
                if bytes.Equal(k, edgeIndexBucket) ||
1,578✔
256
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
1,578✔
257
                        bytes.Equal(k, zombieBucket) ||
1,578✔
258
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
1,578✔
259
                        bytes.Equal(k, channelPointBucket) {
2,166✔
260

588✔
261
                        return nil
588✔
262
                }
588✔
263

264
                // Validate key length.
265
                if len(k) != 33+8 {
993✔
266
                        return fmt.Errorf("invalid edge key %x encountered", k)
×
267
                }
×
268

269
                var key channelMapKey
993✔
270
                copy(key.nodeKey[:], k[:33])
993✔
271
                copy(key.chanID[:], k[33:])
993✔
272

993✔
273
                // No need to deserialize unknown policy.
993✔
274
                if bytes.Equal(edgeBytes, unknownPolicy) {
993✔
275
                        return nil
×
276
                }
×
277

278
                edgeReader := bytes.NewReader(edgeBytes)
993✔
279
                edge, err := deserializeChanEdgePolicyRaw(
993✔
280
                        edgeReader,
993✔
281
                )
993✔
282

993✔
283
                switch {
993✔
284
                // If the db policy was missing an expected optional field, we
285
                // return nil as if the policy was unknown.
286
                case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
287
                        return nil
×
288

289
                case err != nil:
×
290
                        return err
×
291
                }
292

293
                channelMap[key] = edge
993✔
294

993✔
295
                return nil
993✔
296
        })
297
        if err != nil {
148✔
298
                return nil, err
×
299
        }
×
300

301
        return channelMap, nil
148✔
302
}
303

304
var graphTopLevelBuckets = [][]byte{
305
        nodeBucket,
306
        edgeBucket,
307
        graphMetaBucket,
308
        closedScidBucket,
309
}
310

311
// Wipe completely deletes all saved state within all used buckets within the
312
// database. The deletion is done in a single transaction, therefore this
313
// operation is fully atomic.
314
func (c *KVStore) Wipe() error {
×
315
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
316
                for _, tlb := range graphTopLevelBuckets {
×
317
                        err := tx.DeleteTopLevelBucket(tlb)
×
318
                        if err != nil &&
×
319
                                !errors.Is(err, kvdb.ErrBucketNotFound) {
×
320

×
321
                                return err
×
322
                        }
×
323
                }
324

325
                return nil
×
326
        }, func() {})
×
327
        if err != nil {
×
328
                return err
×
329
        }
×
330

331
        return initKVStore(c.db)
×
332
}
333

334
// createChannelDB creates and initializes a fresh version of  In
335
// the case that the target path has not yet been created or doesn't yet exist,
336
// then the path is created. Additionally, all required top-level buckets used
337
// within the database are created.
338
func initKVStore(db kvdb.Backend) error {
177✔
339
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
354✔
340
                for _, tlb := range graphTopLevelBuckets {
876✔
341
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
699✔
342
                                return err
×
343
                        }
×
344
                }
345

346
                nodes := tx.ReadWriteBucket(nodeBucket)
177✔
347
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
177✔
348
                if err != nil {
177✔
349
                        return err
×
350
                }
×
351
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
177✔
352
                if err != nil {
177✔
353
                        return err
×
354
                }
×
355

356
                edges := tx.ReadWriteBucket(edgeBucket)
177✔
357
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
177✔
358
                if err != nil {
177✔
359
                        return err
×
360
                }
×
361
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
177✔
362
                if err != nil {
177✔
363
                        return err
×
364
                }
×
365
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
177✔
366
                if err != nil {
177✔
367
                        return err
×
368
                }
×
369
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
177✔
370
                if err != nil {
177✔
371
                        return err
×
372
                }
×
373

374
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
177✔
375
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
177✔
376

177✔
377
                return err
177✔
378
        }, func() {})
177✔
379
        if err != nil {
177✔
380
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
381
        }
×
382

383
        return nil
177✔
384
}
385

386
// AddrsForNode returns all known addresses for the target node public key that
387
// the graph DB is aware of. The returned boolean indicates if the given node is
388
// unknown to the graph DB or not.
389
//
390
// NOTE: this is part of the channeldb.AddrSource interface.
391
func (c *KVStore) AddrsForNode(nodePub *btcec.PublicKey) (bool, []net.Addr,
392
        error) {
4✔
393

4✔
394
        pubKey, err := route.NewVertexFromBytes(nodePub.SerializeCompressed())
4✔
395
        if err != nil {
4✔
396
                return false, nil, err
×
397
        }
×
398

399
        node, err := c.FetchLightningNode(pubKey)
4✔
400
        // We don't consider it an error if the graph is unaware of the node.
4✔
401
        switch {
4✔
402
        case err != nil && !errors.Is(err, ErrGraphNodeNotFound):
×
403
                return false, nil, err
×
404

405
        case errors.Is(err, ErrGraphNodeNotFound):
3✔
406
                return false, nil, nil
3✔
407
        }
408

409
        return true, node.Addresses, nil
4✔
410
}
411

412
// ForEachChannel iterates through all the channel edges stored within the
413
// graph and invokes the passed callback for each edge. The callback takes two
414
// edges as since this is a directed graph, both the in/out edges are visited.
415
// If the callback returns an error, then the transaction is aborted and the
416
// iteration stops early.
417
//
418
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
419
// for that particular channel edge routing policy will be passed into the
420
// callback.
421
func (c *KVStore) ForEachChannel(cb func(*models.ChannelEdgeInfo,
422
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
148✔
423

148✔
424
        return c.db.View(func(tx kvdb.RTx) error {
296✔
425
                edges := tx.ReadBucket(edgeBucket)
148✔
426
                if edges == nil {
148✔
427
                        return ErrGraphNoEdgesFound
×
428
                }
×
429

430
                // First, load all edges in memory indexed by node and channel
431
                // id.
432
                channelMap, err := c.getChannelMap(edges)
148✔
433
                if err != nil {
148✔
434
                        return err
×
435
                }
×
436

437
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
148✔
438
                if edgeIndex == nil {
148✔
439
                        return ErrGraphNoEdgesFound
×
440
                }
×
441

442
                // Load edge index, recombine each channel with the policies
443
                // loaded above and invoke the callback.
444
                return kvdb.ForAll(
148✔
445
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
646✔
446
                                var chanID [8]byte
498✔
447
                                copy(chanID[:], k)
498✔
448

498✔
449
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
498✔
450
                                info, err := deserializeChanEdgeInfo(
498✔
451
                                        edgeInfoReader,
498✔
452
                                )
498✔
453
                                if err != nil {
498✔
454
                                        return err
×
455
                                }
×
456

457
                                policy1 := channelMap[channelMapKey{
498✔
458
                                        nodeKey: info.NodeKey1Bytes,
498✔
459
                                        chanID:  chanID,
498✔
460
                                }]
498✔
461

498✔
462
                                policy2 := channelMap[channelMapKey{
498✔
463
                                        nodeKey: info.NodeKey2Bytes,
498✔
464
                                        chanID:  chanID,
498✔
465
                                }]
498✔
466

498✔
467
                                return cb(&info, policy1, policy2)
498✔
468
                        },
469
                )
470
        }, func() {})
148✔
471
}
472

473
// forEachNodeDirectedChannel iterates through all channels of a given node,
474
// executing the passed callback on the directed edge representing the channel
475
// and its incoming policy. If the callback returns an error, then the iteration
476
// is halted with the error propagated back up to the caller. An optional read
477
// transaction may be provided. If none is provided, a new one will be created.
478
//
479
// Unknown policies are passed into the callback as nil values.
480
func (c *KVStore) forEachNodeDirectedChannel(tx kvdb.RTx,
481
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
706✔
482

706✔
483
        if c.graphCache != nil {
1,170✔
484
                return c.graphCache.ForEachChannel(node, cb)
464✔
485
        }
464✔
486

487
        // Fallback that uses the database.
488
        toNodeCallback := func() route.Vertex {
380✔
489
                return node
135✔
490
        }
135✔
491
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
245✔
492
        if err != nil {
245✔
493
                return err
×
494
        }
×
495

496
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
245✔
497
                p2 *models.ChannelEdgePolicy) error {
744✔
498

499✔
499
                var cachedInPolicy *models.CachedEdgePolicy
499✔
500
                if p2 != nil {
995✔
501
                        cachedInPolicy = models.NewCachedPolicy(p2)
496✔
502
                        cachedInPolicy.ToNodePubKey = toNodeCallback
496✔
503
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
496✔
504
                }
496✔
505

506
                var inboundFee lnwire.Fee
499✔
507
                if p1 != nil {
997✔
508
                        // Extract inbound fee. If there is a decoding error,
498✔
509
                        // skip this edge.
498✔
510
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
498✔
511
                        if err != nil {
499✔
512
                                return nil
1✔
513
                        }
1✔
514
                }
515

516
                directedChannel := &DirectedChannel{
498✔
517
                        ChannelID:    e.ChannelID,
498✔
518
                        IsNode1:      node == e.NodeKey1Bytes,
498✔
519
                        OtherNode:    e.NodeKey2Bytes,
498✔
520
                        Capacity:     e.Capacity,
498✔
521
                        OutPolicySet: p1 != nil,
498✔
522
                        InPolicy:     cachedInPolicy,
498✔
523
                        InboundFee:   inboundFee,
498✔
524
                }
498✔
525

498✔
526
                if node == e.NodeKey2Bytes {
751✔
527
                        directedChannel.OtherNode = e.NodeKey1Bytes
253✔
528
                }
253✔
529

530
                return cb(directedChannel)
498✔
531
        }
532

533
        return nodeTraversal(tx, node[:], c.db, dbCallback)
245✔
534
}
535

536
// fetchNodeFeatures returns the features of a given node. If no features are
537
// known for the node, an empty feature vector is returned. An optional read
538
// transaction may be provided. If none is provided, a new one will be created.
539
func (c *KVStore) fetchNodeFeatures(tx kvdb.RTx,
540
        node route.Vertex) (*lnwire.FeatureVector, error) {
952✔
541

952✔
542
        if c.graphCache != nil {
1,408✔
543
                return c.graphCache.GetFeatures(node), nil
456✔
544
        }
456✔
545

546
        // Fallback that uses the database.
547
        targetNode, err := c.FetchLightningNodeTx(tx, node)
499✔
548
        switch {
499✔
549
        // If the node exists and has features, return them directly.
550
        case err == nil:
488✔
551
                return targetNode.Features, nil
488✔
552

553
        // If we couldn't find a node announcement, populate a blank feature
554
        // vector.
555
        case errors.Is(err, ErrGraphNodeNotFound):
11✔
556
                return lnwire.EmptyFeatureVector(), nil
11✔
557

558
        // Otherwise, bubble the error up.
559
        default:
×
560
                return nil, err
×
561
        }
562
}
563

564
// ForEachNodeDirectedChannel iterates through all channels of a given node,
565
// executing the passed callback on the directed edge representing the channel
566
// and its incoming policy. If the callback returns an error, then the iteration
567
// is halted with the error propagated back up to the caller. If the graphCache
568
// is available, then it will be used to retrieve the node's channels instead
569
// of the database.
570
//
571
// Unknown policies are passed into the callback as nil values.
572
//
573
// NOTE: this is part of the graphdb.NodeTraverser interface.
574
func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
575
        cb func(channel *DirectedChannel) error) error {
114✔
576

114✔
577
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
114✔
578
}
114✔
579

580
// FetchNodeFeatures returns the features of the given node. If no features are
581
// known for the node, an empty feature vector is returned.
582
// If the graphCache is available, then it will be used to retrieve the node's
583
// features instead of the database.
584
//
585
// NOTE: this is part of the graphdb.NodeTraverser interface.
586
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
587
        *lnwire.FeatureVector, error) {
90✔
588

90✔
589
        return c.fetchNodeFeatures(nil, nodePub)
90✔
590
}
90✔
591

592
// ForEachNodeCached is similar to forEachNode, but it utilizes the channel
593
// graph cache instead. Note that this doesn't return all the information the
594
// regular forEachNode method does.
595
//
596
// NOTE: The callback contents MUST not be modified.
597
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
598
        chans map[uint64]*DirectedChannel) error) error {
1✔
599

1✔
600
        if c.graphCache != nil {
2✔
601
                return c.graphCache.ForEachNode(cb)
1✔
602
        }
1✔
603

604
        // Otherwise call back to a version that uses the database directly.
605
        // We'll iterate over each node, then the set of channels for each
606
        // node, and construct a similar callback functiopn signature as the
607
        // main funcotin expects.
608
        return c.forEachNode(func(tx kvdb.RTx,
×
609
                node *models.LightningNode) error {
×
610

×
611
                channels := make(map[uint64]*DirectedChannel)
×
612

×
613
                err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes,
×
614
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
615
                                p1 *models.ChannelEdgePolicy,
×
616
                                p2 *models.ChannelEdgePolicy) error {
×
617

×
618
                                toNodeCallback := func() route.Vertex {
×
619
                                        return node.PubKeyBytes
×
620
                                }
×
621
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
622
                                        tx, node.PubKeyBytes,
×
623
                                )
×
624
                                if err != nil {
×
625
                                        return err
×
626
                                }
×
627

628
                                var cachedInPolicy *models.CachedEdgePolicy
×
629
                                if p2 != nil {
×
630
                                        cachedInPolicy =
×
631
                                                models.NewCachedPolicy(p2)
×
632
                                        cachedInPolicy.ToNodePubKey =
×
633
                                                toNodeCallback
×
634
                                        cachedInPolicy.ToNodeFeatures =
×
635
                                                toNodeFeatures
×
636
                                }
×
637

638
                                directedChannel := &DirectedChannel{
×
639
                                        ChannelID: e.ChannelID,
×
640
                                        IsNode1: node.PubKeyBytes ==
×
641
                                                e.NodeKey1Bytes,
×
642
                                        OtherNode:    e.NodeKey2Bytes,
×
643
                                        Capacity:     e.Capacity,
×
644
                                        OutPolicySet: p1 != nil,
×
645
                                        InPolicy:     cachedInPolicy,
×
646
                                }
×
647

×
648
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
649
                                        directedChannel.OtherNode =
×
650
                                                e.NodeKey1Bytes
×
651
                                }
×
652

653
                                channels[e.ChannelID] = directedChannel
×
654

×
655
                                return nil
×
656
                        })
657
                if err != nil {
×
658
                        return err
×
659
                }
×
660

661
                return cb(node.PubKeyBytes, channels)
×
662
        })
663
}
664

665
// DisabledChannelIDs returns the channel ids of disabled channels.
666
// A channel is disabled when two of the associated ChanelEdgePolicies
667
// have their disabled bit on.
668
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
6✔
669
        var disabledChanIDs []uint64
6✔
670
        var chanEdgeFound map[uint64]struct{}
6✔
671

6✔
672
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
673
                edges := tx.ReadBucket(edgeBucket)
6✔
674
                if edges == nil {
6✔
675
                        return ErrGraphNoEdgesFound
×
676
                }
×
677

678
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
679
                        disabledEdgePolicyBucket,
6✔
680
                )
6✔
681
                if disabledEdgePolicyIndex == nil {
7✔
682
                        return nil
1✔
683
                }
1✔
684

685
                // We iterate over all disabled policies and we add each channel
686
                // that has more than one disabled policy to disabledChanIDs
687
                // array.
688
                return disabledEdgePolicyIndex.ForEach(
5✔
689
                        func(k, v []byte) error {
16✔
690
                                chanID := byteOrder.Uint64(k[:8])
11✔
691
                                _, edgeFound := chanEdgeFound[chanID]
11✔
692
                                if edgeFound {
15✔
693
                                        delete(chanEdgeFound, chanID)
4✔
694
                                        disabledChanIDs = append(
4✔
695
                                                disabledChanIDs, chanID,
4✔
696
                                        )
4✔
697

4✔
698
                                        return nil
4✔
699
                                }
4✔
700

701
                                chanEdgeFound[chanID] = struct{}{}
7✔
702

7✔
703
                                return nil
7✔
704
                        },
705
                )
706
        }, func() {
6✔
707
                disabledChanIDs = nil
6✔
708
                chanEdgeFound = make(map[uint64]struct{})
6✔
709
        })
6✔
710
        if err != nil {
6✔
711
                return nil, err
×
712
        }
×
713

714
        return disabledChanIDs, nil
6✔
715
}
716

717
// ForEachNode iterates through all the stored vertices/nodes in the graph,
718
// executing the passed callback with each node encountered. If the callback
719
// returns an error, then the transaction is aborted and the iteration stops
720
// early. Any operations performed on the NodeTx passed to the call-back are
721
// executed under the same read transaction and so, methods on the NodeTx object
722
// _MUST_ only be called from within the call-back.
723
func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error {
123✔
724
        return c.forEachNode(func(tx kvdb.RTx,
123✔
725
                node *models.LightningNode) error {
1,096✔
726

973✔
727
                return cb(newChanGraphNodeTx(tx, c, node))
973✔
728
        })
973✔
729
}
730

731
// forEachNode iterates through all the stored vertices/nodes in the graph,
732
// executing the passed callback with each node encountered. If the callback
733
// returns an error, then the transaction is aborted and the iteration stops
734
// early.
735
//
736
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
737
// traversal when graph gets mega.
738
func (c *KVStore) forEachNode(
739
        cb func(kvdb.RTx, *models.LightningNode) error) error {
131✔
740

131✔
741
        traversal := func(tx kvdb.RTx) error {
262✔
742
                // First grab the nodes bucket which stores the mapping from
131✔
743
                // pubKey to node information.
131✔
744
                nodes := tx.ReadBucket(nodeBucket)
131✔
745
                if nodes == nil {
131✔
746
                        return ErrGraphNotFound
×
747
                }
×
748

749
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,551✔
750
                        // If this is the source key, then we skip this
1,420✔
751
                        // iteration as the value for this key is a pubKey
1,420✔
752
                        // rather than raw node information.
1,420✔
753
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,682✔
754
                                return nil
262✔
755
                        }
262✔
756

757
                        nodeReader := bytes.NewReader(nodeBytes)
1,161✔
758
                        node, err := deserializeLightningNode(nodeReader)
1,161✔
759
                        if err != nil {
1,161✔
760
                                return err
×
761
                        }
×
762

763
                        // Execute the callback, the transaction will abort if
764
                        // this returns an error.
765
                        return cb(tx, &node)
1,161✔
766
                })
767
        }
768

769
        return kvdb.View(c.db, traversal, func() {})
262✔
770
}
771

772
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
773
// graph, executing the passed callback with each node encountered. If the
774
// callback returns an error, then the transaction is aborted and the iteration
775
// stops early.
776
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
777
        *lnwire.FeatureVector) error) error {
145✔
778

145✔
779
        traversal := func(tx kvdb.RTx) error {
290✔
780
                // First grab the nodes bucket which stores the mapping from
145✔
781
                // pubKey to node information.
145✔
782
                nodes := tx.ReadBucket(nodeBucket)
145✔
783
                if nodes == nil {
145✔
784
                        return ErrGraphNotFound
×
785
                }
×
786

787
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
552✔
788
                        // If this is the source key, then we skip this
407✔
789
                        // iteration as the value for this key is a pubKey
407✔
790
                        // rather than raw node information.
407✔
791
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
694✔
792
                                return nil
287✔
793
                        }
287✔
794

795
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
796
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
123✔
797
                                nodeReader,
123✔
798
                        )
123✔
799
                        if err != nil {
123✔
800
                                return err
×
801
                        }
×
802

803
                        // Execute the callback, the transaction will abort if
804
                        // this returns an error.
805
                        return cb(node, features)
123✔
806
                })
807
        }
808

809
        return kvdb.View(c.db, traversal, func() {})
290✔
810
}
811

812
// SourceNode returns the source node of the graph. The source node is treated
813
// as the center node within a star-graph. This method may be used to kick off
814
// a path finding algorithm in order to explore the reachability of another
815
// node based off the source node.
816
func (c *KVStore) SourceNode() (*models.LightningNode, error) {
234✔
817
        var source *models.LightningNode
234✔
818
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
468✔
819
                // First grab the nodes bucket which stores the mapping from
234✔
820
                // pubKey to node information.
234✔
821
                nodes := tx.ReadBucket(nodeBucket)
234✔
822
                if nodes == nil {
234✔
823
                        return ErrGraphNotFound
×
824
                }
×
825

826
                node, err := c.sourceNode(nodes)
234✔
827
                if err != nil {
235✔
828
                        return err
1✔
829
                }
1✔
830
                source = node
233✔
831

233✔
832
                return nil
233✔
833
        }, func() {
234✔
834
                source = nil
234✔
835
        })
234✔
836
        if err != nil {
235✔
837
                return nil, err
1✔
838
        }
1✔
839

840
        return source, nil
233✔
841
}
842

843
// sourceNode uses an existing database transaction and returns the source node
844
// of the graph. The source node is treated as the center node within a
845
// star-graph. This method may be used to kick off a path finding algorithm in
846
// order to explore the reachability of another node based off the source node.
847
func (c *KVStore) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
848
        error) {
491✔
849

491✔
850
        selfPub := nodes.Get(sourceKey)
491✔
851
        if selfPub == nil {
492✔
852
                return nil, ErrSourceNodeNotSet
1✔
853
        }
1✔
854

855
        // With the pubKey of the source node retrieved, we're able to
856
        // fetch the full node information.
857
        node, err := fetchLightningNode(nodes, selfPub)
490✔
858
        if err != nil {
490✔
859
                return nil, err
×
860
        }
×
861

862
        return &node, nil
490✔
863
}
864

865
// SetSourceNode sets the source node within the graph database. The source
866
// node is to be used as the center of a star-graph within path finding
867
// algorithms.
868
func (c *KVStore) SetSourceNode(node *models.LightningNode) error {
120✔
869
        nodePubBytes := node.PubKeyBytes[:]
120✔
870

120✔
871
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
240✔
872
                // First grab the nodes bucket which stores the mapping from
120✔
873
                // pubKey to node information.
120✔
874
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
120✔
875
                if err != nil {
120✔
876
                        return err
×
877
                }
×
878

879
                // Next we create the mapping from source to the targeted
880
                // public key.
881
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
120✔
882
                        return err
×
883
                }
×
884

885
                // Finally, we commit the information of the lightning node
886
                // itself.
887
                return addLightningNode(tx, node)
120✔
888
        }, func() {})
120✔
889
}
890

891
// AddLightningNode adds a vertex/node to the graph database. If the node is not
892
// in the database from before, this will add a new, unconnected one to the
893
// graph. If it is present from before, this will update that node's
894
// information. Note that this method is expected to only be called to update an
895
// already present node from a node announcement, or to insert a node found in a
896
// channel update.
897
//
898
// TODO(roasbeef): also need sig of announcement.
899
func (c *KVStore) AddLightningNode(node *models.LightningNode,
900
        op ...batch.SchedulerOption) error {
803✔
901

803✔
902
        r := &batch.Request{
803✔
903
                Update: func(tx kvdb.RwTx) error {
1,606✔
904
                        if c.graphCache != nil {
1,419✔
905
                                c.graphCache.AddNodeFeatures(
616✔
906
                                        node.PubKeyBytes, node.Features,
616✔
907
                                )
616✔
908
                        }
616✔
909

910
                        return addLightningNode(tx, node)
803✔
911
                },
912
        }
913

914
        for _, f := range op {
806✔
915
                f(r)
3✔
916
        }
3✔
917

918
        return c.nodeScheduler.Execute(r)
803✔
919
}
920

921
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
999✔
922
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
999✔
923
        if err != nil {
999✔
924
                return err
×
925
        }
×
926

927
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
999✔
928
        if err != nil {
999✔
929
                return err
×
930
        }
×
931

932
        updateIndex, err := nodes.CreateBucketIfNotExists(
999✔
933
                nodeUpdateIndexBucket,
999✔
934
        )
999✔
935
        if err != nil {
999✔
936
                return err
×
937
        }
×
938

939
        return putLightningNode(nodes, aliases, updateIndex, node)
999✔
940
}
941

942
// LookupAlias attempts to return the alias as advertised by the target node.
943
// TODO(roasbeef): currently assumes that aliases are unique...
944
func (c *KVStore) LookupAlias(pub *btcec.PublicKey) (string, error) {
5✔
945
        var alias string
5✔
946

5✔
947
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
948
                nodes := tx.ReadBucket(nodeBucket)
5✔
949
                if nodes == nil {
5✔
950
                        return ErrGraphNodesNotFound
×
951
                }
×
952

953
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
5✔
954
                if aliases == nil {
5✔
955
                        return ErrGraphNodesNotFound
×
956
                }
×
957

958
                nodePub := pub.SerializeCompressed()
5✔
959
                a := aliases.Get(nodePub)
5✔
960
                if a == nil {
6✔
961
                        return ErrNodeAliasNotFound
1✔
962
                }
1✔
963

964
                // TODO(roasbeef): should actually be using the utf-8
965
                // package...
966
                alias = string(a)
4✔
967

4✔
968
                return nil
4✔
969
        }, func() {
5✔
970
                alias = ""
5✔
971
        })
5✔
972
        if err != nil {
6✔
973
                return "", err
1✔
974
        }
1✔
975

976
        return alias, nil
4✔
977
}
978

979
// DeleteLightningNode starts a new database transaction to remove a vertex/node
980
// from the database according to the node's public key.
981
func (c *KVStore) DeleteLightningNode(nodePub route.Vertex) error {
3✔
982
        // TODO(roasbeef): ensure dangling edges are removed...
3✔
983
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
984
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
985
                if nodes == nil {
3✔
986
                        return ErrGraphNodeNotFound
×
987
                }
×
988

989
                if c.graphCache != nil {
6✔
990
                        c.graphCache.RemoveNode(nodePub)
3✔
991
                }
3✔
992

993
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
994
        }, func() {})
3✔
995
}
996

997
// deleteLightningNode uses an existing database transaction to remove a
998
// vertex/node from the database according to the node's public key.
999
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
1000
        compressedPubKey []byte) error {
74✔
1001

74✔
1002
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
74✔
1003
        if aliases == nil {
74✔
1004
                return ErrGraphNodesNotFound
×
1005
        }
×
1006

1007
        if err := aliases.Delete(compressedPubKey); err != nil {
74✔
1008
                return err
×
1009
        }
×
1010

1011
        // Before we delete the node, we'll fetch its current state so we can
1012
        // determine when its last update was to clear out the node update
1013
        // index.
1014
        node, err := fetchLightningNode(nodes, compressedPubKey)
74✔
1015
        if err != nil {
74✔
1016
                return err
×
1017
        }
×
1018

1019
        if err := nodes.Delete(compressedPubKey); err != nil {
74✔
1020
                return err
×
1021
        }
×
1022

1023
        // Finally, we'll delete the index entry for the node within the
1024
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1025
        // need to track its last update.
1026
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
74✔
1027
        if nodeUpdateIndex == nil {
74✔
1028
                return ErrGraphNodesNotFound
×
1029
        }
×
1030

1031
        // In order to delete the entry, we'll need to reconstruct the key for
1032
        // its last update.
1033
        updateUnix := uint64(node.LastUpdate.Unix())
74✔
1034
        var indexKey [8 + 33]byte
74✔
1035
        byteOrder.PutUint64(indexKey[:8], updateUnix)
74✔
1036
        copy(indexKey[8:], compressedPubKey)
74✔
1037

74✔
1038
        return nodeUpdateIndex.Delete(indexKey[:])
74✔
1039
}
1040

1041
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1042
// undirected edge from the two target nodes are created. The information stored
1043
// denotes the static attributes of the channel, such as the channelID, the keys
1044
// involved in creation of the channel, and the set of features that the channel
1045
// supports. The chanPoint and chanID are used to uniquely identify the edge
1046
// globally within the database.
1047
func (c *KVStore) AddChannelEdge(edge *models.ChannelEdgeInfo,
1048
        op ...batch.SchedulerOption) error {
1,714✔
1049

1,714✔
1050
        var alreadyExists bool
1,714✔
1051
        r := &batch.Request{
1,714✔
1052
                Reset: func() {
3,428✔
1053
                        alreadyExists = false
1,714✔
1054
                },
1,714✔
1055
                Update: func(tx kvdb.RwTx) error {
1,714✔
1056
                        err := c.addChannelEdge(tx, edge)
1,714✔
1057

1,714✔
1058
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,714✔
1059
                        // succeed, but propagate the error via local state.
1,714✔
1060
                        if errors.Is(err, ErrEdgeAlreadyExist) {
1,948✔
1061
                                alreadyExists = true
234✔
1062
                                return nil
234✔
1063
                        }
234✔
1064

1065
                        return err
1,480✔
1066
                },
1067
                OnCommit: func(err error) error {
1,714✔
1068
                        switch {
1,714✔
1069
                        case err != nil:
×
1070
                                return err
×
1071
                        case alreadyExists:
234✔
1072
                                return ErrEdgeAlreadyExist
234✔
1073
                        default:
1,480✔
1074
                                c.rejectCache.remove(edge.ChannelID)
1,480✔
1075
                                c.chanCache.remove(edge.ChannelID)
1,480✔
1076
                                return nil
1,480✔
1077
                        }
1078
                },
1079
        }
1080

1081
        for _, f := range op {
1,717✔
1082
                if f == nil {
3✔
1083
                        return fmt.Errorf("nil scheduler option was used")
×
1084
                }
×
1085

1086
                f(r)
3✔
1087
        }
1088

1089
        return c.chanScheduler.Execute(r)
1,714✔
1090
}
1091

1092
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1093
// utilize an existing db transaction.
1094
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1095
        edge *models.ChannelEdgeInfo) error {
1,714✔
1096

1,714✔
1097
        // Construct the channel's primary key which is the 8-byte channel ID.
1,714✔
1098
        var chanKey [8]byte
1,714✔
1099
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,714✔
1100

1,714✔
1101
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,714✔
1102
        if err != nil {
1,714✔
1103
                return err
×
1104
        }
×
1105
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,714✔
1106
        if err != nil {
1,714✔
1107
                return err
×
1108
        }
×
1109
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,714✔
1110
        if err != nil {
1,714✔
1111
                return err
×
1112
        }
×
1113
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,714✔
1114
        if err != nil {
1,714✔
1115
                return err
×
1116
        }
×
1117

1118
        // First, attempt to check if this edge has already been created. If
1119
        // so, then we can exit early as this method is meant to be idempotent.
1120
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,948✔
1121
                return ErrEdgeAlreadyExist
234✔
1122
        }
234✔
1123

1124
        if c.graphCache != nil {
2,770✔
1125
                c.graphCache.AddChannel(edge, nil, nil)
1,290✔
1126
        }
1,290✔
1127

1128
        // Before we insert the channel into the database, we'll ensure that
1129
        // both nodes already exist in the channel graph. If either node
1130
        // doesn't, then we'll insert a "shell" node that just includes its
1131
        // public key, so subsequent validation and queries can work properly.
1132
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
1,480✔
1133
        switch {
1,480✔
1134
        case errors.Is(node1Err, ErrGraphNodeNotFound):
21✔
1135
                node1Shell := models.LightningNode{
21✔
1136
                        PubKeyBytes:          edge.NodeKey1Bytes,
21✔
1137
                        HaveNodeAnnouncement: false,
21✔
1138
                }
21✔
1139
                err := addLightningNode(tx, &node1Shell)
21✔
1140
                if err != nil {
21✔
1141
                        return fmt.Errorf("unable to create shell node "+
×
1142
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1143
                }
×
1144
        case node1Err != nil:
×
1145
                return node1Err
×
1146
        }
1147

1148
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,480✔
1149
        switch {
1,480✔
1150
        case errors.Is(node2Err, ErrGraphNodeNotFound):
64✔
1151
                node2Shell := models.LightningNode{
64✔
1152
                        PubKeyBytes:          edge.NodeKey2Bytes,
64✔
1153
                        HaveNodeAnnouncement: false,
64✔
1154
                }
64✔
1155
                err := addLightningNode(tx, &node2Shell)
64✔
1156
                if err != nil {
64✔
1157
                        return fmt.Errorf("unable to create shell node "+
×
1158
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1159
                }
×
1160
        case node2Err != nil:
×
1161
                return node2Err
×
1162
        }
1163

1164
        // If the edge hasn't been created yet, then we'll first add it to the
1165
        // edge index in order to associate the edge between two nodes and also
1166
        // store the static components of the channel.
1167
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
1,480✔
1168
                return err
×
1169
        }
×
1170

1171
        // Mark edge policies for both sides as unknown. This is to enable
1172
        // efficient incoming channel lookup for a node.
1173
        keys := []*[33]byte{
1,480✔
1174
                &edge.NodeKey1Bytes,
1,480✔
1175
                &edge.NodeKey2Bytes,
1,480✔
1176
        }
1,480✔
1177
        for _, key := range keys {
4,437✔
1178
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,957✔
1179
                if err != nil {
2,957✔
1180
                        return err
×
1181
                }
×
1182
        }
1183

1184
        // Finally we add it to the channel index which maps channel points
1185
        // (outpoints) to the shorter channel ID's.
1186
        var b bytes.Buffer
1,480✔
1187
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,480✔
1188
                return err
×
1189
        }
×
1190

1191
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,480✔
1192
}
1193

1194
// HasChannelEdge returns true if the database knows of a channel edge with the
1195
// passed channel ID, and false otherwise. If an edge with that ID is found
1196
// within the graph, then two time stamps representing the last time the edge
1197
// was updated for both directed edges are returned along with the boolean. If
1198
// it is not found, then the zombie index is checked and its result is returned
1199
// as the second boolean.
1200
func (c *KVStore) HasChannelEdge(
1201
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
215✔
1202

215✔
1203
        var (
215✔
1204
                upd1Time time.Time
215✔
1205
                upd2Time time.Time
215✔
1206
                exists   bool
215✔
1207
                isZombie bool
215✔
1208
        )
215✔
1209

215✔
1210
        // We'll query the cache with the shared lock held to allow multiple
215✔
1211
        // readers to access values in the cache concurrently if they exist.
215✔
1212
        c.cacheMu.RLock()
215✔
1213
        if entry, ok := c.rejectCache.get(chanID); ok {
284✔
1214
                c.cacheMu.RUnlock()
69✔
1215
                upd1Time = time.Unix(entry.upd1Time, 0)
69✔
1216
                upd2Time = time.Unix(entry.upd2Time, 0)
69✔
1217
                exists, isZombie = entry.flags.unpack()
69✔
1218

69✔
1219
                return upd1Time, upd2Time, exists, isZombie, nil
69✔
1220
        }
69✔
1221
        c.cacheMu.RUnlock()
149✔
1222

149✔
1223
        c.cacheMu.Lock()
149✔
1224
        defer c.cacheMu.Unlock()
149✔
1225

149✔
1226
        // The item was not found with the shared lock, so we'll acquire the
149✔
1227
        // exclusive lock and check the cache again in case another method added
149✔
1228
        // the entry to the cache while no lock was held.
149✔
1229
        if entry, ok := c.rejectCache.get(chanID); ok {
158✔
1230
                upd1Time = time.Unix(entry.upd1Time, 0)
9✔
1231
                upd2Time = time.Unix(entry.upd2Time, 0)
9✔
1232
                exists, isZombie = entry.flags.unpack()
9✔
1233

9✔
1234
                return upd1Time, upd2Time, exists, isZombie, nil
9✔
1235
        }
9✔
1236

1237
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
286✔
1238
                edges := tx.ReadBucket(edgeBucket)
143✔
1239
                if edges == nil {
143✔
1240
                        return ErrGraphNoEdgesFound
×
1241
                }
×
1242
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
143✔
1243
                if edgeIndex == nil {
143✔
1244
                        return ErrGraphNoEdgesFound
×
1245
                }
×
1246

1247
                var channelID [8]byte
143✔
1248
                byteOrder.PutUint64(channelID[:], chanID)
143✔
1249

143✔
1250
                // If the edge doesn't exist, then we'll also check our zombie
143✔
1251
                // index.
143✔
1252
                if edgeIndex.Get(channelID[:]) == nil {
240✔
1253
                        exists = false
97✔
1254
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
97✔
1255
                        if zombieIndex != nil {
194✔
1256
                                isZombie, _, _ = isZombieEdge(
97✔
1257
                                        zombieIndex, chanID,
97✔
1258
                                )
97✔
1259
                        }
97✔
1260

1261
                        return nil
97✔
1262
                }
1263

1264
                exists = true
49✔
1265
                isZombie = false
49✔
1266

49✔
1267
                // If the channel has been found in the graph, then retrieve
49✔
1268
                // the edges itself so we can return the last updated
49✔
1269
                // timestamps.
49✔
1270
                nodes := tx.ReadBucket(nodeBucket)
49✔
1271
                if nodes == nil {
49✔
1272
                        return ErrGraphNodeNotFound
×
1273
                }
×
1274

1275
                e1, e2, err := fetchChanEdgePolicies(
49✔
1276
                        edgeIndex, edges, channelID[:],
49✔
1277
                )
49✔
1278
                if err != nil {
49✔
1279
                        return err
×
1280
                }
×
1281

1282
                // As we may have only one of the edges populated, only set the
1283
                // update time if the edge was found in the database.
1284
                if e1 != nil {
70✔
1285
                        upd1Time = e1.LastUpdate
21✔
1286
                }
21✔
1287
                if e2 != nil {
68✔
1288
                        upd2Time = e2.LastUpdate
19✔
1289
                }
19✔
1290

1291
                return nil
49✔
1292
        }, func() {}); err != nil {
143✔
1293
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1294
        }
×
1295

1296
        c.rejectCache.insert(chanID, rejectCacheEntry{
143✔
1297
                upd1Time: upd1Time.Unix(),
143✔
1298
                upd2Time: upd2Time.Unix(),
143✔
1299
                flags:    packRejectFlags(exists, isZombie),
143✔
1300
        })
143✔
1301

143✔
1302
        return upd1Time, upd2Time, exists, isZombie, nil
143✔
1303
}
1304

1305
// AddEdgeProof sets the proof of an existing edge in the graph database.
1306
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1307
        proof *models.ChannelAuthProof) error {
4✔
1308

4✔
1309
        // Construct the channel's primary key which is the 8-byte channel ID.
4✔
1310
        var chanKey [8]byte
4✔
1311
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
4✔
1312

4✔
1313
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
8✔
1314
                edges := tx.ReadWriteBucket(edgeBucket)
4✔
1315
                if edges == nil {
4✔
1316
                        return ErrEdgeNotFound
×
1317
                }
×
1318

1319
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
4✔
1320
                if edgeIndex == nil {
4✔
1321
                        return ErrEdgeNotFound
×
1322
                }
×
1323

1324
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
4✔
1325
                if err != nil {
4✔
1326
                        return err
×
1327
                }
×
1328

1329
                edge.AuthProof = proof
4✔
1330

4✔
1331
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
4✔
1332
        }, func() {})
4✔
1333
}
1334

1335
const (
1336
        // pruneTipBytes is the total size of the value which stores a prune
1337
        // entry of the graph in the prune log. The "prune tip" is the last
1338
        // entry in the prune log, and indicates if the channel graph is in
1339
        // sync with the current UTXO state. The structure of the value
1340
        // is: blockHash, taking 32 bytes total.
1341
        pruneTipBytes = 32
1342
)
1343

1344
// PruneGraph prunes newly closed channels from the channel graph in response
1345
// to a new block being solved on the network. Any transactions which spend the
1346
// funding output of any known channels within he graph will be deleted.
1347
// Additionally, the "prune tip", or the last block which has been used to
1348
// prune the graph is stored so callers can ensure the graph is fully in sync
1349
// with the current UTXO state. A slice of channels that have been closed by
1350
// the target block are returned if the function succeeds without error.
1351
func (c *KVStore) PruneGraph(spentOutputs []*wire.OutPoint,
1352
        blockHash *chainhash.Hash, blockHeight uint32) (
1353
        []*models.ChannelEdgeInfo, error) {
237✔
1354

237✔
1355
        c.cacheMu.Lock()
237✔
1356
        defer c.cacheMu.Unlock()
237✔
1357

237✔
1358
        var chansClosed []*models.ChannelEdgeInfo
237✔
1359

237✔
1360
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
474✔
1361
                // First grab the edges bucket which houses the information
237✔
1362
                // we'd like to delete
237✔
1363
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
237✔
1364
                if err != nil {
237✔
1365
                        return err
×
1366
                }
×
1367

1368
                // Next grab the two edge indexes which will also need to be
1369
                // updated.
1370
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
237✔
1371
                if err != nil {
237✔
1372
                        return err
×
1373
                }
×
1374
                chanIndex, err := edges.CreateBucketIfNotExists(
237✔
1375
                        channelPointBucket,
237✔
1376
                )
237✔
1377
                if err != nil {
237✔
1378
                        return err
×
1379
                }
×
1380
                nodes := tx.ReadWriteBucket(nodeBucket)
237✔
1381
                if nodes == nil {
237✔
1382
                        return ErrSourceNodeNotSet
×
1383
                }
×
1384
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
237✔
1385
                if err != nil {
237✔
1386
                        return err
×
1387
                }
×
1388

1389
                // For each of the outpoints that have been spent within the
1390
                // block, we attempt to delete them from the graph as if that
1391
                // outpoint was a channel, then it has now been closed.
1392
                for _, chanPoint := range spentOutputs {
340✔
1393
                        // TODO(roasbeef): load channel bloom filter, continue
103✔
1394
                        // if NOT if filter
103✔
1395

103✔
1396
                        var opBytes bytes.Buffer
103✔
1397
                        err := WriteOutpoint(&opBytes, chanPoint)
103✔
1398
                        if err != nil {
103✔
1399
                                return err
×
1400
                        }
×
1401

1402
                        // First attempt to see if the channel exists within
1403
                        // the database, if not, then we can exit early.
1404
                        chanID := chanIndex.Get(opBytes.Bytes())
103✔
1405
                        if chanID == nil {
182✔
1406
                                continue
79✔
1407
                        }
1408

1409
                        // However, if it does, then we'll read out the full
1410
                        // version so we can add it to the set of deleted
1411
                        // channels.
1412
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
24✔
1413
                        if err != nil {
24✔
1414
                                return err
×
1415
                        }
×
1416

1417
                        // Attempt to delete the channel, an ErrEdgeNotFound
1418
                        // will be returned if that outpoint isn't known to be
1419
                        // a channel. If no error is returned, then a channel
1420
                        // was successfully pruned.
1421
                        err = c.delChannelEdgeUnsafe(
24✔
1422
                                edges, edgeIndex, chanIndex, zombieIndex,
24✔
1423
                                chanID, false, false,
24✔
1424
                        )
24✔
1425
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
24✔
1426
                                return err
×
1427
                        }
×
1428

1429
                        chansClosed = append(chansClosed, &edgeInfo)
24✔
1430
                }
1431

1432
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
237✔
1433
                if err != nil {
237✔
1434
                        return err
×
1435
                }
×
1436

1437
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
237✔
1438
                        pruneLogBucket,
237✔
1439
                )
237✔
1440
                if err != nil {
237✔
1441
                        return err
×
1442
                }
×
1443

1444
                // With the graph pruned, add a new entry to the prune log,
1445
                // which can be used to check if the graph is fully synced with
1446
                // the current UTXO state.
1447
                var blockHeightBytes [4]byte
237✔
1448
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
237✔
1449

237✔
1450
                var newTip [pruneTipBytes]byte
237✔
1451
                copy(newTip[:], blockHash[:])
237✔
1452

237✔
1453
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
237✔
1454
                if err != nil {
237✔
1455
                        return err
×
1456
                }
×
1457

1458
                // Now that the graph has been pruned, we'll also attempt to
1459
                // prune any nodes that have had a channel closed within the
1460
                // latest block.
1461
                return c.pruneGraphNodes(nodes, edgeIndex)
237✔
1462
        }, func() {
237✔
1463
                chansClosed = nil
237✔
1464
        })
237✔
1465
        if err != nil {
237✔
1466
                return nil, err
×
1467
        }
×
1468

1469
        for _, channel := range chansClosed {
261✔
1470
                c.rejectCache.remove(channel.ChannelID)
24✔
1471
                c.chanCache.remove(channel.ChannelID)
24✔
1472
        }
24✔
1473

1474
        if c.graphCache != nil {
474✔
1475
                log.Debugf("Pruned graph, cache now has %s",
237✔
1476
                        c.graphCache.Stats())
237✔
1477
        }
237✔
1478

1479
        return chansClosed, nil
237✔
1480
}
1481

1482
// PruneGraphNodes is a garbage collection method which attempts to prune out
1483
// any nodes from the channel graph that are currently unconnected. This ensure
1484
// that we only maintain a graph of reachable nodes. In the event that a pruned
1485
// node gains more channels, it will be re-added back to the graph.
1486
func (c *KVStore) PruneGraphNodes() error {
26✔
1487
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
52✔
1488
                nodes := tx.ReadWriteBucket(nodeBucket)
26✔
1489
                if nodes == nil {
26✔
1490
                        return ErrGraphNodesNotFound
×
1491
                }
×
1492
                edges := tx.ReadWriteBucket(edgeBucket)
26✔
1493
                if edges == nil {
26✔
1494
                        return ErrGraphNotFound
×
1495
                }
×
1496
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
26✔
1497
                if edgeIndex == nil {
26✔
1498
                        return ErrGraphNoEdgesFound
×
1499
                }
×
1500

1501
                return c.pruneGraphNodes(nodes, edgeIndex)
26✔
1502
        }, func() {})
26✔
1503
}
1504

1505
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1506
// channel closed within the current block. If the node still has existing
1507
// channels in the graph, this will act as a no-op.
1508
func (c *KVStore) pruneGraphNodes(nodes kvdb.RwBucket,
1509
        edgeIndex kvdb.RwBucket) error {
260✔
1510

260✔
1511
        log.Trace("Pruning nodes from graph with no open channels")
260✔
1512

260✔
1513
        // We'll retrieve the graph's source node to ensure we don't remove it
260✔
1514
        // even if it no longer has any open channels.
260✔
1515
        sourceNode, err := c.sourceNode(nodes)
260✔
1516
        if err != nil {
260✔
1517
                return err
×
1518
        }
×
1519

1520
        // We'll use this map to keep count the number of references to a node
1521
        // in the graph. A node should only be removed once it has no more
1522
        // references in the graph.
1523
        nodeRefCounts := make(map[[33]byte]int)
260✔
1524
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,527✔
1525
                // If this is the source key, then we skip this
1,267✔
1526
                // iteration as the value for this key is a pubKey
1,267✔
1527
                // rather than raw node information.
1,267✔
1528
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,041✔
1529
                        return nil
774✔
1530
                }
774✔
1531

1532
                var nodePub [33]byte
496✔
1533
                copy(nodePub[:], pubKey)
496✔
1534
                nodeRefCounts[nodePub] = 0
496✔
1535

496✔
1536
                return nil
496✔
1537
        })
1538
        if err != nil {
260✔
1539
                return err
×
1540
        }
×
1541

1542
        // To ensure we never delete the source node, we'll start off by
1543
        // bumping its ref count to 1.
1544
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
260✔
1545

260✔
1546
        // Next, we'll run through the edgeIndex which maps a channel ID to the
260✔
1547
        // edge info. We'll use this scan to populate our reference count map
260✔
1548
        // above.
260✔
1549
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
434✔
1550
                // The first 66 bytes of the edge info contain the pubkeys of
174✔
1551
                // the nodes that this edge attaches. We'll extract them, and
174✔
1552
                // add them to the ref count map.
174✔
1553
                var node1, node2 [33]byte
174✔
1554
                copy(node1[:], edgeInfoBytes[:33])
174✔
1555
                copy(node2[:], edgeInfoBytes[33:])
174✔
1556

174✔
1557
                // With the nodes extracted, we'll increase the ref count of
174✔
1558
                // each of the nodes.
174✔
1559
                nodeRefCounts[node1]++
174✔
1560
                nodeRefCounts[node2]++
174✔
1561

174✔
1562
                return nil
174✔
1563
        })
174✔
1564
        if err != nil {
260✔
1565
                return err
×
1566
        }
×
1567

1568
        // Finally, we'll make a second pass over the set of nodes, and delete
1569
        // any nodes that have a ref count of zero.
1570
        var numNodesPruned int
260✔
1571
        for nodePubKey, refCount := range nodeRefCounts {
756✔
1572
                // If the ref count of the node isn't zero, then we can safely
496✔
1573
                // skip it as it still has edges to or from it within the
496✔
1574
                // graph.
496✔
1575
                if refCount != 0 {
924✔
1576
                        continue
428✔
1577
                }
1578

1579
                if c.graphCache != nil {
142✔
1580
                        c.graphCache.RemoveNode(nodePubKey)
71✔
1581
                }
71✔
1582

1583
                // If we reach this point, then there are no longer any edges
1584
                // that connect this node, so we can delete it.
1585
                err := c.deleteLightningNode(nodes, nodePubKey[:])
71✔
1586
                if err != nil {
71✔
1587
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1588
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1589

×
1590
                                log.Warnf("Unable to prune node %x from the "+
×
1591
                                        "graph: %v", nodePubKey, err)
×
1592
                                continue
×
1593
                        }
1594

1595
                        return err
×
1596
                }
1597

1598
                log.Infof("Pruned unconnected node %x from channel graph",
71✔
1599
                        nodePubKey[:])
71✔
1600

71✔
1601
                numNodesPruned++
71✔
1602
        }
1603

1604
        if numNodesPruned > 0 {
315✔
1605
                log.Infof("Pruned %v unconnected nodes from the channel graph",
55✔
1606
                        numNodesPruned)
55✔
1607
        }
55✔
1608

1609
        return nil
260✔
1610
}
1611

1612
// DisconnectBlockAtHeight is used to indicate that the block specified
1613
// by the passed height has been disconnected from the main chain. This
1614
// will "rewind" the graph back to the height below, deleting channels
1615
// that are no longer confirmed from the graph. The prune log will be
1616
// set to the last prune height valid for the remaining chain.
1617
// Channels that were removed from the graph resulting from the
1618
// disconnected block are returned.
1619
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1620
        []*models.ChannelEdgeInfo, error) {
155✔
1621

155✔
1622
        // Every channel having a ShortChannelID starting at 'height'
155✔
1623
        // will no longer be confirmed.
155✔
1624
        startShortChanID := lnwire.ShortChannelID{
155✔
1625
                BlockHeight: height,
155✔
1626
        }
155✔
1627

155✔
1628
        // Delete everything after this height from the db up until the
155✔
1629
        // SCID alias range.
155✔
1630
        endShortChanID := aliasmgr.StartingAlias
155✔
1631

155✔
1632
        // The block height will be the 3 first bytes of the channel IDs.
155✔
1633
        var chanIDStart [8]byte
155✔
1634
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
155✔
1635
        var chanIDEnd [8]byte
155✔
1636
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
155✔
1637

155✔
1638
        c.cacheMu.Lock()
155✔
1639
        defer c.cacheMu.Unlock()
155✔
1640

155✔
1641
        // Keep track of the channels that are removed from the graph.
155✔
1642
        var removedChans []*models.ChannelEdgeInfo
155✔
1643

155✔
1644
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
310✔
1645
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
155✔
1646
                if err != nil {
155✔
1647
                        return err
×
1648
                }
×
1649
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
155✔
1650
                if err != nil {
155✔
1651
                        return err
×
1652
                }
×
1653
                chanIndex, err := edges.CreateBucketIfNotExists(
155✔
1654
                        channelPointBucket,
155✔
1655
                )
155✔
1656
                if err != nil {
155✔
1657
                        return err
×
1658
                }
×
1659
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
155✔
1660
                if err != nil {
155✔
1661
                        return err
×
1662
                }
×
1663

1664
                // Scan from chanIDStart to chanIDEnd, deleting every
1665
                // found edge.
1666
                // NOTE: we must delete the edges after the cursor loop, since
1667
                // modifying the bucket while traversing is not safe.
1668
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1669
                // so that the StartingAlias itself isn't deleted.
1670
                var keys [][]byte
155✔
1671
                cursor := edgeIndex.ReadWriteCursor()
155✔
1672

155✔
1673
                //nolint:ll
155✔
1674
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
155✔
1675
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
248✔
1676
                        edgeInfoReader := bytes.NewReader(v)
93✔
1677
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
93✔
1678
                        if err != nil {
93✔
1679
                                return err
×
1680
                        }
×
1681

1682
                        keys = append(keys, k)
93✔
1683
                        removedChans = append(removedChans, &edgeInfo)
93✔
1684
                }
1685

1686
                for _, k := range keys {
248✔
1687
                        err = c.delChannelEdgeUnsafe(
93✔
1688
                                edges, edgeIndex, chanIndex, zombieIndex,
93✔
1689
                                k, false, false,
93✔
1690
                        )
93✔
1691
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
93✔
1692
                                return err
×
1693
                        }
×
1694
                }
1695

1696
                // Delete all the entries in the prune log having a height
1697
                // greater or equal to the block disconnected.
1698
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
155✔
1699
                if err != nil {
155✔
1700
                        return err
×
1701
                }
×
1702

1703
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
155✔
1704
                        pruneLogBucket,
155✔
1705
                )
155✔
1706
                if err != nil {
155✔
1707
                        return err
×
1708
                }
×
1709

1710
                var pruneKeyStart [4]byte
155✔
1711
                byteOrder.PutUint32(pruneKeyStart[:], height)
155✔
1712

155✔
1713
                var pruneKeyEnd [4]byte
155✔
1714
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
155✔
1715

155✔
1716
                // To avoid modifying the bucket while traversing, we delete
155✔
1717
                // the keys in a second loop.
155✔
1718
                var pruneKeys [][]byte
155✔
1719
                pruneCursor := pruneBucket.ReadWriteCursor()
155✔
1720
                //nolint:ll
155✔
1721
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
155✔
1722
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
246✔
1723
                        pruneKeys = append(pruneKeys, k)
91✔
1724
                }
91✔
1725

1726
                for _, k := range pruneKeys {
246✔
1727
                        if err := pruneBucket.Delete(k); err != nil {
91✔
1728
                                return err
×
1729
                        }
×
1730
                }
1731

1732
                return nil
155✔
1733
        }, func() {
155✔
1734
                removedChans = nil
155✔
1735
        }); err != nil {
155✔
1736
                return nil, err
×
1737
        }
×
1738

1739
        for _, channel := range removedChans {
248✔
1740
                c.rejectCache.remove(channel.ChannelID)
93✔
1741
                c.chanCache.remove(channel.ChannelID)
93✔
1742
        }
93✔
1743

1744
        return removedChans, nil
155✔
1745
}
1746

1747
// PruneTip returns the block height and hash of the latest block that has been
1748
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1749
// to tell if the graph is currently in sync with the current best known UTXO
1750
// state.
1751
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
56✔
1752
        var (
56✔
1753
                tipHash   chainhash.Hash
56✔
1754
                tipHeight uint32
56✔
1755
        )
56✔
1756

56✔
1757
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
112✔
1758
                graphMeta := tx.ReadBucket(graphMetaBucket)
56✔
1759
                if graphMeta == nil {
56✔
1760
                        return ErrGraphNotFound
×
1761
                }
×
1762
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
56✔
1763
                if pruneBucket == nil {
56✔
1764
                        return ErrGraphNeverPruned
×
1765
                }
×
1766

1767
                pruneCursor := pruneBucket.ReadCursor()
56✔
1768

56✔
1769
                // The prune key with the largest block height will be our
56✔
1770
                // prune tip.
56✔
1771
                k, v := pruneCursor.Last()
56✔
1772
                if k == nil {
77✔
1773
                        return ErrGraphNeverPruned
21✔
1774
                }
21✔
1775

1776
                // Once we have the prune tip, the value will be the block hash,
1777
                // and the key the block height.
1778
                copy(tipHash[:], v)
38✔
1779
                tipHeight = byteOrder.Uint32(k)
38✔
1780

38✔
1781
                return nil
38✔
1782
        }, func() {})
56✔
1783
        if err != nil {
77✔
1784
                return nil, 0, err
21✔
1785
        }
21✔
1786

1787
        return &tipHash, tipHeight, nil
38✔
1788
}
1789

1790
// DeleteChannelEdges removes edges with the given channel IDs from the
1791
// database and marks them as zombies. This ensures that we're unable to re-add
1792
// it to our database once again. If an edge does not exist within the
1793
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1794
// true, then when we mark these edges as zombies, we'll set up the keys such
1795
// that we require the node that failed to send the fresh update to be the one
1796
// that resurrects the channel from its zombie state. The markZombie bool
1797
// denotes whether or not to mark the channel as a zombie.
1798
func (c *KVStore) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1799
        chanIDs ...uint64) error {
151✔
1800

151✔
1801
        // TODO(roasbeef): possibly delete from node bucket if node has no more
151✔
1802
        // channels
151✔
1803
        // TODO(roasbeef): don't delete both edges?
151✔
1804

151✔
1805
        c.cacheMu.Lock()
151✔
1806
        defer c.cacheMu.Unlock()
151✔
1807

151✔
1808
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
302✔
1809
                edges := tx.ReadWriteBucket(edgeBucket)
151✔
1810
                if edges == nil {
151✔
1811
                        return ErrEdgeNotFound
×
1812
                }
×
1813
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
151✔
1814
                if edgeIndex == nil {
151✔
1815
                        return ErrEdgeNotFound
×
1816
                }
×
1817
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
151✔
1818
                if chanIndex == nil {
151✔
1819
                        return ErrEdgeNotFound
×
1820
                }
×
1821
                nodes := tx.ReadWriteBucket(nodeBucket)
151✔
1822
                if nodes == nil {
151✔
1823
                        return ErrGraphNodeNotFound
×
1824
                }
×
1825
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
151✔
1826
                if err != nil {
151✔
1827
                        return err
×
1828
                }
×
1829

1830
                var rawChanID [8]byte
151✔
1831
                for _, chanID := range chanIDs {
240✔
1832
                        byteOrder.PutUint64(rawChanID[:], chanID)
89✔
1833
                        err := c.delChannelEdgeUnsafe(
89✔
1834
                                edges, edgeIndex, chanIndex, zombieIndex,
89✔
1835
                                rawChanID[:], markZombie, strictZombiePruning,
89✔
1836
                        )
89✔
1837
                        if err != nil {
152✔
1838
                                return err
63✔
1839
                        }
63✔
1840
                }
1841

1842
                return nil
88✔
1843
        }, func() {})
151✔
1844
        if err != nil {
214✔
1845
                return err
63✔
1846
        }
63✔
1847

1848
        for _, chanID := range chanIDs {
114✔
1849
                c.rejectCache.remove(chanID)
26✔
1850
                c.chanCache.remove(chanID)
26✔
1851
        }
26✔
1852

1853
        return nil
88✔
1854
}
1855

1856
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1857
// passed channel point (outpoint). If the passed channel doesn't exist within
1858
// the database, then ErrEdgeNotFound is returned.
1859
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
4✔
1860
        var chanID uint64
4✔
1861
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
1862
                var err error
4✔
1863
                chanID, err = getChanID(tx, chanPoint)
4✔
1864
                return err
4✔
1865
        }, func() {
8✔
1866
                chanID = 0
4✔
1867
        }); err != nil {
7✔
1868
                return 0, err
3✔
1869
        }
3✔
1870

1871
        return chanID, nil
4✔
1872
}
1873

1874
// getChanID returns the assigned channel ID for a given channel point.
1875
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
4✔
1876
        var b bytes.Buffer
4✔
1877
        if err := WriteOutpoint(&b, chanPoint); err != nil {
4✔
1878
                return 0, err
×
1879
        }
×
1880

1881
        edges := tx.ReadBucket(edgeBucket)
4✔
1882
        if edges == nil {
4✔
1883
                return 0, ErrGraphNoEdgesFound
×
1884
        }
×
1885
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1886
        if chanIndex == nil {
4✔
1887
                return 0, ErrGraphNoEdgesFound
×
1888
        }
×
1889

1890
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1891
        if chanIDBytes == nil {
7✔
1892
                return 0, ErrEdgeNotFound
3✔
1893
        }
3✔
1894

1895
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1896

4✔
1897
        return chanID, nil
4✔
1898
}
1899

1900
// TODO(roasbeef): allow updates to use Batch?
1901

1902
// HighestChanID returns the "highest" known channel ID in the channel graph.
1903
// This represents the "newest" channel from the PoV of the chain. This method
1904
// can be used by peers to quickly determine if they're graphs are in sync.
1905
func (c *KVStore) HighestChanID() (uint64, error) {
6✔
1906
        var cid uint64
6✔
1907

6✔
1908
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
1909
                edges := tx.ReadBucket(edgeBucket)
6✔
1910
                if edges == nil {
6✔
1911
                        return ErrGraphNoEdgesFound
×
1912
                }
×
1913
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
6✔
1914
                if edgeIndex == nil {
6✔
1915
                        return ErrGraphNoEdgesFound
×
1916
                }
×
1917

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

6✔
1922
                lastChanID, _ := cidCursor.Last()
6✔
1923

6✔
1924
                // If there's no key, then this means that we don't actually
6✔
1925
                // know of any channels, so we'll return a predicable error.
6✔
1926
                if lastChanID == nil {
10✔
1927
                        return ErrGraphNoEdgesFound
4✔
1928
                }
4✔
1929

1930
                // Otherwise, we'll de serialize the channel ID and return it
1931
                // to the caller.
1932
                cid = byteOrder.Uint64(lastChanID)
5✔
1933

5✔
1934
                return nil
5✔
1935
        }, func() {
6✔
1936
                cid = 0
6✔
1937
        })
6✔
1938
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
6✔
1939
                return 0, err
×
1940
        }
×
1941

1942
        return cid, nil
6✔
1943
}
1944

1945
// ChannelEdge represents the complete set of information for a channel edge in
1946
// the known channel graph. This struct couples the core information of the
1947
// edge as well as each of the known advertised edge policies.
1948
type ChannelEdge struct {
1949
        // Info contains all the static information describing the channel.
1950
        Info *models.ChannelEdgeInfo
1951

1952
        // Policy1 points to the "first" edge policy of the channel containing
1953
        // the dynamic information required to properly route through the edge.
1954
        Policy1 *models.ChannelEdgePolicy
1955

1956
        // Policy2 points to the "second" edge policy of the channel containing
1957
        // the dynamic information required to properly route through the edge.
1958
        Policy2 *models.ChannelEdgePolicy
1959

1960
        // Node1 is "node 1" in the channel. This is the node that would have
1961
        // produced Policy1 if it exists.
1962
        Node1 *models.LightningNode
1963

1964
        // Node2 is "node 2" in the channel. This is the node that would have
1965
        // produced Policy2 if it exists.
1966
        Node2 *models.LightningNode
1967
}
1968

1969
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1970
// one edge that has an update timestamp within the specified horizon.
1971
func (c *KVStore) ChanUpdatesInHorizon(startTime,
1972
        endTime time.Time) ([]ChannelEdge, error) {
150✔
1973

150✔
1974
        // To ensure we don't return duplicate ChannelEdges, we'll use an
150✔
1975
        // additional map to keep track of the edges already seen to prevent
150✔
1976
        // re-adding it.
150✔
1977
        var edgesSeen map[uint64]struct{}
150✔
1978
        var edgesToCache map[uint64]ChannelEdge
150✔
1979
        var edgesInHorizon []ChannelEdge
150✔
1980

150✔
1981
        c.cacheMu.Lock()
150✔
1982
        defer c.cacheMu.Unlock()
150✔
1983

150✔
1984
        var hits int
150✔
1985
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
300✔
1986
                edges := tx.ReadBucket(edgeBucket)
150✔
1987
                if edges == nil {
150✔
1988
                        return ErrGraphNoEdgesFound
×
1989
                }
×
1990
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
150✔
1991
                if edgeIndex == nil {
150✔
1992
                        return ErrGraphNoEdgesFound
×
1993
                }
×
1994
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
150✔
1995
                if edgeUpdateIndex == nil {
150✔
1996
                        return ErrGraphNoEdgesFound
×
1997
                }
×
1998

1999
                nodes := tx.ReadBucket(nodeBucket)
150✔
2000
                if nodes == nil {
150✔
2001
                        return ErrGraphNodesNotFound
×
2002
                }
×
2003

2004
                // We'll now obtain a cursor to perform a range query within
2005
                // the index to find all channels within the horizon.
2006
                updateCursor := edgeUpdateIndex.ReadCursor()
150✔
2007

150✔
2008
                var startTimeBytes, endTimeBytes [8 + 8]byte
150✔
2009
                byteOrder.PutUint64(
150✔
2010
                        startTimeBytes[:8], uint64(startTime.Unix()),
150✔
2011
                )
150✔
2012
                byteOrder.PutUint64(
150✔
2013
                        endTimeBytes[:8], uint64(endTime.Unix()),
150✔
2014
                )
150✔
2015

150✔
2016
                // With our start and end times constructed, we'll step through
150✔
2017
                // the index collecting the info and policy of each update of
150✔
2018
                // each channel that has a last update within the time range.
150✔
2019
                //
150✔
2020
                //nolint:ll
150✔
2021
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
150✔
2022
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
199✔
2023
                        // We have a new eligible entry, so we'll slice of the
49✔
2024
                        // chan ID so we can query it in the DB.
49✔
2025
                        chanID := indexKey[8:]
49✔
2026

49✔
2027
                        // If we've already retrieved the info and policies for
49✔
2028
                        // this edge, then we can skip it as we don't need to do
49✔
2029
                        // so again.
49✔
2030
                        chanIDInt := byteOrder.Uint64(chanID)
49✔
2031
                        if _, ok := edgesSeen[chanIDInt]; ok {
68✔
2032
                                continue
19✔
2033
                        }
2034

2035
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
42✔
2036
                                hits++
12✔
2037
                                edgesSeen[chanIDInt] = struct{}{}
12✔
2038
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
2039

12✔
2040
                                continue
12✔
2041
                        }
2042

2043
                        // First, we'll fetch the static edge information.
2044
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
21✔
2045
                        if err != nil {
21✔
2046
                                chanID := byteOrder.Uint64(chanID)
×
2047
                                return fmt.Errorf("unable to fetch info for "+
×
2048
                                        "edge with chan_id=%v: %v", chanID, err)
×
2049
                        }
×
2050

2051
                        // With the static information obtained, we'll now
2052
                        // fetch the dynamic policy info.
2053
                        edge1, edge2, err := fetchChanEdgePolicies(
21✔
2054
                                edgeIndex, edges, chanID,
21✔
2055
                        )
21✔
2056
                        if err != nil {
21✔
2057
                                chanID := byteOrder.Uint64(chanID)
×
2058
                                return fmt.Errorf("unable to fetch policies "+
×
2059
                                        "for edge with chan_id=%v: %v", chanID,
×
2060
                                        err)
×
2061
                        }
×
2062

2063
                        node1, err := fetchLightningNode(
21✔
2064
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
2065
                        )
21✔
2066
                        if err != nil {
21✔
2067
                                return err
×
2068
                        }
×
2069

2070
                        node2, err := fetchLightningNode(
21✔
2071
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
2072
                        )
21✔
2073
                        if err != nil {
21✔
2074
                                return err
×
2075
                        }
×
2076

2077
                        // Finally, we'll collate this edge with the rest of
2078
                        // edges to be returned.
2079
                        edgesSeen[chanIDInt] = struct{}{}
21✔
2080
                        channel := ChannelEdge{
21✔
2081
                                Info:    &edgeInfo,
21✔
2082
                                Policy1: edge1,
21✔
2083
                                Policy2: edge2,
21✔
2084
                                Node1:   &node1,
21✔
2085
                                Node2:   &node2,
21✔
2086
                        }
21✔
2087
                        edgesInHorizon = append(edgesInHorizon, channel)
21✔
2088
                        edgesToCache[chanIDInt] = channel
21✔
2089
                }
2090

2091
                return nil
150✔
2092
        }, func() {
150✔
2093
                edgesSeen = make(map[uint64]struct{})
150✔
2094
                edgesToCache = make(map[uint64]ChannelEdge)
150✔
2095
                edgesInHorizon = nil
150✔
2096
        })
150✔
2097
        switch {
150✔
2098
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2099
                fallthrough
×
2100
        case errors.Is(err, ErrGraphNodesNotFound):
×
2101
                break
×
2102

2103
        case err != nil:
×
2104
                return nil, err
×
2105
        }
2106

2107
        // Insert any edges loaded from disk into the cache.
2108
        for chanid, channel := range edgesToCache {
171✔
2109
                c.chanCache.insert(chanid, channel)
21✔
2110
        }
21✔
2111

2112
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
150✔
2113
                float64(hits)/float64(len(edgesInHorizon)), hits,
150✔
2114
                len(edgesInHorizon))
150✔
2115

150✔
2116
        return edgesInHorizon, nil
150✔
2117
}
2118

2119
// NodeUpdatesInHorizon returns all the known lightning node which have an
2120
// update timestamp within the passed range. This method can be used by two
2121
// nodes to quickly determine if they have the same set of up to date node
2122
// announcements.
2123
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2124
        endTime time.Time) ([]models.LightningNode, error) {
11✔
2125

11✔
2126
        var nodesInHorizon []models.LightningNode
11✔
2127

11✔
2128
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2129
                nodes := tx.ReadBucket(nodeBucket)
11✔
2130
                if nodes == nil {
11✔
2131
                        return ErrGraphNodesNotFound
×
2132
                }
×
2133

2134
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2135
                if nodeUpdateIndex == nil {
11✔
2136
                        return ErrGraphNodesNotFound
×
2137
                }
×
2138

2139
                // We'll now obtain a cursor to perform a range query within
2140
                // the index to find all node announcements within the horizon.
2141
                updateCursor := nodeUpdateIndex.ReadCursor()
11✔
2142

11✔
2143
                var startTimeBytes, endTimeBytes [8 + 33]byte
11✔
2144
                byteOrder.PutUint64(
11✔
2145
                        startTimeBytes[:8], uint64(startTime.Unix()),
11✔
2146
                )
11✔
2147
                byteOrder.PutUint64(
11✔
2148
                        endTimeBytes[:8], uint64(endTime.Unix()),
11✔
2149
                )
11✔
2150

11✔
2151
                // With our start and end times constructed, we'll step through
11✔
2152
                // the index collecting info for each node within the time
11✔
2153
                // range.
11✔
2154
                //
11✔
2155
                //nolint:ll
11✔
2156
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
11✔
2157
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
43✔
2158
                        nodePub := indexKey[8:]
32✔
2159
                        node, err := fetchLightningNode(nodes, nodePub)
32✔
2160
                        if err != nil {
32✔
2161
                                return err
×
2162
                        }
×
2163

2164
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2165
                }
2166

2167
                return nil
11✔
2168
        }, func() {
11✔
2169
                nodesInHorizon = nil
11✔
2170
        })
11✔
2171
        switch {
11✔
2172
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2173
                fallthrough
×
2174
        case errors.Is(err, ErrGraphNodesNotFound):
×
2175
                break
×
2176

2177
        case err != nil:
×
2178
                return nil, err
×
2179
        }
2180

2181
        return nodesInHorizon, nil
11✔
2182
}
2183

2184
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2185
// ID's that we don't know and are not known zombies of the passed set. In other
2186
// words, we perform a set difference of our set of chan ID's and the ones
2187
// passed in. This method can be used by callers to determine the set of
2188
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2189
// known zombies is also returned.
2190
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2191
        []ChannelUpdateInfo, error) {
135✔
2192

135✔
2193
        var (
135✔
2194
                newChanIDs   []uint64
135✔
2195
                knownZombies []ChannelUpdateInfo
135✔
2196
        )
135✔
2197

135✔
2198
        c.cacheMu.Lock()
135✔
2199
        defer c.cacheMu.Unlock()
135✔
2200

135✔
2201
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
270✔
2202
                edges := tx.ReadBucket(edgeBucket)
135✔
2203
                if edges == nil {
135✔
2204
                        return ErrGraphNoEdgesFound
×
2205
                }
×
2206
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
135✔
2207
                if edgeIndex == nil {
135✔
2208
                        return ErrGraphNoEdgesFound
×
2209
                }
×
2210

2211
                // Fetch the zombie index, it may not exist if no edges have
2212
                // ever been marked as zombies. If the index has been
2213
                // initialized, we will use it later to skip known zombie edges.
2214
                zombieIndex := edges.NestedReadBucket(zombieBucket)
135✔
2215

135✔
2216
                // We'll run through the set of chanIDs and collate only the
135✔
2217
                // set of channel that are unable to be found within our db.
135✔
2218
                var cidBytes [8]byte
135✔
2219
                for _, info := range chansInfo {
248✔
2220
                        scid := info.ShortChannelID.ToUint64()
113✔
2221
                        byteOrder.PutUint64(cidBytes[:], scid)
113✔
2222

113✔
2223
                        // If the edge is already known, skip it.
113✔
2224
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
136✔
2225
                                continue
23✔
2226
                        }
2227

2228
                        // If the edge is a known zombie, skip it.
2229
                        if zombieIndex != nil {
186✔
2230
                                isZombie, _, _ := isZombieEdge(
93✔
2231
                                        zombieIndex, scid,
93✔
2232
                                )
93✔
2233

93✔
2234
                                if isZombie {
136✔
2235
                                        knownZombies = append(
43✔
2236
                                                knownZombies, info,
43✔
2237
                                        )
43✔
2238

43✔
2239
                                        continue
43✔
2240
                                }
2241
                        }
2242

2243
                        newChanIDs = append(newChanIDs, scid)
50✔
2244
                }
2245

2246
                return nil
135✔
2247
        }, func() {
135✔
2248
                newChanIDs = nil
135✔
2249
                knownZombies = nil
135✔
2250
        })
135✔
2251
        switch {
135✔
2252
        // If we don't know of any edges yet, then we'll return the entire set
2253
        // of chan IDs specified.
2254
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2255
                ogChanIDs := make([]uint64, len(chansInfo))
×
2256
                for i, info := range chansInfo {
×
2257
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2258
                }
×
2259

NEW
2260
                return ogChanIDs, nil, nil
×
2261

2262
        case err != nil:
×
NEW
2263
                return nil, nil, err
×
2264
        }
2265

2266
        return newChanIDs, knownZombies, nil
135✔
2267
}
2268

2269
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2270
// latest received channel updates for the channel.
2271
type ChannelUpdateInfo struct {
2272
        // ShortChannelID is the SCID identifier of the channel.
2273
        ShortChannelID lnwire.ShortChannelID
2274

2275
        // Node1UpdateTimestamp is the timestamp of the latest received update
2276
        // from the node 1 channel peer. This will be set to zero time if no
2277
        // update has yet been received from this node.
2278
        Node1UpdateTimestamp time.Time
2279

2280
        // Node2UpdateTimestamp is the timestamp of the latest received update
2281
        // from the node 2 channel peer. This will be set to zero time if no
2282
        // update has yet been received from this node.
2283
        Node2UpdateTimestamp time.Time
2284
}
2285

2286
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2287
// timestamps with zero seconds unix timestamp which equals
2288
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2289
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2290
        node2Timestamp time.Time) ChannelUpdateInfo {
221✔
2291

221✔
2292
        chanInfo := ChannelUpdateInfo{
221✔
2293
                ShortChannelID:       scid,
221✔
2294
                Node1UpdateTimestamp: node1Timestamp,
221✔
2295
                Node2UpdateTimestamp: node2Timestamp,
221✔
2296
        }
221✔
2297

221✔
2298
        if node1Timestamp.IsZero() {
432✔
2299
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
211✔
2300
        }
211✔
2301

2302
        if node2Timestamp.IsZero() {
432✔
2303
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
211✔
2304
        }
211✔
2305

2306
        return chanInfo
221✔
2307
}
2308

2309
// BlockChannelRange represents a range of channels for a given block height.
2310
type BlockChannelRange struct {
2311
        // Height is the height of the block all of the channels below were
2312
        // included in.
2313
        Height uint32
2314

2315
        // Channels is the list of channels identified by their short ID
2316
        // representation known to us that were included in the block height
2317
        // above. The list may include channel update timestamp information if
2318
        // requested.
2319
        Channels []ChannelUpdateInfo
2320
}
2321

2322
// FilterChannelRange returns the channel ID's of all known channels which were
2323
// mined in a block height within the passed range. The channel IDs are grouped
2324
// by their common block height. This method can be used to quickly share with a
2325
// peer the set of channels we know of within a particular range to catch them
2326
// up after a period of time offline. If withTimestamps is true then the
2327
// timestamp info of the latest received channel update messages of the channel
2328
// will be included in the response.
2329
func (c *KVStore) FilterChannelRange(startHeight,
2330
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
14✔
2331

14✔
2332
        startChanID := &lnwire.ShortChannelID{
14✔
2333
                BlockHeight: startHeight,
14✔
2334
        }
14✔
2335

14✔
2336
        endChanID := lnwire.ShortChannelID{
14✔
2337
                BlockHeight: endHeight,
14✔
2338
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2339
                TxPosition:  math.MaxUint16,
14✔
2340
        }
14✔
2341

14✔
2342
        // As we need to perform a range scan, we'll convert the starting and
14✔
2343
        // ending height to their corresponding values when encoded using short
14✔
2344
        // channel ID's.
14✔
2345
        var chanIDStart, chanIDEnd [8]byte
14✔
2346
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
14✔
2347
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
14✔
2348

14✔
2349
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2350
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2351
                edges := tx.ReadBucket(edgeBucket)
14✔
2352
                if edges == nil {
14✔
2353
                        return ErrGraphNoEdgesFound
×
2354
                }
×
2355
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2356
                if edgeIndex == nil {
14✔
2357
                        return ErrGraphNoEdgesFound
×
2358
                }
×
2359

2360
                cursor := edgeIndex.ReadCursor()
14✔
2361

14✔
2362
                // We'll now iterate through the database, and find each
14✔
2363
                // channel ID that resides within the specified range.
14✔
2364
                //
14✔
2365
                //nolint:ll
14✔
2366
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
14✔
2367
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
61✔
2368
                        // Don't send alias SCIDs during gossip sync.
47✔
2369
                        edgeReader := bytes.NewReader(v)
47✔
2370
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
47✔
2371
                        if err != nil {
47✔
2372
                                return err
×
2373
                        }
×
2374

2375
                        if edgeInfo.AuthProof == nil {
50✔
2376
                                continue
3✔
2377
                        }
2378

2379
                        // This channel ID rests within the target range, so
2380
                        // we'll add it to our returned set.
2381
                        rawCid := byteOrder.Uint64(k)
47✔
2382
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2383

47✔
2384
                        chanInfo := NewChannelUpdateInfo(
47✔
2385
                                cid, time.Time{}, time.Time{},
47✔
2386
                        )
47✔
2387

47✔
2388
                        if !withTimestamps {
69✔
2389
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2390
                                        channelsPerBlock[cid.BlockHeight],
22✔
2391
                                        chanInfo,
22✔
2392
                                )
22✔
2393

22✔
2394
                                continue
22✔
2395
                        }
2396

2397
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2398

25✔
2399
                        rawPolicy := edges.Get(node1Key)
25✔
2400
                        if len(rawPolicy) != 0 {
34✔
2401
                                r := bytes.NewReader(rawPolicy)
9✔
2402

9✔
2403
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2404
                                if err != nil && !errors.Is(
9✔
2405
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2406
                                ) {
9✔
2407

×
2408
                                        return err
×
2409
                                }
×
2410

2411
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2412
                        }
2413

2414
                        rawPolicy = edges.Get(node2Key)
25✔
2415
                        if len(rawPolicy) != 0 {
39✔
2416
                                r := bytes.NewReader(rawPolicy)
14✔
2417

14✔
2418
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2419
                                if err != nil && !errors.Is(
14✔
2420
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2421
                                ) {
14✔
2422

×
2423
                                        return err
×
2424
                                }
×
2425

2426
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2427
                        }
2428

2429
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2430
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2431
                        )
25✔
2432
                }
2433

2434
                return nil
14✔
2435
        }, func() {
14✔
2436
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2437
        })
14✔
2438

2439
        switch {
14✔
2440
        // If we don't know of any channels yet, then there's nothing to
2441
        // filter, so we'll return an empty slice.
2442
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
6✔
2443
                return nil, nil
6✔
2444

2445
        case err != nil:
×
2446
                return nil, err
×
2447
        }
2448

2449
        // Return the channel ranges in ascending block height order.
2450
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2451
        for block := range channelsPerBlock {
36✔
2452
                blocks = append(blocks, block)
25✔
2453
        }
25✔
2454
        sort.Slice(blocks, func(i, j int) bool {
28✔
2455
                return blocks[i] < blocks[j]
17✔
2456
        })
17✔
2457

2458
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2459
        for _, block := range blocks {
36✔
2460
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2461
                        Height:   block,
25✔
2462
                        Channels: channelsPerBlock[block],
25✔
2463
                })
25✔
2464
        }
25✔
2465

2466
        return channelRanges, nil
11✔
2467
}
2468

2469
// FetchChanInfos returns the set of channel edges that correspond to the passed
2470
// channel ID's. If an edge is the query is unknown to the database, it will
2471
// skipped and the result will contain only those edges that exist at the time
2472
// of the query. This can be used to respond to peer queries that are seeking to
2473
// fill in gaps in their view of the channel graph.
2474
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
6✔
2475
        return c.fetchChanInfos(nil, chanIDs)
6✔
2476
}
6✔
2477

2478
// fetchChanInfos returns the set of channel edges that correspond to the passed
2479
// channel ID's. If an edge is the query is unknown to the database, it will
2480
// skipped and the result will contain only those edges that exist at the time
2481
// of the query. This can be used to respond to peer queries that are seeking to
2482
// fill in gaps in their view of the channel graph.
2483
//
2484
// NOTE: An optional transaction may be provided. If none is provided, then a
2485
// new one will be created.
2486
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2487
        []ChannelEdge, error) {
23✔
2488
        // TODO(roasbeef): sort cids?
23✔
2489

23✔
2490
        var (
23✔
2491
                chanEdges []ChannelEdge
23✔
2492
                cidBytes  [8]byte
23✔
2493
        )
23✔
2494

23✔
2495
        fetchChanInfos := func(tx kvdb.RTx) error {
46✔
2496
                edges := tx.ReadBucket(edgeBucket)
23✔
2497
                if edges == nil {
23✔
2498
                        return ErrGraphNoEdgesFound
×
2499
                }
×
2500
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
23✔
2501
                if edgeIndex == nil {
23✔
2502
                        return ErrGraphNoEdgesFound
×
2503
                }
×
2504
                nodes := tx.ReadBucket(nodeBucket)
23✔
2505
                if nodes == nil {
23✔
2506
                        return ErrGraphNotFound
×
2507
                }
×
2508

2509
                for _, cid := range chanIDs {
53✔
2510
                        byteOrder.PutUint64(cidBytes[:], cid)
30✔
2511

30✔
2512
                        // First, we'll fetch the static edge information. If
30✔
2513
                        // the edge is unknown, we will skip the edge and
30✔
2514
                        // continue gathering all known edges.
30✔
2515
                        edgeInfo, err := fetchChanEdgeInfo(
30✔
2516
                                edgeIndex, cidBytes[:],
30✔
2517
                        )
30✔
2518
                        switch {
30✔
2519
                        case errors.Is(err, ErrEdgeNotFound):
19✔
2520
                                continue
19✔
2521
                        case err != nil:
×
2522
                                return err
×
2523
                        }
2524

2525
                        // With the static information obtained, we'll now
2526
                        // fetch the dynamic policy info.
2527
                        edge1, edge2, err := fetchChanEdgePolicies(
11✔
2528
                                edgeIndex, edges, cidBytes[:],
11✔
2529
                        )
11✔
2530
                        if err != nil {
11✔
2531
                                return err
×
2532
                        }
×
2533

2534
                        node1, err := fetchLightningNode(
11✔
2535
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2536
                        )
11✔
2537
                        if err != nil {
11✔
2538
                                return err
×
2539
                        }
×
2540

2541
                        node2, err := fetchLightningNode(
11✔
2542
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2543
                        )
11✔
2544
                        if err != nil {
11✔
2545
                                return err
×
2546
                        }
×
2547

2548
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2549
                                Info:    &edgeInfo,
11✔
2550
                                Policy1: edge1,
11✔
2551
                                Policy2: edge2,
11✔
2552
                                Node1:   &node1,
11✔
2553
                                Node2:   &node2,
11✔
2554
                        })
11✔
2555
                }
2556

2557
                return nil
23✔
2558
        }
2559

2560
        if tx == nil {
46✔
2561
                err := kvdb.View(c.db, fetchChanInfos, func() {
46✔
2562
                        chanEdges = nil
23✔
2563
                })
23✔
2564
                if err != nil {
23✔
2565
                        return nil, err
×
2566
                }
×
2567

2568
                return chanEdges, nil
23✔
2569
        }
2570

UNCOV
2571
        err := fetchChanInfos(tx)
×
UNCOV
2572
        if err != nil {
×
2573
                return nil, err
×
2574
        }
×
2575

UNCOV
2576
        return chanEdges, nil
×
2577
}
2578

2579
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2580
        edge1, edge2 *models.ChannelEdgePolicy) error {
138✔
2581

138✔
2582
        // First, we'll fetch the edge update index bucket which currently
138✔
2583
        // stores an entry for the channel we're about to delete.
138✔
2584
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
138✔
2585
        if updateIndex == nil {
138✔
2586
                // No edges in bucket, return early.
×
2587
                return nil
×
2588
        }
×
2589

2590
        // Now that we have the bucket, we'll attempt to construct a template
2591
        // for the index key: updateTime || chanid.
2592
        var indexKey [8 + 8]byte
138✔
2593
        byteOrder.PutUint64(indexKey[8:], chanID)
138✔
2594

138✔
2595
        // With the template constructed, we'll attempt to delete an entry that
138✔
2596
        // would have been created by both edges: we'll alternate the update
138✔
2597
        // times, as one may had overridden the other.
138✔
2598
        if edge1 != nil {
151✔
2599
                byteOrder.PutUint64(
13✔
2600
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
13✔
2601
                )
13✔
2602
                if err := updateIndex.Delete(indexKey[:]); err != nil {
13✔
2603
                        return err
×
2604
                }
×
2605
        }
2606

2607
        // We'll also attempt to delete the entry that may have been created by
2608
        // the second edge.
2609
        if edge2 != nil {
153✔
2610
                byteOrder.PutUint64(
15✔
2611
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
15✔
2612
                )
15✔
2613
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
2614
                        return err
×
2615
                }
×
2616
        }
2617

2618
        return nil
138✔
2619
}
2620

2621
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2622
// cache. It then goes on to delete any policy info and edge info for this
2623
// channel from the DB and finally, if isZombie is true, it will add an entry
2624
// for this channel in the zombie index.
2625
//
2626
// NOTE: this method MUST only be called if the cacheMu has already been
2627
// acquired.
2628
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2629
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2630
        strictZombie bool) error {
201✔
2631

201✔
2632
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
201✔
2633
        if err != nil {
264✔
2634
                return err
63✔
2635
        }
63✔
2636

2637
        if c.graphCache != nil {
276✔
2638
                c.graphCache.RemoveChannel(
138✔
2639
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
138✔
2640
                        edgeInfo.ChannelID,
138✔
2641
                )
138✔
2642
        }
138✔
2643

2644
        // We'll also remove the entry in the edge update index bucket before
2645
        // we delete the edges themselves so we can access their last update
2646
        // times.
2647
        cid := byteOrder.Uint64(chanID)
138✔
2648
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
138✔
2649
        if err != nil {
138✔
2650
                return err
×
2651
        }
×
2652
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
138✔
2653
        if err != nil {
138✔
2654
                return err
×
2655
        }
×
2656

2657
        // The edge key is of the format pubKey || chanID. First we construct
2658
        // the latter half, populating the channel ID.
2659
        var edgeKey [33 + 8]byte
138✔
2660
        copy(edgeKey[33:], chanID)
138✔
2661

138✔
2662
        // With the latter half constructed, copy over the first public key to
138✔
2663
        // delete the edge in this direction, then the second to delete the
138✔
2664
        // edge in the opposite direction.
138✔
2665
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
138✔
2666
        if edges.Get(edgeKey[:]) != nil {
276✔
2667
                if err := edges.Delete(edgeKey[:]); err != nil {
138✔
2668
                        return err
×
2669
                }
×
2670
        }
2671
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
138✔
2672
        if edges.Get(edgeKey[:]) != nil {
276✔
2673
                if err := edges.Delete(edgeKey[:]); err != nil {
138✔
2674
                        return err
×
2675
                }
×
2676
        }
2677

2678
        // As part of deleting the edge we also remove all disabled entries
2679
        // from the edgePolicyDisabledIndex bucket. We do that for both
2680
        // directions.
2681
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
138✔
2682
        if err != nil {
138✔
2683
                return err
×
2684
        }
×
2685
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
138✔
2686
        if err != nil {
138✔
2687
                return err
×
2688
        }
×
2689

2690
        // With the edge data deleted, we can purge the information from the two
2691
        // edge indexes.
2692
        if err := edgeIndex.Delete(chanID); err != nil {
138✔
2693
                return err
×
2694
        }
×
2695
        var b bytes.Buffer
138✔
2696
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
138✔
2697
                return err
×
2698
        }
×
2699
        if err := chanIndex.Delete(b.Bytes()); err != nil {
138✔
2700
                return err
×
2701
        }
×
2702

2703
        // Finally, we'll mark the edge as a zombie within our index if it's
2704
        // being removed due to the channel becoming a zombie. We do this to
2705
        // ensure we don't store unnecessary data for spent channels.
2706
        if !isZombie {
254✔
2707
                return nil
116✔
2708
        }
116✔
2709

2710
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
25✔
2711
        if strictZombie {
28✔
2712
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2713
        }
3✔
2714

2715
        return markEdgeZombie(
25✔
2716
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
25✔
2717
        )
25✔
2718
}
2719

2720
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2721
// particular pair of channel policies. The return values are one of:
2722
//  1. (pubkey1, pubkey2)
2723
//  2. (pubkey1, blank)
2724
//  3. (blank, pubkey2)
2725
//
2726
// A blank pubkey means that corresponding node will be unable to resurrect a
2727
// channel on its own. For example, node1 may continue to publish recent
2728
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2729
// we don't want another fresh update from node1 to resurrect, as the edge can
2730
// only become live once node2 finally sends something recent.
2731
//
2732
// In the case where we have neither update, we allow either party to resurrect
2733
// the channel. If the channel were to be marked zombie again, it would be
2734
// marked with the correct lagging channel since we received an update from only
2735
// one side.
2736
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2737
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
3✔
2738

3✔
2739
        switch {
3✔
2740
        // If we don't have either edge policy, we'll return both pubkeys so
2741
        // that the channel can be resurrected by either party.
2742
        case e1 == nil && e2 == nil:
×
2743
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2744

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

2752
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2753
        // return a blank pubkey for edge1. In this case, only an update from
2754
        // edge2 can resurect the channel.
2755
        default:
2✔
2756
                return [33]byte{}, info.NodeKey2Bytes
2✔
2757
        }
2758
}
2759

2760
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2761
// within the database for the referenced channel. The `flags` attribute within
2762
// the ChannelEdgePolicy determines which of the directed edges are being
2763
// updated. If the flag is 1, then the first node's information is being
2764
// updated, otherwise it's the second node's information. The node ordering is
2765
// determined by the lexicographical ordering of the identity public keys of the
2766
// nodes on either side of the channel.
2767
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2768
        op ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
2,666✔
2769

2,666✔
2770
        var (
2,666✔
2771
                isUpdate1    bool
2,666✔
2772
                edgeNotFound bool
2,666✔
2773
                from, to     route.Vertex
2,666✔
2774
        )
2,666✔
2775

2,666✔
2776
        r := &batch.Request{
2,666✔
2777
                Reset: func() {
5,332✔
2778
                        isUpdate1 = false
2,666✔
2779
                        edgeNotFound = false
2,666✔
2780
                },
2,666✔
2781
                Update: func(tx kvdb.RwTx) error {
2,666✔
2782
                        var err error
2,666✔
2783
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
2,666✔
2784
                        if err != nil {
2,669✔
2785
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
3✔
2786
                        }
3✔
2787

2788
                        // Silence ErrEdgeNotFound so that the batch can
2789
                        // succeed, but propagate the error via local state.
2790
                        if errors.Is(err, ErrEdgeNotFound) {
2,669✔
2791
                                edgeNotFound = true
3✔
2792
                                return nil
3✔
2793
                        }
3✔
2794

2795
                        return err
2,663✔
2796
                },
2797
                OnCommit: func(err error) error {
2,666✔
2798
                        switch {
2,666✔
2799
                        case err != nil:
×
2800
                                return err
×
2801
                        case edgeNotFound:
3✔
2802
                                return ErrEdgeNotFound
3✔
2803
                        default:
2,663✔
2804
                                c.updateEdgeCache(edge, isUpdate1)
2,663✔
2805
                                return nil
2,663✔
2806
                        }
2807
                },
2808
        }
2809

2810
        for _, f := range op {
2,669✔
2811
                f(r)
3✔
2812
        }
3✔
2813

2814
        err := c.chanScheduler.Execute(r)
2,666✔
2815

2,666✔
2816
        return from, to, err
2,666✔
2817
}
2818

2819
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2820
        isUpdate1 bool) {
2,663✔
2821

2,663✔
2822
        // If an entry for this channel is found in reject cache, we'll modify
2,663✔
2823
        // the entry with the updated timestamp for the direction that was just
2,663✔
2824
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,663✔
2825
        // during the next query for this edge.
2,663✔
2826
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,671✔
2827
                if isUpdate1 {
14✔
2828
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2829
                } else {
11✔
2830
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2831
                }
5✔
2832
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2833
        }
2834

2835
        // If an entry for this channel is found in channel cache, we'll modify
2836
        // the entry with the updated policy for the direction that was just
2837
        // written. If the edge doesn't exist, we'll defer loading the info and
2838
        // policies and lazily read from disk during the next query.
2839
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,666✔
2840
                if isUpdate1 {
6✔
2841
                        channel.Policy1 = e
3✔
2842
                } else {
6✔
2843
                        channel.Policy2 = e
3✔
2844
                }
3✔
2845
                c.chanCache.insert(e.ChannelID, channel)
3✔
2846
        }
2847
}
2848

2849
// updateEdgePolicy attempts to update an edge's policy within the relevant
2850
// buckets using an existing database transaction. The returned boolean will be
2851
// true if the updated policy belongs to node1, and false if the policy belonged
2852
// to node2.
2853
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2854
        route.Vertex, route.Vertex, bool, error) {
2,666✔
2855

2,666✔
2856
        var noVertex route.Vertex
2,666✔
2857

2,666✔
2858
        edges := tx.ReadWriteBucket(edgeBucket)
2,666✔
2859
        if edges == nil {
2,666✔
NEW
2860
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2861
        }
×
2862
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,666✔
2863
        if edgeIndex == nil {
2,666✔
NEW
2864
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2865
        }
×
2866

2867
        // Create the channelID key be converting the channel ID
2868
        // integer into a byte slice.
2869
        var chanID [8]byte
2,666✔
2870
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,666✔
2871

2,666✔
2872
        // With the channel ID, we then fetch the value storing the two
2,666✔
2873
        // nodes which connect this channel edge.
2,666✔
2874
        nodeInfo := edgeIndex.Get(chanID[:])
2,666✔
2875
        if nodeInfo == nil {
2,669✔
2876
                return noVertex, noVertex, false, ErrEdgeNotFound
3✔
2877
        }
3✔
2878

2879
        // Depending on the flags value passed above, either the first
2880
        // or second edge policy is being updated.
2881
        var fromNode, toNode []byte
2,663✔
2882
        var isUpdate1 bool
2,663✔
2883
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,998✔
2884
                fromNode = nodeInfo[:33]
1,335✔
2885
                toNode = nodeInfo[33:66]
1,335✔
2886
                isUpdate1 = true
1,335✔
2887
        } else {
2,666✔
2888
                fromNode = nodeInfo[33:66]
1,331✔
2889
                toNode = nodeInfo[:33]
1,331✔
2890
                isUpdate1 = false
1,331✔
2891
        }
1,331✔
2892

2893
        // Finally, with the direction of the edge being updated
2894
        // identified, we update the on-disk edge representation.
2895
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,663✔
2896
        if err != nil {
2,663✔
NEW
2897
                return noVertex, noVertex, false, err
×
2898
        }
×
2899

2900
        var (
2,663✔
2901
                fromNodePubKey route.Vertex
2,663✔
2902
                toNodePubKey   route.Vertex
2,663✔
2903
        )
2,663✔
2904
        copy(fromNodePubKey[:], fromNode)
2,663✔
2905
        copy(toNodePubKey[:], toNode)
2,663✔
2906

2,663✔
2907
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
2,663✔
2908
}
2909

2910
// isPublic determines whether the node is seen as public within the graph from
2911
// the source node's point of view. An existing database transaction can also be
2912
// specified.
2913
func (c *KVStore) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2914
        sourcePubKey []byte) (bool, error) {
16✔
2915

16✔
2916
        // In order to determine whether this node is publicly advertised within
16✔
2917
        // the graph, we'll need to look at all of its edges and check whether
16✔
2918
        // they extend to any other node than the source node. errDone will be
16✔
2919
        // used to terminate the check early.
16✔
2920
        nodeIsPublic := false
16✔
2921
        errDone := errors.New("done")
16✔
2922
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
16✔
2923
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
16✔
2924
                _ *models.ChannelEdgePolicy) error {
29✔
2925

13✔
2926
                // If this edge doesn't extend to the source node, we'll
13✔
2927
                // terminate our search as we can now conclude that the node is
13✔
2928
                // publicly advertised within the graph due to the local node
13✔
2929
                // knowing of the current edge.
13✔
2930
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
2931
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
2932

6✔
2933
                        nodeIsPublic = true
6✔
2934
                        return errDone
6✔
2935
                }
6✔
2936

2937
                // Since the edge _does_ extend to the source node, we'll also
2938
                // need to ensure that this is a public edge.
2939
                if info.AuthProof != nil {
19✔
2940
                        nodeIsPublic = true
9✔
2941
                        return errDone
9✔
2942
                }
9✔
2943

2944
                // Otherwise, we'll continue our search.
2945
                return nil
4✔
2946
        })
2947
        if err != nil && !errors.Is(err, errDone) {
16✔
2948
                return false, err
×
2949
        }
×
2950

2951
        return nodeIsPublic, nil
16✔
2952
}
2953

2954
// FetchLightningNodeTx attempts to look up a target node by its identity
2955
// public key. If the node isn't found in the database, then
2956
// ErrGraphNodeNotFound is returned. An optional transaction may be provided.
2957
// If none is provided, then a new one will be created.
2958
func (c *KVStore) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
2959
        *models.LightningNode, error) {
3,443✔
2960

3,443✔
2961
        return c.fetchLightningNode(tx, nodePub)
3,443✔
2962
}
3,443✔
2963

2964
// FetchLightningNode attempts to look up a target node by its identity public
2965
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2966
// returned.
2967
func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
2968
        *models.LightningNode, error) {
155✔
2969

155✔
2970
        return c.fetchLightningNode(nil, nodePub)
155✔
2971
}
155✔
2972

2973
// fetchLightningNode attempts to look up a target node by its identity public
2974
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2975
// returned. An optional transaction may be provided. If none is provided, then
2976
// a new one will be created.
2977
func (c *KVStore) fetchLightningNode(tx kvdb.RTx,
2978
        nodePub route.Vertex) (*models.LightningNode, error) {
3,595✔
2979

3,595✔
2980
        var node *models.LightningNode
3,595✔
2981
        fetch := func(tx kvdb.RTx) error {
7,190✔
2982
                // First grab the nodes bucket which stores the mapping from
3,595✔
2983
                // pubKey to node information.
3,595✔
2984
                nodes := tx.ReadBucket(nodeBucket)
3,595✔
2985
                if nodes == nil {
3,595✔
2986
                        return ErrGraphNotFound
×
2987
                }
×
2988

2989
                // If a key for this serialized public key isn't found, then
2990
                // the target node doesn't exist within the database.
2991
                nodeBytes := nodes.Get(nodePub[:])
3,595✔
2992
                if nodeBytes == nil {
3,612✔
2993
                        return ErrGraphNodeNotFound
17✔
2994
                }
17✔
2995

2996
                // If the node is found, then we can de deserialize the node
2997
                // information to return to the user.
2998
                nodeReader := bytes.NewReader(nodeBytes)
3,581✔
2999
                n, err := deserializeLightningNode(nodeReader)
3,581✔
3000
                if err != nil {
3,581✔
3001
                        return err
×
3002
                }
×
3003

3004
                node = &n
3,581✔
3005

3,581✔
3006
                return nil
3,581✔
3007
        }
3008

3009
        if tx == nil {
3,753✔
3010
                err := kvdb.View(
158✔
3011
                        c.db, fetch, func() {
316✔
3012
                                node = nil
158✔
3013
                        },
158✔
3014
                )
3015
                if err != nil {
164✔
3016
                        return nil, err
6✔
3017
                }
6✔
3018

3019
                return node, nil
155✔
3020
        }
3021

3022
        err := fetch(tx)
3,437✔
3023
        if err != nil {
3,448✔
3024
                return nil, err
11✔
3025
        }
11✔
3026

3027
        return node, nil
3,426✔
3028
}
3029

3030
// HasLightningNode determines if the graph has a vertex identified by the
3031
// target node identity public key. If the node exists in the database, a
3032
// timestamp of when the data for the node was lasted updated is returned along
3033
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3034
// boolean.
3035
func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3036
        error) {
19✔
3037

19✔
3038
        var (
19✔
3039
                updateTime time.Time
19✔
3040
                exists     bool
19✔
3041
        )
19✔
3042

19✔
3043
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
38✔
3044
                // First grab the nodes bucket which stores the mapping from
19✔
3045
                // pubKey to node information.
19✔
3046
                nodes := tx.ReadBucket(nodeBucket)
19✔
3047
                if nodes == nil {
19✔
3048
                        return ErrGraphNotFound
×
3049
                }
×
3050

3051
                // If a key for this serialized public key isn't found, we can
3052
                // exit early.
3053
                nodeBytes := nodes.Get(nodePub[:])
19✔
3054
                if nodeBytes == nil {
25✔
3055
                        exists = false
6✔
3056
                        return nil
6✔
3057
                }
6✔
3058

3059
                // Otherwise we continue on to obtain the time stamp
3060
                // representing the last time the data for this node was
3061
                // updated.
3062
                nodeReader := bytes.NewReader(nodeBytes)
16✔
3063
                node, err := deserializeLightningNode(nodeReader)
16✔
3064
                if err != nil {
16✔
3065
                        return err
×
3066
                }
×
3067

3068
                exists = true
16✔
3069
                updateTime = node.LastUpdate
16✔
3070

16✔
3071
                return nil
16✔
3072
        }, func() {
19✔
3073
                updateTime = time.Time{}
19✔
3074
                exists = false
19✔
3075
        })
19✔
3076
        if err != nil {
19✔
3077
                return time.Time{}, exists, err
×
3078
        }
×
3079

3080
        return updateTime, exists, nil
19✔
3081
}
3082

3083
// nodeTraversal is used to traverse all channels of a node given by its
3084
// public key and passes channel information into the specified callback.
3085
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3086
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3087
                *models.ChannelEdgePolicy) error) error {
1,249✔
3088

1,249✔
3089
        traversal := func(tx kvdb.RTx) error {
2,498✔
3090
                edges := tx.ReadBucket(edgeBucket)
1,249✔
3091
                if edges == nil {
1,249✔
3092
                        return ErrGraphNotFound
×
3093
                }
×
3094
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,249✔
3095
                if edgeIndex == nil {
1,249✔
3096
                        return ErrGraphNoEdgesFound
×
3097
                }
×
3098

3099
                // In order to reach all the edges for this node, we take
3100
                // advantage of the construction of the key-space within the
3101
                // edge bucket. The keys are stored in the form: pubKey ||
3102
                // chanID. Therefore, starting from a chanID of zero, we can
3103
                // scan forward in the bucket, grabbing all the edges for the
3104
                // node. Once the prefix no longer matches, then we know we're
3105
                // done.
3106
                var nodeStart [33 + 8]byte
1,249✔
3107
                copy(nodeStart[:], nodePub)
1,249✔
3108
                copy(nodeStart[33:], chanStart[:])
1,249✔
3109

1,249✔
3110
                // Starting from the key pubKey || 0, we seek forward in the
1,249✔
3111
                // bucket until the retrieved key no longer has the public key
1,249✔
3112
                // as its prefix. This indicates that we've stepped over into
1,249✔
3113
                // another node's edges, so we can terminate our scan.
1,249✔
3114
                edgeCursor := edges.ReadCursor()
1,249✔
3115
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
4,902✔
3116
                        // If the prefix still matches, the channel id is
3,653✔
3117
                        // returned in nodeEdge. Channel id is used to lookup
3,653✔
3118
                        // the node at the other end of the channel and both
3,653✔
3119
                        // edge policies.
3,653✔
3120
                        chanID := nodeEdge[33:]
3,653✔
3121
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,653✔
3122
                        if err != nil {
3,653✔
3123
                                return err
×
3124
                        }
×
3125

3126
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,653✔
3127
                                edges, chanID, nodePub,
3,653✔
3128
                        )
3,653✔
3129
                        if err != nil {
3,653✔
3130
                                return err
×
3131
                        }
×
3132

3133
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,653✔
3134
                        if err != nil {
3,653✔
3135
                                return err
×
3136
                        }
×
3137

3138
                        incomingPolicy, err := fetchChanEdgePolicy(
3,653✔
3139
                                edges, chanID, otherNode[:],
3,653✔
3140
                        )
3,653✔
3141
                        if err != nil {
3,653✔
3142
                                return err
×
3143
                        }
×
3144

3145
                        // Finally, we execute the callback.
3146
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,653✔
3147
                        if err != nil {
3,665✔
3148
                                return err
12✔
3149
                        }
12✔
3150
                }
3151

3152
                return nil
1,240✔
3153
        }
3154

3155
        // If no transaction was provided, then we'll create a new transaction
3156
        // to execute the transaction within.
3157
        if tx == nil {
1,261✔
3158
                return kvdb.View(db, traversal, func() {})
24✔
3159
        }
3160

3161
        // Otherwise, we re-use the existing transaction to execute the graph
3162
        // traversal.
3163
        return traversal(tx)
1,240✔
3164
}
3165

3166
// ForEachNodeChannel iterates through all channels of the given node,
3167
// executing the passed callback with an edge info structure and the policies
3168
// of each end of the channel. The first edge policy is the outgoing edge *to*
3169
// the connecting node, while the second is the incoming edge *from* the
3170
// connecting node. If the callback returns an error, then the iteration is
3171
// halted with the error propagated back up to the caller.
3172
//
3173
// Unknown policies are passed into the callback as nil values.
3174
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3175
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3176
                *models.ChannelEdgePolicy) error) error {
9✔
3177

9✔
3178
        return nodeTraversal(nil, nodePub[:], c.db, cb)
9✔
3179
}
9✔
3180

3181
// ForEachNodeChannelTx iterates through all channels of the given node,
3182
// executing the passed callback with an edge info structure and the policies
3183
// of each end of the channel. The first edge policy is the outgoing edge *to*
3184
// the connecting node, while the second is the incoming edge *from* the
3185
// connecting node. If the callback returns an error, then the iteration is
3186
// halted with the error propagated back up to the caller.
3187
//
3188
// Unknown policies are passed into the callback as nil values.
3189
//
3190
// If the caller wishes to re-use an existing boltdb transaction, then it
3191
// should be passed as the first argument.  Otherwise, the first argument should
3192
// be nil and a fresh transaction will be created to execute the graph
3193
// traversal.
3194
func (c *KVStore) ForEachNodeChannelTx(tx kvdb.RTx,
3195
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3196
                *models.ChannelEdgePolicy,
3197
                *models.ChannelEdgePolicy) error) error {
1,001✔
3198

1,001✔
3199
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3200
}
1,001✔
3201

3202
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3203
// the target node in the channel. This is useful when one knows the pubkey of
3204
// one of the nodes, and wishes to obtain the full LightningNode for the other
3205
// end of the channel.
3206
func (c *KVStore) FetchOtherNode(tx kvdb.RTx,
3207
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3208
        *models.LightningNode, error) {
3✔
3209

3✔
3210
        // Ensure that the node passed in is actually a member of the channel.
3✔
3211
        var targetNodeBytes [33]byte
3✔
3212
        switch {
3✔
3213
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3214
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3215
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3216
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3217
        default:
×
3218
                return nil, fmt.Errorf("node not participating in this channel")
×
3219
        }
3220

3221
        var targetNode *models.LightningNode
3✔
3222
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3223
                // First grab the nodes bucket which stores the mapping from
3✔
3224
                // pubKey to node information.
3✔
3225
                nodes := tx.ReadBucket(nodeBucket)
3✔
3226
                if nodes == nil {
3✔
3227
                        return ErrGraphNotFound
×
3228
                }
×
3229

3230
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3231
                if err != nil {
3✔
3232
                        return err
×
3233
                }
×
3234

3235
                targetNode = &node
3✔
3236

3✔
3237
                return nil
3✔
3238
        }
3239

3240
        // If the transaction is nil, then we'll need to create a new one,
3241
        // otherwise we can use the existing db transaction.
3242
        var err error
3✔
3243
        if tx == nil {
3✔
3244
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3245
                        targetNode = nil
×
3246
                })
×
3247
        } else {
3✔
3248
                err = fetchNodeFunc(tx)
3✔
3249
        }
3✔
3250

3251
        return targetNode, err
3✔
3252
}
3253

3254
// computeEdgePolicyKeys is a helper function that can be used to compute the
3255
// keys used to index the channel edge policy info for the two nodes of the
3256
// edge. The keys for node 1 and node 2 are returned respectively.
3257
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
25✔
3258
        var (
25✔
3259
                node1Key [33 + 8]byte
25✔
3260
                node2Key [33 + 8]byte
25✔
3261
        )
25✔
3262

25✔
3263
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3264
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3265

25✔
3266
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3267
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3268

25✔
3269
        return node1Key[:], node2Key[:]
25✔
3270
}
25✔
3271

3272
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3273
// the channel identified by the funding outpoint. If the channel can't be
3274
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3275
// information for the channel itself is returned as well as two structs that
3276
// contain the routing policies for the channel in either direction.
3277
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3278
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3279
        *models.ChannelEdgePolicy, error) {
14✔
3280

14✔
3281
        var (
14✔
3282
                edgeInfo *models.ChannelEdgeInfo
14✔
3283
                policy1  *models.ChannelEdgePolicy
14✔
3284
                policy2  *models.ChannelEdgePolicy
14✔
3285
        )
14✔
3286

14✔
3287
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3288
                // First, grab the node bucket. This will be used to populate
14✔
3289
                // the Node pointers in each edge read from disk.
14✔
3290
                nodes := tx.ReadBucket(nodeBucket)
14✔
3291
                if nodes == nil {
14✔
3292
                        return ErrGraphNotFound
×
3293
                }
×
3294

3295
                // Next, grab the edge bucket which stores the edges, and also
3296
                // the index itself so we can group the directed edges together
3297
                // logically.
3298
                edges := tx.ReadBucket(edgeBucket)
14✔
3299
                if edges == nil {
14✔
3300
                        return ErrGraphNoEdgesFound
×
3301
                }
×
3302
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
3303
                if edgeIndex == nil {
14✔
3304
                        return ErrGraphNoEdgesFound
×
3305
                }
×
3306

3307
                // If the channel's outpoint doesn't exist within the outpoint
3308
                // index, then the edge does not exist.
3309
                chanIndex := edges.NestedReadBucket(channelPointBucket)
14✔
3310
                if chanIndex == nil {
14✔
3311
                        return ErrGraphNoEdgesFound
×
3312
                }
×
3313
                var b bytes.Buffer
14✔
3314
                if err := WriteOutpoint(&b, op); err != nil {
14✔
3315
                        return err
×
3316
                }
×
3317
                chanID := chanIndex.Get(b.Bytes())
14✔
3318
                if chanID == nil {
27✔
3319
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
13✔
3320
                }
13✔
3321

3322
                // If the channel is found to exists, then we'll first retrieve
3323
                // the general information for the channel.
3324
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
4✔
3325
                if err != nil {
4✔
3326
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3327
                }
×
3328
                edgeInfo = &edge
4✔
3329

4✔
3330
                // Once we have the information about the channels' parameters,
4✔
3331
                // we'll fetch the routing policies for each for the directed
4✔
3332
                // edges.
4✔
3333
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
4✔
3334
                if err != nil {
4✔
3335
                        return fmt.Errorf("failed to find policy: %w", err)
×
3336
                }
×
3337

3338
                policy1 = e1
4✔
3339
                policy2 = e2
4✔
3340

4✔
3341
                return nil
4✔
3342
        }, func() {
14✔
3343
                edgeInfo = nil
14✔
3344
                policy1 = nil
14✔
3345
                policy2 = nil
14✔
3346
        })
14✔
3347
        if err != nil {
27✔
3348
                return nil, nil, nil, err
13✔
3349
        }
13✔
3350

3351
        return edgeInfo, policy1, policy2, nil
4✔
3352
}
3353

3354
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3355
// channel identified by the channel ID. If the channel can't be found, then
3356
// ErrEdgeNotFound is returned. A struct which houses the general information
3357
// for the channel itself is returned as well as two structs that contain the
3358
// routing policies for the channel in either direction.
3359
//
3360
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3361
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3362
// the ChannelEdgeInfo will only include the public keys of each node.
3363
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3364
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3365
        *models.ChannelEdgePolicy, error) {
27✔
3366

27✔
3367
        var (
27✔
3368
                edgeInfo  *models.ChannelEdgeInfo
27✔
3369
                policy1   *models.ChannelEdgePolicy
27✔
3370
                policy2   *models.ChannelEdgePolicy
27✔
3371
                channelID [8]byte
27✔
3372
        )
27✔
3373

27✔
3374
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
54✔
3375
                // First, grab the node bucket. This will be used to populate
27✔
3376
                // the Node pointers in each edge read from disk.
27✔
3377
                nodes := tx.ReadBucket(nodeBucket)
27✔
3378
                if nodes == nil {
27✔
3379
                        return ErrGraphNotFound
×
3380
                }
×
3381

3382
                // Next, grab the edge bucket which stores the edges, and also
3383
                // the index itself so we can group the directed edges together
3384
                // logically.
3385
                edges := tx.ReadBucket(edgeBucket)
27✔
3386
                if edges == nil {
27✔
3387
                        return ErrGraphNoEdgesFound
×
3388
                }
×
3389
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
27✔
3390
                if edgeIndex == nil {
27✔
3391
                        return ErrGraphNoEdgesFound
×
3392
                }
×
3393

3394
                byteOrder.PutUint64(channelID[:], chanID)
27✔
3395

27✔
3396
                // Now, attempt to fetch edge.
27✔
3397
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
27✔
3398

27✔
3399
                // If it doesn't exist, we'll quickly check our zombie index to
27✔
3400
                // see if we've previously marked it as so.
27✔
3401
                if errors.Is(err, ErrEdgeNotFound) {
31✔
3402
                        // If the zombie index doesn't exist, or the edge is not
4✔
3403
                        // marked as a zombie within it, then we'll return the
4✔
3404
                        // original ErrEdgeNotFound error.
4✔
3405
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3406
                        if zombieIndex == nil {
4✔
3407
                                return ErrEdgeNotFound
×
3408
                        }
×
3409

3410
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3411
                                zombieIndex, chanID,
4✔
3412
                        )
4✔
3413
                        if !isZombie {
7✔
3414
                                return ErrEdgeNotFound
3✔
3415
                        }
3✔
3416

3417
                        // Otherwise, the edge is marked as a zombie, so we'll
3418
                        // populate the edge info with the public keys of each
3419
                        // party as this is the only information we have about
3420
                        // it and return an error signaling so.
3421
                        edgeInfo = &models.ChannelEdgeInfo{
4✔
3422
                                NodeKey1Bytes: pubKey1,
4✔
3423
                                NodeKey2Bytes: pubKey2,
4✔
3424
                        }
4✔
3425

4✔
3426
                        return ErrZombieEdge
4✔
3427
                }
3428

3429
                // Otherwise, we'll just return the error if any.
3430
                if err != nil {
26✔
3431
                        return err
×
3432
                }
×
3433

3434
                edgeInfo = &edge
26✔
3435

26✔
3436
                // Then we'll attempt to fetch the accompanying policies of this
26✔
3437
                // edge.
26✔
3438
                e1, e2, err := fetchChanEdgePolicies(
26✔
3439
                        edgeIndex, edges, channelID[:],
26✔
3440
                )
26✔
3441
                if err != nil {
26✔
3442
                        return err
×
3443
                }
×
3444

3445
                policy1 = e1
26✔
3446
                policy2 = e2
26✔
3447

26✔
3448
                return nil
26✔
3449
        }, func() {
27✔
3450
                edgeInfo = nil
27✔
3451
                policy1 = nil
27✔
3452
                policy2 = nil
27✔
3453
        })
27✔
3454
        if errors.Is(err, ErrZombieEdge) {
31✔
3455
                return edgeInfo, nil, nil, err
4✔
3456
        }
4✔
3457
        if err != nil {
29✔
3458
                return nil, nil, nil, err
3✔
3459
        }
3✔
3460

3461
        return edgeInfo, policy1, policy2, nil
26✔
3462
}
3463

3464
// IsPublicNode is a helper method that determines whether the node with the
3465
// given public key is seen as a public node in the graph from the graph's
3466
// source node's point of view.
3467
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
16✔
3468
        var nodeIsPublic bool
16✔
3469
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
32✔
3470
                nodes := tx.ReadBucket(nodeBucket)
16✔
3471
                if nodes == nil {
16✔
3472
                        return ErrGraphNodesNotFound
×
3473
                }
×
3474
                ourPubKey := nodes.Get(sourceKey)
16✔
3475
                if ourPubKey == nil {
16✔
3476
                        return ErrSourceNodeNotSet
×
3477
                }
×
3478
                node, err := fetchLightningNode(nodes, pubKey[:])
16✔
3479
                if err != nil {
16✔
3480
                        return err
×
3481
                }
×
3482

3483
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3484

16✔
3485
                return err
16✔
3486
        }, func() {
16✔
3487
                nodeIsPublic = false
16✔
3488
        })
16✔
3489
        if err != nil {
16✔
3490
                return false, err
×
3491
        }
×
3492

3493
        return nodeIsPublic, nil
16✔
3494
}
3495

3496
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3497
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
49✔
3498
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
49✔
3499
        if err != nil {
49✔
3500
                return nil, err
×
3501
        }
×
3502

3503
        // With the witness script generated, we'll now turn it into a p2wsh
3504
        // script:
3505
        //  * OP_0 <sha256(script)>
3506
        bldr := txscript.NewScriptBuilder(
49✔
3507
                txscript.WithScriptAllocSize(input.P2WSHSize),
49✔
3508
        )
49✔
3509
        bldr.AddOp(txscript.OP_0)
49✔
3510
        scriptHash := sha256.Sum256(witnessScript)
49✔
3511
        bldr.AddData(scriptHash[:])
49✔
3512

49✔
3513
        return bldr.Script()
49✔
3514
}
3515

3516
// EdgePoint couples the outpoint of a channel with the funding script that it
3517
// creates. The FilteredChainView will use this to watch for spends of this
3518
// edge point on chain. We require both of these values as depending on the
3519
// concrete implementation, either the pkScript, or the out point will be used.
3520
type EdgePoint struct {
3521
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3522
        FundingPkScript []byte
3523

3524
        // OutPoint is the outpoint of the target channel.
3525
        OutPoint wire.OutPoint
3526
}
3527

3528
// String returns a human readable version of the target EdgePoint. We return
3529
// the outpoint directly as it is enough to uniquely identify the edge point.
3530
func (e *EdgePoint) String() string {
×
3531
        return e.OutPoint.String()
×
3532
}
×
3533

3534
// ChannelView returns the verifiable edge information for each active channel
3535
// within the known channel graph. The set of UTXO's (along with their scripts)
3536
// returned are the ones that need to be watched on chain to detect channel
3537
// closes on the resident blockchain.
3538
func (c *KVStore) ChannelView() ([]EdgePoint, error) {
25✔
3539
        var edgePoints []EdgePoint
25✔
3540
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
50✔
3541
                // We're going to iterate over the entire channel index, so
25✔
3542
                // we'll need to fetch the edgeBucket to get to the index as
25✔
3543
                // it's a sub-bucket.
25✔
3544
                edges := tx.ReadBucket(edgeBucket)
25✔
3545
                if edges == nil {
25✔
3546
                        return ErrGraphNoEdgesFound
×
3547
                }
×
3548
                chanIndex := edges.NestedReadBucket(channelPointBucket)
25✔
3549
                if chanIndex == nil {
25✔
3550
                        return ErrGraphNoEdgesFound
×
3551
                }
×
3552
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
25✔
3553
                if edgeIndex == nil {
25✔
3554
                        return ErrGraphNoEdgesFound
×
3555
                }
×
3556

3557
                // Once we have the proper bucket, we'll range over each key
3558
                // (which is the channel point for the channel) and decode it,
3559
                // accumulating each entry.
3560
                return chanIndex.ForEach(
25✔
3561
                        func(chanPointBytes, chanID []byte) error {
70✔
3562
                                chanPointReader := bytes.NewReader(
45✔
3563
                                        chanPointBytes,
45✔
3564
                                )
45✔
3565

45✔
3566
                                var chanPoint wire.OutPoint
45✔
3567
                                err := ReadOutpoint(chanPointReader, &chanPoint)
45✔
3568
                                if err != nil {
45✔
3569
                                        return err
×
3570
                                }
×
3571

3572
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3573
                                        edgeIndex, chanID,
45✔
3574
                                )
45✔
3575
                                if err != nil {
45✔
3576
                                        return err
×
3577
                                }
×
3578

3579
                                pkScript, err := genMultiSigP2WSH(
45✔
3580
                                        edgeInfo.BitcoinKey1Bytes[:],
45✔
3581
                                        edgeInfo.BitcoinKey2Bytes[:],
45✔
3582
                                )
45✔
3583
                                if err != nil {
45✔
3584
                                        return err
×
3585
                                }
×
3586

3587
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3588
                                        FundingPkScript: pkScript,
45✔
3589
                                        OutPoint:        chanPoint,
45✔
3590
                                })
45✔
3591

45✔
3592
                                return nil
45✔
3593
                        },
3594
                )
3595
        }, func() {
25✔
3596
                edgePoints = nil
25✔
3597
        }); err != nil {
25✔
3598
                return nil, err
×
3599
        }
×
3600

3601
        return edgePoints, nil
25✔
3602
}
3603

3604
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3605
// zombie. This method is used on an ad-hoc basis, when channels need to be
3606
// marked as zombies outside the normal pruning cycle.
3607
func (c *KVStore) MarkEdgeZombie(chanID uint64,
3608
        pubKey1, pubKey2 [33]byte) error {
121✔
3609

121✔
3610
        c.cacheMu.Lock()
121✔
3611
        defer c.cacheMu.Unlock()
121✔
3612

121✔
3613
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
242✔
3614
                edges := tx.ReadWriteBucket(edgeBucket)
121✔
3615
                if edges == nil {
121✔
3616
                        return ErrGraphNoEdgesFound
×
3617
                }
×
3618
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
121✔
3619
                if err != nil {
121✔
3620
                        return fmt.Errorf("unable to create zombie "+
×
3621
                                "bucket: %w", err)
×
3622
                }
×
3623

3624
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
121✔
3625
        })
3626
        if err != nil {
121✔
3627
                return err
×
3628
        }
×
3629

3630
        c.rejectCache.remove(chanID)
121✔
3631
        c.chanCache.remove(chanID)
121✔
3632

121✔
3633
        return nil
121✔
3634
}
3635

3636
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3637
// keys should represent the node public keys of the two parties involved in the
3638
// edge.
3639
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3640
        pubKey2 [33]byte) error {
146✔
3641

146✔
3642
        var k [8]byte
146✔
3643
        byteOrder.PutUint64(k[:], chanID)
146✔
3644

146✔
3645
        var v [66]byte
146✔
3646
        copy(v[:33], pubKey1[:])
146✔
3647
        copy(v[33:], pubKey2[:])
146✔
3648

146✔
3649
        return zombieIndex.Put(k[:], v[:])
146✔
3650
}
146✔
3651

3652
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3653
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
18✔
3654
        c.cacheMu.Lock()
18✔
3655
        defer c.cacheMu.Unlock()
18✔
3656

18✔
3657
        return c.markEdgeLiveUnsafe(nil, chanID)
18✔
3658
}
18✔
3659

3660
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3661
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3662
// case a new transaction will be created.
3663
//
3664
// NOTE: this method MUST only be called if the cacheMu has already been
3665
// acquired.
3666
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
18✔
3667
        dbFn := func(tx kvdb.RwTx) error {
36✔
3668
                edges := tx.ReadWriteBucket(edgeBucket)
18✔
3669
                if edges == nil {
18✔
3670
                        return ErrGraphNoEdgesFound
×
3671
                }
×
3672
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
18✔
3673
                if zombieIndex == nil {
18✔
3674
                        return nil
×
3675
                }
×
3676

3677
                var k [8]byte
18✔
3678
                byteOrder.PutUint64(k[:], chanID)
18✔
3679

18✔
3680
                if len(zombieIndex.Get(k[:])) == 0 {
19✔
3681
                        return ErrZombieEdgeNotFound
1✔
3682
                }
1✔
3683

3684
                return zombieIndex.Delete(k[:])
17✔
3685
        }
3686

3687
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3688
        // the existing transaction
3689
        var err error
18✔
3690
        if tx == nil {
36✔
3691
                err = kvdb.Update(c.db, dbFn, func() {})
36✔
UNCOV
3692
        } else {
×
UNCOV
3693
                err = dbFn(tx)
×
UNCOV
3694
        }
×
3695
        if err != nil {
19✔
3696
                return err
1✔
3697
        }
1✔
3698

3699
        c.rejectCache.remove(chanID)
17✔
3700
        c.chanCache.remove(chanID)
17✔
3701

17✔
3702
        // We need to add the channel back into our graph cache, otherwise we
17✔
3703
        // won't use it for path finding.
17✔
3704
        if c.graphCache != nil {
34✔
3705
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
17✔
3706
                if err != nil {
17✔
3707
                        return err
×
3708
                }
×
3709

3710
                for _, edgeInfo := range edgeInfos {
17✔
3711
                        c.graphCache.AddChannel(
×
3712
                                edgeInfo.Info, edgeInfo.Policy1,
×
3713
                                edgeInfo.Policy2,
×
3714
                        )
×
3715
                }
×
3716
        }
3717

3718
        return nil
17✔
3719
}
3720

3721
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3722
// zombie, then the two node public keys corresponding to this edge are also
3723
// returned.
3724
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
14✔
3725
        var (
14✔
3726
                isZombie         bool
14✔
3727
                pubKey1, pubKey2 [33]byte
14✔
3728
        )
14✔
3729

14✔
3730
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3731
                edges := tx.ReadBucket(edgeBucket)
14✔
3732
                if edges == nil {
14✔
3733
                        return ErrGraphNoEdgesFound
×
3734
                }
×
3735
                zombieIndex := edges.NestedReadBucket(zombieBucket)
14✔
3736
                if zombieIndex == nil {
14✔
3737
                        return nil
×
3738
                }
×
3739

3740
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
14✔
3741

14✔
3742
                return nil
14✔
3743
        }, func() {
14✔
3744
                isZombie = false
14✔
3745
                pubKey1 = [33]byte{}
14✔
3746
                pubKey2 = [33]byte{}
14✔
3747
        })
14✔
3748
        if err != nil {
14✔
3749
                return false, [33]byte{}, [33]byte{}
×
3750
        }
×
3751

3752
        return isZombie, pubKey1, pubKey2
14✔
3753
}
3754

3755
// isZombieEdge returns whether an entry exists for the given channel in the
3756
// zombie index. If an entry exists, then the two node public keys corresponding
3757
// to this edge are also returned.
3758
func isZombieEdge(zombieIndex kvdb.RBucket,
3759
        chanID uint64) (bool, [33]byte, [33]byte) {
202✔
3760

202✔
3761
        var k [8]byte
202✔
3762
        byteOrder.PutUint64(k[:], chanID)
202✔
3763

202✔
3764
        v := zombieIndex.Get(k[:])
202✔
3765
        if v == nil {
315✔
3766
                return false, [33]byte{}, [33]byte{}
113✔
3767
        }
113✔
3768

3769
        var pubKey1, pubKey2 [33]byte
92✔
3770
        copy(pubKey1[:], v[:33])
92✔
3771
        copy(pubKey2[:], v[33:])
92✔
3772

92✔
3773
        return true, pubKey1, pubKey2
92✔
3774
}
3775

3776
// NumZombies returns the current number of zombie channels in the graph.
3777
func (c *KVStore) NumZombies() (uint64, error) {
4✔
3778
        var numZombies uint64
4✔
3779
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3780
                edges := tx.ReadBucket(edgeBucket)
4✔
3781
                if edges == nil {
4✔
3782
                        return nil
×
3783
                }
×
3784
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3785
                if zombieIndex == nil {
4✔
3786
                        return nil
×
3787
                }
×
3788

3789
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3790
                        numZombies++
2✔
3791
                        return nil
2✔
3792
                })
2✔
3793
        }, func() {
4✔
3794
                numZombies = 0
4✔
3795
        })
4✔
3796
        if err != nil {
4✔
3797
                return 0, err
×
3798
        }
×
3799

3800
        return numZombies, nil
4✔
3801
}
3802

3803
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3804
// that we can ignore channel announcements that we know to be closed without
3805
// having to validate them and fetch a block.
3806
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3807
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3808
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3809
                if err != nil {
1✔
3810
                        return err
×
3811
                }
×
3812

3813
                var k [8]byte
1✔
3814
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3815

1✔
3816
                return closedScids.Put(k[:], []byte{})
1✔
3817
        }, func() {})
1✔
3818
}
3819

3820
// IsClosedScid checks whether a channel identified by the passed in scid is
3821
// closed. This helps avoid having to perform expensive validation checks.
3822
// TODO: Add an LRU cache to cut down on disc reads.
3823
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
5✔
3824
        var isClosed bool
5✔
3825
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3826
                closedScids := tx.ReadBucket(closedScidBucket)
5✔
3827
                if closedScids == nil {
5✔
3828
                        return ErrClosedScidsNotFound
×
3829
                }
×
3830

3831
                var k [8]byte
5✔
3832
                byteOrder.PutUint64(k[:], scid.ToUint64())
5✔
3833

5✔
3834
                if closedScids.Get(k[:]) != nil {
6✔
3835
                        isClosed = true
1✔
3836
                        return nil
1✔
3837
                }
1✔
3838

3839
                return nil
4✔
3840
        }, func() {
5✔
3841
                isClosed = false
5✔
3842
        })
5✔
3843
        if err != nil {
5✔
3844
                return false, err
×
3845
        }
×
3846

3847
        return isClosed, nil
5✔
3848
}
3849

3850
// GraphSession will provide the call-back with access to a NodeTraverser
3851
// instance which can be used to perform queries against the channel graph. If
3852
// the graph cache is not enabled, then the call-back will  be provided with
3853
// access to the graph via a consistent read-only transaction.
3854
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
136✔
3855
        if c.graphCache != nil {
218✔
3856
                return cb(&nodeTraverserSession{db: c})
82✔
3857
        }
82✔
3858

3859
        return c.db.View(func(tx walletdb.ReadTx) error {
108✔
3860
                return cb(&nodeTraverserSession{
54✔
3861
                        db: c,
54✔
3862
                        tx: tx,
54✔
3863
                })
54✔
3864
        }, func() {})
108✔
3865
}
3866

3867
// nodeTraverserSession implements the NodeTraverser interface but with a
3868
// backing read only transaction for a consistent view of the graph in the case
3869
// where the graph Cache has not been enabled.
3870
type nodeTraverserSession struct {
3871
        tx kvdb.RTx
3872
        db *KVStore
3873
}
3874

3875
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3876
// node.
3877
//
3878
// NOTE: Part of the NodeTraverser interface.
3879
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3880
        cb func(channel *DirectedChannel) error) error {
592✔
3881

592✔
3882
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
592✔
3883
}
592✔
3884

3885
// FetchNodeFeatures returns the features of the given node. If the node is
3886
// unknown, assume no additional features are supported.
3887
//
3888
// NOTE: Part of the NodeTraverser interface.
3889
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
3890
        *lnwire.FeatureVector, error) {
623✔
3891

623✔
3892
        return c.db.fetchNodeFeatures(c.tx, nodePub)
623✔
3893
}
623✔
3894

3895
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3896
        node *models.LightningNode) error {
999✔
3897

999✔
3898
        var (
999✔
3899
                scratch [16]byte
999✔
3900
                b       bytes.Buffer
999✔
3901
        )
999✔
3902

999✔
3903
        pub, err := node.PubKey()
999✔
3904
        if err != nil {
999✔
3905
                return err
×
3906
        }
×
3907
        nodePub := pub.SerializeCompressed()
999✔
3908

999✔
3909
        // If the node has the update time set, write it, else write 0.
999✔
3910
        updateUnix := uint64(0)
999✔
3911
        if node.LastUpdate.Unix() > 0 {
1,865✔
3912
                updateUnix = uint64(node.LastUpdate.Unix())
866✔
3913
        }
866✔
3914

3915
        byteOrder.PutUint64(scratch[:8], updateUnix)
999✔
3916
        if _, err := b.Write(scratch[:8]); err != nil {
999✔
3917
                return err
×
3918
        }
×
3919

3920
        if _, err := b.Write(nodePub); err != nil {
999✔
3921
                return err
×
3922
        }
×
3923

3924
        // If we got a node announcement for this node, we will have the rest
3925
        // of the data available. If not we don't have more data to write.
3926
        if !node.HaveNodeAnnouncement {
1,082✔
3927
                // Write HaveNodeAnnouncement=0.
83✔
3928
                byteOrder.PutUint16(scratch[:2], 0)
83✔
3929
                if _, err := b.Write(scratch[:2]); err != nil {
83✔
3930
                        return err
×
3931
                }
×
3932

3933
                return nodeBucket.Put(nodePub, b.Bytes())
83✔
3934
        }
3935

3936
        // Write HaveNodeAnnouncement=1.
3937
        byteOrder.PutUint16(scratch[:2], 1)
919✔
3938
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
3939
                return err
×
3940
        }
×
3941

3942
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
919✔
3943
                return err
×
3944
        }
×
3945
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
919✔
3946
                return err
×
3947
        }
×
3948
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
919✔
3949
                return err
×
3950
        }
×
3951

3952
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
919✔
3953
                return err
×
3954
        }
×
3955

3956
        if err := node.Features.Encode(&b); err != nil {
919✔
3957
                return err
×
3958
        }
×
3959

3960
        numAddresses := uint16(len(node.Addresses))
919✔
3961
        byteOrder.PutUint16(scratch[:2], numAddresses)
919✔
3962
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
3963
                return err
×
3964
        }
×
3965

3966
        for _, address := range node.Addresses {
2,066✔
3967
                if err := SerializeAddr(&b, address); err != nil {
1,147✔
3968
                        return err
×
3969
                }
×
3970
        }
3971

3972
        sigLen := len(node.AuthSigBytes)
919✔
3973
        if sigLen > 80 {
919✔
3974
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
3975
                        sigLen)
×
3976
        }
×
3977

3978
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
919✔
3979
        if err != nil {
919✔
3980
                return err
×
3981
        }
×
3982

3983
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
919✔
3984
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
3985
        }
×
3986
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
919✔
3987
        if err != nil {
919✔
3988
                return err
×
3989
        }
×
3990

3991
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
919✔
3992
                return err
×
3993
        }
×
3994

3995
        // With the alias bucket updated, we'll now update the index that
3996
        // tracks the time series of node updates.
3997
        var indexKey [8 + 33]byte
919✔
3998
        byteOrder.PutUint64(indexKey[:8], updateUnix)
919✔
3999
        copy(indexKey[8:], nodePub)
919✔
4000

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

107✔
4008
                var oldIndexKey [8 + 33]byte
107✔
4009
                copy(oldIndexKey[:8], oldUpdateTime)
107✔
4010
                copy(oldIndexKey[8:], nodePub)
107✔
4011

107✔
4012
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
107✔
4013
                        return err
×
4014
                }
×
4015
        }
4016

4017
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
919✔
4018
                return err
×
4019
        }
×
4020

4021
        return nodeBucket.Put(nodePub, b.Bytes())
919✔
4022
}
4023

4024
func fetchLightningNode(nodeBucket kvdb.RBucket,
4025
        nodePub []byte) (models.LightningNode, error) {
3,609✔
4026

3,609✔
4027
        nodeBytes := nodeBucket.Get(nodePub)
3,609✔
4028
        if nodeBytes == nil {
3,691✔
4029
                return models.LightningNode{}, ErrGraphNodeNotFound
82✔
4030
        }
82✔
4031

4032
        nodeReader := bytes.NewReader(nodeBytes)
3,530✔
4033

3,530✔
4034
        return deserializeLightningNode(nodeReader)
3,530✔
4035
}
4036

4037
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4038
        *lnwire.FeatureVector, error) {
123✔
4039

123✔
4040
        var (
123✔
4041
                pubKey      route.Vertex
123✔
4042
                features    = lnwire.EmptyFeatureVector()
123✔
4043
                nodeScratch [8]byte
123✔
4044
        )
123✔
4045

123✔
4046
        // Skip ahead:
123✔
4047
        // - LastUpdate (8 bytes)
123✔
4048
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
4049
                return pubKey, nil, err
×
4050
        }
×
4051

4052
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
123✔
4053
                return pubKey, nil, err
×
4054
        }
×
4055

4056
        // Read the node announcement flag.
4057
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
4058
                return pubKey, nil, err
×
4059
        }
×
4060
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4061

123✔
4062
        // The rest of the data is optional, and will only be there if we got a
123✔
4063
        // node announcement for this node.
123✔
4064
        if hasNodeAnn == 0 {
126✔
4065
                return pubKey, features, nil
3✔
4066
        }
3✔
4067

4068
        // We did get a node announcement for this node, so we'll have the rest
4069
        // of the data available.
4070
        var rgb uint8
123✔
4071
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4072
                return pubKey, nil, err
×
4073
        }
×
4074
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4075
                return pubKey, nil, err
×
4076
        }
×
4077
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4078
                return pubKey, nil, err
×
4079
        }
×
4080

4081
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4082
                return pubKey, nil, err
×
4083
        }
×
4084

4085
        if err := features.Decode(r); err != nil {
123✔
4086
                return pubKey, nil, err
×
4087
        }
×
4088

4089
        return pubKey, features, nil
123✔
4090
}
4091

4092
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,279✔
4093
        var (
8,279✔
4094
                node    models.LightningNode
8,279✔
4095
                scratch [8]byte
8,279✔
4096
                err     error
8,279✔
4097
        )
8,279✔
4098

8,279✔
4099
        // Always populate a feature vector, even if we don't have a node
8,279✔
4100
        // announcement and short circuit below.
8,279✔
4101
        node.Features = lnwire.EmptyFeatureVector()
8,279✔
4102

8,279✔
4103
        if _, err := r.Read(scratch[:]); err != nil {
8,279✔
4104
                return models.LightningNode{}, err
×
4105
        }
×
4106

4107
        unix := int64(byteOrder.Uint64(scratch[:]))
8,279✔
4108
        node.LastUpdate = time.Unix(unix, 0)
8,279✔
4109

8,279✔
4110
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,279✔
4111
                return models.LightningNode{}, err
×
4112
        }
×
4113

4114
        if _, err := r.Read(scratch[:2]); err != nil {
8,279✔
4115
                return models.LightningNode{}, err
×
4116
        }
×
4117

4118
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,279✔
4119
        if hasNodeAnn == 1 {
16,422✔
4120
                node.HaveNodeAnnouncement = true
8,143✔
4121
        } else {
8,282✔
4122
                node.HaveNodeAnnouncement = false
139✔
4123
        }
139✔
4124

4125
        // The rest of the data is optional, and will only be there if we got a
4126
        // node announcement for this node.
4127
        if !node.HaveNodeAnnouncement {
8,418✔
4128
                return node, nil
139✔
4129
        }
139✔
4130

4131
        // We did get a node announcement for this node, so we'll have the rest
4132
        // of the data available.
4133
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,143✔
4134
                return models.LightningNode{}, err
×
4135
        }
×
4136
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,143✔
4137
                return models.LightningNode{}, err
×
4138
        }
×
4139
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,143✔
4140
                return models.LightningNode{}, err
×
4141
        }
×
4142

4143
        node.Alias, err = wire.ReadVarString(r, 0)
8,143✔
4144
        if err != nil {
8,143✔
4145
                return models.LightningNode{}, err
×
4146
        }
×
4147

4148
        err = node.Features.Decode(r)
8,143✔
4149
        if err != nil {
8,143✔
4150
                return models.LightningNode{}, err
×
4151
        }
×
4152

4153
        if _, err := r.Read(scratch[:2]); err != nil {
8,143✔
4154
                return models.LightningNode{}, err
×
4155
        }
×
4156
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,143✔
4157

8,143✔
4158
        var addresses []net.Addr
8,143✔
4159
        for i := 0; i < numAddresses; i++ {
18,295✔
4160
                address, err := DeserializeAddr(r)
10,152✔
4161
                if err != nil {
10,152✔
4162
                        return models.LightningNode{}, err
×
4163
                }
×
4164
                addresses = append(addresses, address)
10,152✔
4165
        }
4166
        node.Addresses = addresses
8,143✔
4167

8,143✔
4168
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,143✔
4169
        if err != nil {
8,143✔
4170
                return models.LightningNode{}, err
×
4171
        }
×
4172

4173
        // We'll try and see if there are any opaque bytes left, if not, then
4174
        // we'll ignore the EOF error and return the node as is.
4175
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,143✔
4176
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,143✔
4177
        )
8,143✔
4178
        switch {
8,143✔
4179
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4180
        case errors.Is(err, io.EOF):
×
4181
        case err != nil:
×
4182
                return models.LightningNode{}, err
×
4183
        }
4184

4185
        return node, nil
8,143✔
4186
}
4187

4188
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4189
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,481✔
4190

1,481✔
4191
        var b bytes.Buffer
1,481✔
4192

1,481✔
4193
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,481✔
4194
                return err
×
4195
        }
×
4196
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,481✔
4197
                return err
×
4198
        }
×
4199
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,481✔
4200
                return err
×
4201
        }
×
4202
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,481✔
4203
                return err
×
4204
        }
×
4205

4206
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,481✔
4207
                return err
×
4208
        }
×
4209

4210
        authProof := edgeInfo.AuthProof
1,481✔
4211
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,481✔
4212
        if authProof != nil {
2,879✔
4213
                nodeSig1 = authProof.NodeSig1Bytes
1,398✔
4214
                nodeSig2 = authProof.NodeSig2Bytes
1,398✔
4215
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,398✔
4216
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,398✔
4217
        }
1,398✔
4218

4219
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,481✔
4220
                return err
×
4221
        }
×
4222
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,481✔
4223
                return err
×
4224
        }
×
4225
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,481✔
4226
                return err
×
4227
        }
×
4228
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,481✔
4229
                return err
×
4230
        }
×
4231

4232
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,481✔
4233
                return err
×
4234
        }
×
4235
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,481✔
4236
        if err != nil {
1,481✔
4237
                return err
×
4238
        }
×
4239
        if _, err := b.Write(chanID[:]); err != nil {
1,481✔
4240
                return err
×
4241
        }
×
4242
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,481✔
4243
                return err
×
4244
        }
×
4245

4246
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,481✔
4247
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4248
        }
×
4249
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,481✔
4250
        if err != nil {
1,481✔
4251
                return err
×
4252
        }
×
4253

4254
        return edgeIndex.Put(chanID[:], b.Bytes())
1,481✔
4255
}
4256

4257
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4258
        chanID []byte) (models.ChannelEdgeInfo, error) {
3,985✔
4259

3,985✔
4260
        edgeInfoBytes := edgeIndex.Get(chanID)
3,985✔
4261
        if edgeInfoBytes == nil {
4,071✔
4262
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
86✔
4263
        }
86✔
4264

4265
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3,902✔
4266

3,902✔
4267
        return deserializeChanEdgeInfo(edgeInfoReader)
3,902✔
4268
}
4269

4270
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,532✔
4271
        var (
4,532✔
4272
                err      error
4,532✔
4273
                edgeInfo models.ChannelEdgeInfo
4,532✔
4274
        )
4,532✔
4275

4,532✔
4276
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,532✔
4277
                return models.ChannelEdgeInfo{}, err
×
4278
        }
×
4279
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,532✔
4280
                return models.ChannelEdgeInfo{}, err
×
4281
        }
×
4282
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,532✔
4283
                return models.ChannelEdgeInfo{}, err
×
4284
        }
×
4285
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,532✔
4286
                return models.ChannelEdgeInfo{}, err
×
4287
        }
×
4288

4289
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,532✔
4290
        if err != nil {
4,532✔
4291
                return models.ChannelEdgeInfo{}, err
×
4292
        }
×
4293

4294
        proof := &models.ChannelAuthProof{}
4,532✔
4295

4,532✔
4296
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,532✔
4297
        if err != nil {
4,532✔
4298
                return models.ChannelEdgeInfo{}, err
×
4299
        }
×
4300
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,532✔
4301
        if err != nil {
4,532✔
4302
                return models.ChannelEdgeInfo{}, err
×
4303
        }
×
4304
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,532✔
4305
        if err != nil {
4,532✔
4306
                return models.ChannelEdgeInfo{}, err
×
4307
        }
×
4308
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,532✔
4309
        if err != nil {
4,532✔
4310
                return models.ChannelEdgeInfo{}, err
×
4311
        }
×
4312

4313
        if !proof.IsEmpty() {
6,115✔
4314
                edgeInfo.AuthProof = proof
1,583✔
4315
        }
1,583✔
4316

4317
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,532✔
4318
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,532✔
4319
                return models.ChannelEdgeInfo{}, err
×
4320
        }
×
4321
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,532✔
4322
                return models.ChannelEdgeInfo{}, err
×
4323
        }
×
4324
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,532✔
4325
                return models.ChannelEdgeInfo{}, err
×
4326
        }
×
4327

4328
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,532✔
4329
                return models.ChannelEdgeInfo{}, err
×
4330
        }
×
4331

4332
        // We'll try and see if there are any opaque bytes left, if not, then
4333
        // we'll ignore the EOF error and return the edge as is.
4334
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,532✔
4335
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,532✔
4336
        )
4,532✔
4337
        switch {
4,532✔
4338
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4339
        case errors.Is(err, io.EOF):
×
4340
        case err != nil:
×
4341
                return models.ChannelEdgeInfo{}, err
×
4342
        }
4343

4344
        return edgeInfo, nil
4,532✔
4345
}
4346

4347
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4348
        from, to []byte) error {
2,663✔
4349

2,663✔
4350
        var edgeKey [33 + 8]byte
2,663✔
4351
        copy(edgeKey[:], from)
2,663✔
4352
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,663✔
4353

2,663✔
4354
        var b bytes.Buffer
2,663✔
4355
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,663✔
4356
                return err
×
4357
        }
×
4358

4359
        // Before we write out the new edge, we'll create a new entry in the
4360
        // update index in order to keep it fresh.
4361
        updateUnix := uint64(edge.LastUpdate.Unix())
2,663✔
4362
        var indexKey [8 + 8]byte
2,663✔
4363
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,663✔
4364
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,663✔
4365

2,663✔
4366
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,663✔
4367
        if err != nil {
2,663✔
4368
                return err
×
4369
        }
×
4370

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

27✔
4378
                // In order to delete the old entry, we'll need to obtain the
27✔
4379
                // *prior* update time in order to delete it. To do this, we'll
27✔
4380
                // need to deserialize the existing policy within the database
27✔
4381
                // (now outdated by the new one), and delete its corresponding
27✔
4382
                // entry within the update index. We'll ignore any
27✔
4383
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
27✔
4384
                // the channel ID and update time to delete the entry.
27✔
4385
                // TODO(halseth): get rid of these invalid policies in a
27✔
4386
                // migration.
27✔
4387
                oldEdgePolicy, err := deserializeChanEdgePolicy(
27✔
4388
                        bytes.NewReader(edgeBytes),
27✔
4389
                )
27✔
4390
                if err != nil &&
27✔
4391
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) {
27✔
4392

×
4393
                        return err
×
4394
                }
×
4395

4396
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
27✔
4397

27✔
4398
                var oldIndexKey [8 + 8]byte
27✔
4399
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
27✔
4400
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
27✔
4401

27✔
4402
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
27✔
4403
                        return err
×
4404
                }
×
4405
        }
4406

4407
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,663✔
4408
                return err
×
4409
        }
×
4410

4411
        err = updateEdgePolicyDisabledIndex(
2,663✔
4412
                edges, edge.ChannelID,
2,663✔
4413
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,663✔
4414
                edge.IsDisabled(),
2,663✔
4415
        )
2,663✔
4416
        if err != nil {
2,663✔
4417
                return err
×
4418
        }
×
4419

4420
        return edges.Put(edgeKey[:], b.Bytes())
2,663✔
4421
}
4422

4423
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4424
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4425
// one.
4426
// The direction represents the direction of the edge and disabled is used for
4427
// deciding whether to remove or add an entry to the bucket.
4428
// In general a channel is disabled if two entries for the same chanID exist
4429
// in this bucket.
4430
// Maintaining the bucket this way allows a fast retrieval of disabled
4431
// channels, for example when prune is needed.
4432
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4433
        direction bool, disabled bool) error {
2,933✔
4434

2,933✔
4435
        var disabledEdgeKey [8 + 1]byte
2,933✔
4436
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,933✔
4437
        if direction {
4,399✔
4438
                disabledEdgeKey[8] = 1
1,466✔
4439
        }
1,466✔
4440

4441
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,933✔
4442
                disabledEdgePolicyBucket,
2,933✔
4443
        )
2,933✔
4444
        if err != nil {
2,933✔
4445
                return err
×
4446
        }
×
4447

4448
        if disabled {
2,962✔
4449
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4450
        }
29✔
4451

4452
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,907✔
4453
}
4454

4455
// putChanEdgePolicyUnknown marks the edge policy as unknown
4456
// in the edges bucket.
4457
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4458
        from []byte) error {
2,957✔
4459

2,957✔
4460
        var edgeKey [33 + 8]byte
2,957✔
4461
        copy(edgeKey[:], from)
2,957✔
4462
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,957✔
4463

2,957✔
4464
        if edges.Get(edgeKey[:]) != nil {
2,957✔
4465
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4466
                        " when there is already a policy present", channelID)
×
4467
        }
×
4468

4469
        return edges.Put(edgeKey[:], unknownPolicy)
2,957✔
4470
}
4471

4472
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4473
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
7,765✔
4474

7,765✔
4475
        var edgeKey [33 + 8]byte
7,765✔
4476
        copy(edgeKey[:], nodePub)
7,765✔
4477
        copy(edgeKey[33:], chanID)
7,765✔
4478

7,765✔
4479
        edgeBytes := edges.Get(edgeKey[:])
7,765✔
4480
        if edgeBytes == nil {
7,765✔
4481
                return nil, ErrEdgeNotFound
×
4482
        }
×
4483

4484
        // No need to deserialize unknown policy.
4485
        if bytes.Equal(edgeBytes, unknownPolicy) {
8,113✔
4486
                return nil, nil
348✔
4487
        }
348✔
4488

4489
        edgeReader := bytes.NewReader(edgeBytes)
7,420✔
4490

7,420✔
4491
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,420✔
4492
        switch {
7,420✔
4493
        // If the db policy was missing an expected optional field, we return
4494
        // nil as if the policy was unknown.
4495
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
1✔
4496
                return nil, nil
1✔
4497

4498
        case err != nil:
×
4499
                return nil, err
×
4500
        }
4501

4502
        return ep, nil
7,419✔
4503
}
4504

4505
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4506
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4507
        error) {
234✔
4508

234✔
4509
        edgeInfo := edgeIndex.Get(chanID)
234✔
4510
        if edgeInfo == nil {
234✔
4511
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4512
                        chanID)
×
4513
        }
×
4514

4515
        // The first node is contained within the first half of the edge
4516
        // information. We only propagate the error here and below if it's
4517
        // something other than edge non-existence.
4518
        node1Pub := edgeInfo[:33]
234✔
4519
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
234✔
4520
        if err != nil {
234✔
4521
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4522
                        node1Pub)
×
4523
        }
×
4524

4525
        // Similarly, the second node is contained within the latter
4526
        // half of the edge information.
4527
        node2Pub := edgeInfo[33:66]
234✔
4528
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
234✔
4529
        if err != nil {
234✔
4530
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4531
                        node2Pub)
×
4532
        }
×
4533

4534
        return edge1, edge2, nil
234✔
4535
}
4536

4537
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4538
        to []byte) error {
2,665✔
4539

2,665✔
4540
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,665✔
4541
        if err != nil {
2,665✔
4542
                return err
×
4543
        }
×
4544

4545
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,665✔
4546
                return err
×
4547
        }
×
4548

4549
        var scratch [8]byte
2,665✔
4550
        updateUnix := uint64(edge.LastUpdate.Unix())
2,665✔
4551
        byteOrder.PutUint64(scratch[:], updateUnix)
2,665✔
4552
        if _, err := w.Write(scratch[:]); err != nil {
2,665✔
4553
                return err
×
4554
        }
×
4555

4556
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,665✔
4557
                return err
×
4558
        }
×
4559
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,665✔
4560
                return err
×
4561
        }
×
4562
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,665✔
4563
                return err
×
4564
        }
×
4565
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,665✔
4566
                return err
×
4567
        }
×
4568
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,665✔
4569
        if err != nil {
2,665✔
4570
                return err
×
4571
        }
×
4572
        err = binary.Write(
2,665✔
4573
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,665✔
4574
        )
2,665✔
4575
        if err != nil {
2,665✔
4576
                return err
×
4577
        }
×
4578

4579
        if _, err := w.Write(to); err != nil {
2,665✔
4580
                return err
×
4581
        }
×
4582

4583
        // If the max_htlc field is present, we write it. To be compatible with
4584
        // older versions that wasn't aware of this field, we write it as part
4585
        // of the opaque data.
4586
        // TODO(halseth): clean up when moving to TLV.
4587
        var opaqueBuf bytes.Buffer
2,665✔
4588
        if edge.MessageFlags.HasMaxHtlc() {
4,946✔
4589
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,281✔
4590
                if err != nil {
2,281✔
4591
                        return err
×
4592
                }
×
4593
        }
4594

4595
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,665✔
4596
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4597
        }
×
4598
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,665✔
4599
                return err
×
4600
        }
×
4601

4602
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,665✔
4603
                return err
×
4604
        }
×
4605

4606
        return nil
2,665✔
4607
}
4608

4609
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,445✔
4610
        // Deserialize the policy. Note that in case an optional field is not
7,445✔
4611
        // found, both an error and a populated policy object are returned.
7,445✔
4612
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,445✔
4613
        if deserializeErr != nil &&
7,445✔
4614
                !errors.Is(deserializeErr, ErrEdgePolicyOptionalFieldNotFound) {
7,445✔
4615

×
4616
                return nil, deserializeErr
×
4617
        }
×
4618

4619
        return edge, deserializeErr
7,445✔
4620
}
4621

4622
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4623
        error) {
8,452✔
4624

8,452✔
4625
        edge := &models.ChannelEdgePolicy{}
8,452✔
4626

8,452✔
4627
        var err error
8,452✔
4628
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,452✔
4629
        if err != nil {
8,452✔
4630
                return nil, err
×
4631
        }
×
4632

4633
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,452✔
4634
                return nil, err
×
4635
        }
×
4636

4637
        var scratch [8]byte
8,452✔
4638
        if _, err := r.Read(scratch[:]); err != nil {
8,452✔
4639
                return nil, err
×
4640
        }
×
4641
        unix := int64(byteOrder.Uint64(scratch[:]))
8,452✔
4642
        edge.LastUpdate = time.Unix(unix, 0)
8,452✔
4643

8,452✔
4644
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,452✔
4645
                return nil, err
×
4646
        }
×
4647
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,452✔
4648
                return nil, err
×
4649
        }
×
4650
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,452✔
4651
                return nil, err
×
4652
        }
×
4653

4654
        var n uint64
8,452✔
4655
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,452✔
4656
                return nil, err
×
4657
        }
×
4658
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,452✔
4659

8,452✔
4660
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,452✔
4661
                return nil, err
×
4662
        }
×
4663
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,452✔
4664

8,452✔
4665
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,452✔
4666
                return nil, err
×
4667
        }
×
4668
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,452✔
4669

8,452✔
4670
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,452✔
4671
                return nil, err
×
4672
        }
×
4673

4674
        // We'll try and see if there are any opaque bytes left, if not, then
4675
        // we'll ignore the EOF error and return the edge as is.
4676
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,452✔
4677
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,452✔
4678
        )
8,452✔
4679
        switch {
8,452✔
4680
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4681
        case errors.Is(err, io.EOF):
3✔
4682
        case err != nil:
×
4683
                return nil, err
×
4684
        }
4685

4686
        // See if optional fields are present.
4687
        if edge.MessageFlags.HasMaxHtlc() {
16,530✔
4688
                // The max_htlc field should be at the beginning of the opaque
8,078✔
4689
                // bytes.
8,078✔
4690
                opq := edge.ExtraOpaqueData
8,078✔
4691

8,078✔
4692
                // If the max_htlc field is not present, it might be old data
8,078✔
4693
                // stored before this field was validated. We'll return the
8,078✔
4694
                // edge along with an error.
8,078✔
4695
                if len(opq) < 8 {
8,081✔
4696
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4697
                }
3✔
4698

4699
                maxHtlc := byteOrder.Uint64(opq[:8])
8,075✔
4700
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,075✔
4701

8,075✔
4702
                // Exclude the parsed field from the rest of the opaque data.
8,075✔
4703
                edge.ExtraOpaqueData = opq[8:]
8,075✔
4704
        }
4705

4706
        return edge, nil
8,449✔
4707
}
4708

4709
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4710
// KVStore and a kvdb.RTx.
4711
type chanGraphNodeTx struct {
4712
        tx   kvdb.RTx
4713
        db   *KVStore
4714
        node *models.LightningNode
4715
}
4716

4717
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4718
// interface.
4719
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4720

4721
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4722
        node *models.LightningNode) *chanGraphNodeTx {
3,917✔
4723

3,917✔
4724
        return &chanGraphNodeTx{
3,917✔
4725
                tx:   tx,
3,917✔
4726
                db:   db,
3,917✔
4727
                node: node,
3,917✔
4728
        }
3,917✔
4729
}
3,917✔
4730

4731
// Node returns the raw information of the node.
4732
//
4733
// NOTE: This is a part of the NodeRTx interface.
4734
func (c *chanGraphNodeTx) Node() *models.LightningNode {
4,842✔
4735
        return c.node
4,842✔
4736
}
4,842✔
4737

4738
// FetchNode fetches the node with the given pub key under the same transaction
4739
// used to fetch the current node. The returned node is also a NodeRTx and any
4740
// operations on that NodeRTx will also be done under the same transaction.
4741
//
4742
// NOTE: This is a part of the NodeRTx interface.
4743
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
2,944✔
4744
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
2,944✔
4745
        if err != nil {
2,944✔
4746
                return nil, err
×
4747
        }
×
4748

4749
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4750
}
4751

4752
// ForEachChannel can be used to iterate over the node's channels under
4753
// the same transaction used to fetch the node.
4754
//
4755
// NOTE: This is a part of the NodeRTx interface.
4756
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4757
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4758

965✔
4759
        return c.db.ForEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4760
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4761
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4762

2,944✔
4763
                        return f(info, policy1, policy2)
2,944✔
4764
                },
2,944✔
4765
        )
4766
}
4767

4768
// MakeTestGraph creates a new instance of the KVStore for testing
4769
// purposes.
4770
func MakeTestGraph(t testing.TB, modifiers ...KVStoreOptionModifier) (
4771
        *ChannelGraph, error) {
41✔
4772

41✔
4773
        opts := DefaultOptions()
41✔
4774
        for _, modifier := range modifiers {
41✔
4775
                modifier(opts)
×
4776
        }
×
4777

4778
        // Next, create KVStore for the first time.
4779
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
41✔
4780
        if err != nil {
41✔
4781
                backendCleanup()
×
4782

×
4783
                return nil, err
×
4784
        }
×
4785

4786
        graph, err := NewChannelGraph(&Config{
41✔
4787
                KVDB:        backend,
41✔
4788
                KVStoreOpts: modifiers,
41✔
4789
        })
41✔
4790
        if err != nil {
41✔
4791
                backendCleanup()
×
4792

×
4793
                return nil, err
×
4794
        }
×
4795

4796
        t.Cleanup(func() {
82✔
4797
                _ = backend.Close()
41✔
4798
                backendCleanup()
41✔
4799
        })
41✔
4800

4801
        return graph, nil
41✔
4802
}
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