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

lightningnetwork / lnd / 13517631772

25 Feb 2025 09:12AM UTC coverage: 58.815% (-0.01%) from 58.825%
13517631772

Pull #9544

github

web-flow
Merge pull request #9545 from ellemouton/graph13

graph: extract cache from CRUD [2]
Pull Request #9544: graph: move graph cache out of CRUD layer

2479 of 3249 new or added lines in 5 files covered. (76.3%)

302 existing lines in 19 files now uncovered.

136348 of 231825 relevant lines covered (58.82%)

19321.72 hits per line

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

76.05
/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) {
176✔
203

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

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

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

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

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

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

584✔
261
                        return nil
584✔
262
                }
584✔
263

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

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

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

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

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

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

293
                channelMap[key] = edge
993✔
294

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

301
        return channelMap, nil
147✔
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.
NEW
314
func (c *KVStore) Wipe() error {
×
NEW
315
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
NEW
316
                for _, tlb := range graphTopLevelBuckets {
×
NEW
317
                        err := tx.DeleteTopLevelBucket(tlb)
×
NEW
318
                        if err != nil &&
×
NEW
319
                                !errors.Is(err, kvdb.ErrBucketNotFound) {
×
NEW
320

×
NEW
321
                                return err
×
NEW
322
                        }
×
323
                }
324

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

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

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

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

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

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

383
        return nil
176✔
384
}
385

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

530
                return cb(directedChannel)
498✔
531
        }
532

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

NEW
653
                                channels[e.ChannelID] = directedChannel
×
NEW
654

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

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

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

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

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

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

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

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

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

714
        return disabledChanIDs, nil
6✔
715
}
716

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

840
        return source, nil
233✔
841
}
842

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

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

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

862
        return &node, nil
493✔
863
}
864

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

976
        return alias, nil
4✔
977
}
978

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1086
                f(r)
3✔
1087
        }
1088

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1261
                        return nil
94✔
1262
                }
1263

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

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

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

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

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

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

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

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

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

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

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

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

1329
                edge.AuthProof = proof
4✔
1330

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1479
        return chansClosed, nil
240✔
1480
}
1481

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

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

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

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

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

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

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

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

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

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

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

193✔
1562
                return nil
193✔
1563
        })
193✔
1564
        if err != nil {
263✔
NEW
1565
                return err
×
NEW
1566
        }
×
1567

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

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

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

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

NEW
1595
                        return err
×
1596
                }
1597

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

64✔
1601
                numNodesPruned++
64✔
1602
        }
1603

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

1609
        return nil
263✔
1610
}
1611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1744
        return removedChans, nil
165✔
1745
}
1746

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

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

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

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

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

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

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

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

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

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

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

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

1842
                return nil
86✔
1843
        }, func() {})
148✔
1844
        if err != nil {
210✔
1845
                return err
62✔
1846
        }
62✔
1847

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

1853
        return nil
86✔
1854
}
1855

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

1871
        return chanID, nil
4✔
1872
}
1873

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

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

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

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

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

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

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

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

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

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

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

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

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

1942
        return cid, nil
6✔
1943
}
1944

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12✔
2040
                                continue
12✔
2041
                        }
2042

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2181
        return nodesInHorizon, nil
11✔
2182
}
2183

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

121✔
2192
        var newChanIDs []uint64
121✔
2193

121✔
2194
        c.cacheMu.Lock()
121✔
2195
        defer c.cacheMu.Unlock()
121✔
2196

121✔
2197
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
242✔
2198
                edges := tx.ReadBucket(edgeBucket)
121✔
2199
                if edges == nil {
121✔
NEW
2200
                        return ErrGraphNoEdgesFound
×
NEW
2201
                }
×
2202
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
121✔
2203
                if edgeIndex == nil {
121✔
NEW
2204
                        return ErrGraphNoEdgesFound
×
NEW
2205
                }
×
2206

2207
                // Fetch the zombie index, it may not exist if no edges have
2208
                // ever been marked as zombies. If the index has been
2209
                // initialized, we will use it later to skip known zombie edges.
2210
                zombieIndex := edges.NestedReadBucket(zombieBucket)
121✔
2211

121✔
2212
                // We'll run through the set of chanIDs and collate only the
121✔
2213
                // set of channel that are unable to be found within our db.
121✔
2214
                var cidBytes [8]byte
121✔
2215
                for _, info := range chansInfo {
218✔
2216
                        scid := info.ShortChannelID.ToUint64()
97✔
2217
                        byteOrder.PutUint64(cidBytes[:], scid)
97✔
2218

97✔
2219
                        // If the edge is already known, skip it.
97✔
2220
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
117✔
2221
                                continue
20✔
2222
                        }
2223

2224
                        // If the edge is a known zombie, skip it.
2225
                        if zombieIndex != nil {
160✔
2226
                                isZombie, _, _ := isZombieEdge(
80✔
2227
                                        zombieIndex, scid,
80✔
2228
                                )
80✔
2229

80✔
2230
                                // TODO(ziggie): Make sure that for the strict
80✔
2231
                                // pruning case we compare the pubkeys and
80✔
2232
                                // whether the right timestamp is not older than
80✔
2233
                                // the `ChannelPruneExpiry`.
80✔
2234
                                //
80✔
2235
                                // NOTE: The timestamp data has no verification
80✔
2236
                                // attached to it in the `ReplyChannelRange` msg
80✔
2237
                                // so we are trusting this data at this point.
80✔
2238
                                // However it is not critical because we are
80✔
2239
                                // just removing the channel from the db when
80✔
2240
                                // the timestamps are more recent. During the
80✔
2241
                                // querying of the gossip msg verification
80✔
2242
                                // happens as usual.
80✔
2243
                                // However we should start punishing peers when
80✔
2244
                                // they don't provide us honest data ?
80✔
2245
                                isStillZombie := isZombieChan(
80✔
2246
                                        info.Node1UpdateTimestamp,
80✔
2247
                                        info.Node2UpdateTimestamp,
80✔
2248
                                )
80✔
2249

80✔
2250
                                switch {
80✔
2251
                                // If the edge is a known zombie and if we
2252
                                // would still consider it a zombie given the
2253
                                // latest update timestamps, then we skip this
2254
                                // channel.
2255
                                case isZombie && isStillZombie:
20✔
2256
                                        continue
20✔
2257

2258
                                // Otherwise, if we have marked it as a zombie
2259
                                // but the latest update timestamps could bring
2260
                                // it back from the dead, then we mark it alive,
2261
                                // and we let it be added to the set of IDs to
2262
                                // query our peer for.
2263
                                case isZombie && !isStillZombie:
17✔
2264
                                        err := c.markEdgeLiveUnsafe(tx, scid)
17✔
2265
                                        if err != nil {
17✔
NEW
2266
                                                return err
×
NEW
2267
                                        }
×
2268
                                }
2269
                        }
2270

2271
                        newChanIDs = append(newChanIDs, scid)
60✔
2272
                }
2273

2274
                return nil
121✔
2275
        }, func() {
121✔
2276
                newChanIDs = nil
121✔
2277
        })
121✔
2278
        switch {
121✔
2279
        // If we don't know of any edges yet, then we'll return the entire set
2280
        // of chan IDs specified.
NEW
2281
        case errors.Is(err, ErrGraphNoEdgesFound):
×
NEW
2282
                ogChanIDs := make([]uint64, len(chansInfo))
×
NEW
2283
                for i, info := range chansInfo {
×
NEW
2284
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
NEW
2285
                }
×
2286

NEW
2287
                return ogChanIDs, nil
×
2288

NEW
2289
        case err != nil:
×
NEW
2290
                return nil, err
×
2291
        }
2292

2293
        return newChanIDs, nil
121✔
2294
}
2295

2296
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2297
// latest received channel updates for the channel.
2298
type ChannelUpdateInfo struct {
2299
        // ShortChannelID is the SCID identifier of the channel.
2300
        ShortChannelID lnwire.ShortChannelID
2301

2302
        // Node1UpdateTimestamp is the timestamp of the latest received update
2303
        // from the node 1 channel peer. This will be set to zero time if no
2304
        // update has yet been received from this node.
2305
        Node1UpdateTimestamp time.Time
2306

2307
        // Node2UpdateTimestamp is the timestamp of the latest received update
2308
        // from the node 2 channel peer. This will be set to zero time if no
2309
        // update has yet been received from this node.
2310
        Node2UpdateTimestamp time.Time
2311
}
2312

2313
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2314
// timestamps with zero seconds unix timestamp which equals
2315
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2316
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2317
        node2Timestamp time.Time) ChannelUpdateInfo {
221✔
2318

221✔
2319
        chanInfo := ChannelUpdateInfo{
221✔
2320
                ShortChannelID:       scid,
221✔
2321
                Node1UpdateTimestamp: node1Timestamp,
221✔
2322
                Node2UpdateTimestamp: node2Timestamp,
221✔
2323
        }
221✔
2324

221✔
2325
        if node1Timestamp.IsZero() {
432✔
2326
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
211✔
2327
        }
211✔
2328

2329
        if node2Timestamp.IsZero() {
432✔
2330
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
211✔
2331
        }
211✔
2332

2333
        return chanInfo
221✔
2334
}
2335

2336
// BlockChannelRange represents a range of channels for a given block height.
2337
type BlockChannelRange struct {
2338
        // Height is the height of the block all of the channels below were
2339
        // included in.
2340
        Height uint32
2341

2342
        // Channels is the list of channels identified by their short ID
2343
        // representation known to us that were included in the block height
2344
        // above. The list may include channel update timestamp information if
2345
        // requested.
2346
        Channels []ChannelUpdateInfo
2347
}
2348

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

14✔
2359
        startChanID := &lnwire.ShortChannelID{
14✔
2360
                BlockHeight: startHeight,
14✔
2361
        }
14✔
2362

14✔
2363
        endChanID := lnwire.ShortChannelID{
14✔
2364
                BlockHeight: endHeight,
14✔
2365
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2366
                TxPosition:  math.MaxUint16,
14✔
2367
        }
14✔
2368

14✔
2369
        // As we need to perform a range scan, we'll convert the starting and
14✔
2370
        // ending height to their corresponding values when encoded using short
14✔
2371
        // channel ID's.
14✔
2372
        var chanIDStart, chanIDEnd [8]byte
14✔
2373
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
14✔
2374
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
14✔
2375

14✔
2376
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2377
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2378
                edges := tx.ReadBucket(edgeBucket)
14✔
2379
                if edges == nil {
14✔
NEW
2380
                        return ErrGraphNoEdgesFound
×
NEW
2381
                }
×
2382
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2383
                if edgeIndex == nil {
14✔
NEW
2384
                        return ErrGraphNoEdgesFound
×
NEW
2385
                }
×
2386

2387
                cursor := edgeIndex.ReadCursor()
14✔
2388

14✔
2389
                // We'll now iterate through the database, and find each
14✔
2390
                // channel ID that resides within the specified range.
14✔
2391
                //
14✔
2392
                //nolint:ll
14✔
2393
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
14✔
2394
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
61✔
2395
                        // Don't send alias SCIDs during gossip sync.
47✔
2396
                        edgeReader := bytes.NewReader(v)
47✔
2397
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
47✔
2398
                        if err != nil {
47✔
NEW
2399
                                return err
×
NEW
2400
                        }
×
2401

2402
                        if edgeInfo.AuthProof == nil {
50✔
2403
                                continue
3✔
2404
                        }
2405

2406
                        // This channel ID rests within the target range, so
2407
                        // we'll add it to our returned set.
2408
                        rawCid := byteOrder.Uint64(k)
47✔
2409
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2410

47✔
2411
                        chanInfo := NewChannelUpdateInfo(
47✔
2412
                                cid, time.Time{}, time.Time{},
47✔
2413
                        )
47✔
2414

47✔
2415
                        if !withTimestamps {
69✔
2416
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2417
                                        channelsPerBlock[cid.BlockHeight],
22✔
2418
                                        chanInfo,
22✔
2419
                                )
22✔
2420

22✔
2421
                                continue
22✔
2422
                        }
2423

2424
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2425

25✔
2426
                        rawPolicy := edges.Get(node1Key)
