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

lightningnetwork / lnd / 13547803395

26 Feb 2025 03:44PM UTC coverage: 49.37% (-9.5%) from 58.865%
13547803395

Pull #9552

github

ellemouton
graph/db: move cache write for UpdateEdgePolicy

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

42 of 95 new or added lines in 2 files covered. (44.21%)

27496 existing lines in 436 files now uncovered.

101025 of 204628 relevant lines covered (49.37%)

1.54 hits per line

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

67.68
/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) {
3✔
203

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

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

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

3✔
227
        return g, nil
3✔
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) {
3✔
236
        c.graphCache = cache
3✔
237
}
3✔
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) {
3✔
249

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

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

3✔
261
                        return nil
3✔
262
                }
3✔
263

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

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

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

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

3✔
283
                switch {
3✔
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
3✔
294

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

301
        return channelMap, nil
3✔
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 {
3✔
339
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
6✔
340
                for _, tlb := range graphTopLevelBuckets {
6✔
341
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
3✔
342
                                return err
×
343
                        }
×
344
                }
345

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

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

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

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

383
        return nil
3✔
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) {
3✔
393

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

399
        node, err := c.FetchLightningNode(pubKey)
3✔
400
        // We don't consider it an error if the graph is unaware of the node.
3✔
401
        switch {
3✔
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
3✔
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 {
3✔
423

3✔
424
        return c.db.View(func(tx kvdb.RTx) error {
6✔
425
                edges := tx.ReadBucket(edgeBucket)
3✔
426
                if edges == nil {
3✔
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)
3✔
433
                if err != nil {
3✔
434
                        return err
×
435
                }
×
436

437
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
438
                if edgeIndex == nil {
3✔
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(
3✔
445
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
6✔
446
                                var chanID [8]byte
3✔
447
                                copy(chanID[:], k)
3✔
448

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

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

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

3✔
467
                                return cb(&info, policy1, policy2)
3✔
468
                        },
469
                )
470
        }, func() {})
3✔
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 {
3✔
482

3✔
483
        // Fallback that uses the database.
3✔
484
        toNodeCallback := func() route.Vertex {
6✔
485
                return node
3✔
486
        }
3✔
487
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
488
        if err != nil {
3✔
489
                return err
×
490
        }
×
491

492
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
3✔
493
                p2 *models.ChannelEdgePolicy) error {
6✔
494

3✔
495
                var cachedInPolicy *models.CachedEdgePolicy
3✔
496
                if p2 != nil {
6✔
497
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
498
                        cachedInPolicy.ToNodePubKey = toNodeCallback
3✔
499
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
3✔
500
                }
3✔
501

502
                var inboundFee lnwire.Fee
3✔
503
                if p1 != nil {
6✔
504
                        // Extract inbound fee. If there is a decoding error,
3✔
505
                        // skip this edge.
3✔
506
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
507
                        if err != nil {
3✔
UNCOV
508
                                return nil
×
UNCOV
509
                        }
×
510
                }
511

512
                directedChannel := &DirectedChannel{
3✔
513
                        ChannelID:    e.ChannelID,
3✔
514
                        IsNode1:      node == e.NodeKey1Bytes,
3✔
515
                        OtherNode:    e.NodeKey2Bytes,
3✔
516
                        Capacity:     e.Capacity,
3✔
517
                        OutPolicySet: p1 != nil,
3✔
518
                        InPolicy:     cachedInPolicy,
3✔
519
                        InboundFee:   inboundFee,
3✔
520
                }
3✔
521

3✔
522
                if node == e.NodeKey2Bytes {
6✔
523
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
524
                }
3✔
525

526
                return cb(directedChannel)
3✔
527
        }
528

529
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
530
}
531

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

3✔
538
        // Fallback that uses the database.
3✔
539
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
540
        switch {
3✔
541
        // If the node exists and has features, return them directly.
542
        case err == nil:
3✔
543
                return targetNode.Features, nil
3✔
544

545
        // If we couldn't find a node announcement, populate a blank feature
546
        // vector.
UNCOV
547
        case errors.Is(err, ErrGraphNodeNotFound):
×
UNCOV
548
                return lnwire.EmptyFeatureVector(), nil
×
549

550
        // Otherwise, bubble the error up.
551
        default:
×
552
                return nil, err
×
553
        }
554
}
555

556
// ForEachNodeDirectedChannel iterates through all channels of a given node,
557
// executing the passed callback on the directed edge representing the channel
558
// and its incoming policy. If the callback returns an error, then the iteration
559
// is halted with the error propagated back up to the caller.
560
//
561
// Unknown policies are passed into the callback as nil values.
562
//
563
// NOTE: this is part of the graphdb.NodeTraverser interface.
564
func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
565
        cb func(channel *DirectedChannel) error) error {
3✔
566

3✔
567
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
3✔
568
}
3✔
569

570
// FetchNodeFeatures returns the features of the given node. If no features are
571
// known for the node, an empty feature vector is returned.
572
//
573
// NOTE: this is part of the graphdb.NodeTraverser interface.
574
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
575
        *lnwire.FeatureVector, error) {
3✔
576

3✔
577
        return c.fetchNodeFeatures(nil, nodePub)
3✔
578
}
3✔
579

580
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
581
// data to the call-back.
582
//
583
// NOTE: The callback contents MUST not be modified.
584
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
UNCOV
585
        chans map[uint64]*DirectedChannel) error) error {
×
UNCOV
586

×
UNCOV
587
        // Otherwise call back to a version that uses the database directly.
×
UNCOV
588
        // We'll iterate over each node, then the set of channels for each
×
UNCOV
589
        // node, and construct a similar callback functiopn signature as the
×
UNCOV
590
        // main funcotin expects.
×
UNCOV
591
        return c.forEachNode(func(tx kvdb.RTx,
×
UNCOV
592
                node *models.LightningNode) error {
×
UNCOV
593

×
UNCOV
594
                channels := make(map[uint64]*DirectedChannel)
×
UNCOV
595

×
UNCOV
596
                err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes,
×
UNCOV
597
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
UNCOV
598
                                p1 *models.ChannelEdgePolicy,
×
UNCOV
599
                                p2 *models.ChannelEdgePolicy) error {
×
UNCOV
600

×
UNCOV
601
                                toNodeCallback := func() route.Vertex {
×
602
                                        return node.PubKeyBytes
×
603
                                }
×
UNCOV
604
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
UNCOV
605
                                        tx, node.PubKeyBytes,
×
UNCOV
606
                                )
×
UNCOV
607
                                if err != nil {
×
608
                                        return err
×
609
                                }
×
610

UNCOV
611
                                var cachedInPolicy *models.CachedEdgePolicy
×
UNCOV
612
                                if p2 != nil {
×
UNCOV
613
                                        cachedInPolicy =
×
UNCOV
614
                                                models.NewCachedPolicy(p2)
×
UNCOV
615
                                        cachedInPolicy.ToNodePubKey =
×
UNCOV
616
                                                toNodeCallback
×
UNCOV
617
                                        cachedInPolicy.ToNodeFeatures =
×
UNCOV
618
                                                toNodeFeatures
×
UNCOV
619
                                }
×
620

UNCOV
621
                                directedChannel := &DirectedChannel{
×
UNCOV
622
                                        ChannelID: e.ChannelID,
×
UNCOV
623
                                        IsNode1: node.PubKeyBytes ==
×
UNCOV
624
                                                e.NodeKey1Bytes,
×
UNCOV
625
                                        OtherNode:    e.NodeKey2Bytes,
×
UNCOV
626
                                        Capacity:     e.Capacity,
×
UNCOV
627
                                        OutPolicySet: p1 != nil,
×
UNCOV
628
                                        InPolicy:     cachedInPolicy,
×
UNCOV
629
                                }
×
UNCOV
630

×
UNCOV
631
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
UNCOV
632
                                        directedChannel.OtherNode =
×
UNCOV
633
                                                e.NodeKey1Bytes
×
UNCOV
634
                                }
×
635

UNCOV
636
                                channels[e.ChannelID] = directedChannel
×
UNCOV
637

×
UNCOV
638
                                return nil
×
639
                        })
UNCOV
640
                if err != nil {
×
641
                        return err
×
642
                }
×
643

UNCOV
644
                return cb(node.PubKeyBytes, channels)
×
645
        })
646
}
647

648
// DisabledChannelIDs returns the channel ids of disabled channels.
649
// A channel is disabled when two of the associated ChanelEdgePolicies
650
// have their disabled bit on.
UNCOV
651
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
×
UNCOV
652
        var disabledChanIDs []uint64
×
UNCOV
653
        var chanEdgeFound map[uint64]struct{}
×
UNCOV
654

×
UNCOV
655
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
656
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
657
                if edges == nil {
×
658
                        return ErrGraphNoEdgesFound
×
659
                }
×
660

UNCOV
661
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
UNCOV
662
                        disabledEdgePolicyBucket,
×
UNCOV
663
                )
×
UNCOV
664
                if disabledEdgePolicyIndex == nil {
×
UNCOV
665
                        return nil
×
UNCOV
666
                }
×
667

668
                // We iterate over all disabled policies and we add each channel
669
                // that has more than one disabled policy to disabledChanIDs
670
                // array.
UNCOV
671
                return disabledEdgePolicyIndex.ForEach(
×
UNCOV
672
                        func(k, v []byte) error {
×
UNCOV
673
                                chanID := byteOrder.Uint64(k[:8])
×
UNCOV
674
                                _, edgeFound := chanEdgeFound[chanID]
×
UNCOV
675
                                if edgeFound {
×
UNCOV
676
                                        delete(chanEdgeFound, chanID)
×
UNCOV
677
                                        disabledChanIDs = append(
×
UNCOV
678
                                                disabledChanIDs, chanID,
×
UNCOV
679
                                        )
×
UNCOV
680

×
UNCOV
681
                                        return nil
×
UNCOV
682
                                }
×
683

UNCOV
684
                                chanEdgeFound[chanID] = struct{}{}
×
UNCOV
685

×
UNCOV
686
                                return nil
×
687
                        },
688
                )
UNCOV
689
        }, func() {
×
UNCOV
690
                disabledChanIDs = nil
×
UNCOV
691
                chanEdgeFound = make(map[uint64]struct{})
×
UNCOV
692
        })
×
UNCOV
693
        if err != nil {
×
694
                return nil, err
×
695
        }
×
696

UNCOV
697
        return disabledChanIDs, nil
×
698
}
699

700
// ForEachNode iterates through all the stored vertices/nodes in the graph,
701
// executing the passed callback with each node encountered. If the callback
702
// returns an error, then the transaction is aborted and the iteration stops
703
// early. Any operations performed on the NodeTx passed to the call-back are
704
// executed under the same read transaction and so, methods on the NodeTx object
705
// _MUST_ only be called from within the call-back.
706
func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error {
3✔
707
        return c.forEachNode(func(tx kvdb.RTx,
3✔
708
                node *models.LightningNode) error {
6✔
709

3✔
710
                return cb(newChanGraphNodeTx(tx, c, node))
3✔
711
        })
3✔
712
}
713

714
// forEachNode iterates through all the stored vertices/nodes in the graph,
715
// executing the passed callback with each node encountered. If the callback
716
// returns an error, then the transaction is aborted and the iteration stops
717
// early.
718
//
719
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
720
// traversal when graph gets mega.
721
func (c *KVStore) forEachNode(
722
        cb func(kvdb.RTx, *models.LightningNode) error) error {
3✔
723

3✔
724
        traversal := func(tx kvdb.RTx) error {
6✔
725
                // First grab the nodes bucket which stores the mapping from
3✔
726
                // pubKey to node information.
3✔
727
                nodes := tx.ReadBucket(nodeBucket)
3✔
728
                if nodes == nil {
3✔
729
                        return ErrGraphNotFound
×
730
                }
×
731

732
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
733
                        // If this is the source key, then we skip this
3✔
734
                        // iteration as the value for this key is a pubKey
3✔
735
                        // rather than raw node information.
3✔
736
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
737
                                return nil
3✔
738
                        }
3✔
739

740
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
741
                        node, err := deserializeLightningNode(nodeReader)
3✔
742
                        if err != nil {
3✔
743
                                return err
×
744
                        }
×
745

746
                        // Execute the callback, the transaction will abort if
747
                        // this returns an error.
748
                        return cb(tx, &node)
3✔
749
                })
750
        }
751

752
        return kvdb.View(c.db, traversal, func() {})
6✔
753
}
754

755
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
756
// graph, executing the passed callback with each node encountered. If the
757
// callback returns an error, then the transaction is aborted and the iteration
758
// stops early.
759
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
760
        *lnwire.FeatureVector) error) error {
3✔
761

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

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

778
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
779
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
780
                                nodeReader,
3✔
781
                        )
3✔
782
                        if err != nil {
3✔
783
                                return err
×
784
                        }
×
785

786
                        // Execute the callback, the transaction will abort if
787
                        // this returns an error.
788
                        return cb(node, features)
3✔
789
                })
790
        }
791

792
        return kvdb.View(c.db, traversal, func() {})
6✔
793
}
794

795
// SourceNode returns the source node of the graph. The source node is treated
796
// as the center node within a star-graph. This method may be used to kick off
797
// a path finding algorithm in order to explore the reachability of another
798
// node based off the source node.
799
func (c *KVStore) SourceNode() (*models.LightningNode, error) {
3✔
800
        var source *models.LightningNode
3✔
801
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
802
                // First grab the nodes bucket which stores the mapping from
3✔
803
                // pubKey to node information.
3✔
804
                nodes := tx.ReadBucket(nodeBucket)
3✔
805
                if nodes == nil {
3✔
806
                        return ErrGraphNotFound
×
807
                }
×
808

809
                node, err := c.sourceNode(nodes)
3✔
810
                if err != nil {
3✔
UNCOV
811
                        return err
×
UNCOV
812
                }
×
813
                source = node
3✔
814

3✔
815
                return nil
3✔
816
        }, func() {
3✔
817
                source = nil
3✔
818
        })
3✔
819
        if err != nil {
3✔
UNCOV
820
                return nil, err
×
UNCOV
821
        }
×
822

823
        return source, nil
3✔
824
}
825

826
// sourceNode uses an existing database transaction and returns the source node
827
// of the graph. The source node is treated as the center node within a
828
// star-graph. This method may be used to kick off a path finding algorithm in
829
// order to explore the reachability of another node based off the source node.
830
func (c *KVStore) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
831
        error) {
3✔
832

3✔
833
        selfPub := nodes.Get(sourceKey)
3✔
834
        if selfPub == nil {
3✔
UNCOV
835
                return nil, ErrSourceNodeNotSet
×
UNCOV
836
        }
×
837

838
        // With the pubKey of the source node retrieved, we're able to
839
        // fetch the full node information.
840
        node, err := fetchLightningNode(nodes, selfPub)
3✔
841
        if err != nil {
3✔
842
                return nil, err
×
843
        }
×
844

845
        return &node, nil
3✔
846
}
847

848
// SetSourceNode sets the source node within the graph database. The source
849
// node is to be used as the center of a star-graph within path finding
850
// algorithms.
851
func (c *KVStore) SetSourceNode(node *models.LightningNode) error {
3✔
852
        nodePubBytes := node.PubKeyBytes[:]
3✔
853

3✔
854
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
855
                // First grab the nodes bucket which stores the mapping from
3✔
856
                // pubKey to node information.
3✔
857
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
858
                if err != nil {
3✔
859
                        return err
×
860
                }
×
861

862
                // Next we create the mapping from source to the targeted
863
                // public key.
864
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
3✔
865
                        return err
×
866
                }
×
867

868
                // Finally, we commit the information of the lightning node
869
                // itself.
870
                return addLightningNode(tx, node)
3✔
871
        }, func() {})
3✔
872
}
873

874
// AddLightningNode adds a vertex/node to the graph database. If the node is not
875
// in the database from before, this will add a new, unconnected one to the
876
// graph. If it is present from before, this will update that node's
877
// information. Note that this method is expected to only be called to update an
878
// already present node from a node announcement, or to insert a node found in a
879
// channel update.
880
//
881
// TODO(roasbeef): also need sig of announcement.
882
func (c *KVStore) AddLightningNode(node *models.LightningNode,
883
        op ...batch.SchedulerOption) error {
3✔
884

3✔
885
        r := &batch.Request{
3✔
886
                Update: func(tx kvdb.RwTx) error {
6✔
887
                        return addLightningNode(tx, node)
3✔
888
                },
3✔
889
        }
890

891
        for _, f := range op {
6✔
892
                f(r)
3✔
893
        }
3✔
894

895
        return c.nodeScheduler.Execute(r)
3✔
896
}
897

898
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
899
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
900
        if err != nil {
3✔
901
                return err
×
902
        }
×
903

904
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
905
        if err != nil {
3✔
906
                return err
×
907
        }
×
908

909
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
910
                nodeUpdateIndexBucket,
3✔
911
        )
3✔
912
        if err != nil {
3✔
913
                return err
×
914
        }
×
915

916
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
917
}
918

919
// LookupAlias attempts to return the alias as advertised by the target node.
920
// TODO(roasbeef): currently assumes that aliases are unique...
921
func (c *KVStore) LookupAlias(pub *btcec.PublicKey) (string, error) {
3✔
922
        var alias string
3✔
923

3✔
924
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
925
                nodes := tx.ReadBucket(nodeBucket)
3✔
926
                if nodes == nil {
3✔
927
                        return ErrGraphNodesNotFound
×
928
                }
×
929

930
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
3✔
931
                if aliases == nil {
3✔
932
                        return ErrGraphNodesNotFound
×
933
                }
×
934

935
                nodePub := pub.SerializeCompressed()
3✔
936
                a := aliases.Get(nodePub)
3✔
937
                if a == nil {
3✔
UNCOV
938
                        return ErrNodeAliasNotFound
×
UNCOV
939
                }
×
940

941
                // TODO(roasbeef): should actually be using the utf-8
942
                // package...
943
                alias = string(a)
3✔
944

3✔
945
                return nil
3✔
946
        }, func() {
3✔
947
                alias = ""
3✔
948
        })