25✔
2427
                        if len(rawPolicy) != 0 {
34✔
2428
                                r := bytes.NewReader(rawPolicy)
9✔
2429

9✔
2430
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2431
                                if err != nil && !errors.Is(
9✔
2432
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2433
                                ) {
9✔
NEW
2434

×
NEW
2435
                                        return err
×
NEW
2436
                                }
×
2437

2438
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2439
                        }
2440

2441
                        rawPolicy = edges.Get(node2Key)
25✔
2442
                        if len(rawPolicy) != 0 {
39✔
2443
                                r := bytes.NewReader(rawPolicy)
14✔
2444

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

×
NEW
2450
                                        return err
×
NEW
2451
                                }
×
2452

2453
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2454
                        }
2455

2456
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2457
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2458
                        )
25✔
2459
                }
2460

2461
                return nil
14✔
2462
        }, func() {
14✔
2463
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2464
        })
14✔
2465

2466
        switch {
14✔
2467
        // If we don't know of any channels yet, then there's nothing to
2468
        // filter, so we'll return an empty slice.
2469
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
6✔
2470
                return nil, nil
6✔
2471

NEW
2472
        case err != nil:
×
NEW
2473
                return nil, err
×
2474
        }
2475

2476
        // Return the channel ranges in ascending block height order.
2477
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2478
        for block := range channelsPerBlock {
36✔
2479
                blocks = append(blocks, block)
25✔
2480
        }
25✔
2481
        sort.Slice(blocks, func(i, j int) bool {
33✔
2482
                return blocks[i] < blocks[j]
22✔
2483
        })
22✔
2484

2485
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2486
        for _, block := range blocks {
36✔
2487
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2488
                        Height:   block,
25✔
2489
                        Channels: channelsPerBlock[block],
25✔
2490
                })
25✔
2491
        }
25✔
2492

2493
        return channelRanges, nil
11✔
2494
}
2495

2496
// FetchChanInfos returns the set of channel edges that correspond to the passed
2497
// channel ID's. If an edge is the query is unknown to the database, it will
2498
// skipped and the result will contain only those edges that exist at the time
2499
// of the query. This can be used to respond to peer queries that are seeking to
2500
// fill in gaps in their view of the channel graph.
2501
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
6✔
2502
        return c.fetchChanInfos(nil, chanIDs)
6✔
2503
}
6✔
2504

2505
// fetchChanInfos returns the set of channel edges that correspond to the passed
2506
// channel ID's. If an edge is the query is unknown to the database, it will
2507
// skipped and the result will contain only those edges that exist at the time
2508
// of the query. This can be used to respond to peer queries that are seeking to
2509
// fill in gaps in their view of the channel graph.
2510
//
2511
// NOTE: An optional transaction may be provided. If none is provided, then a
2512
// new one will be created.
2513
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2514
        []ChannelEdge, error) {
24✔
2515
        // TODO(roasbeef): sort cids?
24✔
2516

24✔
2517
        var (
24✔
2518
                chanEdges []ChannelEdge
24✔
2519
                cidBytes  [8]byte
24✔
2520
        )
24✔
2521

24✔
2522
        fetchChanInfos := func(tx kvdb.RTx) error {
48✔
2523
                edges := tx.ReadBucket(edgeBucket)
24✔
2524
                if edges == nil {
24✔
NEW
2525
                        return ErrGraphNoEdgesFound
×
NEW
2526
                }
×
2527
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
24✔
2528
                if edgeIndex == nil {
24✔
NEW
2529
                        return ErrGraphNoEdgesFound
×
NEW
2530
                }
×
2531
                nodes := tx.ReadBucket(nodeBucket)
24✔
2532
                if nodes == nil {
24✔
NEW
2533
                        return ErrGraphNotFound
×
NEW
2534
                }
×
2535

2536
                for _, cid := range chanIDs {
55✔
2537
                        byteOrder.PutUint64(cidBytes[:], cid)
31✔
2538

31✔
2539
                        // First, we'll fetch the static edge information. If
31✔
2540
                        // the edge is unknown, we will skip the edge and
31✔
2541
                        // continue gathering all known edges.
31✔
2542
                        edgeInfo, err := fetchChanEdgeInfo(
31✔
2543
                                edgeIndex, cidBytes[:],
31✔
2544
                        )
31✔
2545
                        switch {
31✔
2546
                        case errors.Is(err, ErrEdgeNotFound):
20✔
2547
                                continue
20✔
NEW
2548
                        case err != nil:
×
NEW
2549
                                return err
×
2550
                        }
2551

2552
                        // With the static information obtained, we'll now
2553
                        // fetch the dynamic policy info.
2554
                        edge1, edge2, err := fetchChanEdgePolicies(
11✔
2555
                                edgeIndex, edges, cidBytes[:],
11✔
2556
                        )
11✔
2557
                        if err != nil {
11✔
NEW
2558
                                return err
×
NEW
2559
                        }
×
2560

2561
                        node1, err := fetchLightningNode(
11✔
2562
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2563
                        )
11✔
2564
                        if err != nil {
11✔
NEW
2565
                                return err
×
NEW
2566
                        }
×
2567

2568
                        node2, err := fetchLightningNode(
11✔
2569
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2570
                        )
11✔
2571
                        if err != nil {
11✔
NEW
2572
                                return err
×
NEW
2573
                        }
×
2574

2575
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2576
                                Info:    &edgeInfo,
11✔
2577
                                Policy1: edge1,
11✔
2578
                                Policy2: edge2,
11✔
2579
                                Node1:   &node1,
11✔
2580
                                Node2:   &node2,
11✔
2581
                        })
11✔
2582
                }
2583

2584
                return nil
24✔
2585
        }
2586

2587
        if tx == nil {
31✔
2588
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2589
                        chanEdges = nil
7✔
2590
                })
7✔
2591
                if err != nil {
7✔
NEW
2592
                        return nil, err
×
NEW
2593
                }
×
2594

2595
                return chanEdges, nil
7✔
2596
        }
2597

2598
        err := fetchChanInfos(tx)
17✔
2599
        if err != nil {
17✔
NEW
2600
                return nil, err
×
NEW
2601
        }
×
2602

2603
        return chanEdges, nil
17✔
2604
}
2605

2606
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2607
        edge1, edge2 *models.ChannelEdgePolicy) error {
142✔
2608

142✔
2609
        // First, we'll fetch the edge update index bucket which currently
142✔
2610
        // stores an entry for the channel we're about to delete.
142✔
2611
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
142✔
2612
        if updateIndex == nil {
142✔
NEW
2613
                // No edges in bucket, return early.
×
NEW
2614
                return nil
×
NEW
2615
        }
×
2616

2617
        // Now that we have the bucket, we'll attempt to construct a template
2618
        // for the index key: updateTime || chanid.
2619
        var indexKey [8 + 8]byte
142✔
2620
        byteOrder.PutUint64(indexKey[8:], chanID)
142✔
2621

142✔
2622
        // With the template constructed, we'll attempt to delete an entry that
142✔
2623
        // would have been created by both edges: we'll alternate the update
142✔
2624
        // times, as one may had overridden the other.
142✔
2625
        if edge1 != nil {
155✔
2626
                byteOrder.PutUint64(
13✔
2627
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
13✔
2628
                )
13✔
2629
                if err := updateIndex.Delete(indexKey[:]); err != nil {
13✔
NEW
2630
                        return err
×
NEW
2631
                }
×
2632
        }
2633

2634
        // We'll also attempt to delete the entry that may have been created by
2635
        // the second edge.
2636
        if edge2 != nil {
157✔
2637
                byteOrder.PutUint64(
15✔
2638
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
15✔
2639
                )
15✔
2640
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
NEW
2641
                        return err
×
NEW
2642
                }
×
2643
        }
2644

2645
        return nil
142✔
2646
}
2647

2648
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2649
// cache. It then goes on to delete any policy info and edge info for this
2650
// channel from the DB and finally, if isZombie is true, it will add an entry
2651
// for this channel in the zombie index.
2652
//
2653
// NOTE: this method MUST only be called if the cacheMu has already been
2654
// acquired.
2655
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2656
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2657
        strictZombie bool) error {
204✔
2658

204✔
2659
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
204✔
2660
        if err != nil {
266✔
2661
                return err
62✔
2662
        }
62✔
2663

2664
        if c.graphCache != nil {
284✔
2665
                c.graphCache.RemoveChannel(
142✔
2666
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
142✔
2667
                        edgeInfo.ChannelID,
142✔
2668
                )
142✔
2669
        }
142✔
2670

2671
        // We'll also remove the entry in the edge update index bucket before
2672
        // we delete the edges themselves so we can access their last update
2673
        // times.
2674
        cid := byteOrder.Uint64(chanID)
142✔
2675
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
142✔
2676
        if err != nil {
142✔
NEW
2677
                return err
×
NEW
2678
        }
×
2679
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
142✔
2680
        if err != nil {
142✔
NEW
2681
                return err
×
NEW
2682
        }
×
2683

2684
        // The edge key is of the format pubKey || chanID. First we construct
2685
        // the latter half, populating the channel ID.
2686
        var edgeKey [33 + 8]byte
142✔
2687
        copy(edgeKey[33:], chanID)
142✔
2688

142✔
2689
        // With the latter half constructed, copy over the first public key to
142✔
2690
        // delete the edge in this direction, then the second to delete the
142✔
2691
        // edge in the opposite direction.
142✔
2692
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
142✔
2693
        if edges.Get(edgeKey[:]) != nil {
284✔
2694
                if err := edges.Delete(edgeKey[:]); err != nil {
142✔
NEW
2695
                        return err
×
NEW
2696
                }
×
2697
        }
2698
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
142✔
2699
        if edges.Get(edgeKey[:]) != nil {
284✔
2700
                if err := edges.Delete(edgeKey[:]); err != nil {
142✔
NEW
2701
                        return err
×
NEW
2702
                }
×
2703
        }
2704

2705
        // As part of deleting the edge we also remove all disabled entries
2706
        // from the edgePolicyDisabledIndex bucket. We do that for both
2707
        // directions.
2708
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
142✔
2709
        if err != nil {
142✔
NEW
2710
                return err
×
NEW
2711
        }
×
2712
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
142✔
2713
        if err != nil {
142✔
NEW
2714
                return err
×
NEW
2715
        }
×
2716

2717
        // With the edge data deleted, we can purge the information from the two
2718
        // edge indexes.
2719
        if err := edgeIndex.Delete(chanID); err != nil {
142✔
NEW
2720
                return err
×
NEW
2721
        }
×
2722
        var b bytes.Buffer
142✔
2723
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
142✔
NEW
2724
                return err
×
NEW
2725
        }
×
2726
        if err := chanIndex.Delete(b.Bytes()); err != nil {
142✔
NEW
2727
                return err
×
NEW
2728
        }
×
2729

2730
        // Finally, we'll mark the edge as a zombie within our index if it's
2731
        // being removed due to the channel becoming a zombie. We do this to
2732
        // ensure we don't store unnecessary data for spent channels.
2733
        if !isZombie {
261✔
2734
                return nil
119✔
2735
        }
119✔
2736

2737
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
26✔
2738
        if strictZombie {
29✔
2739
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2740
        }
3✔
2741

2742
        return markEdgeZombie(
26✔
2743
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
26✔
2744
        )
26✔
2745
}
2746

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

3✔
2766
        switch {
3✔
2767
        // If we don't have either edge policy, we'll return both pubkeys so
2768
        // that the channel can be resurrected by either party.
NEW
2769
        case e1 == nil && e2 == nil:
×
NEW
2770
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2771

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

2779
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2780
        // return a blank pubkey for edge1. In this case, only an update from
2781
        // edge2 can resurect the channel.
2782
        default:
2✔
2783
                return [33]byte{}, info.NodeKey2Bytes
2✔
2784
        }
2785
}
2786

2787
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2788
// within the database for the referenced channel. The `flags` attribute within
2789
// the ChannelEdgePolicy determines which of the directed edges are being
2790
// updated. If the flag is 1, then the first node's information is being
2791
// updated, otherwise it's the second node's information. The node ordering is
2792
// determined by the lexicographical ordering of the identity public keys of the
2793
// nodes on either side of the channel.
2794
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2795
        op ...batch.SchedulerOption) error {
2,666✔
2796

2,666✔
2797
        var (
2,666✔
2798
                isUpdate1    bool
2,666✔
2799
                edgeNotFound bool
2,666✔
2800
        )
2,666✔
2801

2,666✔
2802
        r := &batch.Request{
2,666✔
2803
                Reset: func() {
5,332✔
2804
                        isUpdate1 = false
2,666✔
2805
                        edgeNotFound = false
2,666✔
2806
                },
2,666✔
2807
                Update: func(tx kvdb.RwTx) error {
2,666✔
2808
                        var err error
2,666✔
2809
                        isUpdate1, err = updateEdgePolicy(
2,666✔
2810
                                tx, edge, c.graphCache,
2,666✔
2811
                        )
2,666✔
2812

2,666✔
2813
                        if err != nil {
2,669✔
2814
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
3✔
2815
                        }
3✔
2816

2817
                        // Silence ErrEdgeNotFound so that the batch can
2818
                        // succeed, but propagate the error via local state.
2819
                        if errors.Is(err, ErrEdgeNotFound) {
2,669✔
2820
                                edgeNotFound = true
3✔
2821
                                return nil
3✔
2822
                        }
3✔
2823

2824
                        return err
2,663✔
2825
                },
2826
                OnCommit: func(err error) error {
2,666✔
2827
                        switch {
2,666✔
NEW
2828
                        case err != nil:
×
NEW
2829
                                return err
×
2830
                        case edgeNotFound:
3✔
2831
                                return ErrEdgeNotFound
3✔
2832
                        default:
2,663✔
2833
                                c.updateEdgeCache(edge, isUpdate1)
2,663✔
2834
                                return nil
2,663✔
2835
                        }
2836
                },
2837
        }
2838

2839
        for _, f := range op {
2,669✔
2840
                f(r)
3✔
2841
        }
3✔
2842

2843
        return c.chanScheduler.Execute(r)
2,666✔
2844
}
2845

2846
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2847
        isUpdate1 bool) {
2,663✔
2848

2,663✔
2849
        // If an entry for this channel is found in reject cache, we'll modify
2,663✔
2850
        // the entry with the updated timestamp for the direction that was just
2,663✔
2851
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,663✔
2852
        // during the next query for this edge.
2,663✔
2853
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,671✔
2854
                if isUpdate1 {
14✔
2855
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2856
                } else {
11✔
2857
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2858
                }
5✔
2859
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2860
        }
2861

2862
        // If an entry for this channel is found in channel cache, we'll modify
2863
        // the entry with the updated policy for the direction that was just
2864
        // written. If the edge doesn't exist, we'll defer loading the info and
2865
        // policies and lazily read from disk during the next query.
2866
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,666✔
2867
                if isUpdate1 {
6✔
2868
                        channel.Policy1 = e
3✔
2869
                } else {
6✔
2870
                        channel.Policy2 = e
3✔
2871
                }
3✔
2872
                c.chanCache.insert(e.ChannelID, channel)
3✔
2873
        }
2874
}
2875

2876
// updateEdgePolicy attempts to update an edge's policy within the relevant
2877
// buckets using an existing database transaction. The returned boolean will be
2878
// true if the updated policy belongs to node1, and false if the policy belonged
2879
// to node2.
2880
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2881
        graphCache *GraphCache) (bool, error) {
2,666✔
2882

2,666✔
2883
        edges := tx.ReadWriteBucket(edgeBucket)
2,666✔
2884
        if edges == nil {
2,666✔
NEW
2885
                return false, ErrEdgeNotFound
×
NEW
2886
        }
×
2887
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,666✔
2888
        if edgeIndex == nil {
2,666✔
NEW
2889
                return false, ErrEdgeNotFound
×
NEW
2890
        }
×
2891

2892
        // Create the channelID key be converting the channel ID
2893
        // integer into a byte slice.
2894
        var chanID [8]byte
2,666✔
2895
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,666✔
2896

2,666✔
2897
        // With the channel ID, we then fetch the value storing the two
2,666✔
2898
        // nodes which connect this channel edge.
2,666✔
2899
        nodeInfo := edgeIndex.Get(chanID[:])
2,666✔
2900
        if nodeInfo == nil {
2,669✔
2901
                return false, ErrEdgeNotFound
3✔
2902
        }
3✔
2903

2904
        // Depending on the flags value passed above, either the first
2905
        // or second edge policy is being updated.
2906
        var fromNode, toNode []byte
2,663✔
2907
        var isUpdate1 bool
2,663✔
2908
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,000✔
2909
                fromNode = nodeInfo[:33]
1,337✔
2910
                toNode = nodeInfo[33:66]
1,337✔
2911
                isUpdate1 = true
1,337✔
2912
        } else {
2,666✔
2913
                fromNode = nodeInfo[33:66]
1,329✔
2914
                toNode = nodeInfo[:33]
1,329✔
2915
                isUpdate1 = false
1,329✔
2916
        }
1,329✔
2917

2918
        // Finally, with the direction of the edge being updated
2919
        // identified, we update the on-disk edge representation.
2920
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,663✔
2921
        if err != nil {
2,663✔
NEW
2922
                return false, err
×
NEW
2923
        }
×
2924

2925
        var (
2,663✔
2926
                fromNodePubKey route.Vertex
2,663✔
2927
                toNodePubKey   route.Vertex
2,663✔
2928
        )
2,663✔
2929
        copy(fromNodePubKey[:], fromNode)
2,663✔
2930
        copy(toNodePubKey[:], toNode)
2,663✔
2931

2,663✔
2932
        if graphCache != nil {
4,940✔
2933
                graphCache.UpdatePolicy(
2,277✔
2934
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,277✔
2935
                )
2,277✔
2936
        }
2,277✔
2937

2938
        return isUpdate1, nil
2,663✔
2939
}
2940

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

16✔
2947
        // In order to determine whether this node is publicly advertised within
16✔
2948
        // the graph, we'll need to look at all of its edges and check whether
16✔
2949
        // they extend to any other node than the source node. errDone will be
16✔
2950
        // used to terminate the check early.
16✔
2951
        nodeIsPublic := false
16✔
2952
        errDone := errors.New("done")
16✔
2953
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
16✔
2954
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
16✔
2955
                _ *models.ChannelEdgePolicy) error {
29✔
2956

13✔
2957
                // If this edge doesn't extend to the source node, we'll
13✔
2958
                // terminate our search as we can now conclude that the node is
13✔
2959
                // publicly advertised within the graph due to the local node
13✔
2960
                // knowing of the current edge.
13✔
2961
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
2962
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
2963

6✔
2964
                        nodeIsPublic = true
6✔
2965
                        return errDone
6✔
2966
                }
6✔
2967

2968
                // Since the edge _does_ extend to the source node, we'll also
2969
                // need to ensure that this is a public edge.
2970
                if info.AuthProof != nil {
19✔
2971
                        nodeIsPublic = true
9✔
2972
                        return errDone
9✔
2973
                }
9✔
2974

2975
                // Otherwise, we'll continue our search.
2976
                return nil
4✔
2977
        })
2978
        if err != nil && !errors.Is(err, errDone) {
16✔
NEW
2979
                return false, err
×
NEW
2980
        }
×
2981

2982
        return nodeIsPublic, nil
16✔
2983
}
2984

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

3,443✔
2992
        return c.fetchLightningNode(tx, nodePub)
3,443✔
2993
}
3,443✔
2994

2995
// FetchLightningNode attempts to look up a target node by its identity public
2996
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2997
// returned.
2998
func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
2999
        *models.LightningNode, error) {
155✔
3000

155✔
3001
        return c.fetchLightningNode(nil, nodePub)
155✔
3002
}
155✔
3003

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

3,595✔
3011
        var node *models.LightningNode
3,595✔
3012
        fetch := func(tx kvdb.RTx) error {
7,190✔
3013
                // First grab the nodes bucket which stores the mapping from
3,595✔
3014
                // pubKey to node information.
3,595✔
3015
                nodes := tx.ReadBucket(nodeBucket)
3,595✔
3016
                if nodes == nil {
3,595✔
NEW
3017
                        return ErrGraphNotFound
×
NEW
3018
                }
×
3019

3020
                // If a key for this serialized public key isn't found, then
3021
                // the target node doesn't exist within the database.
3022
                nodeBytes := nodes.Get(nodePub[:])
3,595✔
3023
                if nodeBytes == nil {
3,612✔
3024
                        return ErrGraphNodeNotFound
17✔
3025
                }
17✔
3026

3027
                // If the node is found, then we can de deserialize the node
3028
                // information to return to the user.
3029
                nodeReader := bytes.NewReader(nodeBytes)
3,581✔
3030
                n, err := deserializeLightningNode(nodeReader)
3,581✔
3031
                if err != nil {
3,581✔
NEW
3032
                        return err
×
NEW
3033
                }
×
3034

3035
                node = &n
3,581✔
3036

3,581✔
3037
                return nil
3,581✔
3038
        }
3039

3040
        if tx == nil {
3,753✔
3041
                err := kvdb.View(
158✔
3042
                        c.db, fetch, func() {
316✔
3043
                                node = nil
158✔
3044
                        },
158✔
3045
                )
3046
                if err != nil {
164✔
3047
                        return nil, err
6✔
3048
                }
6✔
3049

3050
                return node, nil
155✔
3051
        }
3052

3053
        err := fetch(tx)
3,437✔
3054
        if err != nil {
3,448✔
3055
                return nil, err
11✔
3056
        }
11✔
3057

3058
        return node, nil
3,426✔
3059
}
3060

3061
// HasLightningNode determines if the graph has a vertex identified by the
3062
// target node identity public key. If the node exists in the database, a
3063
// timestamp of when the data for the node was lasted updated is returned along
3064
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3065
// boolean.
3066
func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3067
        error) {
19✔
3068

19✔
3069
        var (
19✔
3070
                updateTime time.Time
19✔
3071
                exists     bool
19✔
3072
        )
19✔
3073

19✔
3074
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
38✔
3075
                // First grab the nodes bucket which stores the mapping from
19✔
3076
                // pubKey to node information.
19✔
3077
                nodes := tx.ReadBucket(nodeBucket)
19✔
3078
                if nodes == nil {
19✔
NEW
3079
                        return ErrGraphNotFound
×
NEW
3080
                }
×
3081

3082
                // If a key for this serialized public key isn't found, we can
3083
                // exit early.
3084
                nodeBytes := nodes.Get(nodePub[:])
19✔
3085
                if nodeBytes == nil {
25✔
3086
                        exists = false
6✔
3087
                        return nil
6✔
3088
                }
6✔
3089

3090
                // Otherwise we continue on to obtain the time stamp
3091
                // representing the last time the data for this node was
3092
                // updated.
3093
                nodeReader := bytes.NewReader(nodeBytes)
16✔
3094
                node, err := deserializeLightningNode(nodeReader)
16✔
3095
                if err != nil {
16✔
NEW
3096
                        return err
×
NEW
3097
                }
×
3098

3099
                exists = true
16✔
3100
                updateTime = node.LastUpdate
16✔
3101

16✔
3102
                return nil
16✔
3103
        }, func() {
19✔
3104
                updateTime = time.Time{}
19✔
3105
                exists = false
19✔
3106
        })
19✔
3107
        if err != nil {
19✔
NEW
3108
                return time.Time{}, exists, err
×
NEW
3109
        }
×
3110

3111
        return updateTime, exists, nil
19✔
3112
}
3113

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