3✔
949
        if err != nil {
3✔
UNCOV
950
                return "", err
×
UNCOV
951
        }
×
952

953
        return alias, nil
3✔
954
}
955

956
// DeleteLightningNode starts a new database transaction to remove a vertex/node
957
// from the database according to the node's public key.
UNCOV
958
func (c *KVStore) DeleteLightningNode(nodePub route.Vertex) error {
×
UNCOV
959
        // TODO(roasbeef): ensure dangling edges are removed...
×
UNCOV
960
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
961
                nodes := tx.ReadWriteBucket(nodeBucket)
×
UNCOV
962
                if nodes == nil {
×
963
                        return ErrGraphNodeNotFound
×
964
                }
×
965

UNCOV
966
                return c.deleteLightningNode(nodes, nodePub[:])
×
UNCOV
967
        }, func() {})
×
968
}
969

970
// deleteLightningNode uses an existing database transaction to remove a
971
// vertex/node from the database according to the node's public key.
972
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
973
        compressedPubKey []byte) error {
3✔
974

3✔
975
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
3✔
976
        if aliases == nil {
3✔
977
                return ErrGraphNodesNotFound
×
978
        }
×
979

980
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
981
                return err
×
982
        }
×
983

984
        // Before we delete the node, we'll fetch its current state so we can
985
        // determine when its last update was to clear out the node update
986
        // index.
987
        node, err := fetchLightningNode(nodes, compressedPubKey)
3✔
988
        if err != nil {
3✔
989
                return err
×
990
        }
×
991

992
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
993
                return err
×
994
        }
×
995

996
        // Finally, we'll delete the index entry for the node within the
997
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
998
        // need to track its last update.
999
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
1000
        if nodeUpdateIndex == nil {
3✔
1001
                return ErrGraphNodesNotFound
×
1002
        }
×
1003

1004
        // In order to delete the entry, we'll need to reconstruct the key for
1005
        // its last update.
1006
        updateUnix := uint64(node.LastUpdate.Unix())
3✔
1007
        var indexKey [8 + 33]byte
3✔
1008
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
1009
        copy(indexKey[8:], compressedPubKey)
3✔
1010

3✔
1011
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
1012
}
1013

1014
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1015
// undirected edge from the two target nodes are created. The information stored
1016
// denotes the static attributes of the channel, such as the channelID, the keys
1017
// involved in creation of the channel, and the set of features that the channel
1018
// supports. The chanPoint and chanID are used to uniquely identify the edge
1019
// globally within the database.
1020
func (c *KVStore) AddChannelEdge(edge *models.ChannelEdgeInfo,
1021
        op ...batch.SchedulerOption) error {
3✔
1022

3✔
1023
        var alreadyExists bool
3✔
1024
        r := &batch.Request{
3✔
1025
                Reset: func() {
6✔
1026
                        alreadyExists = false
3✔
1027
                },
3✔
1028
                Update: func(tx kvdb.RwTx) error {
3✔
1029
                        err := c.addChannelEdge(tx, edge)
3✔
1030

3✔
1031
                        // Silence ErrEdgeAlreadyExist so that the batch can
3✔
1032
                        // succeed, but propagate the error via local state.
3✔
1033
                        if errors.Is(err, ErrEdgeAlreadyExist) {
3✔
UNCOV
1034
                                alreadyExists = true
×
UNCOV
1035
                                return nil
×
UNCOV
1036
                        }
×
1037

1038
                        return err
3✔
1039
                },
1040
                OnCommit: func(err error) error {
3✔
1041
                        switch {
3✔
1042
                        case err != nil:
×
1043
                                return err
×
UNCOV
1044
                        case alreadyExists:
×
UNCOV
1045
                                return ErrEdgeAlreadyExist
×
1046
                        default:
3✔
1047
                                c.rejectCache.remove(edge.ChannelID)
3✔
1048
                                c.chanCache.remove(edge.ChannelID)
3✔
1049
                                return nil
3✔
1050
                        }
1051
                },
1052
        }
1053

1054
        for _, f := range op {
6✔
1055
                if f == nil {
3✔
1056
                        return fmt.Errorf("nil scheduler option was used")
×
1057
                }
×
1058

1059
                f(r)
3✔
1060
        }
1061

1062
        return c.chanScheduler.Execute(r)
3✔
1063
}
1064

1065
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1066
// utilize an existing db transaction.
1067
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1068
        edge *models.ChannelEdgeInfo) error {
3✔
1069

3✔
1070
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1071
        var chanKey [8]byte
3✔
1072
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1073

3✔
1074
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1075
        if err != nil {
3✔
1076
                return err
×
1077
        }
×
1078
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1079
        if err != nil {
3✔
1080
                return err
×
1081
        }
×
1082
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1083
        if err != nil {
3✔
1084
                return err
×
1085
        }
×
1086
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1087
        if err != nil {
3✔
1088
                return err
×
1089
        }
×
1090

1091
        // First, attempt to check if this edge has already been created. If
1092
        // so, then we can exit early as this method is meant to be idempotent.
1093
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
3✔
UNCOV
1094
                return ErrEdgeAlreadyExist
×
UNCOV
1095
        }
×
1096

1097
        // Before we insert the channel into the database, we'll ensure that
1098
        // both nodes already exist in the channel graph. If either node
1099
        // doesn't, then we'll insert a "shell" node that just includes its
1100
        // public key, so subsequent validation and queries can work properly.
1101
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
3✔
1102
        switch {
3✔
1103
        case errors.Is(node1Err, ErrGraphNodeNotFound):
3✔
1104
                node1Shell := models.LightningNode{
3✔
1105
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1106
                        HaveNodeAnnouncement: false,
3✔
1107
                }
3✔
1108
                err := addLightningNode(tx, &node1Shell)
3✔
1109
                if err != nil {
3✔
1110
                        return fmt.Errorf("unable to create shell node "+
×
1111
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1112
                }
×
1113
        case node1Err != nil:
×
1114
                return node1Err
×
1115
        }
1116

1117
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
1118
        switch {
3✔
1119
        case errors.Is(node2Err, ErrGraphNodeNotFound):
3✔
1120
                node2Shell := models.LightningNode{
3✔
1121
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1122
                        HaveNodeAnnouncement: false,
3✔
1123
                }
3✔
1124
                err := addLightningNode(tx, &node2Shell)
3✔
1125
                if err != nil {
3✔
1126
                        return fmt.Errorf("unable to create shell node "+
×
1127
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1128
                }
×
1129
        case node2Err != nil:
×
1130
                return node2Err
×
1131
        }
1132

1133
        // If the edge hasn't been created yet, then we'll first add it to the
1134
        // edge index in order to associate the edge between two nodes and also
1135
        // store the static components of the channel.
1136
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1137
                return err
×
1138
        }
×
1139

1140
        // Mark edge policies for both sides as unknown. This is to enable
1141
        // efficient incoming channel lookup for a node.
1142
        keys := []*[33]byte{
3✔
1143
                &edge.NodeKey1Bytes,
3✔
1144
                &edge.NodeKey2Bytes,
3✔
1145
        }
3✔
1146
        for _, key := range keys {
6✔
1147
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1148
                if err != nil {
3✔
1149
                        return err
×
1150
                }
×
1151
        }
1152

1153
        // Finally we add it to the channel index which maps channel points
1154
        // (outpoints) to the shorter channel ID's.
1155
        var b bytes.Buffer
3✔
1156
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1157
                return err
×
1158
        }
×
1159

1160
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1161
}
1162

1163
// HasChannelEdge returns true if the database knows of a channel edge with the
1164
// passed channel ID, and false otherwise. If an edge with that ID is found
1165
// within the graph, then two time stamps representing the last time the edge
1166
// was updated for both directed edges are returned along with the boolean. If
1167
// it is not found, then the zombie index is checked and its result is returned
1168
// as the second boolean.
1169
func (c *KVStore) HasChannelEdge(
1170
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1171

3✔
1172
        var (
3✔
1173
                upd1Time time.Time
3✔
1174
                upd2Time time.Time
3✔
1175
                exists   bool
3✔
1176
                isZombie bool
3✔
1177
        )
3✔
1178

3✔
1179
        // We'll query the cache with the shared lock held to allow multiple
3✔
1180
        // readers to access values in the cache concurrently if they exist.
3✔
1181
        c.cacheMu.RLock()
3✔
1182
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1183
                c.cacheMu.RUnlock()
3✔
1184
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1185
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1186
                exists, isZombie = entry.flags.unpack()
3✔
1187

3✔
1188
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1189
        }
3✔
1190
        c.cacheMu.RUnlock()
3✔
1191

3✔
1192
        c.cacheMu.Lock()
3✔
1193
        defer c.cacheMu.Unlock()
3✔
1194

3✔
1195
        // The item was not found with the shared lock, so we'll acquire the
3✔
1196
        // exclusive lock and check the cache again in case another method added
3✔
1197
        // the entry to the cache while no lock was held.
3✔
1198
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1199
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1200
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1201
                exists, isZombie = entry.flags.unpack()
3✔
1202

3✔
1203
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1204
        }
3✔
1205

1206
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1207
                edges := tx.ReadBucket(edgeBucket)
3✔
1208
                if edges == nil {
3✔
1209
                        return ErrGraphNoEdgesFound
×
1210
                }
×
1211
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1212
                if edgeIndex == nil {
3✔
1213
                        return ErrGraphNoEdgesFound
×
1214
                }
×
1215

1216
                var channelID [8]byte
3✔
1217
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1218

3✔
1219
                // If the edge doesn't exist, then we'll also check our zombie
3✔
1220
                // index.
3✔
1221
                if edgeIndex.Get(channelID[:]) == nil {
6✔
1222
                        exists = false
3✔
1223
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1224
                        if zombieIndex != nil {
6✔
1225
                                isZombie, _, _ = isZombieEdge(
3✔
1226
                                        zombieIndex, chanID,
3✔
1227
                                )
3✔
1228
                        }
3✔
1229

1230
                        return nil
3✔
1231
                }
1232

1233
                exists = true
3✔
1234
                isZombie = false
3✔
1235

3✔
1236
                // If the channel has been found in the graph, then retrieve
3✔
1237
                // the edges itself so we can return the last updated
3✔
1238
                // timestamps.
3✔
1239
                nodes := tx.ReadBucket(nodeBucket)
3✔
1240
                if nodes == nil {
3✔
1241
                        return ErrGraphNodeNotFound
×
1242
                }
×
1243

1244
                e1, e2, err := fetchChanEdgePolicies(
3✔
1245
                        edgeIndex, edges, channelID[:],
3✔
1246
                )
3✔
1247
                if err != nil {
3✔
1248
                        return err
×
1249
                }
×
1250

1251
                // As we may have only one of the edges populated, only set the
1252
                // update time if the edge was found in the database.
1253
                if e1 != nil {
6✔
1254
                        upd1Time = e1.LastUpdate
3✔
1255
                }
3✔
1256
                if e2 != nil {
6✔
1257
                        upd2Time = e2.LastUpdate
3✔
1258
                }
3✔
1259

1260
                return nil
3✔
1261
        }, func() {}); err != nil {
3✔
1262
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1263
        }
×
1264

1265
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1266
                upd1Time: upd1Time.Unix(),
3✔
1267
                upd2Time: upd2Time.Unix(),
3✔
1268
                flags:    packRejectFlags(exists, isZombie),
3✔
1269
        })
3✔
1270

3✔
1271
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1272
}
1273

1274
// AddEdgeProof sets the proof of an existing edge in the graph database.
1275
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1276
        proof *models.ChannelAuthProof) error {
3✔
1277

3✔
1278
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1279
        var chanKey [8]byte
3✔
1280
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1281

3✔
1282
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1283
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1284
                if edges == nil {
3✔
1285
                        return ErrEdgeNotFound
×
1286
                }
×
1287

1288
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1289
                if edgeIndex == nil {
3✔
1290
                        return ErrEdgeNotFound
×
1291
                }
×
1292

1293
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1294
                if err != nil {
3✔
1295
                        return err
×
1296
                }
×
1297

1298
                edge.AuthProof = proof
3✔
1299

3✔
1300
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1301
        }, func() {})
3✔
1302
}
1303

1304
const (
1305
        // pruneTipBytes is the total size of the value which stores a prune
1306
        // entry of the graph in the prune log. The "prune tip" is the last
1307
        // entry in the prune log, and indicates if the channel graph is in
1308
        // sync with the current UTXO state. The structure of the value
1309
        // is: blockHash, taking 32 bytes total.
1310
        pruneTipBytes = 32
1311
)
1312

1313
// PruneGraph prunes newly closed channels from the channel graph in response
1314
// to a new block being solved on the network. Any transactions which spend the
1315
// funding output of any known channels within he graph will be deleted.
1316
// Additionally, the "prune tip", or the last block which has been used to
1317
// prune the graph is stored so callers can ensure the graph is fully in sync
1318
// with the current UTXO state. A slice of channels that have been closed by
1319
// the target block along with any pruned nodes are returned if the function
1320
// succeeds without error.
1321
func (c *KVStore) PruneGraph(spentOutputs []*wire.OutPoint,
1322
        blockHash *chainhash.Hash, blockHeight uint32) (
1323
        []*models.ChannelEdgeInfo, []route.Vertex, error) {
3✔
1324

3✔
1325
        c.cacheMu.Lock()
3✔
1326
        defer c.cacheMu.Unlock()
3✔
1327

3✔
1328
        var (
3✔
1329
                chansClosed []*models.ChannelEdgeInfo
3✔
1330
                prunedNodes []route.Vertex
3✔
1331
        )
3✔
1332

3✔
1333
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1334
                // First grab the edges bucket which houses the information
3✔
1335
                // we'd like to delete
3✔
1336
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1337
                if err != nil {
3✔
1338
                        return err
×
1339
                }
×
1340

1341
                // Next grab the two edge indexes which will also need to be
1342
                // updated.
1343
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1344
                if err != nil {
3✔
1345
                        return err
×
1346
                }
×
1347
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1348
                        channelPointBucket,
3✔
1349
                )
3✔
1350
                if err != nil {
3✔
1351
                        return err
×
1352
                }
×
1353
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1354
                if nodes == nil {
3✔
1355
                        return ErrSourceNodeNotSet
×
1356
                }
×
1357
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1358
                if err != nil {
3✔
1359
                        return err
×
1360
                }
×
1361

1362
                // For each of the outpoints that have been spent within the
1363
                // block, we attempt to delete them from the graph as if that
1364
                // outpoint was a channel, then it has now been closed.
1365
                for _, chanPoint := range spentOutputs {
6✔
1366
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1367
                        // if NOT if filter
3✔
1368

3✔
1369
                        var opBytes bytes.Buffer
3✔
1370
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1371
                        if err != nil {
3✔
1372
                                return err
×
1373
                        }
×
1374

1375
                        // First attempt to see if the channel exists within
1376
                        // the database, if not, then we can exit early.
1377
                        chanID := chanIndex.Get(opBytes.Bytes())
3✔
1378
                        if chanID == nil {
3✔
UNCOV
1379
                                continue
×
1380
                        }
1381

1382
                        // Attempt to delete the channel, an ErrEdgeNotFound
1383
                        // will be returned if that outpoint isn't known to be
1384
                        // a channel. If no error is returned, then a channel
1385
                        // was successfully pruned.
1386
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1387
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1388
                                chanID, false, false,
3✔
1389
                        )
3✔
1390
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1391
                                return err
×
1392
                        }
×
1393

1394
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1395
                }
1396

1397
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1398
                if err != nil {
3✔
1399
                        return err
×
1400
                }
×
1401

1402
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1403
                        pruneLogBucket,
3✔
1404
                )
3✔
1405
                if err != nil {
3✔
1406
                        return err
×
1407
                }
×
1408

1409
                // With the graph pruned, add a new entry to the prune log,
1410
                // which can be used to check if the graph is fully synced with
1411
                // the current UTXO state.
1412
                var blockHeightBytes [4]byte
3✔
1413
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
3✔
1414

3✔
1415
                var newTip [pruneTipBytes]byte
3✔
1416
                copy(newTip[:], blockHash[:])
3✔
1417

3✔
1418
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1419
                if err != nil {
3✔
1420
                        return err
×
1421
                }
×
1422

1423
                // Now that the graph has been pruned, we'll also attempt to
1424
                // prune any nodes that have had a channel closed within the
1425
                // latest block.
1426
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1427

3✔
1428
                return err
3✔
1429
        }, func() {
3✔
1430
                chansClosed = nil
3✔
1431
                prunedNodes = nil
3✔
1432
        })
3✔
1433
        if err != nil {
3✔
1434
                return nil, nil, err
×
1435
        }
×
1436

1437
        for _, channel := range chansClosed {
6✔
1438
                c.rejectCache.remove(channel.ChannelID)
3✔
1439
                c.chanCache.remove(channel.ChannelID)
3✔
1440
        }
3✔
1441

1442
        return chansClosed, prunedNodes, nil
3✔
1443
}
1444

1445
// PruneGraphNodes is a garbage collection method which attempts to prune out
1446
// any nodes from the channel graph that are currently unconnected. This ensure
1447
// that we only maintain a graph of reachable nodes. In the event that a pruned
1448
// node gains more channels, it will be re-added back to the graph.
1449
func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error) {
3✔
1450
        var prunedNodes []route.Vertex
3✔
1451
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1452
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1453
                if nodes == nil {
3✔
1454
                        return ErrGraphNodesNotFound
×
1455
                }
×
1456
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1457
                if edges == nil {
3✔
1458
                        return ErrGraphNotFound
×
1459
                }
×
1460
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1461
                if edgeIndex == nil {
3✔
1462
                        return ErrGraphNoEdgesFound
×
1463
                }
×
1464

1465
                var err error
3✔
1466
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1467
                if err != nil {
3✔
1468
                        return err
×
1469
                }
×
1470

1471
                return nil
3✔
1472
        }, func() {
3✔
1473
                prunedNodes = nil
3✔
1474
        })
3✔
1475