1,249✔
3120
        traversal := func(tx kvdb.RTx) error {
2,498✔
3121
                edges := tx.ReadBucket(edgeBucket)
1,249✔
3122
                if edges == nil {
1,249✔
NEW
3123
                        return ErrGraphNotFound
×
NEW
3124
                }
×
3125
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,249✔
3126
                if edgeIndex == nil {
1,249✔
NEW
3127
                        return ErrGraphNoEdgesFound
×
NEW
3128
                }
×
3129

3130
                // In order to reach all the edges for this node, we take
3131
                // advantage of the construction of the key-space within the
3132
                // edge bucket. The keys are stored in the form: pubKey ||
3133
                // chanID. Therefore, starting from a chanID of zero, we can
3134
                // scan forward in the bucket, grabbing all the edges for the
3135
                // node. Once the prefix no longer matches, then we know we're
3136
                // done.
3137
                var nodeStart [33 + 8]byte
1,249✔
3138
                copy(nodeStart[:], nodePub)
1,249✔
3139
                copy(nodeStart[33:], chanStart[:])
1,249✔
3140

1,249✔
3141
                // Starting from the key pubKey || 0, we seek forward in the
1,249✔
3142
                // bucket until the retrieved key no longer has the public key
1,249✔
3143
                // as its prefix. This indicates that we've stepped over into
1,249✔
3144
                // another node's edges, so we can terminate our scan.
1,249✔
3145
                edgeCursor := edges.ReadCursor()
1,249✔
3146
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
4,902✔
3147
                        // If the prefix still matches, the channel id is
3,653✔
3148
                        // returned in nodeEdge. Channel id is used to lookup
3,653✔
3149
                        // the node at the other end of the channel and both
3,653✔
3150
                        // edge policies.
3,653✔
3151
                        chanID := nodeEdge[33:]
3,653✔
3152
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,653✔
3153
                        if err != nil {
3,653✔
NEW
3154
                                return err
×
NEW
3155
                        }
×
3156

3157
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,653✔
3158
                                edges, chanID, nodePub,
3,653✔
3159
                        )
3,653✔
3160
                        if err != nil {
3,653✔
NEW
3161
                                return err
×
NEW
3162
                        }
×
3163

3164
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,653✔
3165
                        if err != nil {
3,653✔
NEW
3166
                                return err
×
NEW
3167
                        }
×
3168

3169
                        incomingPolicy, err := fetchChanEdgePolicy(
3,653✔
3170
                                edges, chanID, otherNode[:],
3,653✔
3171
                        )
3,653✔
3172
                        if err != nil {
3,653✔
NEW
3173
                                return err
×
NEW
3174
                        }
×
3175

3176
                        // Finally, we execute the callback.
3177
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,653✔
3178
                        if err != nil {
3,665✔
3179
                                return err
12✔
3180
                        }
12✔
3181
                }
3182

3183
                return nil
1,240✔
3184
        }
3185

3186
        // If no transaction was provided, then we'll create a new transaction
3187
        // to execute the transaction within.
3188
        if tx == nil {
1,261✔
3189
                return kvdb.View(db, traversal, func() {})
24✔
3190
        }
3191

3192
        // Otherwise, we re-use the existing transaction to execute the graph
3193
        // traversal.
3194
        return traversal(tx)
1,240✔
3195
}
3196

3197
// ForEachNodeChannel iterates through all channels of the given node,
3198
// executing the passed callback with an edge info structure and the policies
3199
// of each end of the channel. The first edge policy is the outgoing edge *to*
3200
// the connecting node, while the second is the incoming edge *from* the
3201
// connecting node. If the callback returns an error, then the iteration is
3202
// halted with the error propagated back up to the caller.
3203
//
3204
// Unknown policies are passed into the callback as nil values.
3205
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3206
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3207
                *models.ChannelEdgePolicy) error) error {
9✔
3208

9✔
3209
        return nodeTraversal(nil, nodePub[:], c.db, cb)
9✔
3210
}
9✔
3211

3212
// ForEachNodeChannelTx iterates through all channels of the given node,
3213
// executing the passed callback with an edge info structure and the policies
3214
// of each end of the channel. The first edge policy is the outgoing edge *to*
3215
// the connecting node, while the second is the incoming edge *from* the
3216
// connecting node. If the callback returns an error, then the iteration is
3217
// halted with the error propagated back up to the caller.
3218
//
3219
// Unknown policies are passed into the callback as nil values.
3220
//
3221
// If the caller wishes to re-use an existing boltdb transaction, then it
3222
// should be passed as the first argument.  Otherwise, the first argument should
3223
// be nil and a fresh transaction will be created to execute the graph
3224
// traversal.
3225
func (c *KVStore) ForEachNodeChannelTx(tx kvdb.RTx,
3226
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3227
                *models.ChannelEdgePolicy,
3228
                *models.ChannelEdgePolicy) error) error {
1,001✔
3229

1,001✔
3230
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3231
}
1,001✔
3232

3233
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3234
// the target node in the channel. This is useful when one knows the pubkey of
3235
// one of the nodes, and wishes to obtain the full LightningNode for the other
3236
// end of the channel.
3237
func (c *KVStore) FetchOtherNode(tx kvdb.RTx,
3238
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3239
        *models.LightningNode, error) {
3✔
3240

3✔
3241
        // Ensure that the node passed in is actually a member of the channel.
3✔
3242
        var targetNodeBytes [33]byte
3✔
3243
        switch {
3✔
3244
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3245
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3246
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3247
                targetNodeBytes = channel.NodeKey1Bytes
3✔
NEW
3248
        default:
×
NEW
3249
                return nil, fmt.Errorf("node not participating in this channel")
×
3250
        }
3251

3252
        var targetNode *models.LightningNode
3✔
3253
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3254
                // First grab the nodes bucket which stores the mapping from
3✔
3255
                // pubKey to node information.
3✔
3256
                nodes := tx.ReadBucket(nodeBucket)
3✔
3257
                if nodes == nil {
3✔
NEW
3258
                        return ErrGraphNotFound
×
NEW
3259
                }
×
3260

3261
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3262
                if err != nil {
3✔
NEW
3263
                        return err
×
NEW
3264
                }
×
3265

3266
                targetNode = &node
3✔
3267

3✔
3268
                return nil
3✔
3269
        }
3270

3271
        // If the transaction is nil, then we'll need to create a new one,
3272
        // otherwise we can use the existing db transaction.
3273
        var err error
3✔
3274
        if tx == nil {
3✔
NEW
3275
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
NEW
3276
                        targetNode = nil
×
NEW
3277
                })
×
3278
        } else {
3✔
3279
                err = fetchNodeFunc(tx)
3✔
3280
        }
3✔
3281

3282
        return targetNode, err
3✔
3283
}
3284

3285
// computeEdgePolicyKeys is a helper function that can be used to compute the
3286
// keys used to index the channel edge policy info for the two nodes of the
3287
// edge. The keys for node 1 and node 2 are returned respectively.
3288
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
25✔
3289
        var (
25✔
3290
                node1Key [33 + 8]byte
25✔
3291
                node2Key [33 + 8]byte
25✔
3292
        )
25✔
3293

25✔
3294
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3295
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3296

25✔
3297
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3298
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3299

25✔
3300
        return node1Key[:], node2Key[:]
25✔
3301
}
25✔
3302

3303
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3304
// the channel identified by the funding outpoint. If the channel can't be
3305
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3306
// information for the channel itself is returned as well as two structs that
3307
// contain the routing policies for the channel in either direction.
3308
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3309
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3310
        *models.ChannelEdgePolicy, error) {
14✔
3311

14✔
3312
        var (
14✔
3313
                edgeInfo *models.ChannelEdgeInfo
14✔
3314
                policy1  *models.ChannelEdgePolicy
14✔
3315
                policy2  *models.ChannelEdgePolicy
14✔
3316
        )
14✔
3317

14✔
3318
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3319
                // First, grab the node bucket. This will be used to populate
14✔
3320
                // the Node pointers in each edge read from disk.
14✔
3321
                nodes := tx.ReadBucket(nodeBucket)
14✔
3322
                if nodes == nil {
14✔
NEW
3323
                        return ErrGraphNotFound
×
NEW
3324
                }
×
3325

3326
                // Next, grab the edge bucket which stores the edges, and also
3327
                // the index itself so we can group the directed edges together
3328
                // logically.
3329
                edges := tx.ReadBucket(edgeBucket)
14✔
3330
                if edges == nil {
14✔
NEW
3331
                        return ErrGraphNoEdgesFound
×
NEW
3332
                }
×
3333
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
3334
                if edgeIndex == nil {
14✔
NEW
3335
                        return ErrGraphNoEdgesFound
×
NEW
3336
                }
×
3337

3338
                // If the channel's outpoint doesn't exist within the outpoint
3339
                // index, then the edge does not exist.
3340
                chanIndex := edges.NestedReadBucket(channelPointBucket)
14✔
3341
                if chanIndex == nil {
14✔
NEW
3342
                        return ErrGraphNoEdgesFound
×
NEW
3343
                }
×
3344
                var b bytes.Buffer
14✔
3345
                if err := WriteOutpoint(&b, op); err != nil {
14✔
NEW
3346
                        return err
×
NEW
3347
                }
×
3348
                chanID := chanIndex.Get(b.Bytes())
14✔
3349
                if chanID == nil {
27✔
3350
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
13✔
3351
                }
13✔
3352

3353
                // If the channel is found to exists, then we'll first retrieve
3354
                // the general information for the channel.
3355
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
4✔
3356
                if err != nil {
4✔
NEW
3357
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
NEW
3358
                }
×
3359
                edgeInfo = &edge
4✔
3360

4✔
3361
                // Once we have the information about the channels' parameters,
4✔
3362
                // we'll fetch the routing policies for each for the directed
4✔
3363
                // edges.
4✔
3364
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
4✔
3365
                if err != nil {
4✔
NEW
3366
                        return fmt.Errorf("failed to find policy: %w", err)
×
NEW
3367
                }
×
3368

3369
                policy1 = e1
4✔
3370
                policy2 = e2
4✔
3371

4✔
3372
                return nil
4✔
3373
        }, func() {
14✔
3374
                edgeInfo = nil
14✔
3375
                policy1 = nil
14✔
3376
                policy2 = nil
14✔
3377
        })
14✔
3378
        if err != nil {
27✔
3379
                return nil, nil, nil, err
13✔
3380
        }
13✔
3381

3382
        return edgeInfo, policy1, policy2, nil
4✔
3383
}
3384

3385
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3386
// channel identified by the channel ID. If the channel can't be found, then
3387
// ErrEdgeNotFound is returned. A struct which houses the general information
3388
// for the channel itself is returned as well as two structs that contain the
3389
// routing policies for the channel in either direction.
3390
//
3391
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3392
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3393
// the ChannelEdgeInfo will only include the public keys of each node.
3394
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3395
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3396
        *models.ChannelEdgePolicy, error) {
27✔
3397

27✔
3398
        var (
27✔
3399
                edgeInfo  *models.ChannelEdgeInfo
27✔
3400
                policy1   *models.ChannelEdgePolicy
27✔
3401
                policy2   *models.ChannelEdgePolicy
27✔
3402
                channelID [8]byte
27✔
3403
        )
27✔
3404

27✔
3405
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
54✔
3406
                // First, grab the node bucket. This will be used to populate
27✔
3407
                // the Node pointers in each edge read from disk.
27✔
3408
                nodes := tx.ReadBucket(nodeBucket)
27✔
3409
                if nodes == nil {
27✔
NEW
3410
                        return ErrGraphNotFound
×
NEW
3411
                }
×
3412

3413
                // Next, grab the edge bucket which stores the edges, and also
3414
                // the index itself so we can group the directed edges together
3415
                // logically.
3416
                edges := tx.ReadBucket(edgeBucket)
27✔
3417
                if edges == nil {
27✔
NEW
3418
                        return ErrGraphNoEdgesFound
×
NEW
3419
                }
×
3420
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
27✔
3421
                if edgeIndex == nil {
27✔
NEW
3422
                        return ErrGraphNoEdgesFound
×
NEW
3423
                }
×
3424

3425
                byteOrder.PutUint64(channelID[:], chanID)
27✔
3426

27✔
3427
                // Now, attempt to fetch edge.
27✔
3428
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
27✔
3429

27✔
3430
                // If it doesn't exist, we'll quickly check our zombie index to
27✔
3431
                // see if we've previously marked it as so.
27✔
3432
                if errors.Is(err, ErrEdgeNotFound) {
31✔
3433
                        // If the zombie index doesn't exist, or the edge is not
4✔
3434
                        // marked as a zombie within it, then we'll return the
4✔
3435
                        // original ErrEdgeNotFound error.
4✔
3436
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3437
                        if zombieIndex == nil {
4✔
NEW
3438
                                return ErrEdgeNotFound
×
NEW
3439
                        }
×
3440

3441
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3442
                                zombieIndex, chanID,
4✔
3443
                        )
4✔
3444
                        if !isZombie {
7✔
3445
                                return ErrEdgeNotFound
3✔
3446
                        }
3✔
3447

3448
                        // Otherwise, the edge is marked as a zombie, so we'll
3449
                        // populate the edge info with the public keys of each
3450
                        // party as this is the only information we have about
3451
                        // it and return an error signaling so.
3452
                        edgeInfo = &models.ChannelEdgeInfo{
4✔
3453
                                NodeKey1Bytes: pubKey1,
4✔
3454
                                NodeKey2Bytes: pubKey2,
4✔
3455
                        }
4✔
3456

4✔
3457
                        return ErrZombieEdge
4✔
3458
                }
3459

3460
                // Otherwise, we'll just return the error if any.
3461
                if err != nil {
26✔
NEW
3462
                        return err
×
NEW
3463
                }
×
3464

3465
                edgeInfo = &edge
26✔
3466

26✔
3467
                // Then we'll attempt to fetch the accompanying policies of this
26✔
3468
                // edge.
26✔
3469
                e1, e2, err := fetchChanEdgePolicies(
26✔
3470
                        edgeIndex, edges, channelID[:],
26✔
3471
                )
26✔
3472
                if err != nil {
26✔
NEW
3473
                        return err
×
NEW
3474
                }
×
3475

3476
                policy1 = e1
26✔
3477
                policy2 = e2
26✔
3478

26✔
3479
                return nil
26✔
3480
        }, func() {
27✔
3481
                edgeInfo = nil
27✔
3482
                policy1 = nil
27✔
3483
                policy2 = nil
27✔
3484
        })
27✔
3485
        if errors.Is(err, ErrZombieEdge) {
31✔
3486
                return edgeInfo, nil, nil, err
4✔
3487
        }
4✔
3488
        if err != nil {
29✔
3489
                return nil, nil, nil, err
3✔
3490
        }
3✔
3491

3492
        return edgeInfo, policy1, policy2, nil
26✔
3493
}
3494

3495
// IsPublicNode is a helper method that determines whether the node with the
3496
// given public key is seen as a public node in the graph from the graph's
3497
// source node's point of view.
3498
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
16✔
3499
        var nodeIsPublic bool
16✔
3500
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
32✔
3501
                nodes := tx.ReadBucket(nodeBucket)
16✔
3502
                if nodes == nil {
16✔
NEW
3503
                        return ErrGraphNodesNotFound
×
NEW
3504
                }
×
3505
                ourPubKey := nodes.Get(sourceKey)
16✔
3506
                if ourPubKey == nil {
16✔
NEW
3507
                        return ErrSourceNodeNotSet
×
NEW
3508
                }
×
3509
                node, err := fetchLightningNode(nodes, pubKey[:])
16✔
3510
                if err != nil {
16✔
NEW
3511
                        return err
×
NEW
3512
                }
×
3513

3514
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3515

16✔
3516
                return err
16✔
3517
        }, func() {
16✔
3518
                nodeIsPublic = false
16✔
3519
        })
16✔
3520
        if err != nil {
16✔
NEW
3521
                return false, err
×
NEW
3522
        }
×
3523

3524
        return nodeIsPublic, nil
16✔
3525
}
3526

3527
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3528
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
49✔
3529
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
49✔
3530
        if err != nil {
49✔
NEW
3531
                return nil, err
×
NEW
3532
        }
×
3533

3534
        // With the witness script generated, we'll now turn it into a p2wsh
3535
        // script:
3536
        //  * OP_0 <sha256(script)>
3537
        bldr := txscript.NewScriptBuilder(
49✔
3538
                txscript.WithScriptAllocSize(input.P2WSHSize),
49✔
3539
        )
49✔
3540
        bldr.AddOp(txscript.OP_0)
49✔
3541
        scriptHash := sha256.Sum256(witnessScript)
49✔
3542
        bldr.AddData(scriptHash[:])
49✔
3543

49✔
3544
        return bldr.Script()
49✔
3545
}
3546

3547
// EdgePoint couples the outpoint of a channel with the funding script that it
3548
// creates. The FilteredChainView will use this to watch for spends of this
3549
// edge point on chain. We require both of these values as depending on the
3550
// concrete implementation, either the pkScript, or the out point will be used.
3551
type EdgePoint struct {
3552
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3553
        FundingPkScript []byte
3554

3555
        // OutPoint is the outpoint of the target channel.
3556
        OutPoint wire.OutPoint
3557
}
3558

3559
// String returns a human readable version of the target EdgePoint. We return
3560
// the outpoint directly as it is enough to uniquely identify the edge point.
NEW
3561
func (e *EdgePoint) String() string {
×
NEW
3562
        return e.OutPoint.String()
×
NEW
3563
}
×
3564

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

3588
                // Once we have the proper bucket, we'll range over each key
3589
                // (which is the channel point for the channel) and decode it,
3590
                // accumulating each entry.
3591
                return chanIndex.ForEach(
25✔
3592
                        func(chanPointBytes, chanID []byte) error {
70✔
3593
                                chanPointReader := bytes.NewReader(
45✔
3594
                                        chanPointBytes,
45✔
3595
                                )
45✔
3596

45✔
3597
                                var chanPoint wire.OutPoint
45✔
3598
                                err := ReadOutpoint(chanPointReader, &chanPoint)
45✔
3599
                                if err != nil {
45✔
NEW
3600
                                        return err
×
NEW
3601
                                }
×
3602

3603
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3604
                                        edgeIndex, chanID,
45✔
3605
                                )
45✔
3606
                                if err != nil {
45✔
NEW
3607
                                        return err
×
NEW
3608
                                }
×
3609

3610
                                pkScript, err := genMultiSigP2WSH(
45✔
3611
                                        edgeInfo.BitcoinKey1Bytes[:],
45✔
3612
                                        edgeInfo.BitcoinKey2Bytes[:],
45✔
3613
                                )
45✔
3614
                                if err != nil {
45✔
NEW
3615
                                        return err
×
NEW
3616
                                }
×
3617

3618
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3619
                                        FundingPkScript: pkScript,
45✔
3620
                                        OutPoint:        chanPoint,
45✔
3621
                                })
45✔
3622

45✔
3623
                                return nil
45✔
3624
                        },
3625
                )
3626
        }, func() {
25✔
3627
                edgePoints = nil
25✔
3628
        }); err != nil {
25✔
NEW
3629
                return nil, err
×
NEW
3630
        }
×
3631

3632
        return edgePoints, nil
25✔
3633
}
3634

3635
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3636
// zombie. This method is used on an ad-hoc basis, when channels need to be
3637
// marked as zombies outside the normal pruning cycle.
3638
func (c *KVStore) MarkEdgeZombie(chanID uint64,
3639
        pubKey1, pubKey2 [33]byte) error {
117✔
3640

117✔
3641
        c.cacheMu.Lock()
117✔
3642
        defer c.cacheMu.Unlock()
117✔
3643

117✔
3644
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
234✔
3645
                edges := tx.ReadWriteBucket(edgeBucket)
117✔
3646
                if edges == nil {
117✔
NEW
3647
                        return ErrGraphNoEdgesFound
×
NEW
3648
                }
×
3649
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
117✔
3650
                if err != nil {
117✔
NEW
3651
                        return fmt.Errorf("unable to create zombie "+
×
NEW
3652
                                "bucket: %w", err)
×
NEW
3653
                }
×
3654

3655
                if c.graphCache != nil {
234✔
3656
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
117✔
3657
                }
117✔
3658

3659
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
117✔
3660
        })
3661
        if err != nil {
117✔
NEW
3662
                return err
×
NEW
3663
        }
×
3664

3665
        c.rejectCache.remove(chanID)
117✔
3666
        c.chanCache.remove(chanID)
117✔
3667

117✔
3668
        return nil
117✔
3669
}
3670

3671
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3672
// keys should represent the node public keys of the two parties involved in the
3673
// edge.
3674
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3675
        pubKey2 [33]byte) error {
143✔
3676

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

143✔
3680
        var v [66]byte
143✔
3681
        copy(v[:33], pubKey1[:])
143✔
3682
        copy(v[33:], pubKey2[:])
143✔
3683

143✔
3684
        return zombieIndex.Put(k[:], v[:])
143✔
3685
}
143✔
3686

3687
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3688
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
2✔
3689
        c.cacheMu.Lock()
2✔
3690
        defer c.cacheMu.Unlock()
2✔
3691

2✔
3692
        return c.markEdgeLiveUnsafe(nil, chanID)
2✔
3693
}
2✔
3694

3695
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3696
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3697
// case a new transaction will be created.
3698
//
3699
// NOTE: this method MUST only be called if the cacheMu has already been
3700
// acquired.
3701
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
19✔
3702
        dbFn := func(tx kvdb.RwTx) error {
38✔
3703
                edges := tx.ReadWriteBucket(edgeBucket)
19✔
3704
                if edges == nil {
19✔
NEW
3705
                        return ErrGraphNoEdgesFound
×
NEW
3706
                }
×
3707
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
19✔
3708
                if zombieIndex == nil {
19✔
NEW
3709
                        return nil
×
NEW
3710
                }
×
3711

3712
                var k [8]byte
19✔
3713
                byteOrder.PutUint64(k[:], chanID)
19✔
3714

19✔
3715
                if len(zombieIndex.Get(k[:])) == 0 {
20✔
3716
                        return ErrZombieEdgeNotFound
1✔
3717
                }
1✔
3718

3719
                return zombieIndex.Delete(k[:])
18✔
3720
        }
3721

3722
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3723
        // the existing transaction
3724
        var err error
19✔
3725
        if tx == nil {
21✔
3726
                err = kvdb.Update(c.db, dbFn, func() {})
4✔
3727
        } else {
17✔
3728
                err = dbFn(tx)
17✔
3729
        }
17✔
3730
        if err != nil {
20✔
3731
                return err
1✔
3732
        }
1✔
3733

3734
        c.rejectCache.remove(chanID)
18✔
3735
        c.chanCache.remove(chanID)
18✔
3736

18✔
3737
        // We need to add the channel back into our graph cache, otherwise we
18✔
3738
        // won't use it for path finding.
18✔
3739
        if c.graphCache != nil {
36✔
3740
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
18✔
3741
                if err != nil {
18✔
NEW
3742
                        return err
×
NEW
3743
                }
×
3744

3745
                for _, edgeInfo := range edgeInfos {
18✔
NEW
3746
                        c.graphCache.AddChannel(
×
NEW
3747
                                edgeInfo.Info, edgeInfo.Policy1,
×
NEW
3748
                                edgeInfo.Policy2,
×
NEW
3749
                        )
×
NEW
3750
                }
×
3751
        }
3752

3753
        return nil
18✔
3754
}
3755

3756
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3757
// zombie, then the two node public keys corresponding to this edge are also
3758
// returned.
3759
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3760
        var (
5✔
3761
                isZombie         bool
5✔
3762
                pubKey1, pubKey2 [33]byte
5✔
3763
        )
5✔
3764

5✔
3765
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3766
                edges := tx.ReadBucket(edgeBucket)
5✔
3767
                if edges == nil {
5✔
NEW
3768
                        return ErrGraphNoEdgesFound
×
NEW
3769
                }
×
3770
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3771
                if zombieIndex == nil {
5✔
NEW
3772
                        return nil
×
NEW
3773
                }
×
3774

3775
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3776

5✔
3777
                return nil
5✔
3778
        }, func() {
5✔
3779
                isZombie = false
5✔
3780
                pubKey1 = [33]byte{}
5✔
3781
                pubKey2 = [33]byte{}
5✔
3782
        })
5✔
3783
        if err != nil {
5✔
NEW
3784
                return false, [33]byte{}, [33]byte{}
×
NEW
3785
        }
×
3786

3787
        return isZombie, pubKey1, pubKey2
5✔
3788
}
3789