1476
        return prunedNodes, err
3✔
1477
}
1478

1479
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1480
// channel closed within the current block. If the node still has existing
1481
// channels in the graph, this will act as a no-op.
1482
func (c *KVStore) pruneGraphNodes(nodes kvdb.RwBucket,
1483
        edgeIndex kvdb.RwBucket) ([]route.Vertex, error) {
3✔
1484

3✔
1485
        log.Trace("Pruning nodes from graph with no open channels")
3✔
1486

3✔
1487
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1488
        // even if it no longer has any open channels.
3✔
1489
        sourceNode, err := c.sourceNode(nodes)
3✔
1490
        if err != nil {
3✔
1491
                return nil, err
×
1492
        }
×
1493

1494
        // We'll use this map to keep count the number of references to a node
1495
        // in the graph. A node should only be removed once it has no more
1496
        // references in the graph.
1497
        nodeRefCounts := make(map[[33]byte]int)
3✔
1498
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1499
                // If this is the source key, then we skip this
3✔
1500
                // iteration as the value for this key is a pubKey
3✔
1501
                // rather than raw node information.
3✔
1502
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1503
                        return nil
3✔
1504
                }
3✔
1505

1506
                var nodePub [33]byte
3✔
1507
                copy(nodePub[:], pubKey)
3✔
1508
                nodeRefCounts[nodePub] = 0
3✔
1509

3✔
1510
                return nil
3✔
1511
        })
1512
        if err != nil {
3✔
1513
                return nil, err
×
1514
        }
×
1515

1516
        // To ensure we never delete the source node, we'll start off by
1517
        // bumping its ref count to 1.
1518
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1519

3✔
1520
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1521
        // edge info. We'll use this scan to populate our reference count map
3✔
1522
        // above.
3✔
1523
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
6✔
1524
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1525
                // the nodes that this edge attaches. We'll extract them, and
3✔
1526
                // add them to the ref count map.
3✔
1527
                var node1, node2 [33]byte
3✔
1528
                copy(node1[:], edgeInfoBytes[:33])
3✔
1529
                copy(node2[:], edgeInfoBytes[33:])
3✔
1530

3✔
1531
                // With the nodes extracted, we'll increase the ref count of
3✔
1532
                // each of the nodes.
3✔
1533
                nodeRefCounts[node1]++
3✔
1534
                nodeRefCounts[node2]++
3✔
1535

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

1542
        // Finally, we'll make a second pass over the set of nodes, and delete
1543
        // any nodes that have a ref count of zero.
1544
        var pruned []route.Vertex
3✔
1545
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1546
                // If the ref count of the node isn't zero, then we can safely
3✔
1547
                // skip it as it still has edges to or from it within the
3✔
1548
                // graph.
3✔
1549
                if refCount != 0 {
6✔
1550
                        continue
3✔
1551
                }
1552

1553
                // If we reach this point, then there are no longer any edges
1554
                // that connect this node, so we can delete it.
1555
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1556
                if err != nil {
3✔
1557
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1558
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1559

×
1560
                                log.Warnf("Unable to prune node %x from the "+
×
1561
                                        "graph: %v", nodePubKey, err)
×
1562
                                continue
×
1563
                        }
1564

1565
                        return nil, err
×
1566
                }
1567

1568
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1569
                        nodePubKey[:])
3✔
1570

3✔
1571
                pruned = append(pruned, nodePubKey)
3✔
1572
        }
1573

1574
        if len(pruned) > 0 {
6✔
1575
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1576
                        len(pruned))
3✔
1577
        }
3✔
1578

1579
        return pruned, err
3✔
1580
}
1581

1582
// DisconnectBlockAtHeight is used to indicate that the block specified
1583
// by the passed height has been disconnected from the main chain. This
1584
// will "rewind" the graph back to the height below, deleting channels
1585
// that are no longer confirmed from the graph. The prune log will be
1586
// set to the last prune height valid for the remaining chain.
1587
// Channels that were removed from the graph resulting from the
1588
// disconnected block are returned.
1589
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1590
        []*models.ChannelEdgeInfo, error) {
2✔
1591

2✔
1592
        // Every channel having a ShortChannelID starting at 'height'
2✔
1593
        // will no longer be confirmed.
2✔
1594
        startShortChanID := lnwire.ShortChannelID{
2✔
1595
                BlockHeight: height,
2✔
1596
        }
2✔
1597

2✔
1598
        // Delete everything after this height from the db up until the
2✔
1599
        // SCID alias range.
2✔
1600
        endShortChanID := aliasmgr.StartingAlias
2✔
1601

2✔
1602
        // The block height will be the 3 first bytes of the channel IDs.
2✔
1603
        var chanIDStart [8]byte
2✔
1604
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
2✔
1605
        var chanIDEnd [8]byte
2✔
1606
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
2✔
1607

2✔
1608
        c.cacheMu.Lock()
2✔
1609
        defer c.cacheMu.Unlock()
2✔
1610

2✔
1611
        // Keep track of the channels that are removed from the graph.
2✔
1612
        var removedChans []*models.ChannelEdgeInfo
2✔
1613

2✔
1614
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
4✔
1615
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
2✔
1616
                if err != nil {
2✔
1617
                        return err
×
1618
                }
×
1619
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
2✔
1620
                if err != nil {
2✔
1621
                        return err
×
1622
                }
×
1623
                chanIndex, err := edges.CreateBucketIfNotExists(
2✔
1624
                        channelPointBucket,
2✔
1625
                )
2✔
1626
                if err != nil {
2✔
1627
                        return err
×
1628
                }
×
1629
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
2✔
1630
                if err != nil {
2✔
1631
                        return err
×
1632
                }
×
1633

1634
                // Scan from chanIDStart to chanIDEnd, deleting every
1635
                // found edge.
1636
                // NOTE: we must delete the edges after the cursor loop, since
1637
                // modifying the bucket while traversing is not safe.
1638
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1639
                // so that the StartingAlias itself isn't deleted.
1640
                var keys [][]byte
2✔
1641
                cursor := edgeIndex.ReadWriteCursor()
2✔
1642

2✔
1643
                //nolint:ll
2✔
1644
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
2✔
1645
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
4✔
1646
                        keys = append(keys, k)
2✔
1647
                }
2✔
1648

1649
                for _, k := range keys {
4✔
1650
                        edgeInfo, err := c.delChannelEdgeUnsafe(
2✔
1651
                                edges, edgeIndex, chanIndex, zombieIndex,
2✔
1652
                                k, false, false,
2✔
1653
                        )
2✔
1654
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
2✔
1655
                                return err
×
1656
                        }
×
1657

1658
                        removedChans = append(removedChans, edgeInfo)
2✔
1659
                }
1660

1661
                // Delete all the entries in the prune log having a height
1662
                // greater or equal to the block disconnected.
1663
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
2✔
1664
                if err != nil {
2✔
1665
                        return err
×
1666
                }
×
1667

1668
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1669
                        pruneLogBucket,
2✔
1670
                )
2✔
1671
                if err != nil {
2✔
1672
                        return err
×
1673
                }
×
1674

1675
                var pruneKeyStart [4]byte
2✔
1676
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1677

2✔
1678
                var pruneKeyEnd [4]byte
2✔
1679
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1680

2✔
1681
                // To avoid modifying the bucket while traversing, we delete
2✔
1682
                // the keys in a second loop.
2✔
1683
                var pruneKeys [][]byte
2✔
1684
                pruneCursor := pruneBucket.ReadWriteCursor()
2✔
1685
                //nolint:ll
2✔
1686
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
2✔
1687
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
4✔
1688
                        pruneKeys = append(pruneKeys, k)
2✔
1689
                }
2✔
1690

1691
                for _, k := range pruneKeys {
4✔
1692
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1693
                                return err
×
1694
                        }
×
1695
                }
1696

1697
                return nil
2✔
1698
        }, func() {
2✔
1699
                removedChans = nil
2✔
1700
        }); err != nil {
2✔
1701
                return nil, err
×
1702
        }
×
1703

1704
        for _, channel := range removedChans {
4✔
1705
                c.rejectCache.remove(channel.ChannelID)
2✔
1706
                c.chanCache.remove(channel.ChannelID)
2✔
1707
        }
2✔
1708

1709
        return removedChans, nil
2✔
1710
}
1711

1712
// PruneTip returns the block height and hash of the latest block that has been
1713
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1714
// to tell if the graph is currently in sync with the current best known UTXO
1715
// state.
1716
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
3✔
1717
        var (
3✔
1718
                tipHash   chainhash.Hash
3✔
1719
                tipHeight uint32
3✔
1720
        )
3✔
1721

3✔
1722
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1723
                graphMeta := tx.ReadBucket(graphMetaBucket)
3✔
1724
                if graphMeta == nil {
3✔
1725
                        return ErrGraphNotFound
×
1726
                }
×
1727
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
3✔
1728
                if pruneBucket == nil {
3✔
1729
                        return ErrGraphNeverPruned
×
1730
                }
×
1731

1732
                pruneCursor := pruneBucket.ReadCursor()
3✔
1733

3✔
1734
                // The prune key with the largest block height will be our
3✔
1735
                // prune tip.
3✔
1736
                k, v := pruneCursor.Last()
3✔
1737
                if k == nil {
6✔
1738
                        return ErrGraphNeverPruned
3✔
1739
                }
3✔
1740

1741
                // Once we have the prune tip, the value will be the block hash,
1742
                // and the key the block height.
1743
                copy(tipHash[:], v)
3✔
1744
                tipHeight = byteOrder.Uint32(k)
3✔
1745

3✔
1746
                return nil
3✔
1747
        }, func() {})
3✔
1748
        if err != nil {
6✔
1749
                return nil, 0, err
3✔
1750
        }
3✔
1751

1752
        return &tipHash, tipHeight, nil
3✔
1753
}
1754

1755
// DeleteChannelEdges removes edges with the given channel IDs from the
1756
// database and marks them as zombies. This ensures that we're unable to re-add
1757
// it to our database once again. If an edge does not exist within the
1758
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1759
// true, then when we mark these edges as zombies, we'll set up the keys such
1760
// that we require the node that failed to send the fresh update to be the one
1761
// that resurrects the channel from its zombie state. The markZombie bool
1762
// denotes whether or not to mark the channel as a zombie.
1763
func (c *KVStore) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1764
        chanIDs ...uint64) ([]*models.ChannelEdgeInfo, error) {
3✔
1765

3✔
1766
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1767
        // channels
3✔
1768
        // TODO(roasbeef): don't delete both edges?
3✔
1769

3✔
1770
        c.cacheMu.Lock()
3✔
1771
        defer c.cacheMu.Unlock()
3✔
1772

3✔
1773
        var infos []*models.ChannelEdgeInfo
3✔
1774
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1775
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1776
                if edges == nil {
3✔
1777
                        return ErrEdgeNotFound
×
1778
                }
×
1779
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1780
                if edgeIndex == nil {
3✔
1781
                        return ErrEdgeNotFound
×
1782
                }
×
1783
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
3✔
1784
                if chanIndex == nil {
3✔
1785
                        return ErrEdgeNotFound
×
1786
                }
×
1787
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1788
                if nodes == nil {
3✔
1789
                        return ErrGraphNodeNotFound
×
1790
                }
×
1791
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1792
                if err != nil {
3✔
1793
                        return err
×
1794
                }
×
1795

1796
                var rawChanID [8]byte
3✔
1797
                for _, chanID := range chanIDs {
6✔
1798
                        byteOrder.PutUint64(rawChanID[:], chanID)
3✔
1799
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1800
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1801
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1802
                        )
3✔
1803
                        if err != nil {
3✔
UNCOV
1804
                                return err
×
UNCOV
1805
                        }
×
1806

1807
                        infos = append(infos, edgeInfo)
3✔
1808
                }
1809

1810
                return nil
3✔
1811
        }, func() {
3✔
1812
                infos = nil
3✔
1813
        })
3✔
1814
        if err != nil {
3✔
UNCOV
1815
                return nil, err
×
UNCOV
1816
        }
×
1817

1818
        for _, chanID := range chanIDs {
6✔
1819
                c.rejectCache.remove(chanID)
3✔
1820
                c.chanCache.remove(chanID)
3✔
1821
        }
3✔
1822

1823
        return infos, nil
3✔
1824
}
1825

1826
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1827
// passed channel point (outpoint). If the passed channel doesn't exist within
1828
// the database, then ErrEdgeNotFound is returned.
1829
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1830
        var chanID uint64
3✔
1831
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1832
                var err error
3✔
1833
                chanID, err = getChanID(tx, chanPoint)
3✔
1834
                return err
3✔
1835
        }, func() {
6✔
1836
                chanID = 0
3✔
1837
        }); err != nil {
6✔
1838
                return 0, err
3✔
1839
        }
3✔
1840

1841
        return chanID, nil
3✔
1842
}
1843

1844
// getChanID returns the assigned channel ID for a given channel point.
1845
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1846
        var b bytes.Buffer
3✔
1847
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1848
                return 0, err
×
1849
        }
×
1850

1851
        edges := tx.ReadBucket(edgeBucket)
3✔
1852
        if edges == nil {
3✔
1853
                return 0, ErrGraphNoEdgesFound
×
1854
        }
×
1855
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1856
        if chanIndex == nil {
3✔
1857
                return 0, ErrGraphNoEdgesFound
×
1858
        }
×
1859

1860
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1861
        if chanIDBytes == nil {
6✔
1862
                return 0, ErrEdgeNotFound
3✔
1863
        }
3✔
1864

1865
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1866

3✔
1867
        return chanID, nil
3✔
1868
}
1869

1870
// TODO(roasbeef): allow updates to use Batch?
1871

1872
// HighestChanID returns the "highest" known channel ID in the channel graph.
1873
// This represents the "newest" channel from the PoV of the chain. This method
1874
// can be used by peers to quickly determine if they're graphs are in sync.
1875
func (c *KVStore) HighestChanID() (uint64, error) {
3✔
1876
        var cid uint64
3✔
1877

3✔
1878
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1879
                edges := tx.ReadBucket(edgeBucket)
3✔
1880
                if edges == nil {
3✔
1881
                        return ErrGraphNoEdgesFound
×
1882
                }
×
1883
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1884
                if edgeIndex == nil {
3✔
1885
                        return ErrGraphNoEdgesFound
×
1886
                }
×
1887

1888
                // In order to find the highest chan ID, we'll fetch a cursor
1889
                // and use that to seek to the "end" of our known rage.
1890
                cidCursor := edgeIndex.ReadCursor()
3✔
1891

3✔
1892
                lastChanID, _ := cidCursor.Last()
3✔
1893

3✔
1894
                // If there's no key, then this means that we don't actually
3✔
1895
                // know of any channels, so we'll return a predicable error.
3✔
1896
                if lastChanID == nil {
6✔
1897
                        return ErrGraphNoEdgesFound
3✔
1898
                }
3✔
1899

1900
                // Otherwise, we'll de serialize the channel ID and return it
1901
                // to the caller.
1902
                cid = byteOrder.Uint64(lastChanID)
3✔
1903

3✔
1904
                return nil
3✔
1905
        }, func() {
3✔
1906
                cid = 0
3✔
1907
        })
3✔
1908
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
3✔
1909
                return 0, err
×
1910
        }
×
1911

1912
        return cid, nil
3✔
1913
}
1914

1915
// ChannelEdge represents the complete set of information for a channel edge in
1916
// the known channel graph. This struct couples the core information of the
1917
// edge as well as each of the known advertised edge policies.
1918
type ChannelEdge struct {
1919
        // Info contains all the static information describing the channel.
1920
        Info *models.ChannelEdgeInfo
1921

1922
        // Policy1 points to the "first" edge policy of the channel containing
1923
        // the dynamic information required to properly route through the edge.
1924
        Policy1 *models.ChannelEdgePolicy
1925

1926
        // Policy2 points to the "second" edge policy of the channel containing
1927
        // the dynamic information required to properly route through the edge.
1928
        Policy2 *models.ChannelEdgePolicy
1929

1930
        // Node1 is "node 1" in the channel. This is the node that would have
1931
        // produced Policy1 if it exists.
1932
        Node1 *models.LightningNode
1933

1934
        // Node2 is "node 2" in the channel. This is the node that would have
1935
        // produced Policy2 if it exists.
1936
        Node2 *models.LightningNode
1937
}
1938

1939
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1940
// one edge that has an update timestamp within the specified horizon.
1941
func (c *KVStore) ChanUpdatesInHorizon(startTime,
1942
        endTime time.Time) ([]ChannelEdge, error) {
3✔
1943

3✔
1944
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
1945
        // additional map to keep track of the edges already seen to prevent
3✔
1946
        // re-adding it.
3✔
1947
        var edgesSeen map[uint64]struct{}
3✔
1948
        var edgesToCache map[uint64]ChannelEdge
3✔
1949
        var edgesInHorizon []ChannelEdge
3✔
1950

3✔
1951
        c.cacheMu.Lock()
3✔
1952
        defer c.cacheMu.Unlock()
3✔
1953

3✔
1954
        var hits int
3✔
1955
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1956
                edges := tx.ReadBucket(edgeBucket)
3✔
1957
                if edges == nil {
3✔
1958
                        return ErrGraphNoEdgesFound
×
1959
                }
×
1960
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1961
                if edgeIndex == nil {
3✔
1962
                        return ErrGraphNoEdgesFound
×
1963
                }
×
1964
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
3✔
1965
                if edgeUpdateIndex == nil {
3✔
1966
                        return ErrGraphNoEdgesFound
×
1967
                }
×
1968

1969
                nodes := tx.ReadBucket(nodeBucket)
3✔
1970
                if nodes == nil {
3✔
1971
                        return ErrGraphNodesNotFound
×
1972
                }
×
1973

1974
                // We'll now obtain a cursor to perform a range query within
1975
                // the index to find all channels within the horizon.
1976
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
1977

3✔
1978
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
1979
                byteOrder.PutUint64(
3✔
1980
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
1981
                )
3✔
1982
                byteOrder.PutUint64(
3✔
1983
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
1984
                )
3✔
1985

3✔
1986
                // With our start and end times constructed, we'll step through
3✔
1987
                // the index collecting the info and policy of each update of
3✔
1988
                // each channel that has a last update within the time range.
3✔
1989
                //
3✔
1990
                //nolint:ll
3✔
1991
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
1992
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
1993
                        // We have a new eligible entry, so we'll slice of the
3✔
1994
                        // chan ID so we can query it in the DB.
3✔
1995
                        chanID := indexKey[8:]
3✔
1996

3✔
1997
                        // If we've already retrieved the info and policies for
3✔
1998
                        // this edge, then we can skip it as we don't need to do
3✔
1999
                        // so again.
3✔
2000
                        chanIDInt := byteOrder.Uint64(chanID)
3✔
2001
                        if _, ok := edgesSeen[chanIDInt]; ok {
3✔
UNCOV
2002
                                continue
×
2003
                        }
2004

2005
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
2006
                                hits++
3✔
2007
                                edgesSeen[chanIDInt] = struct{}{}
3✔
2008
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
2009

3✔
2010
                                continue
3✔
2011
                        }