3790
// isZombieEdge returns whether an entry exists for the given channel in the
3791
// zombie index. If an entry exists, then the two node public keys corresponding
3792
// to this edge are also returned.
3793
func isZombieEdge(zombieIndex kvdb.RBucket,
3794
        chanID uint64) (bool, [33]byte, [33]byte) {
177✔
3795

177✔
3796
        var k [8]byte
177✔
3797
        byteOrder.PutUint64(k[:], chanID)
177✔
3798

177✔
3799
        v := zombieIndex.Get(k[:])
177✔
3800
        if v == nil {
279✔
3801
                return false, [33]byte{}, [33]byte{}
102✔
3802
        }
102✔
3803

3804
        var pubKey1, pubKey2 [33]byte
78✔
3805
        copy(pubKey1[:], v[:33])
78✔
3806
        copy(pubKey2[:], v[33:])
78✔
3807

78✔
3808
        return true, pubKey1, pubKey2
78✔
3809
}
3810

3811
// NumZombies returns the current number of zombie channels in the graph.
3812
func (c *KVStore) NumZombies() (uint64, error) {
4✔
3813
        var numZombies uint64
4✔
3814
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3815
                edges := tx.ReadBucket(edgeBucket)
4✔
3816
                if edges == nil {
4✔
NEW
3817
                        return nil
×
NEW
3818
                }
×
3819
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3820
                if zombieIndex == nil {
4✔
NEW
3821
                        return nil
×
NEW
3822
                }
×
3823

3824
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3825
                        numZombies++
2✔
3826
                        return nil
2✔
3827
                })
2✔
3828
        }, func() {
4✔
3829
                numZombies = 0
4✔
3830
        })
4✔
3831
        if err != nil {
4✔
NEW
3832
                return 0, err
×
NEW
3833
        }
×
3834

3835
        return numZombies, nil
4✔
3836
}
3837

3838
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3839
// that we can ignore channel announcements that we know to be closed without
3840
// having to validate them and fetch a block.
3841
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3842
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3843
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3844
                if err != nil {
1✔
NEW
3845
                        return err
×
NEW
3846
                }
×
3847

3848
                var k [8]byte
1✔
3849
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3850

1✔
3851
                return closedScids.Put(k[:], []byte{})
1✔
3852
        }, func() {})
1✔
3853
}
3854

3855
// IsClosedScid checks whether a channel identified by the passed in scid is
3856
// closed. This helps avoid having to perform expensive validation checks.
3857
// TODO: Add an LRU cache to cut down on disc reads.
3858
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
5✔
3859
        var isClosed bool
5✔
3860
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3861
                closedScids := tx.ReadBucket(closedScidBucket)
5✔
3862
                if closedScids == nil {
5✔
NEW
3863
                        return ErrClosedScidsNotFound
×
NEW
3864
                }
×
3865

3866
                var k [8]byte
5✔
3867
                byteOrder.PutUint64(k[:], scid.ToUint64())
5✔
3868

5✔
3869
                if closedScids.Get(k[:]) != nil {
6✔
3870
                        isClosed = true
1✔
3871
                        return nil
1✔
3872
                }
1✔
3873

3874
                return nil
4✔
3875
        }, func() {
5✔
3876
                isClosed = false
5✔
3877
        })
5✔
3878
        if err != nil {
5✔
NEW
3879
                return false, err
×
NEW
3880
        }
×
3881

3882
        return isClosed, nil
5✔
3883
}
3884

3885
// GraphSession will provide the call-back with access to a NodeTraverser
3886
// instance which can be used to perform queries against the channel graph. If
3887
// the graph cache is not enabled, then the call-back will  be provided with
3888
// access to the graph via a consistent read-only transaction.
3889
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
136✔
3890
        if c.graphCache != nil {
218✔
3891
                return cb(&nodeTraverserSession{db: c})
82✔
3892
        }
82✔
3893

3894
        return c.db.View(func(tx walletdb.ReadTx) error {
108✔
3895
                return cb(&nodeTraverserSession{
54✔
3896
                        db: c,
54✔
3897
                        tx: tx,
54✔
3898
                })
54✔
3899
        }, func() {})
108✔
3900
}
3901

3902
// nodeTraverserSession implements the NodeTraverser interface but with a
3903
// backing read only transaction for a consistent view of the graph in the case
3904
// where the graph Cache has not been enabled.
3905
type nodeTraverserSession struct {
3906
        tx kvdb.RTx
3907
        db *KVStore
3908
}
3909

3910
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3911
// node.
3912
//
3913
// NOTE: Part of the NodeTraverser interface.
3914
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3915
        cb func(channel *DirectedChannel) error) error {
592✔
3916

592✔
3917
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
592✔
3918
}
592✔
3919

3920
// FetchNodeFeatures returns the features of the given node. If the node is
3921
// unknown, assume no additional features are supported.
3922
//
3923
// NOTE: Part of the NodeTraverser interface.
3924
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
3925
        *lnwire.FeatureVector, error) {
623✔
3926

623✔
3927
        return c.db.fetchNodeFeatures(c.tx, nodePub)
623✔
3928
}
623✔
3929

3930
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3931
        node *models.LightningNode) error {
992✔
3932

992✔
3933
        var (
992✔
3934
                scratch [16]byte
992✔
3935
                b       bytes.Buffer
992✔
3936
        )
992✔
3937

992✔
3938
        pub, err := node.PubKey()
992✔
3939
        if err != nil {
992✔
NEW
3940
                return err
×
NEW
3941
        }
×
3942
        nodePub := pub.SerializeCompressed()
992✔
3943

992✔
3944
        // If the node has the update time set, write it, else write 0.
992✔
3945
        updateUnix := uint64(0)
992✔
3946
        if node.LastUpdate.Unix() > 0 {
1,858✔
3947
                updateUnix = uint64(node.LastUpdate.Unix())
866✔
3948
        }
866✔
3949

3950
        byteOrder.PutUint64(scratch[:8], updateUnix)
992✔
3951
        if _, err := b.Write(scratch[:8]); err != nil {
992✔
NEW
3952
                return err
×
NEW
3953
        }
×
3954

3955
        if _, err := b.Write(nodePub); err != nil {
992✔
NEW
3956
                return err
×
NEW
3957
        }
×
3958

3959
        // If we got a node announcement for this node, we will have the rest
3960
        // of the data available. If not we don't have more data to write.
3961
        if !node.HaveNodeAnnouncement {
1,068✔
3962
                // Write HaveNodeAnnouncement=0.
76✔
3963
                byteOrder.PutUint16(scratch[:2], 0)
76✔
3964
                if _, err := b.Write(scratch[:2]); err != nil {
76✔
NEW
3965
                        return err
×
NEW
3966
                }
×
3967

3968
                return nodeBucket.Put(nodePub, b.Bytes())
76✔
3969
        }
3970

3971
        // Write HaveNodeAnnouncement=1.
3972
        byteOrder.PutUint16(scratch[:2], 1)
919✔
3973
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
NEW
3974
                return err
×
NEW
3975
        }
×
3976

3977
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
919✔
NEW
3978
                return err
×
NEW
3979
        }
×
3980
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
919✔
NEW
3981
                return err
×
NEW
3982
        }
×
3983
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
919✔
NEW
3984
                return err
×
NEW
3985
        }
×
3986

3987
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
919✔
NEW
3988
                return err
×
NEW
3989
        }
×
3990

3991
        if err := node.Features.Encode(&b); err != nil {
919✔
NEW
3992
                return err
×
NEW
3993
        }
×
3994

3995
        numAddresses := uint16(len(node.Addresses))
919✔
3996
        byteOrder.PutUint16(scratch[:2], numAddresses)
919✔
3997
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
NEW
3998
                return err
×
NEW
3999
        }
×
4000

4001
        for _, address := range node.Addresses {
2,066✔
4002
                if err := SerializeAddr(&b, address); err != nil {
1,147✔
NEW
4003
                        return err
×
NEW
4004
                }
×
4005
        }
4006

4007
        sigLen := len(node.AuthSigBytes)
919✔
4008
        if sigLen > 80 {
919✔
NEW
4009
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
NEW
4010
                        sigLen)
×
NEW
4011
        }
×
4012

4013
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
919✔
4014
        if err != nil {
919✔
NEW
4015
                return err
×
NEW
4016
        }
×
4017

4018
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
919✔
NEW
4019
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
NEW
4020
        }
×
4021
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
919✔
4022
        if err != nil {
919✔
NEW
4023
                return err
×
NEW
4024
        }
×
4025

4026
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
919✔
NEW
4027
                return err
×
NEW
4028
        }
×
4029

4030
        // With the alias bucket updated, we'll now update the index that
4031
        // tracks the time series of node updates.
4032
        var indexKey [8 + 33]byte
919✔
4033
        byteOrder.PutUint64(indexKey[:8], updateUnix)
919✔
4034
        copy(indexKey[8:], nodePub)
919✔
4035

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

107✔
4043
                var oldIndexKey [8 + 33]byte
107✔
4044
                copy(oldIndexKey[:8], oldUpdateTime)
107✔
4045
                copy(oldIndexKey[8:], nodePub)
107✔
4046

107✔
4047
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
107✔
NEW
4048
                        return err
×
NEW
4049
                }
×
4050
        }
4051

4052
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
919✔
NEW
4053
                return err
×
NEW
4054
        }
×
4055

4056
        return nodeBucket.Put(nodePub, b.Bytes())
919✔
4057
}
4058

4059
func fetchLightningNode(nodeBucket kvdb.RBucket,
4060
        nodePub []byte) (models.LightningNode, error) {
3,613✔
4061

3,613✔
4062
        nodeBytes := nodeBucket.Get(nodePub)
3,613✔
4063
        if nodeBytes == nil {
3,688✔
4064
                return models.LightningNode{}, ErrGraphNodeNotFound
75✔
4065
        }
75✔
4066

4067
        nodeReader := bytes.NewReader(nodeBytes)
3,541✔
4068

3,541✔
4069
        return deserializeLightningNode(nodeReader)
3,541✔
4070
}
4071

4072
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4073
        *lnwire.FeatureVector, error) {
123✔
4074

123✔
4075
        var (
123✔
4076
                pubKey      route.Vertex
123✔
4077
                features    = lnwire.EmptyFeatureVector()
123✔
4078
                nodeScratch [8]byte
123✔
4079
        )
123✔
4080

123✔
4081
        // Skip ahead:
123✔
4082
        // - LastUpdate (8 bytes)
123✔
4083
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
NEW
4084
                return pubKey, nil, err
×
NEW
4085
        }
×
4086

4087
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
123✔
NEW
4088
                return pubKey, nil, err
×
NEW
4089
        }
×
4090

4091
        // Read the node announcement flag.
4092
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
NEW
4093
                return pubKey, nil, err
×
NEW
4094
        }
×
4095
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4096

123✔
4097
        // The rest of the data is optional, and will only be there if we got a
123✔
4098
        // node announcement for this node.
123✔
4099
        if hasNodeAnn == 0 {
126✔
4100
                return pubKey, features, nil
3✔
4101
        }
3✔
4102

4103
        // We did get a node announcement for this node, so we'll have the rest
4104
        // of the data available.
4105
        var rgb uint8
123✔
4106
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
NEW
4107
                return pubKey, nil, err
×
NEW
4108
        }
×
4109
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
NEW
4110
                return pubKey, nil, err
×
NEW
4111
        }
×
4112
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
NEW
4113
                return pubKey, nil, err
×
NEW
4114
        }
×
4115

4116
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
NEW
4117
                return pubKey, nil, err
×
NEW
4118
        }
×
4119

4120
        if err := features.Decode(r); err != nil {
123✔
NEW
4121
                return pubKey, nil, err
×
NEW
4122
        }
×
4123

4124
        return pubKey, features, nil
123✔
4125
}
4126

4127
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,290✔
4128
        var (
8,290✔
4129
                node    models.LightningNode
8,290✔
4130
                scratch [8]byte
8,290✔
4131
                err     error
8,290✔
4132
        )
8,290✔
4133

8,290✔
4134
        // Always populate a feature vector, even if we don't have a node
8,290✔
4135
        // announcement and short circuit below.
8,290✔
4136
        node.Features = lnwire.EmptyFeatureVector()
8,290✔
4137

8,290✔
4138
        if _, err := r.Read(scratch[:]); err != nil {
8,290✔
NEW
4139
                return models.LightningNode{}, err
×
NEW
4140
        }
×
4141

4142
        unix := int64(byteOrder.Uint64(scratch[:]))
8,290✔
4143
        node.LastUpdate = time.Unix(unix, 0)
8,290✔
4144

8,290✔
4145
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,290✔
NEW
4146
                return models.LightningNode{}, err
×
NEW
4147
        }
×
4148

4149
        if _, err := r.Read(scratch[:2]); err != nil {
8,290✔
NEW
4150
                return models.LightningNode{}, err
×
NEW
4151
        }
×
4152

4153
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,290✔
4154
        if hasNodeAnn == 1 {
16,440✔
4155
                node.HaveNodeAnnouncement = true
8,150✔
4156
        } else {
8,293✔
4157
                node.HaveNodeAnnouncement = false
143✔
4158
        }
143✔
4159

4160
        // The rest of the data is optional, and will only be there if we got a
4161
        // node announcement for this node.
4162
        if !node.HaveNodeAnnouncement {
8,433✔
4163
                return node, nil
143✔
4164
        }
143✔
4165

4166
        // We did get a node announcement for this node, so we'll have the rest
4167
        // of the data available.
4168
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,150✔
NEW
4169
                return models.LightningNode{}, err
×
NEW
4170
        }
×
4171
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,150✔
NEW
4172
                return models.LightningNode{}, err
×
NEW
4173
        }
×
4174
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,150✔
NEW
4175
                return models.LightningNode{}, err
×
NEW
4176
        }
×
4177

4178
        node.Alias, err = wire.ReadVarString(r, 0)
8,150✔
4179
        if err != nil {
8,150✔
NEW
4180
                return models.LightningNode{}, err
×
NEW
4181
        }
×
4182

4183
        err = node.Features.Decode(r)
8,150✔
4184
        if err != nil {
8,150✔
NEW
4185
                return models.LightningNode{}, err
×
NEW
4186
        }
×
4187

4188
        if _, err := r.Read(scratch[:2]); err != nil {
8,150✔
NEW
4189
                return models.LightningNode{}, err
×
NEW
4190
        }
×
4191
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,150✔
4192

8,150✔
4193
        var addresses []net.Addr
8,150✔
4194
        for i := 0; i < numAddresses; i++ {
18,319✔
4195
                address, err := DeserializeAddr(r)
10,169✔
4196
                if err != nil {
10,169✔
NEW
4197
                        return models.LightningNode{}, err
×
NEW
4198
                }
×
4199
                addresses = append(addresses, address)
10,169✔
4200
        }
4201
        node.Addresses = addresses
8,150✔
4202

8,150✔
4203
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,150✔
4204
        if err != nil {
8,150✔
NEW
4205
                return models.LightningNode{}, err
×
NEW
4206
        }
×
4207

4208
        // We'll try and see if there are any opaque bytes left, if not, then
4209
        // we'll ignore the EOF error and return the node as is.
4210
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,150✔
4211
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,150✔
4212
        )
8,150✔
4213
        switch {
8,150✔
NEW
4214
        case errors.Is(err, io.ErrUnexpectedEOF):
×
NEW
4215
        case errors.Is(err, io.EOF):
×
NEW
4216
        case err != nil:
×
NEW
4217
                return models.LightningNode{}, err
×
4218
        }
4219

4220
        return node, nil
8,150✔
4221
}
4222

4223
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4224
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,485✔
4225

1,485✔
4226
        var b bytes.Buffer
1,485✔
4227

1,485✔
4228
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,485✔
NEW
4229
                return err
×
NEW
4230
        }
×
4231
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,485✔
NEW
4232
                return err
×
NEW
4233
        }
×
4234
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,485✔
NEW
4235
                return err
×
NEW
4236
        }
×
4237
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,485✔
NEW
4238
                return err
×
NEW
4239
        }
×
4240

4241
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,485✔
NEW
4242
                return err
×
NEW
4243
        }
×
4244

4245
        authProof := edgeInfo.AuthProof
1,485✔
4246
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,485✔
4247
        if authProof != nil {
2,887✔
4248
                nodeSig1 = authProof.NodeSig1Bytes
1,402✔
4249
                nodeSig2 = authProof.NodeSig2Bytes
1,402✔
4250
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,402✔
4251
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,402✔
4252
        }
1,402✔
4253

4254
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,485✔
NEW
4255
                return err
×
NEW
4256
        }
×
4257
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,485✔
NEW
4258
                return err
×
NEW
4259
        }
×
4260
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,485✔
NEW
4261
                return err
×
NEW
4262
        }
×
4263
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,485✔
NEW
4264
                return err
×
NEW
4265
        }
×
4266

4267
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,485✔
NEW
4268
                return err
×
NEW
4269
        }
×
4270
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,485✔
4271
        if err != nil {
1,485✔
NEW
4272
                return err
×
NEW
4273
        }
×
4274
        if _, err := b.Write(chanID[:]); err != nil {
1,485✔
NEW
4275
                return err
×
NEW
4276
        }
×
4277
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,485✔
NEW
4278
                return err
×
NEW
4279
        }
×
4280

4281
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,485✔
NEW
4282
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
NEW
4283
        }
×
4284
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,485✔
4285
        if err != nil {
1,485✔
NEW
4286
                return err
×
NEW
4287
        }
×
4288

4289
        return edgeIndex.Put(chanID[:], b.Bytes())
1,485✔
4290
}
4291

4292
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4293
        chanID []byte) (models.ChannelEdgeInfo, error) {
3,990✔
4294

3,990✔
4295
        edgeInfoBytes := edgeIndex.Get(chanID)
3,990✔
4296
        if edgeInfoBytes == nil {
4,076✔
4297
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
86✔
4298
        }
86✔
4299

4300
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3,907✔
4301

3,907✔
4302
        return deserializeChanEdgeInfo(edgeInfoReader)
3,907✔
4303
}
4304

4305
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,536✔
4306
        var (
4,536✔
4307
                err      error
4,536✔
4308
                edgeInfo models.ChannelEdgeInfo
4,536✔
4309
        )
4,536✔
4310

4,536✔
4311
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,536✔
NEW
4312
                return models.ChannelEdgeInfo{}, err
×
NEW
4313
        }
×
4314
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,536✔
NEW
4315
                return models.ChannelEdgeInfo{}, err
×
NEW
4316
        }
×
4317
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,536✔
NEW
4318
                return models.ChannelEdgeInfo{}, err
×
NEW
4319
        }
×
4320
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,536✔
NEW
4321
                return models.ChannelEdgeInfo{}, err
×
NEW
4322
        }
×
4323

4324
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,536✔
4325
        if err != nil {
4,536✔
NEW
4326
                return models.ChannelEdgeInfo{}, err
×
NEW
4327
        }
×
4328

4329
        proof := &models.ChannelAuthProof{}
4,536✔
4330

4,536✔
4331
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,536✔
4332
        if err != nil {
4,536✔
NEW
4333
                return models.ChannelEdgeInfo{}, err
×
NEW
4334
        }
×
4335
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,536✔
4336
        if err != nil {
4,536✔
NEW
4337
                return models.ChannelEdgeInfo{}, err
×
NEW
4338
        }
×
4339
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,536✔
4340
        if err != nil {
4,536✔
NEW
4341
                return models.ChannelEdgeInfo{}, err
×
NEW
4342
        }
×
4343
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,536✔
4344
        if err != nil {
4,536✔
NEW
4345
                return models.ChannelEdgeInfo{}, err
×
NEW
4346
        }
×
4347

4348
        if !proof.IsEmpty() {
6,123✔
4349
                edgeInfo.AuthProof = proof
1,587✔
4350
        }
1,587✔
4351

4352
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,536✔
4353
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,536✔
NEW
4354
                return models.ChannelEdgeInfo{}, err
×
NEW
4355
        }
×
4356
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,536✔
NEW
4357
                return models.ChannelEdgeInfo{}, err
×
NEW
4358
        }
×
4359
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,536✔
NEW
4360
                return models.ChannelEdgeInfo{}, err
×
NEW
4361
        }
×
4362

4363
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,536✔
NEW
4364
                return models.ChannelEdgeInfo{}, err
×
NEW
4365
        }
×
4366

4367
        // We'll try and see if there are any opaque bytes left, if not, then
4368
        // we'll ignore the EOF error and return the edge as is.
4369
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,536✔
4370
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,536✔
4371
        )
4,536✔
4372
        switch {
4,536✔
NEW
4373
        case errors.Is(err, io.ErrUnexpectedEOF):
×
NEW
4374
        case errors.Is(err, io.EOF):
×
NEW
4375
        case err != nil:
×
NEW
4376
                return models.ChannelEdgeInfo{}, err
×
4377
        }
4378

4379
        return edgeInfo, nil
4,536✔
4380
}
4381

4382
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4383
        from, to []byte) error {
2,663✔
4384

2,663✔
4385
        var edgeKey [33 + 8]byte
2,663✔
4386
        copy(edgeKey[:], from)
2,663✔
4387
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,663✔
4388

2,663✔
4389
        var b bytes.Buffer
2,663✔
4390
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,663✔
NEW
4391
                return err
×
NEW
4392
        }
×
4393

4394
        // Before we write out the new edge, we'll create a new entry in the
4395
        // update index in order to keep it fresh.
4396
        updateUnix := uint64(edge.LastUpdate.Unix())
2,663✔
4397
        var indexKey [8 + 8]byte
2,663✔
4398
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,663✔
4399
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,663✔
4400

2,663✔
4401
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,663✔
4402
        if err != nil {
2,663✔
NEW
4403
                return err
×
NEW
4404
        }
×
4405

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

27✔
4413
                // In order to delete the old entry, we'll need to obtain the
27✔
4414
                // *prior* update time in order to delete it. To do this, we'll
27✔
4415
                // need to deserialize the existing policy within the database
27✔
4416
                // (now outdated by the new one), and delete its corresponding
27✔
4417
                // entry within the update index. We'll ignore any
27✔
4418
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
27✔
4419
                // the channel ID and update time to delete the entry.
27✔
4420
                // TODO(halseth): get rid of these invalid policies in a
27✔
4421
                // migration.
27✔
4422
                oldEdgePolicy, err := deserializeChanEdgePolicy(
27✔
4423
                        bytes.NewReader(edgeBytes),
27✔
4424
                )
27✔
4425
                if err != nil &&
27✔
4426
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) {
27✔
NEW
4427

×
NEW
4428
                        return err
×
NEW
4429
                }
×
4430

4431
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
27✔
4432

27✔
4433
                var oldIndexKey [8 + 8]byte
27✔
4434
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
27✔
4435
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
27✔
4436

27✔
4437
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
27✔
NEW
4438
                        return err
×
NEW
4439
                }
×
4440
        }
4441

4442
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,663✔
NEW
4443
                return err
×
NEW
4444
        }
×
4445

4446
        err = updateEdgePolicyDisabledIndex(
2,663✔
4447
                edges, edge.ChannelID,
2,663✔
4448
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,663✔
4449
                edge.IsDisabled(),
2,663✔
4450
        )
2,663✔
4451
        if err != nil {
2,663✔
NEW
4452
                return err
×
NEW
4453
        }
×
4454

4455
        return edges.Put(edgeKey[:], b.Bytes())
2,663✔
4456
}
4457

4458
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4459
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4460
// one.
4461
// The direction represents the direction of the edge and disabled is used for
4462
// deciding whether to remove or add an entry to the bucket.
4463
// In general a channel is disabled if two entries for the same chanID exist
4464
// in this bucket.
4465
// Maintaining the bucket this way allows a fast retrieval of disabled
4466
// channels, for example when prune is needed.
4467
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4468
        direction bool, disabled bool) error {
2,941✔
4469

2,941✔
4470
        var disabledEdgeKey [8 + 1]byte
2,941✔
4471
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,941✔
4472
        if direction {
4,409✔
4473
                disabledEdgeKey[8] = 1
1,468✔
4474
        }
1,468✔
4475

4476
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,941✔
4477
                disabledEdgePolicyBucket,
2,941✔
4478
        )