2012

2013
                        // First, we'll fetch the static edge information.
2014
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2015
                        if err != nil {
3✔
2016
                                chanID := byteOrder.Uint64(chanID)
×
2017
                                return fmt.Errorf("unable to fetch info for "+
×
2018
                                        "edge with chan_id=%v: %v", chanID, err)
×
2019
                        }
×
2020

2021
                        // With the static information obtained, we'll now
2022
                        // fetch the dynamic policy info.
2023
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2024
                                edgeIndex, edges, chanID,
3✔
2025
                        )
3✔
2026
                        if err != nil {
3✔
2027
                                chanID := byteOrder.Uint64(chanID)
×
2028
                                return fmt.Errorf("unable to fetch policies "+
×
2029
                                        "for edge with chan_id=%v: %v", chanID,
×
2030
                                        err)
×
2031
                        }
×
2032

2033
                        node1, err := fetchLightningNode(
3✔
2034
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2035
                        )
3✔
2036
                        if err != nil {
3✔
2037
                                return err
×
2038
                        }
×
2039

2040
                        node2, err := fetchLightningNode(
3✔
2041
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2042
                        )
3✔
2043
                        if err != nil {
3✔
2044
                                return err
×
2045
                        }
×
2046

2047
                        // Finally, we'll collate this edge with the rest of
2048
                        // edges to be returned.
2049
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2050
                        channel := ChannelEdge{
3✔
2051
                                Info:    &edgeInfo,
3✔
2052
                                Policy1: edge1,
3✔
2053
                                Policy2: edge2,
3✔
2054
                                Node1:   &node1,
3✔
2055
                                Node2:   &node2,
3✔
2056
                        }
3✔
2057
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2058
                        edgesToCache[chanIDInt] = channel
3✔
2059
                }
2060

2061
                return nil
3✔
2062
        }, func() {
3✔
2063
                edgesSeen = make(map[uint64]struct{})
3✔
2064
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2065
                edgesInHorizon = nil
3✔
2066
        })
3✔
2067
        switch {
3✔
2068
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2069
                fallthrough
×
2070
        case errors.Is(err, ErrGraphNodesNotFound):
×
2071
                break
×
2072

2073
        case err != nil:
×
2074
                return nil, err
×
2075
        }
2076

2077
        // Insert any edges loaded from disk into the cache.
2078
        for chanid, channel := range edgesToCache {
6✔
2079
                c.chanCache.insert(chanid, channel)
3✔
2080
        }
3✔
2081

2082
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
3✔
2083
                float64(hits)/float64(len(edgesInHorizon)), hits,
3✔
2084
                len(edgesInHorizon))
3✔
2085

3✔
2086
        return edgesInHorizon, nil
3✔
2087
}
2088

2089
// NodeUpdatesInHorizon returns all the known lightning node which have an
2090
// update timestamp within the passed range. This method can be used by two
2091
// nodes to quickly determine if they have the same set of up to date node
2092
// announcements.
2093
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2094
        endTime time.Time) ([]models.LightningNode, error) {
3✔
2095

3✔
2096
        var nodesInHorizon []models.LightningNode
3✔
2097

3✔
2098
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2099
                nodes := tx.ReadBucket(nodeBucket)
3✔
2100
                if nodes == nil {
3✔
2101
                        return ErrGraphNodesNotFound
×
2102
                }
×
2103

2104
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2105
                if nodeUpdateIndex == nil {
3✔
2106
                        return ErrGraphNodesNotFound
×
2107
                }
×
2108

2109
                // We'll now obtain a cursor to perform a range query within
2110
                // the index to find all node announcements within the horizon.
2111
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2112

3✔
2113
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2114
                byteOrder.PutUint64(
3✔
2115
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2116
                )
3✔
2117
                byteOrder.PutUint64(
3✔
2118
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2119
                )
3✔
2120

3✔
2121
                // With our start and end times constructed, we'll step through
3✔
2122
                // the index collecting info for each node within the time
3✔
2123
                // range.
3✔
2124
                //
3✔
2125
                //nolint:ll
3✔
2126
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2127
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2128
                        nodePub := indexKey[8:]
3✔
2129
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2130
                        if err != nil {
3✔
2131
                                return err
×
2132
                        }
×
2133

2134
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2135
                }
2136

2137
                return nil
3✔
2138
        }, func() {
3✔
2139
                nodesInHorizon = nil
3✔
2140
        })
3✔
2141
        switch {
3✔
2142
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2143
                fallthrough
×
2144
        case errors.Is(err, ErrGraphNodesNotFound):
×
2145
                break
×
2146

2147
        case err != nil:
×
2148
                return nil, err
×
2149
        }
2150

2151
        return nodesInHorizon, nil
3✔
2152
}
2153

2154
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2155
// ID's that we don't know and are not known zombies of the passed set. In other
2156
// words, we perform a set difference of our set of chan ID's and the ones
2157
// passed in. This method can be used by callers to determine the set of
2158
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2159
// known zombies is also returned.
2160
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2161
        []ChannelUpdateInfo, error) {
3✔
2162

3✔
2163
        var (
3✔
2164
                newChanIDs   []uint64
3✔
2165
                knownZombies []ChannelUpdateInfo
3✔
2166
        )
3✔
2167

3✔
2168
        c.cacheMu.Lock()
3✔
2169
        defer c.cacheMu.Unlock()
3✔
2170

3✔
2171
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2172
                edges := tx.ReadBucket(edgeBucket)
3✔
2173
                if edges == nil {
3✔
2174
                        return ErrGraphNoEdgesFound
×
2175
                }
×
2176
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2177
                if edgeIndex == nil {
3✔
2178
                        return ErrGraphNoEdgesFound
×
2179
                }
×
2180

2181
                // Fetch the zombie index, it may not exist if no edges have
2182
                // ever been marked as zombies. If the index has been
2183
                // initialized, we will use it later to skip known zombie edges.
2184
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2185

3✔
2186
                // We'll run through the set of chanIDs and collate only the
3✔
2187
                // set of channel that are unable to be found within our db.
3✔
2188
                var cidBytes [8]byte
3✔
2189
                for _, info := range chansInfo {
6✔
2190
                        scid := info.ShortChannelID.ToUint64()
3✔
2191
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2192

3✔
2193
                        // If the edge is already known, skip it.
3✔
2194
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
6✔
2195
                                continue
3✔
2196
                        }
2197

2198
                        // If the edge is a known zombie, skip it.
2199
                        if zombieIndex != nil {
6✔
2200
                                isZombie, _, _ := isZombieEdge(
3✔
2201
                                        zombieIndex, scid,
3✔
2202
                                )
3✔
2203

3✔
2204
                                if isZombie {
3✔
NEW
2205
                                        knownZombies = append(
×
NEW
2206
                                                knownZombies, info,
×
NEW
2207
                                        )
×
UNCOV
2208

×
UNCOV
2209
                                        continue
×
2210
                                }
2211
                        }
2212

2213
                        newChanIDs = append(newChanIDs, scid)
3✔
2214
                }
2215

2216
                return nil
3✔
2217
        }, func() {
3✔
2218
                newChanIDs = nil
3✔
2219
                knownZombies = nil
3✔
2220
        })
3✔
2221
        switch {
3✔
2222
        // If we don't know of any edges yet, then we'll return the entire set
2223
        // of chan IDs specified.
2224
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2225
                ogChanIDs := make([]uint64, len(chansInfo))
×
2226
                for i, info := range chansInfo {
×
2227
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2228
                }
×
2229

NEW
2230
                return ogChanIDs, nil, nil
×
2231

2232
        case err != nil:
×
NEW
2233
                return nil, nil, err
×
2234
        }
2235

2236
        return newChanIDs, knownZombies, nil
3✔
2237
}
2238

2239
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2240
// latest received channel updates for the channel.
2241
type ChannelUpdateInfo struct {
2242
        // ShortChannelID is the SCID identifier of the channel.
2243
        ShortChannelID lnwire.ShortChannelID
2244

2245
        // Node1UpdateTimestamp is the timestamp of the latest received update
2246
        // from the node 1 channel peer. This will be set to zero time if no
2247
        // update has yet been received from this node.
2248
        Node1UpdateTimestamp time.Time
2249

2250
        // Node2UpdateTimestamp is the timestamp of the latest received update
2251
        // from the node 2 channel peer. This will be set to zero time if no
2252
        // update has yet been received from this node.
2253
        Node2UpdateTimestamp time.Time
2254
}
2255

2256
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2257
// timestamps with zero seconds unix timestamp which equals
2258
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2259
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2260
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2261

3✔
2262
        chanInfo := ChannelUpdateInfo{
3✔
2263
                ShortChannelID:       scid,
3✔
2264
                Node1UpdateTimestamp: node1Timestamp,
3✔
2265
                Node2UpdateTimestamp: node2Timestamp,
3✔
2266
        }
3✔
2267

3✔
2268
        if node1Timestamp.IsZero() {
6✔
2269
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2270
        }
3✔
2271

2272
        if node2Timestamp.IsZero() {
6✔
2273
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2274
        }
3✔
2275

2276
        return chanInfo
3✔
2277
}
2278

2279
// BlockChannelRange represents a range of channels for a given block height.
2280
type BlockChannelRange struct {
2281
        // Height is the height of the block all of the channels below were
2282
        // included in.
2283
        Height uint32
2284

2285
        // Channels is the list of channels identified by their short ID
2286
        // representation known to us that were included in the block height
2287
        // above. The list may include channel update timestamp information if
2288
        // requested.
2289
        Channels []ChannelUpdateInfo
2290
}
2291

2292
// FilterChannelRange returns the channel ID's of all known channels which were
2293
// mined in a block height within the passed range. The channel IDs are grouped
2294
// by their common block height. This method can be used to quickly share with a
2295
// peer the set of channels we know of within a particular range to catch them
2296
// up after a period of time offline. If withTimestamps is true then the
2297
// timestamp info of the latest received channel update messages of the channel
2298
// will be included in the response.
2299
func (c *KVStore) FilterChannelRange(startHeight,
2300
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
3✔
2301

3✔
2302
        startChanID := &lnwire.ShortChannelID{
3✔
2303
                BlockHeight: startHeight,
3✔
2304
        }
3✔
2305

3✔
2306
        endChanID := lnwire.ShortChannelID{
3✔
2307
                BlockHeight: endHeight,
3✔
2308
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2309
                TxPosition:  math.MaxUint16,
3✔
2310
        }
3✔
2311

3✔
2312
        // As we need to perform a range scan, we'll convert the starting and
3✔
2313
        // ending height to their corresponding values when encoded using short
3✔
2314
        // channel ID's.
3✔
2315
        var chanIDStart, chanIDEnd [8]byte
3✔
2316
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
3✔
2317
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
3✔
2318

3✔
2319
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
3✔
2320
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2321
                edges := tx.ReadBucket(edgeBucket)
3✔
2322
                if edges == nil {
3✔
2323
                        return ErrGraphNoEdgesFound
×
2324
                }
×
2325
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2326
                if edgeIndex == nil {
3✔
2327
                        return ErrGraphNoEdgesFound
×
2328
                }
×
2329

2330
                cursor := edgeIndex.ReadCursor()
3✔
2331

3✔
2332
                // We'll now iterate through the database, and find each
3✔
2333
                // channel ID that resides within the specified range.
3✔
2334
                //
3✔
2335
                //nolint:ll
3✔
2336
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
2337
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
6✔
2338
                        // Don't send alias SCIDs during gossip sync.
3✔
2339
                        edgeReader := bytes.NewReader(v)
3✔
2340
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
3✔
2341
                        if err != nil {
3✔
2342
                                return err
×
2343
                        }
×
2344

2345
                        if edgeInfo.AuthProof == nil {
6✔
2346
                                continue
3✔
2347
                        }
2348

2349
                        // This channel ID rests within the target range, so
2350
                        // we'll add it to our returned set.
2351
                        rawCid := byteOrder.Uint64(k)
3✔
2352
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2353

3✔
2354
                        chanInfo := NewChannelUpdateInfo(
3✔
2355
                                cid, time.Time{}, time.Time{},
3✔
2356
                        )
3✔
2357

3✔
2358
                        if !withTimestamps {
3✔
UNCOV
2359
                                channelsPerBlock[cid.BlockHeight] = append(
×
UNCOV
2360
                                        channelsPerBlock[cid.BlockHeight],
×
UNCOV
2361
                                        chanInfo,
×
UNCOV
2362
                                )
×
UNCOV
2363

×
UNCOV
2364
                                continue
×
2365
                        }
2366

2367
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2368

3✔
2369
                        rawPolicy := edges.Get(node1Key)
3✔
2370
                        if len(rawPolicy) != 0 {
6✔
2371
                                r := bytes.NewReader(rawPolicy)
3✔
2372

3✔
2373
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2374
                                if err != nil && !errors.Is(
3✔
2375
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2376
                                ) {
3✔
2377

×
2378
                                        return err
×
2379
                                }
×
2380

2381
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2382
                        }
2383

2384
                        rawPolicy = edges.Get(node2Key)
3✔
2385
                        if len(rawPolicy) != 0 {
6✔
2386
                                r := bytes.NewReader(rawPolicy)
3✔
2387

3✔
2388
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2389
                                if err != nil && !errors.Is(
3✔
2390
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2391
                                ) {
3✔
2392

×
2393
                                        return err
×
2394
                                }
×
2395

2396
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2397
                        }
2398

2399
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2400
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2401
                        )
3✔
2402
                }
2403

2404
                return nil
3✔
2405
        }, func() {
3✔
2406
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2407
        })
3✔
2408

2409
        switch {
3✔
2410
        // If we don't know of any channels yet, then there's nothing to
2411
        // filter, so we'll return an empty slice.
2412
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
3✔
2413
                return nil, nil
3✔
2414

2415
        case err != nil:
×
2416
                return nil, err
×
2417
        }
2418

2419
        // Return the channel ranges in ascending block height order.
2420
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2421
        for block := range channelsPerBlock {
6✔
2422
                blocks = append(blocks, block)
3✔
2423
        }
3✔
2424
        sort.Slice(blocks, func(i, j int) bool {
6✔
2425
                return blocks[i] < blocks[j]
3✔
2426
        })
3✔
2427

2428
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2429
        for _, block := range blocks {
6✔
2430
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2431
                        Height:   block,
3✔
2432
                        Channels: channelsPerBlock[block],
3✔
2433
                })
3✔
2434
        }
3✔
2435

2436
        return channelRanges, nil
3✔
2437
}
2438

2439
// FetchChanInfos returns the set of channel edges that correspond to the passed
2440
// channel ID's. If an edge is the query is unknown to the database, it will
2441
// skipped and the result will contain only those edges that exist at the time
2442
// of the query. This can be used to respond to peer queries that are seeking to
2443
// fill in gaps in their view of the channel graph.
2444
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
2445
        return c.fetchChanInfos(nil, chanIDs)
3✔
2446
}
3✔
2447

2448
// fetchChanInfos returns the set of channel edges that correspond to the passed
2449
// channel ID's. If an edge is the query is unknown to the database, it will
2450
// skipped and the result will contain only those edges that exist at the time
2451
// of the query. This can be used to respond to peer queries that are seeking to
2452
// fill in gaps in their view of the channel graph.
2453
//
2454
// NOTE: An optional transaction may be provided. If none is provided, then a
2455
// new one will be created.
2456
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2457
        []ChannelEdge, error) {
3✔
2458
        // TODO(roasbeef): sort cids?
3✔
2459

3✔
2460
        var (
3✔
2461
                chanEdges []ChannelEdge
3✔
2462
                cidBytes  [8]byte
3✔
2463
        )
3✔
2464

3✔
2465
        fetchChanInfos := func(tx kvdb.RTx) error {
6✔
2466
                edges := tx.ReadBucket(edgeBucket)
3✔
2467
                if edges == nil {
3✔
2468
                        return ErrGraphNoEdgesFound
×
2469
                }
×
2470
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2471
                if edgeIndex == nil {
3✔
2472
                        return ErrGraphNoEdgesFound
×
2473
                }
×
2474
                nodes := tx.ReadBucket(nodeBucket)
3✔
2475
                if nodes == nil {
3✔
2476
                        return ErrGraphNotFound
×
2477
                }
×
2478

2479
                for _, cid := range chanIDs {
6✔
2480
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2481

3✔
2482
                        // First, we'll fetch the static edge information. If
3✔
2483
                        // the edge is unknown, we will skip the edge and
3✔
2484
                        // continue gathering all known edges.
3✔
2485
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2486
                                edgeIndex, cidBytes[:],
3✔
2487
                        )
3✔
2488
                        switch {
3✔
UNCOV
2489
                        case errors.Is(err, ErrEdgeNotFound):
×
UNCOV
2490
                                continue
×
2491
                        case err != nil:
×
2492
                                return err
×
2493
                        }
2494

2495
                        // With the static information obtained, we'll now
2496
                        // fetch the dynamic policy info.
2497
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2498
                                edgeIndex, edges, cidBytes[:],
3✔
2499
                        )
3✔
2500
                        if err != nil {
3✔
2501
                                return err
×
2502
                        }
×
2503

2504
                        node1, err := fetchLightningNode(
3✔
2505
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2506
                        )
3✔
2507
                        if err != nil {
3✔
2508
                                return err
×
2509
                        }
×
2510

2511
                        node2, err := fetchLightningNode(
3✔
2512
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2513
                        )
3✔
2514
                        if err != nil {
3✔
2515
                                return err
×
2516
                        }
×
2517

2518
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2519
                                Info:    &edgeInfo,
3✔
2520
                                Policy1: edge1,
3✔
2521
                                Policy2: edge2,
3✔
2522
                                Node1:   &node1,
3✔
2523
                                Node2:   &node2,
3✔
2524
                        })
3✔
2525
                }
2526

2527
                return nil
3✔
2528
        }
2529

2530
        if tx == nil {
6✔
2531
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2532
                        chanEdges = nil
3✔
2533
                })
3✔
2534
                if err != nil {
3✔
2535
                        return nil, err
×
2536
                }
×
2537

2538
                return chanEdges, nil
3✔
2539
        }
2540

2541
        err := fetchChanInfos(tx)
×
2542
        if err != nil {
×
2543
                return nil, err
×
2544
        }
×
2545

2546
        return chanEdges, nil
×
2547
}
2548

2549
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2550
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2551

3✔
2552
        // First, we'll fetch the edge update index bucket which currently
3✔
2553
        // stores an entry for the channel we're about to delete.
3✔
2554
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2555
        if updateIndex == nil {
3✔
2556
                // No edges in bucket, return early.
×
2557
                return nil
×
2558
        }
×
2559

2560
        // Now that we have the bucket, we'll attempt to construct a template
2561
        // for the index key: updateTime || chanid.
2562
        var indexKey [8 + 8]byte
3✔
2563
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2564

3✔
2565
        // With the template constructed, we'll attempt to delete an entry that
3✔
2566
        // would have been created by both edges: we'll alternate the update
3✔
2567
        // times, as one may had overridden the other.
3✔
2568
        if edge1 != nil {
6✔
2569
                byteOrder.PutUint64(
3✔
2570
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
3✔
2571
                )
3✔
2572
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2573
                        return err
×
2574
                }
×
2575
        }
2576

2577
        // We'll also attempt to delete the entry that may have been created by
2578
        // the second edge.
2579
        if edge2 != nil {
6✔
2580
                byteOrder.PutUint64(
3✔
2581
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2582
                )
3✔
2583
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2584
                        return err
×
2585
                }
×
2586
        }
2587

2588
        return nil
3✔
2589
}
2590

2591
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2592
// cache. It then goes on to delete any policy info and edge info for this
2593
// channel from the DB and finally, if isZombie is true, it will add an entry
2594
// for this channel in the zombie index.
2595
//
2596
// NOTE: this method MUST only be called if the cacheMu has already been
2597
// acquired.
2598
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2599
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2600
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
3✔
2601

3✔
2602
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2603
        if err != nil {
3✔
UNCOV
2604
                return nil, err
×
UNCOV
2605
        }
×
2606

2607
        // We'll also remove the entry in the edge update index bucket before
2608
        // we delete the edges themselves so we can access their last update
2609
        // times.
2610
        cid := byteOrder.Uint64(chanID)
3✔
2611
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2612
        if err != nil {
3✔
2613
                return nil, err
×
2614
        }
×
2615
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2616
        if err != nil {
3✔
2617
                return nil, err
×
2618
        }
×
2619

2620
        // The edge key is of the format pubKey || chanID. First we construct
2621
        // the latter half, populating the channel ID.
2622
        var edgeKey [33 + 8]byte
3✔
2623
        copy(edgeKey[33:], chanID)
3✔
2624

3✔
2625
        // With the latter half constructed, copy over the first public key to
3✔
2626
        // delete the edge in this direction, then the second to delete the
3✔
2627
        // edge in the opposite direction.
3✔
2628
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2629
        if edges.Get(edgeKey[:]) != nil {
6✔
2630
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2631
                        return nil, err
×
2632
                }
×
2633
        }
2634
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2635
        if edges.Get(edgeKey[:]) != nil {
6✔
2636
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2637
                        return nil, err
×
2638
                }
×
2639
        }
2640

2641
        // As part of deleting the edge we also remove all disabled entries
2642
        // from the edgePolicyDisabledIndex bucket. We do that for both
2643
        // directions.
2644
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
3✔
2645
        if err != nil {
3✔
2646
                return nil, err
×
2647
        }
×
2648
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2649
        if err != nil {
3✔
2650
                return nil, err
×
2651
        }
×
2652

2653
        // With the edge data deleted, we can purge the information from the two
2654
        // edge indexes.
2655
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2656
                return nil, err
×
2657
        }
×
2658
        var b bytes.Buffer
3✔
2659
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2660
                return nil, err
×
2661
        }
×
2662
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
2663
                return nil, err
×
2664
        }
×
2665

2666
        // Finally, we'll mark the edge as a zombie within our index if it's
2667
        // being removed due to the channel becoming a zombie. We do this to
2668
        // ensure we don't store unnecessary data for spent channels.
2669
        if !isZombie {
6✔
2670
                return &edgeInfo, nil
3✔
2671
        }
3✔
2672

2673
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2674
        if strictZombie {
3✔
UNCOV
2675
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
×
UNCOV
2676
        }
×
2677

2678
        return &edgeInfo, markEdgeZombie(
3✔
2679
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2680
        )
3✔
2681
}
2682

2683
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2684
// particular pair of channel policies. The return values are one of:
2685
//  1. (pubkey1, pubkey2)
2686
//  2. (pubkey1, blank)
2687
//  3. (blank, pubkey2)
2688
//
2689
// A blank pubkey means that corresponding node will be unable to resurrect a
2690
// channel on its own. For example, node1 may continue to publish recent
2691
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2692
// we don't want another fresh update from node1 to resurrect, as the edge can
2693
// only become live once node2 finally sends something recent.
2694
//
2695
// In the case where we have neither update, we allow either party to resurrect
2696
// the channel. If the channel were to be marked zombie again, it would be
2697
// marked with the correct lagging channel since we received an update from only
2698
// one side.
2699
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
UNCOV
2700
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
×
UNCOV
2701

×
UNCOV
2702
        switch {
×
2703
        // If we don't have either edge policy, we'll return both pubkeys so
2704
        // that the channel can be resurrected by either party.
UNCOV
2705
        case e1 == nil && e2 == nil:
×
UNCOV
2706
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2707

2708
        // If we're missing edge1, or if both edges are present but edge1 is
2709
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2710
        // means that only an update from edge1 will be able to resurrect the
2711
        // channel.
UNCOV
2712
        case e1 == nil || (e2 != nil && e1.LastUpdate.Before(e2.LastUpdate)):
×
UNCOV
2713
                return info.NodeKey1Bytes, [33]byte{}
×
2714

2715
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2716
        // return a blank pubkey for edge1. In this case, only an update from
2717
        // edge2 can resurect the channel.
UNCOV
2718
        default:
×
UNCOV
2719
                return [33]byte{}, info.NodeKey2Bytes
×
2720
        }
2721
}
2722

2723
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2724
// within the database for the referenced channel. The `flags` attribute within
2725
// the ChannelEdgePolicy determines which of the directed edges are being
2726
// updated. If the flag is 1, then the first node's information is being
2727
// updated, otherwise it's the second node's information. The node ordering is
2728
// determined by the lexicographical ordering of the identity public keys of the
2729
// nodes on either side of the channel.
2730
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2731
        op ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
3✔
2732

3✔
2733
        var (
3✔
2734
                isUpdate1    bool
3✔
2735
                edgeNotFound bool
3✔
2736
                from, to     route.Vertex
3✔
2737
        )
3✔
2738

3✔
2739
        r := &batch.Request{
3✔
2740
                Reset: func() {
6✔
2741
                        isUpdate1 = false
3✔
2742
                        edgeNotFound = false
3✔
2743
                },
3✔
2744
                Update: func(tx kvdb.RwTx) error {
3✔
2745
                        var err error
3✔
2746
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
3✔
2747
                        if err != nil {
3✔
UNCOV
2748
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
×
UNCOV
2749
                        }
×
2750

2751
                        // Silence ErrEdgeNotFound so that the batch can
2752
                        // succeed, but propagate the error via local state.
2753
                        if errors.Is(err, ErrEdgeNotFound) {
3✔
UNCOV
2754
                                edgeNotFound = true
×
UNCOV
2755
                                return nil
×
UNCOV
2756
                        }
×
2757

2758
                        return err
3✔
2759
                },
2760
                OnCommit: func(err error) error {
3✔
2761
                        switch {
3✔
2762
                        case err != nil:
×
2763
                                return err
×
UNCOV
2764
                        case edgeNotFound:
×
UNCOV
2765
                                return ErrEdgeNotFound
×
2766
                        default:
3✔
2767
                                c.updateEdgeCache(edge, isUpdate1)
3✔
2768
                                return nil
3✔
2769
                        }
2770
                },
2771
        }
2772

2773
        for _, f := range op {
6✔
2774
                f(r)
3✔
2775
        }
3✔
2776

2777
        err := c.chanScheduler.Execute(r)
3✔
2778

3✔
2779
        return from, to, err
3✔
2780
}
2781

2782
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2783
        isUpdate1 bool) {
3✔
2784

3✔
2785
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2786
        // the entry with the updated timestamp for the direction that was just
3✔
2787
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2788
        // during the next query for this edge.
3✔
2789
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2790
                if isUpdate1 {
6✔
2791
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2792
                } else {
6✔
2793
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2794
                }
3✔
2795
                c.rejectCache.insert(e.ChannelID, entry)
3✔
2796
        }
2797

2798
        // If an entry for this channel is found in channel cache, we'll modify
2799
        // the entry with the updated policy for the direction that was just
2800
        // written. If the edge doesn't exist, we'll defer loading the info and
2801
        // policies and lazily read from disk during the next query.
2802
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
6✔
2803
                if isUpdate1 {
6✔
2804
                        channel.Policy1 = e
3✔
2805
                } else {
6✔
2806
                        channel.Policy2 = e
3✔
2807
                }
3✔
2808
                c.chanCache.insert(e.ChannelID, channel)
3✔
2809
        }
2810
}
2811

2812
// updateEdgePolicy attempts to update an edge's policy within the relevant
2813
// buckets using an existing database transaction. The returned boolean will be
2814
// true if the updated policy belongs to node1, and false if the policy belonged
2815
// to node2.
2816
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2817
        route.Vertex, route.Vertex, bool, error) {
3✔
2818

3✔
2819
        var noVertex route.Vertex
3✔
2820

3✔
2821
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2822
        if edges == nil {
3✔
NEW
2823
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2824
        }
×
2825
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2826
        if edgeIndex == nil {
3✔
NEW
2827
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2828
        }
×
2829

2830
        // Create the channelID key be converting the channel ID
2831
        // integer into a byte slice.
2832
        var chanID [8]byte
3✔
2833
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2834

3✔
2835
        // With the channel ID, we then fetch the value storing the two
3✔
2836
        // nodes which connect this channel edge.
3✔
2837
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2838
        if nodeInfo == nil {
3✔
NEW
2839
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2840
        }
×
2841

2842
        // Depending on the flags value passed above, either the first
2843
        // or second edge policy is being updated.
2844
        var fromNode, toNode []byte
3✔
2845
        var isUpdate1 bool
3✔
2846
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2847
                fromNode = nodeInfo[:33]
3✔
2848
                toNode = nodeInfo[33:66]
3✔
2849
                isUpdate1 = true
3✔
2850
        } else {
6✔
2851
                fromNode = nodeInfo[33:66]
3✔
2852
                toNode = nodeInfo[:33]
3✔
2853
                isUpdate1 = false
3✔
2854
        }
3✔
2855

2856
        // Finally, with the direction of the edge being updated
2857
        // identified, we update the on-disk edge representation.
2858
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
3✔
2859
        if err != nil {
3✔
NEW
2860
                return noVertex, noVertex, false, err
×
2861
        }
×
2862

2863
        var (
3✔
2864
                fromNodePubKey route.Vertex
3✔
2865
                toNodePubKey   route.Vertex
3✔
2866
        )
3✔
2867
        copy(fromNodePubKey[:], fromNode)
3✔
2868
        copy(toNodePubKey[:], toNode)
3✔
2869

3✔
2870
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
3✔
2871
}
2872

2873
// isPublic determines whether the node is seen as public within the graph from
2874
// the source node's point of view. An existing database transaction can also be
2875
// specified.
2876
func (c *KVStore) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2877
        sourcePubKey []byte) (bool, error) {
3✔
2878

3✔
2879
        // In order to determine whether this node is publicly advertised within
3✔
2880
        // the graph, we'll need to look at all of its edges and check whether
3✔
2881
        // they extend to any other node than the source node. errDone will be
3✔
2882
        // used to terminate the check early.
3✔
2883
        nodeIsPublic := false
3✔
2884
        errDone := errors.New("done")
3✔
2885
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
3✔
2886
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
3✔
2887
                _ *models.ChannelEdgePolicy) error {
6✔
2888

3✔
2889
                // If this edge doesn't extend to the source node, we'll
3✔
2890
                // terminate our search as we can now conclude that the node is
3✔
2891
                // publicly advertised within the graph due to the local node
3✔
2892
                // knowing of the current edge.
3✔
2893
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
3✔
2894
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
6✔
2895

3✔
2896
                        nodeIsPublic = true
3✔
2897
                        return errDone
3✔
2898
                }
3✔
2899

2900
                // Since the edge _does_ extend to the source node, we'll also
2901
                // need to ensure that this is a public edge.
2902
                if info.AuthProof != nil {
6✔
2903
                        nodeIsPublic = true
3✔
2904
                        return errDone
3✔
2905
                }
3✔
2906

2907
                // Otherwise, we'll continue our search.
2908
                return nil
3✔
2909
        })
2910
        if err != nil && !errors.Is(err, errDone) {
3✔
2911
                return false, err
×
2912
        }
×
2913

2914
        return nodeIsPublic, nil
3✔
2915
}
2916

2917
// FetchLightningNodeTx attempts to look up a target node by its identity
2918
// public key. If the node isn't found in the database, then
2919
// ErrGraphNodeNotFound is returned. An optional transaction may be provided.
2920
// If none is provided, then a new one will be created.
2921
func (c *KVStore) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
2922
        *models.LightningNode, error) {
3✔
2923

3✔
2924
        return c.fetchLightningNode(tx, nodePub)
3✔
2925
}
3✔
2926

2927
// FetchLightningNode attempts to look up a target node by its identity public
2928
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2929
// returned.
2930
func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
2931
        *models.LightningNode, error) {
3✔
2932

3✔
2933
        return c.fetchLightningNode(nil, nodePub)
3✔
2934
}
3✔
2935

2936
// fetchLightningNode attempts to look up a target node by its identity public
2937
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2938
// returned. An optional transaction may be provided. If none is provided, then
2939
// a new one will be created.
2940
func (c *KVStore) fetchLightningNode(tx kvdb.RTx,
2941
        nodePub route.Vertex) (*models.LightningNode, error) {
3✔
2942

3✔
2943
        var node *models.LightningNode
3✔
2944
        fetch := func(tx kvdb.RTx) error {
6✔
2945
                // First grab the nodes bucket which stores the mapping from
3✔
2946
                // pubKey to node information.
3✔
2947
                nodes := tx.ReadBucket(nodeBucket)
3✔
2948
                if nodes == nil {
3✔
2949
                        return ErrGraphNotFound
×
2950
                }
×
2951

2952
                // If a key for this serialized public key isn't found, then
2953
                // the target node doesn't exist within the database.
2954
                nodeBytes := nodes.Get(nodePub[:])
3✔
2955
                if nodeBytes == nil {
6✔
2956
                        return ErrGraphNodeNotFound
3✔
2957
                }
3✔
2958

2959
                // If the node is found, then we can de deserialize the node
2960
                // information to return to the user.
2961
                nodeReader := bytes.NewReader(nodeBytes)
3✔
2962
                n, err := deserializeLightningNode(nodeReader)
3✔
2963
                if err != nil {
3✔
2964
                        return err
×
2965
                }
×
2966

2967
                node = &n
3✔
2968

3✔
2969
                return nil
3✔
2970
        }
2971

2972
        if tx == nil {
6✔
2973
                err := kvdb.View(
3✔
2974
                        c.db, fetch, func() {
6✔
2975
                                node = nil
3✔
2976
                        },
3✔
2977
                )
2978
                if err != nil {
6✔
2979
                        return nil, err
3✔
2980
                }
3✔
2981

2982
                return node, nil
3✔
2983
        }
2984

UNCOV
2985
        err := fetch(tx)
×
UNCOV
2986
        if err != nil {
×
UNCOV
2987
                return nil, err
×
UNCOV
2988
        }
×
2989

UNCOV
2990
        return node, nil
×
2991
}
2992

2993
// HasLightningNode determines if the graph has a vertex identified by the
2994
// target node identity public key. If the node exists in the database, a
2995
// timestamp of when the data for the node was lasted updated is returned along
2996
// with a true boolean. Otherwise, an empty time.Time is returned with a false
2997
// boolean.
2998
func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
2999
        error) {
3✔
3000

3✔
3001
        var (
3✔
3002
                updateTime time.Time
3✔
3003
                exists     bool
3✔
3004
        )
3✔
3005

3✔
3006
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3007
                // First grab the nodes bucket which stores the mapping from
3✔
3008
                // pubKey to node information.
3✔
3009
                nodes := tx.ReadBucket(nodeBucket)
3✔
3010
                if nodes == nil {
3✔
3011
                        return ErrGraphNotFound
×
3012
                }
×
3013

3014
                // If a key for this serialized public key isn't found, we can
3015
                // exit early.
3016
                nodeBytes := nodes.Get(nodePub[:])
3✔
3017
                if nodeBytes == nil {
6✔
3018
                        exists = false
3✔
3019
                        return nil
3✔
3020
                }
3✔
3021

3022
                // Otherwise we continue on to obtain the time stamp
3023
                // representing the last time the data for this node was
3024
                // updated.
3025
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3026
                node, err := deserializeLightningNode(nodeReader)
3✔
3027
                if err != nil {
3✔
3028
                        return err
×
3029
                }
×
3030

3031
                exists = true
3✔
3032
                updateTime = node.LastUpdate
3✔
3033

3✔
3034
                return nil
3✔
3035
        }, func() {
3✔
3036
                updateTime = time.Time{}
3✔
3037
                exists = false
3✔
3038
        })