2,941✔
4479
        if err != nil {
2,941✔
NEW
4480
                return err
×
NEW
4481
        }
×
4482

4483
        if disabled {
2,970✔
4484
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4485
        }
29✔
4486

4487
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,915✔
4488
}
4489

4490
// putChanEdgePolicyUnknown marks the edge policy as unknown
4491
// in the edges bucket.
4492
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4493
        from []byte) error {
2,965✔
4494

2,965✔
4495
        var edgeKey [33 + 8]byte
2,965✔
4496
        copy(edgeKey[:], from)
2,965✔
4497
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,965✔
4498

2,965✔
4499
        if edges.Get(edgeKey[:]) != nil {
2,965✔
NEW
4500
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
NEW
4501
                        " when there is already a policy present", channelID)
×
NEW
4502
        }
×
4503

4504
        return edges.Put(edgeKey[:], unknownPolicy)
2,965✔
4505
}
4506

4507
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4508
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
7,771✔
4509

7,771✔
4510
        var edgeKey [33 + 8]byte
7,771✔
4511
        copy(edgeKey[:], nodePub)
7,771✔
4512
        copy(edgeKey[33:], chanID)
7,771✔
4513

7,771✔
4514
        edgeBytes := edges.Get(edgeKey[:])
7,771✔
4515
        if edgeBytes == nil {
7,771✔
NEW
4516
                return nil, ErrEdgeNotFound
×
NEW
4517
        }
×
4518

4519
        // No need to deserialize unknown policy.
4520
        if bytes.Equal(edgeBytes, unknownPolicy) {
8,125✔
4521
                return nil, nil
354✔
4522
        }
354✔
4523

4524
        edgeReader := bytes.NewReader(edgeBytes)
7,420✔
4525

7,420✔
4526
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,420✔
4527
        switch {
7,420✔
4528
        // If the db policy was missing an expected optional field, we return
4529
        // nil as if the policy was unknown.
4530
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
1✔
4531
                return nil, nil
1✔
4532

NEW
4533
        case err != nil:
×
NEW
4534
                return nil, err
×
4535
        }
4536

4537
        return ep, nil
7,419✔
4538
}
4539

4540
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4541
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4542
        error) {
237✔
4543

237✔
4544
        edgeInfo := edgeIndex.Get(chanID)
237✔
4545
        if edgeInfo == nil {
237✔
NEW
4546
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
NEW
4547
                        chanID)
×
NEW
4548
        }
×
4549

4550
        // The first node is contained within the first half of the edge
4551
        // information. We only propagate the error here and below if it's
4552
        // something other than edge non-existence.
4553
        node1Pub := edgeInfo[:33]
237✔
4554
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
237✔
4555
        if err != nil {
237✔
NEW
4556
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
NEW
4557
                        node1Pub)
×
NEW
4558
        }
×
4559

4560
        // Similarly, the second node is contained within the latter
4561
        // half of the edge information.
4562
        node2Pub := edgeInfo[33:66]
237✔
4563
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
237✔
4564
        if err != nil {
237✔
NEW
4565
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
NEW
4566
                        node2Pub)
×
NEW
4567
        }
×
4568

4569
        return edge1, edge2, nil
237✔
4570
}
4571

4572
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4573
        to []byte) error {
2,665✔
4574

2,665✔
4575
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,665✔
4576
        if err != nil {
2,665✔
NEW
4577
                return err
×
NEW
4578
        }
×
4579

4580
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,665✔
NEW
4581
                return err
×
NEW
4582
        }
×
4583

4584
        var scratch [8]byte
2,665✔
4585
        updateUnix := uint64(edge.LastUpdate.Unix())
2,665✔
4586
        byteOrder.PutUint64(scratch[:], updateUnix)
2,665✔
4587
        if _, err := w.Write(scratch[:]); err != nil {
2,665✔
NEW
4588
                return err
×
NEW
4589
        }
×
4590

4591
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,665✔
NEW
4592
                return err
×
NEW
4593
        }
×
4594
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,665✔
NEW
4595
                return err
×
NEW
4596
        }
×
4597
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,665✔
NEW
4598
                return err
×
NEW
4599
        }
×
4600
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,665✔
NEW
4601
                return err
×
NEW
4602
        }
×
4603
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,665✔
4604
        if err != nil {
2,665✔
NEW
4605
                return err
×
NEW
4606
        }
×
4607
        err = binary.Write(
2,665✔
4608
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,665✔
4609
        )
2,665✔
4610
        if err != nil {
2,665✔
NEW
4611
                return err
×
NEW
4612
        }
×
4613

4614
        if _, err := w.Write(to); err != nil {
2,665✔
NEW
4615
                return err
×
NEW
4616
        }
×
4617

4618
        // If the max_htlc field is present, we write it. To be compatible with
4619
        // older versions that wasn't aware of this field, we write it as part
4620
        // of the opaque data.
4621
        // TODO(halseth): clean up when moving to TLV.
4622
        var opaqueBuf bytes.Buffer
2,665✔
4623
        if edge.MessageFlags.HasMaxHtlc() {
4,946✔
4624
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,281✔
4625
                if err != nil {
2,281✔
NEW
4626
                        return err
×
NEW
4627
                }
×
4628
        }
4629

4630
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,665✔
NEW
4631
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
NEW
4632
        }
×
4633
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,665✔
NEW
4634
                return err
×
NEW
4635
        }
×
4636

4637
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,665✔
NEW
4638
                return err
×
NEW
4639
        }
×
4640

4641
        return nil
2,665✔
4642
}
4643

4644
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,445✔
4645
        // Deserialize the policy. Note that in case an optional field is not
7,445✔
4646
        // found, both an error and a populated policy object are returned.
7,445✔
4647
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,445✔
4648
        if deserializeErr != nil &&
7,445✔
4649
                !errors.Is(deserializeErr, ErrEdgePolicyOptionalFieldNotFound) {
7,445✔
NEW
4650

×
NEW
4651
                return nil, deserializeErr
×
NEW
4652
        }
×
4653

4654
        return edge, deserializeErr
7,445✔
4655
}
4656

4657
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4658
        error) {
8,452✔
4659

8,452✔
4660
        edge := &models.ChannelEdgePolicy{}
8,452✔
4661

8,452✔
4662
        var err error
8,452✔
4663
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,452✔
4664
        if err != nil {
8,452✔
NEW
4665
                return nil, err
×
NEW
4666
        }
×
4667

4668
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,452✔
NEW
4669
                return nil, err
×
NEW
4670
        }
×
4671

4672
        var scratch [8]byte
8,452✔
4673
        if _, err := r.Read(scratch[:]); err != nil {
8,452✔
NEW
4674
                return nil, err
×
NEW
4675
        }
×
4676
        unix := int64(byteOrder.Uint64(scratch[:]))
8,452✔
4677
        edge.LastUpdate = time.Unix(unix, 0)
8,452✔
4678

8,452✔
4679
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,452✔
NEW
4680
                return nil, err
×
NEW
4681
        }
×
4682
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,452✔
NEW
4683
                return nil, err
×
NEW
4684
        }
×
4685
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,452✔
NEW
4686
                return nil, err
×
NEW
4687
        }
×
4688

4689
        var n uint64
8,452✔
4690
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,452✔
NEW
4691
                return nil, err
×
NEW
4692
        }
×
4693
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,452✔
4694

8,452✔
4695
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,452✔
NEW
4696
                return nil, err
×
NEW
4697
        }
×
4698
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,452✔
4699

8,452✔
4700
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,452✔
NEW
4701
                return nil, err
×
NEW
4702
        }
×
4703
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,452✔
4704

8,452✔
4705
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,452✔
NEW
4706
                return nil, err
×
NEW
4707
        }
×
4708

4709
        // We'll try and see if there are any opaque bytes left, if not, then
4710
        // we'll ignore the EOF error and return the edge as is.
4711
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,452✔
4712
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,452✔
4713
        )
8,452✔
4714
        switch {
8,452✔
NEW
4715
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4716
        case errors.Is(err, io.EOF):
3✔
NEW
4717
        case err != nil:
×
NEW
4718
                return nil, err
×
4719
        }
4720

4721
        // See if optional fields are present.
4722
        if edge.MessageFlags.HasMaxHtlc() {
16,530✔
4723
                // The max_htlc field should be at the beginning of the opaque
8,078✔
4724
                // bytes.
8,078✔
4725
                opq := edge.ExtraOpaqueData
8,078✔
4726

8,078✔
4727
                // If the max_htlc field is not present, it might be old data
8,078✔
4728
                // stored before this field was validated. We'll return the
8,078✔
4729
                // edge along with an error.
8,078✔
4730
                if len(opq) < 8 {
8,081✔
4731
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4732
                }
3✔
4733

4734
                maxHtlc := byteOrder.Uint64(opq[:8])
8,075✔
4735
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,075✔
4736

8,075✔
4737
                // Exclude the parsed field from the rest of the opaque data.
8,075✔
4738
                edge.ExtraOpaqueData = opq[8:]
8,075✔
4739
        }
4740

4741
        return edge, nil
8,449✔
4742
}
4743

4744
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4745
// KVStore and a kvdb.RTx.
4746
type chanGraphNodeTx struct {
4747
        tx   kvdb.RTx
4748
        db   *KVStore
4749
        node *models.LightningNode
4750
}
4751

4752
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4753
// interface.
4754
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4755

4756
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4757
        node *models.LightningNode) *chanGraphNodeTx {
3,917✔
4758

3,917✔
4759
        return &chanGraphNodeTx{
3,917✔
4760
                tx:   tx,
3,917✔
4761
                db:   db,
3,917✔
4762
                node: node,
3,917✔
4763
        }
3,917✔
4764
}
3,917✔
4765

4766
// Node returns the raw information of the node.
4767
//
4768
// NOTE: This is a part of the NodeRTx interface.
4769
func (c *chanGraphNodeTx) Node() *models.LightningNode {
4,842✔
4770
        return c.node
4,842✔
4771
}
4,842✔
4772

4773
// FetchNode fetches the node with the given pub key under the same transaction
4774
// used to fetch the current node. The returned node is also a NodeRTx and any
4775
// operations on that NodeRTx will also be done under the same transaction.
4776
//
4777
// NOTE: This is a part of the NodeRTx interface.
4778
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
2,944✔
4779
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
2,944✔
4780
        if err != nil {
2,944✔
NEW
4781
                return nil, err
×
NEW
4782
        }
×
4783

4784
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4785
}
4786

4787
// ForEachChannel can be used to iterate over the node's channels under
4788
// the same transaction used to fetch the node.
4789
//
4790
// NOTE: This is a part of the NodeRTx interface.
4791
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4792
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4793

965✔
4794
        return c.db.ForEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4795
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4796
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4797

2,944✔
4798
                        return f(info, policy1, policy2)
2,944✔
4799
                },
2,944✔
4800
        )
4801
}
4802

4803
// MakeTestGraph creates a new instance of the KVStore for testing
4804
// purposes.
4805
func MakeTestGraph(t testing.TB, modifiers ...KVStoreOptionModifier) (
4806
        *ChannelGraph, error) {
40✔
4807

40✔
4808
        opts := DefaultOptions()
40✔
4809
        for _, modifier := range modifiers {
40✔
NEW
4810
                modifier(opts)
×
NEW
4811
        }
×
4812

4813
        // Next, create KVStore for the first time.
4814
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
40✔
4815
        if err != nil {
40✔
NEW
4816
                backendCleanup()
×
NEW
4817

×
NEW
4818
                return nil, err
×
NEW
4819
        }
×
4820

4821
        graph, err := NewChannelGraph(&Config{
40✔
4822
                KVDB:        backend,
40✔
4823
                KVStoreOpts: modifiers,
40✔
4824
        })
40✔
4825
        if err != nil {
40✔
NEW
4826
                backendCleanup()
×
NEW
4827

×
NEW
4828
                return nil, err
×
NEW
4829
        }
×
4830

4831
        t.Cleanup(func() {
80✔
4832
                _ = backend.Close()
40✔
4833
                backendCleanup()
40✔
4834
        })
40✔
4835

4836
        return graph, nil
40✔
4837
}
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