3✔
3039
        if err != nil {
3✔
3040
                return time.Time{}, exists, err
×
3041
        }
×
3042

3043
        return updateTime, exists, nil
3✔
3044
}
3045

3046
// nodeTraversal is used to traverse all channels of a node given by its
3047
// public key and passes channel information into the specified callback.
3048
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3049
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3050
                *models.ChannelEdgePolicy) error) error {
3✔
3051

3✔
3052
        traversal := func(tx kvdb.RTx) error {
6✔
3053
                edges := tx.ReadBucket(edgeBucket)
3✔
3054
                if edges == nil {
3✔
3055
                        return ErrGraphNotFound
×
3056
                }
×
3057
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3058
                if edgeIndex == nil {
3✔
3059
                        return ErrGraphNoEdgesFound
×
3060
                }
×
3061

3062
                // In order to reach all the edges for this node, we take
3063
                // advantage of the construction of the key-space within the
3064
                // edge bucket. The keys are stored in the form: pubKey ||
3065
                // chanID. Therefore, starting from a chanID of zero, we can
3066
                // scan forward in the bucket, grabbing all the edges for the
3067
                // node. Once the prefix no longer matches, then we know we're
3068
                // done.
3069
                var nodeStart [33 + 8]byte
3✔
3070
                copy(nodeStart[:], nodePub)
3✔
3071
                copy(nodeStart[33:], chanStart[:])
3✔
3072

3✔
3073
                // Starting from the key pubKey || 0, we seek forward in the
3✔
3074
                // bucket until the retrieved key no longer has the public key
3✔
3075
                // as its prefix. This indicates that we've stepped over into
3✔
3076
                // another node's edges, so we can terminate our scan.
3✔
3077
                edgeCursor := edges.ReadCursor()
3✔
3078
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
6✔
3079
                        // If the prefix still matches, the channel id is
3✔
3080
                        // returned in nodeEdge. Channel id is used to lookup
3✔
3081
                        // the node at the other end of the channel and both
3✔
3082
                        // edge policies.
3✔
3083
                        chanID := nodeEdge[33:]
3✔
3084
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3085
                        if err != nil {
3✔
3086
                                return err
×
3087
                        }
×
3088

3089
                        outgoingPolicy, err := fetchChanEdgePolicy(
3✔
3090
                                edges, chanID, nodePub,
3✔
3091
                        )
3✔
3092
                        if err != nil {
3✔
3093
                                return err
×
3094
                        }
×
3095

3096
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3097
                        if err != nil {
3✔
3098
                                return err
×
3099
                        }
×
3100

3101
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3102
                                edges, chanID, otherNode[:],
3✔
3103
                        )
3✔
3104
                        if err != nil {
3✔
3105
                                return err
×
3106
                        }
×
3107

3108
                        // Finally, we execute the callback.
3109
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3110
                        if err != nil {
6✔
3111
                                return err
3✔
3112
                        }
3✔
3113
                }
3114

3115
                return nil
3✔
3116
        }
3117

3118
        // If no transaction was provided, then we'll create a new transaction
3119
        // to execute the transaction within.
3120
        if tx == nil {
6✔
3121
                return kvdb.View(db, traversal, func() {})
6✔
3122
        }
3123

3124
        // Otherwise, we re-use the existing transaction to execute the graph
3125
        // traversal.
3126
        return traversal(tx)
3✔
3127
}
3128

3129
// ForEachNodeChannel iterates through all channels of the given node,
3130
// executing the passed callback with an edge info structure and the policies
3131
// of each end of the channel. The first edge policy is the outgoing edge *to*
3132
// the connecting node, while the second is the incoming edge *from* the
3133
// connecting node. If the callback returns an error, then the iteration is
3134
// halted with the error propagated back up to the caller.
3135
//
3136
// Unknown policies are passed into the callback as nil values.
3137
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3138
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3139
                *models.ChannelEdgePolicy) error) error {
3✔
3140

3✔
3141
        return nodeTraversal(nil, nodePub[:], c.db, cb)
3✔
3142
}
3✔
3143

3144
// ForEachNodeChannelTx iterates through all channels of the given node,
3145
// executing the passed callback with an edge info structure and the policies
3146
// of each end of the channel. The first edge policy is the outgoing edge *to*
3147
// the connecting node, while the second is the incoming edge *from* the
3148
// connecting node. If the callback returns an error, then the iteration is
3149
// halted with the error propagated back up to the caller.
3150
//
3151
// Unknown policies are passed into the callback as nil values.
3152
//
3153
// If the caller wishes to re-use an existing boltdb transaction, then it
3154
// should be passed as the first argument.  Otherwise, the first argument should
3155
// be nil and a fresh transaction will be created to execute the graph
3156
// traversal.
3157
func (c *KVStore) ForEachNodeChannelTx(tx kvdb.RTx,
3158
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3159
                *models.ChannelEdgePolicy,
3160
                *models.ChannelEdgePolicy) error) error {
3✔
3161

3✔
3162
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3163
}
3✔
3164

3165
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3166
// the target node in the channel. This is useful when one knows the pubkey of
3167
// one of the nodes, and wishes to obtain the full LightningNode for the other
3168
// end of the channel.
3169
func (c *KVStore) FetchOtherNode(tx kvdb.RTx,
3170
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3171
        *models.LightningNode, error) {
3✔
3172

3✔
3173
        // Ensure that the node passed in is actually a member of the channel.
3✔
3174
        var targetNodeBytes [33]byte
3✔
3175
        switch {
3✔
3176
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3177
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3178
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3179
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3180
        default:
×
3181
                return nil, fmt.Errorf("node not participating in this channel")
×
3182
        }
3183

3184
        var targetNode *models.LightningNode
3✔
3185
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3186
                // First grab the nodes bucket which stores the mapping from
3✔
3187
                // pubKey to node information.
3✔
3188
                nodes := tx.ReadBucket(nodeBucket)
3✔
3189
                if nodes == nil {
3✔
3190
                        return ErrGraphNotFound
×
3191
                }
×
3192

3193
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3194
                if err != nil {
3✔
3195
                        return err
×
3196
                }
×
3197

3198
                targetNode = &node
3✔
3199

3✔
3200
                return nil
3✔
3201
        }
3202

3203
        // If the transaction is nil, then we'll need to create a new one,
3204
        // otherwise we can use the existing db transaction.
3205
        var err error
3✔
3206
        if tx == nil {
3✔
3207
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3208
                        targetNode = nil
×
3209
                })
×
3210
        } else {
3✔
3211
                err = fetchNodeFunc(tx)
3✔
3212
        }
3✔
3213

3214
        return targetNode, err
3✔
3215
}
3216

3217
// computeEdgePolicyKeys is a helper function that can be used to compute the
3218
// keys used to index the channel edge policy info for the two nodes of the
3219
// edge. The keys for node 1 and node 2 are returned respectively.
3220
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3✔
3221
        var (
3✔
3222
                node1Key [33 + 8]byte
3✔
3223
                node2Key [33 + 8]byte
3✔
3224
        )
3✔
3225

3✔
3226
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3227
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3228

3✔
3229
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3230
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3231

3✔
3232
        return node1Key[:], node2Key[:]
3✔
3233
}
3✔
3234

3235
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3236
// the channel identified by the funding outpoint. If the channel can't be
3237
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3238
// information for the channel itself is returned as well as two structs that
3239
// contain the routing policies for the channel in either direction.
3240
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3241
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3242
        *models.ChannelEdgePolicy, error) {
3✔
3243

3✔
3244
        var (
3✔
3245
                edgeInfo *models.ChannelEdgeInfo
3✔
3246
                policy1  *models.ChannelEdgePolicy
3✔
3247
                policy2  *models.ChannelEdgePolicy
3✔
3248
        )
3✔
3249

3✔
3250
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3251
                // First, grab the node bucket. This will be used to populate
3✔
3252
                // the Node pointers in each edge read from disk.
3✔
3253
                nodes := tx.ReadBucket(nodeBucket)
3✔
3254
                if nodes == nil {
3✔
3255
                        return ErrGraphNotFound
×
3256
                }
×
3257

3258
                // Next, grab the edge bucket which stores the edges, and also
3259
                // the index itself so we can group the directed edges together
3260
                // logically.
3261
                edges := tx.ReadBucket(edgeBucket)
3✔
3262
                if edges == nil {
3✔
3263
                        return ErrGraphNoEdgesFound
×
3264
                }
×
3265
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3266
                if edgeIndex == nil {
3✔
3267
                        return ErrGraphNoEdgesFound
×
3268
                }
×
3269

3270
                // If the channel's outpoint doesn't exist within the outpoint
3271
                // index, then the edge does not exist.
3272
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3273
                if chanIndex == nil {
3✔
3274
                        return ErrGraphNoEdgesFound
×
3275
                }
×
3276
                var b bytes.Buffer
3✔
3277
                if err := WriteOutpoint(&b, op); err != nil {
3✔
3278
                        return err
×
3279
                }
×
3280
                chanID := chanIndex.Get(b.Bytes())
3✔
3281
                if chanID == nil {
6✔
3282
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3283
                }
3✔
3284

3285
                // If the channel is found to exists, then we'll first retrieve
3286
                // the general information for the channel.
3287
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3288
                if err != nil {
3✔
3289
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3290
                }
×
3291
                edgeInfo = &edge
3✔
3292

3✔
3293
                // Once we have the information about the channels' parameters,
3✔
3294
                // we'll fetch the routing policies for each for the directed
3✔
3295
                // edges.
3✔
3296
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3297
                if err != nil {
3✔
3298
                        return fmt.Errorf("failed to find policy: %w", err)
×
3299
                }
×
3300

3301
                policy1 = e1
3✔
3302
                policy2 = e2
3✔
3303

3✔
3304
                return nil
3✔
3305
        }, func() {
3✔
3306
                edgeInfo = nil
3✔
3307
                policy1 = nil
3✔
3308
                policy2 = nil
3✔
3309
        })
3✔
3310
        if err != nil {
6✔
3311
                return nil, nil, nil, err
3✔
3312
        }
3✔
3313

3314
        return edgeInfo, policy1, policy2, nil
3✔
3315
}
3316

3317
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3318
// channel identified by the channel ID. If the channel can't be found, then
3319
// ErrEdgeNotFound is returned. A struct which houses the general information
3320
// for the channel itself is returned as well as two structs that contain the
3321
// routing policies for the channel in either direction.
3322
//
3323
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3324
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3325
// the ChannelEdgeInfo will only include the public keys of each node.
3326
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3327
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3328
        *models.ChannelEdgePolicy, error) {
3✔
3329

3✔
3330
        var (
3✔
3331
                edgeInfo  *models.ChannelEdgeInfo
3✔
3332
                policy1   *models.ChannelEdgePolicy
3✔
3333
                policy2   *models.ChannelEdgePolicy
3✔
3334
                channelID [8]byte
3✔
3335
        )
3✔
3336

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

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

3357
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3358

3✔
3359
                // Now, attempt to fetch edge.
3✔
3360
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3361

3✔
3362
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3363
                // see if we've previously marked it as so.
3✔
3364
                if errors.Is(err, ErrEdgeNotFound) {
6✔
3365
                        // If the zombie index doesn't exist, or the edge is not
3✔
3366
                        // marked as a zombie within it, then we'll return the
3✔
3367
                        // original ErrEdgeNotFound error.
3✔
3368
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3369
                        if zombieIndex == nil {
3✔
3370
                                return ErrEdgeNotFound
×
3371
                        }
×
3372

3373
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3374
                                zombieIndex, chanID,
3✔
3375
                        )
3✔
3376
                        if !isZombie {
6✔
3377
                                return ErrEdgeNotFound
3✔
3378
                        }
3✔
3379

3380
                        // Otherwise, the edge is marked as a zombie, so we'll
3381
                        // populate the edge info with the public keys of each
3382
                        // party as this is the only information we have about
3383
                        // it and return an error signaling so.
3384
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3385
                                NodeKey1Bytes: pubKey1,
3✔
3386
                                NodeKey2Bytes: pubKey2,
3✔
3387
                        }
3✔
3388

3✔
3389
                        return ErrZombieEdge
3✔
3390
                }
3391

3392
                // Otherwise, we'll just return the error if any.
3393
                if err != nil {
3✔
3394
                        return err
×
3395
                }
×
3396

3397
                edgeInfo = &edge
3✔
3398

3✔
3399
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3400
                // edge.
3✔
3401
                e1, e2, err := fetchChanEdgePolicies(
3✔
3402
                        edgeIndex, edges, channelID[:],
3✔
3403
                )
3✔
3404
                if err != nil {
3✔
3405
                        return err
×
3406
                }
×
3407

3408
                policy1 = e1
3✔
3409
                policy2 = e2
3✔
3410

3✔
3411
                return nil
3✔
3412
        }, func() {
3✔
3413
                edgeInfo = nil
3✔
3414
                policy1 = nil
3✔
3415
                policy2 = nil
3✔
3416
        })
3✔
3417
        if errors.Is(err, ErrZombieEdge) {
6✔
3418
                return edgeInfo, nil, nil, err
3✔
3419
        }
3✔
3420
        if err != nil {
6✔
3421
                return nil, nil, nil, err
3✔
3422
        }
3✔
3423

3424
        return edgeInfo, policy1, policy2, nil
3✔
3425
}
3426

3427
// IsPublicNode is a helper method that determines whether the node with the
3428
// given public key is seen as a public node in the graph from the graph's
3429
// source node's point of view.
3430
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3431
        var nodeIsPublic bool
3✔
3432
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3433
                nodes := tx.ReadBucket(nodeBucket)
3✔
3434
                if nodes == nil {
3✔
3435
                        return ErrGraphNodesNotFound
×
3436
                }
×
3437
                ourPubKey := nodes.Get(sourceKey)
3✔
3438
                if ourPubKey == nil {
3✔
3439
                        return ErrSourceNodeNotSet
×
3440
                }
×
3441
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3442
                if err != nil {
3✔
3443
                        return err
×
3444
                }
×
3445

3446
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3447

3✔
3448
                return err
3✔
3449
        }, func() {
3✔
3450
                nodeIsPublic = false
3✔
3451
        })
3✔
3452
        if err != nil {
3✔
3453
                return false, err
×
3454
        }
×
3455

3456
        return nodeIsPublic, nil
3✔
3457
}
3458

3459
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3460
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3461
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3462
        if err != nil {
3✔
3463
                return nil, err
×
3464
        }
×
3465

3466
        // With the witness script generated, we'll now turn it into a p2wsh
3467
        // script:
3468
        //  * OP_0 <sha256(script)>
3469
        bldr := txscript.NewScriptBuilder(
3✔
3470
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3471
        )
3✔
3472
        bldr.AddOp(txscript.OP_0)
3✔
3473
        scriptHash := sha256.Sum256(witnessScript)
3✔
3474
        bldr.AddData(scriptHash[:])
3✔
3475

3✔
3476
        return bldr.Script()
3✔
3477
}
3478

3479
// EdgePoint couples the outpoint of a channel with the funding script that it
3480
// creates. The FilteredChainView will use this to watch for spends of this
3481
// edge point on chain. We require both of these values as depending on the
3482
// concrete implementation, either the pkScript, or the out point will be used.
3483
type EdgePoint struct {
3484
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3485
        FundingPkScript []byte
3486

3487
        // OutPoint is the outpoint of the target channel.
3488
        OutPoint wire.OutPoint
3489
}
3490

3491
// String returns a human readable version of the target EdgePoint. We return
3492
// the outpoint directly as it is enough to uniquely identify the edge point.
3493
func (e *EdgePoint) String() string {
×
3494
        return e.OutPoint.String()
×
3495
}
×
3496

3497
// ChannelView returns the verifiable edge information for each active channel
3498
// within the known channel graph. The set of UTXO's (along with their scripts)
3499
// returned are the ones that need to be watched on chain to detect channel
3500
// closes on the resident blockchain.
3501
func (c *KVStore) ChannelView() ([]EdgePoint, error) {
3✔
3502
        var edgePoints []EdgePoint
3✔
3503
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3504
                // We're going to iterate over the entire channel index, so
3✔
3505
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3506
                // it's a sub-bucket.
3✔
3507
                edges := tx.ReadBucket(edgeBucket)
3✔
3508
                if edges == nil {
3✔
3509
                        return ErrGraphNoEdgesFound
×
3510
                }
×
3511
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3512
                if chanIndex == nil {
3✔
3513
                        return ErrGraphNoEdgesFound
×
3514
                }
×
3515
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3516
                if edgeIndex == nil {
3✔
3517
                        return ErrGraphNoEdgesFound
×
3518
                }
×
3519

3520
                // Once we have the proper bucket, we'll range over each key
3521
                // (which is the channel point for the channel) and decode it,
3522
                // accumulating each entry.
3523
                return chanIndex.ForEach(
3✔
3524
                        func(chanPointBytes, chanID []byte) error {
6✔
3525
                                chanPointReader := bytes.NewReader(
3✔
3526
                                        chanPointBytes,
3✔
3527
                                )
3✔
3528

3✔
3529
                                var chanPoint wire.OutPoint
3✔
3530
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3531
                                if err != nil {
3✔
3532
                                        return err
×
3533
                                }
×
3534

3535
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3536
                                        edgeIndex, chanID,
3✔
3537
                                )
3✔
3538
                                if err != nil {
3✔
3539
                                        return err
×
3540
                                }
×
3541

3542
                                pkScript, err := genMultiSigP2WSH(
3✔
3543
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3544
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3545
                                )
3✔
3546
                                if err != nil {
3✔
3547
                                        return err
×
3548
                                }
×
3549

3550
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3551
                                        FundingPkScript: pkScript,
3✔
3552
                                        OutPoint:        chanPoint,
3✔
3553
                                })
3✔
3554

3✔
3555
                                return nil
3✔
3556
                        },
3557
                )
3558
        }, func() {
3✔
3559
                edgePoints = nil
3✔
3560
        }); err != nil {
3✔
3561
                return nil, err
×
3562
        }
×
3563

3564
        return edgePoints, nil
3✔
3565
}
3566

3567
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3568
// zombie. This method is used on an ad-hoc basis, when channels need to be
3569
// marked as zombies outside the normal pruning cycle.
3570
func (c *KVStore) MarkEdgeZombie(chanID uint64,
UNCOV
3571
        pubKey1, pubKey2 [33]byte) error {
×
UNCOV
3572

×
UNCOV
3573
        c.cacheMu.Lock()
×
UNCOV
3574
        defer c.cacheMu.Unlock()
×
UNCOV
3575

×
UNCOV
3576
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3577
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3578
                if edges == nil {
×
3579
                        return ErrGraphNoEdgesFound
×
3580
                }
×
UNCOV
3581
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
UNCOV
3582
                if err != nil {
×
3583
                        return fmt.Errorf("unable to create zombie "+
×
3584
                                "bucket: %w", err)
×
3585
                }
×
3586

UNCOV
3587
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3588
        })
UNCOV
3589
        if err != nil {
×
3590
                return err
×
3591
        }
×
3592

UNCOV
3593
        c.rejectCache.remove(chanID)
×
UNCOV
3594
        c.chanCache.remove(chanID)
×
UNCOV
3595

×
UNCOV
3596
        return nil
×
3597
}
3598

3599
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3600
// keys should represent the node public keys of the two parties involved in the
3601
// edge.
3602
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3603
        pubKey2 [33]byte) error {
3✔
3604

3✔
3605
        var k [8]byte
3✔
3606
        byteOrder.PutUint64(k[:], chanID)
3✔
3607

3✔
3608
        var v [66]byte
3✔
3609
        copy(v[:33], pubKey1[:])
3✔
3610
        copy(v[33:], pubKey2[:])
3✔
3611

3✔
3612
        return zombieIndex.Put(k[:], v[:])
3✔
3613
}
3✔
3614

3615
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
UNCOV
3616
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
UNCOV
3617
        c.cacheMu.Lock()
×
UNCOV
3618
        defer c.cacheMu.Unlock()
×
UNCOV
3619

×
UNCOV
3620
        return c.markEdgeLiveUnsafe(nil, chanID)
×
UNCOV
3621
}
×
3622

3623
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3624
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3625
// case a new transaction will be created.
3626
//
3627
// NOTE: this method MUST only be called if the cacheMu has already been
3628
// acquired.
UNCOV
3629
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
UNCOV
3630
        dbFn := func(tx kvdb.RwTx) error {
×
UNCOV
3631
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3632
                if edges == nil {
×
3633
                        return ErrGraphNoEdgesFound
×
3634
                }
×
UNCOV
3635
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
×
UNCOV
3636
                if zombieIndex == nil {
×
3637
                        return nil
×
3638
                }
×
3639

UNCOV
3640
                var k [8]byte
×
UNCOV
3641
                byteOrder.PutUint64(k[:], chanID)
×
UNCOV
3642

×
UNCOV
3643
                if len(zombieIndex.Get(k[:])) == 0 {
×
UNCOV
3644
                        return ErrZombieEdgeNotFound
×
UNCOV
3645
                }
×
3646

UNCOV
3647
                return zombieIndex.Delete(k[:])
×
3648
        }
3649

3650
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3651
        // the existing transaction
UNCOV
3652
        var err error
×
UNCOV
3653
        if tx == nil {
×
UNCOV
3654
                err = kvdb.Update(c.db, dbFn, func() {})
×
UNCOV
3655
        } else {
×
UNCOV
3656
                err = dbFn(tx)
×
UNCOV
3657
        }
×
UNCOV
3658
        if err != nil {
×
UNCOV
3659
                return err
×
UNCOV
3660
        }
×
3661

UNCOV
3662
        c.rejectCache.remove(chanID)
×
UNCOV
3663
        c.chanCache.remove(chanID)
×
UNCOV
3664

×
UNCOV
3665
        return nil
×
3666
}
3667

3668
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3669
// zombie, then the two node public keys corresponding to this edge are also
3670
// returned.
UNCOV
3671
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
×
UNCOV
3672
        var (
×
UNCOV
3673
                isZombie         bool
×
UNCOV
3674
                pubKey1, pubKey2 [33]byte
×
UNCOV
3675
        )
×
UNCOV
3676

×
UNCOV
3677
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3678
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3679
                if edges == nil {
×
3680
                        return ErrGraphNoEdgesFound
×
3681
                }
×
UNCOV
3682
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3683
                if zombieIndex == nil {
×
3684
                        return nil
×
3685
                }
×
3686

UNCOV
3687
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
UNCOV
3688

×
UNCOV
3689
                return nil
×
UNCOV
3690
        }, func() {
×
UNCOV
3691
                isZombie = false
×
UNCOV
3692
                pubKey1 = [33]byte{}
×
UNCOV
3693
                pubKey2 = [33]byte{}
×
UNCOV
3694
        })
×
UNCOV
3695
        if err != nil {
×
3696
                return false, [33]byte{}, [33]byte{}
×
3697
        }
×
3698

UNCOV
3699
        return isZombie, pubKey1, pubKey2
×
3700
}
3701

3702
// isZombieEdge returns whether an entry exists for the given channel in the
3703
// zombie index. If an entry exists, then the two node public keys corresponding
3704
// to this edge are also returned.
3705
func isZombieEdge(zombieIndex kvdb.RBucket,
3706
        chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3707

3✔
3708
        var k [8]byte
3✔
3709
        byteOrder.PutUint64(k[:], chanID)
3✔
3710

3✔
3711
        v := zombieIndex.Get(k[:])
3✔
3712
        if v == nil {
6✔
3713
                return false, [33]byte{}, [33]byte{}
3✔
3714
        }
3✔
3715

3716
        var pubKey1, pubKey2 [33]byte
3✔
3717
        copy(pubKey1[:], v[:33])
3✔
3718
        copy(pubKey2[:], v[33:])
3✔
3719

3✔
3720
        return true, pubKey1, pubKey2
3✔
3721
}
3722

3723
// NumZombies returns the current number of zombie channels in the graph.
UNCOV
3724
func (c *KVStore) NumZombies() (uint64, error) {
×
UNCOV
3725
        var numZombies uint64
×
UNCOV
3726
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3727
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3728
                if edges == nil {
×
3729
                        return nil
×
3730
                }
×
UNCOV
3731
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3732
                if zombieIndex == nil {
×
3733
                        return nil
×
3734
                }
×
3735

UNCOV
3736
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
UNCOV
3737
                        numZombies++
×
UNCOV
3738
                        return nil
×
UNCOV
3739
                })
×
UNCOV
3740
        }, func() {
×
UNCOV
3741
                numZombies = 0
×
UNCOV
3742
        })
×
UNCOV
3743
        if err != nil {
×
3744
                return 0, err
×
3745
        }
×
3746

UNCOV
3747
        return numZombies, nil
×
3748
}
3749

3750
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3751
// that we can ignore channel announcements that we know to be closed without
3752
// having to validate them and fetch a block.
UNCOV
3753
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
×
UNCOV
3754
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3755
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
UNCOV
3756
                if err != nil {
×
3757
                        return err
×
3758
                }
×
3759

UNCOV
3760
                var k [8]byte
×
UNCOV
3761
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
UNCOV
3762

×
UNCOV
3763
                return closedScids.Put(k[:], []byte{})
×
UNCOV
3764
        }, func() {})
×
3765
}
3766

3767
// IsClosedScid checks whether a channel identified by the passed in scid is
3768
// closed. This helps avoid having to perform expensive validation checks.
3769
// TODO: Add an LRU cache to cut down on disc reads.
3770
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3771
        var isClosed bool
3✔
3772
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3773
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3774
                if closedScids == nil {
3✔
3775
                        return ErrClosedScidsNotFound
×
3776
                }
×
3777

3778
                var k [8]byte
3✔
3779
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3780

3✔
3781
                if closedScids.Get(k[:]) != nil {
3✔
UNCOV
3782
                        isClosed = true
×
UNCOV
3783
                        return nil
×
UNCOV
3784
                }
×
3785

3786
                return nil
3✔
3787
        }, func() {
3✔
3788
                isClosed = false
3✔
3789
        })
3✔
3790
        if err != nil {
3✔
3791
                return false, err
×
3792
        }
×
3793

3794
        return isClosed, nil
3✔
3795
}
3796

3797
// GraphSession will provide the call-back with access to a NodeTraverser
3798
// instance which can be used to perform queries against the channel graph.
UNCOV
3799
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
×
UNCOV
3800
        return c.db.View(func(tx walletdb.ReadTx) error {
×
UNCOV
3801
                return cb(&nodeTraverserSession{
×
UNCOV
3802
                        db: c,
×
UNCOV
3803
                        tx: tx,
×
UNCOV
3804
                })
×
UNCOV
3805
        }, func() {})
×
3806
}
3807

3808
// nodeTraverserSession implements the NodeTraverser interface but with a
3809
// backing read only transaction for a consistent view of the graph.
3810
type nodeTraverserSession struct {
3811
        tx kvdb.RTx
3812
        db *KVStore
3813
}
3814

3815
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3816
// node.
3817
//
3818
// NOTE: Part of the NodeTraverser interface.
3819
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
UNCOV
3820
        cb func(channel *DirectedChannel) error) error {
×
UNCOV
3821

×
UNCOV
3822
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
×
UNCOV
3823
}
×
3824

3825
// FetchNodeFeatures returns the features of the given node. If the node is
3826
// unknown, assume no additional features are supported.
3827
//
3828
// NOTE: Part of the NodeTraverser interface.
3829
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
UNCOV
3830
        *lnwire.FeatureVector, error) {
×
UNCOV
3831

×
UNCOV
3832
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
UNCOV
3833
}
×
3834

3835
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3836
        node *models.LightningNode) error {
3✔
3837

3✔
3838
        var (
3✔
3839
                scratch [16]byte
3✔
3840
                b       bytes.Buffer
3✔
3841
        )
3✔
3842

3✔
3843
        pub, err := node.PubKey()
3✔
3844
        if err != nil {
3✔
3845
                return err
×
3846
        }
×
3847
        nodePub := pub.SerializeCompressed()
3✔
3848

3✔
3849
        // If the node has the update time set, write it, else write 0.
3✔
3850
        updateUnix := uint64(0)
3✔
3851
        if node.LastUpdate.Unix() > 0 {
6✔
3852
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
3853
        }
3✔
3854

3855
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
3856
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
3857
                return err
×
3858
        }
×
3859

3860
        if _, err := b.Write(nodePub); err != nil {
3✔
3861
                return err
×
3862
        }
×
3863

3864
        // If we got a node announcement for this node, we will have the rest
3865
        // of the data available. If not we don't have more data to write.
3866
        if !node.HaveNodeAnnouncement {
6✔
3867
                // Write HaveNodeAnnouncement=0.
3✔
3868
                byteOrder.PutUint16(scratch[:2], 0)
3✔
3869
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
3870
                        return err
×
3871
                }
×
3872

3873
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
3874
        }
3875

3876
        // Write HaveNodeAnnouncement=1.
3877
        byteOrder.PutUint16(scratch[:2], 1)
3✔
3878
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
3879
                return err
×
3880
        }
×
3881

3882
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
3883
                return err
×
3884
        }
×
3885
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
3886
                return err
×
3887
        }
×
3888
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
3889
                return err
×
3890
        }
×
3891

3892
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
3893
                return err
×
3894
        }
×
3895

3896
        if err := node.Features.Encode(&b); err != nil {
3✔
3897
                return err
×
3898
        }
×
3899

3900
        numAddresses := uint16(len(node.Addresses))
3✔
3901
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
3902
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
3903
                return err
×
3904
        }
×
3905

3906
        for _, address := range node.Addresses {
6✔
3907
                if err := SerializeAddr(&b, address); err != nil {
3✔
3908
                        return err
×
3909
                }
×
3910
        }
3911

3912
        sigLen := len(node.AuthSigBytes)
3✔
3913
        if sigLen > 80 {
3✔
3914
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
3915
                        sigLen)
×
3916
        }
×
3917

3918
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
3919
        if err != nil {
3✔
3920
                return err
×
3921
        }
×
3922

3923
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
3924
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
3925
        }
×
3926
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
3927
        if err != nil {
3✔
3928
                return err
×
3929
        }
×
3930

3931
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
3932
                return err
×
3933
        }
×
3934

3935
        // With the alias bucket updated, we'll now update the index that
3936
        // tracks the time series of node updates.
3937
        var indexKey [8 + 33]byte
3✔
3938
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
3939
        copy(indexKey[8:], nodePub)
3✔
3940

3✔
3941
        // If there was already an old index entry for this node, then we'll
3✔
3942
        // delete the old one before we write the new entry.
3✔
3943
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
6✔
3944
                // Extract out the old update time to we can reconstruct the
3✔
3945
                // prior index key to delete it from the index.
3✔
3946
                oldUpdateTime := nodeBytes[:8]
3✔
3947

3✔
3948
                var oldIndexKey [8 + 33]byte
3✔
3949
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
3950
                copy(oldIndexKey[8:], nodePub)
3✔
3951

3✔
3952
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
3953
                        return err
×
3954
                }
×
3955
        }
3956

3957
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
3958
                return err
×
3959
        }
×
3960

3961
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
3962
}
3963

3964
func fetchLightningNode(nodeBucket kvdb.RBucket,
3965
        nodePub []byte) (models.LightningNode, error) {
3✔
3966

3✔
3967
        nodeBytes := nodeBucket.Get(nodePub)
3✔
3968
        if nodeBytes == nil {
6✔
3969
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
3970
        }
3✔
3971

3972
        nodeReader := bytes.NewReader(nodeBytes)
3✔
3973

3✔
3974
        return deserializeLightningNode(nodeReader)
3✔
3975
}
3976

3977
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
3978
        *lnwire.FeatureVector, error) {
3✔
3979

3✔
3980
        var (
3✔
3981
                pubKey      route.Vertex
3✔
3982
                features    = lnwire.EmptyFeatureVector()
3✔
3983
                nodeScratch [8]byte
3✔
3984
        )
3✔
3985

3✔
3986
        // Skip ahead:
3✔
3987
        // - LastUpdate (8 bytes)
3✔
3988
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
3989
                return pubKey, nil, err
×
3990
        }
×
3991

3992
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
3993
                return pubKey, nil, err
×
3994
        }
×
3995

3996
        // Read the node announcement flag.
3997
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
3998
                return pubKey, nil, err
×
3999
        }
×
4000
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4001

3✔
4002
        // The rest of the data is optional, and will only be there if we got a
3✔
4003
        // node announcement for this node.
3✔
4004
        if hasNodeAnn == 0 {
6✔
4005
                return pubKey, features, nil
3✔
4006
        }
3✔
4007

4008
        // We did get a node announcement for this node, so we'll have the rest
4009
        // of the data available.
4010
        var rgb uint8
3✔
4011
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4012
                return pubKey, nil, err
×
4013
        }
×
4014
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4015
                return pubKey, nil, err
×
4016
        }
×
4017
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4018
                return pubKey, nil, err
×
4019
        }
×
4020

4021
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4022
                return pubKey, nil, err
×
4023
        }
×
4024

4025
        if err := features.Decode(r); err != nil {
3✔
4026
                return pubKey, nil, err
×
4027
        }
×
4028

4029
        return pubKey, features, nil
3✔
4030
}
4031

4032
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4033
        var (
3✔
4034
                node    models.LightningNode
3✔
4035
                scratch [8]byte
3✔
4036
                err     error
3✔
4037
        )
3✔
4038

3✔
4039
        // Always populate a feature vector, even if we don't have a node
3✔
4040
        // announcement and short circuit below.
3✔
4041
        node.Features = lnwire.EmptyFeatureVector()
3✔
4042

3✔
4043
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4044
                return models.LightningNode{}, err
×
4045
        }
×
4046

4047
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4048
        node.LastUpdate = time.Unix(unix, 0)
3✔
4049

3✔
4050
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4051
                return models.LightningNode{}, err
×
4052
        }
×
4053

4054
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4055
                return models.LightningNode{}, err
×
4056
        }
×
4057

4058
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4059
        if hasNodeAnn == 1 {
6✔
4060
                node.HaveNodeAnnouncement = true
3✔
4061
        } else {
6✔
4062
                node.HaveNodeAnnouncement = false
3✔
4063
        }
3✔
4064

4065
        // The rest of the data is optional, and will only be there if we got a
4066
        // node announcement for this node.
4067
        if !node.HaveNodeAnnouncement {
6✔
4068
                return node, nil
3✔
4069
        }
3✔
4070

4071
        // We did get a node announcement for this node, so we'll have the rest
4072
        // of the data available.
4073
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
3✔
4074
                return models.LightningNode{}, err
×
4075
        }
×
4076
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
3✔
4077
                return models.LightningNode{}, err
×
4078
        }
×
4079
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4080
                return models.LightningNode{}, err
×
4081
        }
×
4082

4083
        node.Alias, err = wire.ReadVarString(r, 0)
3✔
4084
        if err != nil {
3✔
4085
                return models.LightningNode{}, err
×
4086
        }
×
4087

4088
        err = node.Features.Decode(r)
3✔
4089
        if err != nil {
3✔
4090
                return models.LightningNode{}, err
×
4091
        }
×
4092

4093
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4094
                return models.LightningNode{}, err
×
4095
        }
×
4096
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4097

3✔
4098
        var addresses []net.Addr
3✔
4099
        for i := 0; i < numAddresses; i++ {
6✔
4100
                address, err := DeserializeAddr(r)
3✔
4101
                if err != nil {
3✔
4102
                        return models.LightningNode{}, err
×
4103
                }
×
4104
                addresses = append(addresses, address)
3✔
4105
        }
4106
        node.Addresses = addresses
3✔
4107

3✔
4108
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4109
        if err != nil {
3✔
4110
                return models.LightningNode{}, err
×
4111
        }
×
4112

4113
        // We'll try and see if there are any opaque bytes left, if not, then
4114
        // we'll ignore the EOF error and return the node as is.
4115
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4116
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4117
        )
3✔
4118
        switch {
3✔
4119
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4120
        case errors.Is(err, io.EOF):
×
4121
        case err != nil:
×
4122
                return models.LightningNode{}, err
×
4123
        }
4124

4125
        return node, nil
3✔
4126
}
4127

4128
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4129
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4130

3✔
4131
        var b bytes.Buffer
3✔
4132

3✔
4133
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4134
                return err
×
4135
        }
×
4136
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4137
                return err
×
4138
        }
×
4139
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4140
                return err
×
4141
        }
×
4142
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4143
                return err
×
4144
        }
×
4145

4146
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
3✔
4147
                return err
×
4148
        }
×
4149

4150
        authProof := edgeInfo.AuthProof
3✔
4151
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4152
        if authProof != nil {
6✔
4153
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4154
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4155
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4156
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4157
        }
3✔
4158

4159
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4160
                return err
×
4161
        }
×
4162
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4163
                return err
×
4164
        }
×
4165
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4166
                return err
×
4167
        }
×
4168
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4169
                return err
×
4170
        }
×
4171

4172
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4173
                return err
×
4174
        }
×
4175
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
3✔
4176
        if err != nil {
3✔
4177
                return err
×
4178
        }
×
4179
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4180
                return err
×
4181
        }
×
4182
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4183
                return err
×
4184
        }
×
4185

4186
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4187
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4188
        }
×
4189
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4190
        if err != nil {
3✔
4191
                return err
×
4192
        }
×
4193

4194
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4195
}
4196

4197
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4198
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4199

3✔
4200
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4201
        if edgeInfoBytes == nil {
6✔
4202
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4203
        }
3✔
4204

4205
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4206

3✔
4207
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4208
}
4209

4210
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4211
        var (
3✔
4212
                err      error
3✔
4213
                edgeInfo models.ChannelEdgeInfo
3✔
4214
        )
3✔
4215

3✔
4216
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4217
                return models.ChannelEdgeInfo{}, err
×
4218
        }
×
4219
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4220
                return models.ChannelEdgeInfo{}, err
×
4221
        }
×
4222
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4223
                return models.ChannelEdgeInfo{}, err
×
4224
        }
×
4225
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4226
                return models.ChannelEdgeInfo{}, err
×
4227
        }
×
4228

4229
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
3✔
4230
        if err != nil {
3✔
4231
                return models.ChannelEdgeInfo{}, err
×
4232
        }
×
4233

4234
        proof := &models.ChannelAuthProof{}
3✔
4235

3✔
4236
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4237
        if err != nil {
3✔
4238
                return models.ChannelEdgeInfo{}, err
×
4239
        }
×
4240
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4241
        if err != nil {
3✔
4242
                return models.ChannelEdgeInfo{}, err
×
4243
        }
×
4244
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4245
        if err != nil {
3✔
4246
                return models.ChannelEdgeInfo{}, err
×
4247
        }
×
4248
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4249
        if err != nil {
3✔
4250
                return models.ChannelEdgeInfo{}, err
×
4251
        }
×
4252

4253
        if !proof.IsEmpty() {
6✔
4254
                edgeInfo.AuthProof = proof
3✔
4255
        }
3✔
4256

4257
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4258
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4259
                return models.ChannelEdgeInfo{}, err
×
4260
        }
×
4261
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4262
                return models.ChannelEdgeInfo{}, err
×
4263
        }
×
4264
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4265
                return models.ChannelEdgeInfo{}, err
×
4266
        }
×
4267

4268
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4269
                return models.ChannelEdgeInfo{}, err
×
4270
        }
×
4271

4272
        // We'll try and see if there are any opaque bytes left, if not, then
4273
        // we'll ignore the EOF error and return the edge as is.
4274
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4275
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4276
        )
3✔
4277
        switch {
3✔
4278
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4279
        case errors.Is(err, io.EOF):
×
4280
        case err != nil:
×
4281
                return models.ChannelEdgeInfo{}, err
×
4282
        }
4283

4284
        return edgeInfo, nil
3✔
4285
}
4286

4287
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4288
        from, to []byte) error {
3✔
4289

3✔
4290
        var edgeKey [33 + 8]byte
3✔
4291
        copy(edgeKey[:], from)
3✔
4292
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4293

3✔
4294
        var b bytes.Buffer
3✔
4295
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
4296
                return err
×
4297
        }
×
4298

4299
        // Before we write out the new edge, we'll create a new entry in the
4300
        // update index in order to keep it fresh.
4301
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4302
        var indexKey [8 + 8]byte
3✔
4303
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4304
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4305

3✔
4306
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4307
        if err != nil {
3✔
4308
                return err
×
4309
        }
×
4310

4311
        // If there was already an entry for this edge, then we'll need to
4312
        // delete the old one to ensure we don't leave around any after-images.
4313
        // An unknown policy value does not have a update time recorded, so
4314
        // it also does not need to be removed.
4315
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
3✔
4316
                !bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4317

3✔
4318
                // In order to delete the old entry, we'll need to obtain the
3✔
4319
                // *prior* update time in order to delete it. To do this, we'll
3✔
4320
                // need to deserialize the existing policy within the database
3✔
4321
                // (now outdated by the new one), and delete its corresponding
3✔
4322
                // entry within the update index. We'll ignore any
3✔
4323
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
3✔
4324
                // the channel ID and update time to delete the entry.
3✔
4325
                // TODO(halseth): get rid of these invalid policies in a
3✔
4326
                // migration.
3✔
4327
                oldEdgePolicy, err := deserializeChanEdgePolicy(
3✔
4328
                        bytes.NewReader(edgeBytes),
3✔
4329
                )
3✔
4330
                if err != nil &&
3✔
4331
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) {
3✔
4332

×
4333
                        return err
×
4334
                }
×
4335

4336
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4337

3✔
4338
                var oldIndexKey [8 + 8]byte
3✔
4339
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4340
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4341

3✔
4342
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4343
                        return err
×
4344
                }
×
4345
        }
4346

4347
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4348
                return err
×
4349
        }
×
4350

4351
        err = updateEdgePolicyDisabledIndex(
3✔
4352
                edges, edge.ChannelID,
3✔
4353
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4354
                edge.IsDisabled(),
3✔
4355
        )
3✔
4356
        if err != nil {
3✔
4357
                return err
×
4358
        }
×
4359

4360
        return edges.Put(edgeKey[:], b.Bytes())
3✔
4361
}
4362

4363
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4364
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4365
// one.
4366
// The direction represents the direction of the edge and disabled is used for
4367
// deciding whether to remove or add an entry to the bucket.
4368
// In general a channel is disabled if two entries for the same chanID exist
4369
// in this bucket.
4370
// Maintaining the bucket this way allows a fast retrieval of disabled
4371
// channels, for example when prune is needed.
4372
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4373
        direction bool, disabled bool) error {
3✔
4374

3✔
4375
        var disabledEdgeKey [8 + 1]byte
3✔
4376
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4377
        if direction {
6✔
4378
                disabledEdgeKey[8] = 1
3✔
4379
        }
3✔
4380

4381
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4382
                disabledEdgePolicyBucket,
3✔
4383
        )
3✔
4384
        if err != nil {
3✔
4385
                return err
×
4386
        }
×
4387

4388
        if disabled {
6✔
4389
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4390
        }
3✔
4391

4392
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4393
}
4394

4395
// putChanEdgePolicyUnknown marks the edge policy as unknown
4396
// in the edges bucket.
4397
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4398
        from []byte) error {
3✔
4399

3✔
4400
        var edgeKey [33 + 8]byte
3✔
4401
        copy(edgeKey[:], from)
3✔
4402
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4403

3✔
4404
        if edges.Get(edgeKey[:]) != nil {
3✔
4405
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4406
                        " when there is already a policy present", channelID)
×
4407
        }
×
4408

4409
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4410
}
4411

4412
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4413
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
3✔
4414

3✔
4415
        var edgeKey [33 + 8]byte
3✔
4416
        copy(edgeKey[:], nodePub)
3✔
4417
        copy(edgeKey[33:], chanID)
3✔
4418

3✔
4419
        edgeBytes := edges.Get(edgeKey[:])
3✔
4420
        if edgeBytes == nil {
3✔
4421
                return nil, ErrEdgeNotFound
×
4422
        }
×
4423

4424
        // No need to deserialize unknown policy.
4425
        if bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4426
                return nil, nil
3✔
4427
        }
3✔
4428

4429
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4430

3✔
4431
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4432
        switch {
3✔
4433
        // If the db policy was missing an expected optional field, we return
4434
        // nil as if the policy was unknown.
UNCOV
4435
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
UNCOV
4436
                return nil, nil
×
4437

4438
        case err != nil:
×
4439
                return nil, err
×
4440
        }
4441

4442
        return ep, nil
3✔
4443
}
4444

4445
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4446
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4447
        error) {
3✔
4448

3✔
4449
        edgeInfo := edgeIndex.Get(chanID)
3✔
4450
        if edgeInfo == nil {
3✔
4451
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4452
                        chanID)
×
4453
        }
×
4454

4455
        // The first node is contained within the first half of the edge
4456
        // information. We only propagate the error here and below if it's
4457
        // something other than edge non-existence.
4458
        node1Pub := edgeInfo[:33]
3✔
4459
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4460
        if err != nil {
3✔
4461
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4462
                        node1Pub)
×
4463
        }
×
4464

4465
        // Similarly, the second node is contained within the latter
4466
        // half of the edge information.
4467
        node2Pub := edgeInfo[33:66]
3✔
4468
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4469
        if err != nil {
3✔
4470
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4471
                        node2Pub)
×
4472
        }
×
4473

4474
        return edge1, edge2, nil
3✔
4475
}
4476

4477
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4478
        to []byte) error {
3✔
4479

3✔
4480
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4481
        if err != nil {
3✔
4482
                return err
×
4483
        }
×
4484

4485
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4486
                return err
×
4487
        }
×
4488

4489
        var scratch [8]byte
3✔
4490
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4491
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4492
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4493
                return err
×
4494
        }
×
4495

4496
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
3✔
4497
                return err
×
4498
        }
×
4499
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
3✔
4500
                return err
×
4501
        }
×
4502
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
3✔
4503
                return err
×
4504
        }
×
4505
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
3✔
4506
                return err
×
4507
        }
×
4508
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
3✔
4509
        if err != nil {
3✔
4510
                return err
×
4511
        }
×
4512
        err = binary.Write(
3✔
4513
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
3✔
4514
        )
3✔
4515
        if err != nil {
3✔
4516
                return err
×
4517
        }
×
4518

4519
        if _, err := w.Write(to); err != nil {
3✔
4520
                return err
×
4521
        }
×
4522

4523
        // If the max_htlc field is present, we write it. To be compatible with
4524
        // older versions that wasn't aware of this field, we write it as part
4525
        // of the opaque data.
4526
        // TODO(halseth): clean up when moving to TLV.
4527
        var opaqueBuf bytes.Buffer
3✔
4528
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4529
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4530
                if err != nil {
3✔
4531
                        return err
×
4532
                }
×
4533
        }
4534

4535
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4536
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4537
        }
×
4538
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4539
                return err
×
4540
        }
×
4541

4542
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4543
                return err
×
4544
        }
×
4545

4546
        return nil
3✔
4547
}
4548

4549
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
3✔
4550
        // Deserialize the policy. Note that in case an optional field is not
3✔
4551
        // found, both an error and a populated policy object are returned.
3✔
4552
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
3✔
4553
        if deserializeErr != nil &&
3✔
4554
                !errors.Is(deserializeErr, ErrEdgePolicyOptionalFieldNotFound) {
3✔
4555

×
4556
                return nil, deserializeErr
×
4557
        }
×
4558

4559
        return edge, deserializeErr
3✔
4560
}
4561

4562
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4563
        error) {
3✔
4564

3✔
4565
        edge := &models.ChannelEdgePolicy{}
3✔
4566

3✔
4567
        var err error
3✔
4568
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4569
        if err != nil {
3✔
4570
                return nil, err
×
4571
        }
×
4572

4573
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4574
                return nil, err
×
4575
        }
×
4576

4577
        var scratch [8]byte
3✔
4578
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4579
                return nil, err
×
4580
        }
×
4581
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4582
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4583

3✔
4584
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4585
                return nil, err
×
4586
        }
×
4587
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4588
                return nil, err
×
4589
        }
×
4590
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4591
                return nil, err
×
4592
        }
×
4593

4594
        var n uint64
3✔
4595
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4596
                return nil, err
×
4597
        }
×
4598
        edge.MinHTLC = lnwire.MilliSatoshi(n)
3✔
4599

3✔
4600
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4601
                return nil, err
×
4602
        }
×
4603
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
4604

3✔
4605
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4606
                return nil, err
×
4607
        }
×
4608
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4609

3✔
4610
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4611
                return nil, err
×
4612
        }
×
4613

4614
        // We'll try and see if there are any opaque bytes left, if not, then
4615
        // we'll ignore the EOF error and return the edge as is.
4616
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4617
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4618
        )
3✔
4619
        switch {
3✔
4620
        case errors.Is(err, io.ErrUnexpectedEOF):
×
UNCOV
4621
        case errors.Is(err, io.EOF):
×
4622
        case err != nil:
×
4623
                return nil, err
×
4624
        }
4625

4626
        // See if optional fields are present.
4627
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4628
                // The max_htlc field should be at the beginning of the opaque
3✔
4629
                // bytes.
3✔
4630
                opq := edge.ExtraOpaqueData
3✔
4631

3✔
4632
                // If the max_htlc field is not present, it might be old data
3✔
4633
                // stored before this field was validated. We'll return the
3✔
4634
                // edge along with an error.
3✔
4635
                if len(opq) < 8 {
3✔
UNCOV
4636
                        return edge, ErrEdgePolicyOptionalFieldNotFound
×
UNCOV
4637
                }
×
4638

4639
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4640
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4641

3✔
4642
                // Exclude the parsed field from the rest of the opaque data.
3✔
4643
                edge.ExtraOpaqueData = opq[8:]
3✔
4644
        }
4645

4646
        return edge, nil
3✔
4647
}
4648

4649
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4650
// KVStore and a kvdb.RTx.
4651
type chanGraphNodeTx struct {
4652
        tx   kvdb.RTx
4653
        db   *KVStore
4654
        node *models.LightningNode
4655
}
4656

4657
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4658
// interface.
4659
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4660

4661
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4662
        node *models.LightningNode) *chanGraphNodeTx {
3✔
4663

3✔
4664
        return &chanGraphNodeTx{
3✔
4665
                tx:   tx,
3✔
4666
                db:   db,
3✔
4667
                node: node,
3✔
4668
        }
3✔
4669
}
3✔
4670

4671
// Node returns the raw information of the node.
4672
//
4673
// NOTE: This is a part of the NodeRTx interface.
4674
func (c *chanGraphNodeTx) Node() *models.LightningNode {
3✔
4675
        return c.node
3✔
4676
}
3✔
4677

4678
// FetchNode fetches the node with the given pub key under the same transaction
4679
// used to fetch the current node. The returned node is also a NodeRTx and any
4680
// operations on that NodeRTx will also be done under the same transaction.
4681
//
4682
// NOTE: This is a part of the NodeRTx interface.
UNCOV
4683
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
×
UNCOV
4684
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
×
UNCOV
4685
        if err != nil {
×
4686
                return nil, err
×
4687
        }
×
4688

UNCOV
4689
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4690
}
4691

4692
// ForEachChannel can be used to iterate over the node's channels under
4693
// the same transaction used to fetch the node.
4694
//
4695
// NOTE: This is a part of the NodeRTx interface.
4696
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
UNCOV
4697
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
×
UNCOV
4698

×
UNCOV
4699
        return c.db.ForEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
×
UNCOV
4700
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
×
UNCOV
4701
                        policy2 *models.ChannelEdgePolicy) error {
×
UNCOV
4702

×
UNCOV
4703
                        return f(info, policy1, policy2)
×
UNCOV
4704
                },
×
4705
        )
4706
}
4707

4708
// MakeTestGraph creates a new instance of the KVStore for testing
4709
// purposes.
4710
func MakeTestGraph(t testing.TB, modifiers ...KVStoreOptionModifier) (
UNCOV
4711
        *ChannelGraph, error) {
×
UNCOV
4712

×
UNCOV
4713
        opts := DefaultOptions()
×
UNCOV
4714
        for _, modifier := range modifiers {
×
4715
                modifier(opts)
×
4716
        }
×
4717

4718
        // Next, create KVStore for the first time.
UNCOV
4719
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
×
UNCOV
4720
        if err != nil {
×
4721
                backendCleanup()
×
4722

×
4723
                return nil, err
×
4724
        }
×
4725

UNCOV
4726
        graph, err := NewChannelGraph(&Config{
×
UNCOV
4727
                KVDB:        backend,
×
UNCOV
4728
                KVStoreOpts: modifiers,
×
UNCOV
4729
        })
×
UNCOV
4730
        if err != nil {
×
4731
                backendCleanup()
×
4732

×
4733
                return nil, err
×
4734
        }
×
4735

UNCOV
4736
        t.Cleanup(func() {
×
UNCOV
4737
                _ = backend.Close()
×
UNCOV
4738
                backendCleanup()
×
UNCOV
4739
        })
×
4740

UNCOV
4741
        return graph, nil
×
4742
}
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