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

lightningnetwork / lnd / 15591525289

11 Jun 2025 05:26PM UTC coverage: 67.412% (+9.1%) from 58.306%
15591525289

Pull #9932

github

web-flow
Merge 0149d1bb0 into 92a5d35cf
Pull Request #9932: [draft] graph/db+sqldb: graph store SQL implementation + migration

19 of 3311 new or added lines in 7 files covered. (0.57%)

573 existing lines in 10 files now uncovered.

134443 of 199434 relevant lines covered (67.41%)

21909.5 hits per line

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

76.8
/graph/db/kv_store.go
1
package graphdb
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/sha256"
7
        "encoding/binary"
8
        "errors"
9
        "fmt"
10
        "io"
11
        "math"
12
        "net"
13
        "sort"
14
        "sync"
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/fn/v2"
25
        "github.com/lightningnetwork/lnd/graph/db/models"
26
        "github.com/lightningnetwork/lnd/input"
27
        "github.com/lightningnetwork/lnd/kvdb"
28
        "github.com/lightningnetwork/lnd/lnwire"
29
        "github.com/lightningnetwork/lnd/routing/route"
30
)
31

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

195
        chanScheduler batch.Scheduler[kvdb.RwTx]
196
        nodeScheduler batch.Scheduler[kvdb.RwTx]
197
}
198

199
// A compile-time assertion to ensure that the KVStore struct implements the
200
// V1Store interface.
201
var _ V1Store = (*KVStore)(nil)
202

203
// NewKVStore allocates a new KVStore backed by a DB instance. The
204
// returned instance has its own unique reject cache and channel cache.
205
func NewKVStore(db kvdb.Backend, options ...StoreOptionModifier) (*KVStore,
206
        error) {
172✔
207

172✔
208
        opts := DefaultOptions()
172✔
209
        for _, o := range options {
175✔
210
                o(opts)
3✔
211
        }
3✔
212

213
        if !opts.NoMigration {
344✔
214
                if err := initKVStore(db); err != nil {
172✔
215
                        return nil, err
×
216
                }
×
217
        }
218

219
        g := &KVStore{
172✔
220
                db:          db,
172✔
221
                rejectCache: newRejectCache(opts.RejectCacheSize),
172✔
222
                chanCache:   newChannelCache(opts.ChannelCacheSize),
172✔
223
        }
172✔
224
        g.chanScheduler = batch.NewTimeScheduler(
172✔
225
                batch.NewBoltBackend[kvdb.RwTx](db), &g.cacheMu,
172✔
226
                opts.BatchCommitInterval,
172✔
227
        )
172✔
228
        g.nodeScheduler = batch.NewTimeScheduler(
172✔
229
                batch.NewBoltBackend[kvdb.RwTx](db), nil,
172✔
230
                opts.BatchCommitInterval,
172✔
231
        )
172✔
232

172✔
233
        return g, nil
172✔
234
}
235

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

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

144✔
247
        // Create a map to store all channel edge policies.
144✔
248
        channelMap := make(map[channelMapKey]*models.ChannelEdgePolicy)
144✔
249

144✔
250
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
1,706✔
251
                // Skip embedded buckets.
1,562✔
252
                if bytes.Equal(k, edgeIndexBucket) ||
1,562✔
253
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
1,562✔
254
                        bytes.Equal(k, zombieBucket) ||
1,562✔
255
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
1,562✔
256
                        bytes.Equal(k, channelPointBucket) {
2,134✔
257

572✔
258
                        return nil
572✔
259
                }
572✔
260

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

266
                var key channelMapKey
993✔
267
                copy(key.nodeKey[:], k[:33])
993✔
268
                copy(key.chanID[:], k[33:])
993✔
269

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

275
                edgeReader := bytes.NewReader(edgeBytes)
993✔
276
                edge, err := deserializeChanEdgePolicyRaw(
993✔
277
                        edgeReader,
993✔
278
                )
993✔
279

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

286
                // We don't want a single policy with bad TLV data to stop us
287
                // from loading the rest of the data, so we just skip this
288
                // policy. This is for backwards compatibility since we did not
289
                // use to validate TLV data in the past before persisting it.
290
                case errors.Is(err, ErrParsingExtraTLVBytes):
×
291
                        return nil
×
292

293
                case err != nil:
×
294
                        return err
×
295
                }
296

297
                channelMap[key] = edge
993✔
298

993✔
299
                return nil
993✔
300
        })
301
        if err != nil {
144✔
302
                return nil, err
×
303
        }
×
304

305
        return channelMap, nil
144✔
306
}
307

308
var graphTopLevelBuckets = [][]byte{
309
        nodeBucket,
310
        edgeBucket,
311
        graphMetaBucket,
312
        closedScidBucket,
313
}
314

315
// createChannelDB creates and initializes a fresh version of  In
316
// the case that the target path has not yet been created or doesn't yet exist,
317
// then the path is created. Additionally, all required top-level buckets used
318
// within the database are created.
319
func initKVStore(db kvdb.Backend) error {
172✔
320
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
344✔
321
                for _, tlb := range graphTopLevelBuckets {
851✔
322
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
679✔
323
                                return err
×
324
                        }
×
325
                }
326

327
                nodes := tx.ReadWriteBucket(nodeBucket)
172✔
328
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
172✔
329
                if err != nil {
172✔
330
                        return err
×
331
                }
×
332
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
172✔
333
                if err != nil {
172✔
334
                        return err
×
335
                }
×
336

337
                edges := tx.ReadWriteBucket(edgeBucket)
172✔
338
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
172✔
339
                if err != nil {
172✔
340
                        return err
×
341
                }
×
342
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
172✔
343
                if err != nil {
172✔
344
                        return err
×
345
                }
×
346
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
172✔
347
                if err != nil {
172✔
348
                        return err
×
349
                }
×
350
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
172✔
351
                if err != nil {
172✔
352
                        return err
×
353
                }
×
354

355
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
172✔
356
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
172✔
357

172✔
358
                return err
172✔
359
        }, func() {})
172✔
360
        if err != nil {
172✔
361
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
362
        }
×
363

364
        return nil
172✔
365
}
366

367
// AddrsForNode returns all known addresses for the target node public key that
368
// the graph DB is aware of. The returned boolean indicates if the given node is
369
// unknown to the graph DB or not.
370
//
371
// NOTE: this is part of the channeldb.AddrSource interface.
372
func (c *KVStore) AddrsForNode(nodePub *btcec.PublicKey) (bool, []net.Addr,
373
        error) {
6✔
374

6✔
375
        pubKey, err := route.NewVertexFromBytes(nodePub.SerializeCompressed())
6✔
376
        if err != nil {
6✔
377
                return false, nil, err
×
378
        }
×
379

380
        node, err := c.FetchLightningNode(pubKey)
6✔
381
        // We don't consider it an error if the graph is unaware of the node.
6✔
382
        switch {
6✔
383
        case err != nil && !errors.Is(err, ErrGraphNodeNotFound):
×
384
                return false, nil, err
×
385

386
        case errors.Is(err, ErrGraphNodeNotFound):
4✔
387
                return false, nil, nil
4✔
388
        }
389

390
        return true, node.Addresses, nil
5✔
391
}
392

393
// ForEachChannel iterates through all the channel edges stored within the
394
// graph and invokes the passed callback for each edge. The callback takes two
395
// edges as since this is a directed graph, both the in/out edges are visited.
396
// If the callback returns an error, then the transaction is aborted and the
397
// iteration stops early.
398
//
399
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
400
// for that particular channel edge routing policy will be passed into the
401
// callback.
402
func (c *KVStore) ForEachChannel(cb func(*models.ChannelEdgeInfo,
403
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
7✔
404

7✔
405
        return c.db.View(func(tx kvdb.RTx) error {
14✔
406
                edges := tx.ReadBucket(edgeBucket)
7✔
407
                if edges == nil {
7✔
408
                        return ErrGraphNoEdgesFound
×
409
                }
×
410

411
                // First, load all edges in memory indexed by node and channel
412
                // id.
413
                channelMap, err := c.getChannelMap(edges)
7✔
414
                if err != nil {
7✔
415
                        return err
×
416
                }
×
417

418
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
419
                if edgeIndex == nil {
7✔
420
                        return ErrGraphNoEdgesFound
×
421
                }
×
422

423
                // Load edge index, recombine each channel with the policies
424
                // loaded above and invoke the callback.
425
                return kvdb.ForAll(
7✔
426
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
109✔
427
                                var chanID [8]byte
102✔
428
                                copy(chanID[:], k)
102✔
429

102✔
430
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
102✔
431
                                info, err := deserializeChanEdgeInfo(
102✔
432
                                        edgeInfoReader,
102✔
433
                                )
102✔
434
                                if err != nil {
102✔
435
                                        return err
×
436
                                }
×
437

438
                                policy1 := channelMap[channelMapKey{
102✔
439
                                        nodeKey: info.NodeKey1Bytes,
102✔
440
                                        chanID:  chanID,
102✔
441
                                }]
102✔
442

102✔
443
                                policy2 := channelMap[channelMapKey{
102✔
444
                                        nodeKey: info.NodeKey2Bytes,
102✔
445
                                        chanID:  chanID,
102✔
446
                                }]
102✔
447

102✔
448
                                return cb(&info, policy1, policy2)
102✔
449
                        },
450
                )
451
        }, func() {})
7✔
452
}
453

454
// ForEachChannelCacheable iterates through all the channel edges stored within
455
// the graph and invokes the passed callback for each edge. The callback takes
456
// two edges as since this is a directed graph, both the in/out edges are
457
// visited. If the callback returns an error, then the transaction is aborted
458
// and the iteration stops early.
459
//
460
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
461
// for that particular channel edge routing policy will be passed into the
462
// callback.
463
//
464
// NOTE: this method is like ForEachChannel but fetches only the data required
465
// for the graph cache.
466
func (c *KVStore) ForEachChannelCacheable(cb func(*models.CachedEdgeInfo,
467
        *models.CachedEdgePolicy, *models.CachedEdgePolicy) error) error {
140✔
468

140✔
469
        return c.db.View(func(tx kvdb.RTx) error {
280✔
470
                edges := tx.ReadBucket(edgeBucket)
140✔
471
                if edges == nil {
140✔
UNCOV
472
                        return ErrGraphNoEdgesFound
×
UNCOV
473
                }
×
474

475
                // First, load all edges in memory indexed by node and channel
476
                // id.
477
                channelMap, err := c.getChannelMap(edges)
140✔
478
                if err != nil {
140✔
UNCOV
479
                        return err
×
UNCOV
480
                }
×
481

482
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
140✔
483
                if edgeIndex == nil {
140✔
UNCOV
484
                        return ErrGraphNoEdgesFound
×
UNCOV
485
                }
×
486

487
                // Load edge index, recombine each channel with the policies
488
                // loaded above and invoke the callback.
489
                return kvdb.ForAll(
140✔
490
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
539✔
491
                                var chanID [8]byte
399✔
492
                                copy(chanID[:], k)
399✔
493

399✔
494
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
399✔
495
                                info, err := deserializeChanEdgeInfo(
399✔
496
                                        edgeInfoReader,
399✔
497
                                )
399✔
498
                                if err != nil {
399✔
UNCOV
499
                                        return err
×
UNCOV
500
                                }
×
501

502
                                policy1 := channelMap[channelMapKey{
399✔
503
                                        nodeKey: info.NodeKey1Bytes,
399✔
504
                                        chanID:  chanID,
399✔
505
                                }]
399✔
506

399✔
507
                                policy2 := channelMap[channelMapKey{
399✔
508
                                        nodeKey: info.NodeKey2Bytes,
399✔
509
                                        chanID:  chanID,
399✔
510
                                }]
399✔
511

399✔
512
                                return cb(
399✔
513
                                        models.NewCachedEdge(&info),
399✔
514
                                        models.NewCachedPolicy(policy1),
399✔
515
                                        models.NewCachedPolicy(policy2),
399✔
516
                                )
399✔
517
                        },
518
                )
519
        }, func() {})
140✔
520
}
521

522
// forEachNodeDirectedChannel iterates through all channels of a given node,
523
// executing the passed callback on the directed edge representing the channel
524
// and its incoming policy. If the callback returns an error, then the iteration
525
// is halted with the error propagated back up to the caller. An optional read
526
// transaction may be provided. If none is provided, a new one will be created.
527
//
528
// Unknown policies are passed into the callback as nil values.
529
func (c *KVStore) forEachNodeDirectedChannel(tx kvdb.RTx,
530
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
265✔
531

265✔
532
        // Fallback that uses the database.
265✔
533
        toNodeCallback := func() route.Vertex {
400✔
534
                return node
135✔
535
        }
135✔
536
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
265✔
537
        if err != nil {
265✔
UNCOV
538
                return err
×
UNCOV
539
        }
×
540

541
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
265✔
542
                p2 *models.ChannelEdgePolicy) error {
954✔
543

689✔
544
                var cachedInPolicy *models.CachedEdgePolicy
689✔
545
                if p2 != nil {
1,375✔
546
                        cachedInPolicy = models.NewCachedPolicy(p2)
686✔
547
                        cachedInPolicy.ToNodePubKey = toNodeCallback
686✔
548
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
686✔
549
                }
686✔
550

551
                directedChannel := &DirectedChannel{
689✔
552
                        ChannelID:    e.ChannelID,
689✔
553
                        IsNode1:      node == e.NodeKey1Bytes,
689✔
554
                        OtherNode:    e.NodeKey2Bytes,
689✔
555
                        Capacity:     e.Capacity,
689✔
556
                        OutPolicySet: p1 != nil,
689✔
557
                        InPolicy:     cachedInPolicy,
689✔
558
                }
689✔
559

689✔
560
                if p1 != nil {
1,377✔
561
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
1,024✔
562
                                directedChannel.InboundFee = fee
336✔
563
                        })
336✔
564
                }
565

566
                if node == e.NodeKey2Bytes {
1,035✔
567
                        directedChannel.OtherNode = e.NodeKey1Bytes
346✔
568
                }
346✔
569

570
                return cb(directedChannel)
689✔
571
        }
572

573
        return nodeTraversal(tx, node[:], c.db, dbCallback)
265✔
574
}
575

576
// fetchNodeFeatures returns the features of a given node. If no features are
577
// known for the node, an empty feature vector is returned. An optional read
578
// transaction may be provided. If none is provided, a new one will be created.
579
func (c *KVStore) fetchNodeFeatures(tx kvdb.RTx,
580
        node route.Vertex) (*lnwire.FeatureVector, error) {
710✔
581

710✔
582
        // Fallback that uses the database.
710✔
583
        targetNode, err := c.FetchLightningNodeTx(tx, node)
710✔
584
        switch {
710✔
585
        // If the node exists and has features, return them directly.
586
        case err == nil:
699✔
587
                return targetNode.Features, nil
699✔
588

589
        // If we couldn't find a node announcement, populate a blank feature
590
        // vector.
591
        case errors.Is(err, ErrGraphNodeNotFound):
11✔
592
                return lnwire.EmptyFeatureVector(), nil
11✔
593

594
        // Otherwise, bubble the error up.
595
        default:
×
UNCOV
596
                return nil, err
×
597
        }
598
}
599

600
// ForEachNodeDirectedChannel iterates through all channels of a given node,
601
// executing the passed callback on the directed edge representing the channel
602
// and its incoming policy. If the callback returns an error, then the iteration
603
// is halted with the error propagated back up to the caller.
604
//
605
// Unknown policies are passed into the callback as nil values.
606
//
607
// NOTE: this is part of the graphdb.NodeTraverser interface.
608
func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
609
        cb func(channel *DirectedChannel) error) error {
26✔
610

26✔
611
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
26✔
612
}
26✔
613

614
// FetchNodeFeatures returns the features of the given node. If no features are
615
// known for the node, an empty feature vector is returned.
616
//
617
// NOTE: this is part of the graphdb.NodeTraverser interface.
618
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
619
        *lnwire.FeatureVector, error) {
4✔
620

4✔
621
        return c.fetchNodeFeatures(nil, nodePub)
4✔
622
}
4✔
623

624
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
625
// data to the call-back.
626
//
627
// NOTE: The callback contents MUST not be modified.
628
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
629
        chans map[uint64]*DirectedChannel) error) error {
1✔
630

1✔
631
        // Otherwise call back to a version that uses the database directly.
1✔
632
        // We'll iterate over each node, then the set of channels for each
1✔
633
        // node, and construct a similar callback functiopn signature as the
1✔
634
        // main funcotin expects.
1✔
635
        return c.forEachNode(func(tx kvdb.RTx,
1✔
636
                node *models.LightningNode) error {
21✔
637

20✔
638
                channels := make(map[uint64]*DirectedChannel)
20✔
639

20✔
640
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
20✔
641
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
642
                                p1 *models.ChannelEdgePolicy,
20✔
643
                                p2 *models.ChannelEdgePolicy) error {
210✔
644

190✔
645
                                toNodeCallback := func() route.Vertex {
190✔
UNCOV
646
                                        return node.PubKeyBytes
×
647
                                }
×
648
                                toNodeFeatures, err := c.fetchNodeFeatures(
190✔
649
                                        tx, node.PubKeyBytes,
190✔
650
                                )
190✔
651
                                if err != nil {
190✔
652
                                        return err
×
653
                                }
×
654

655
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
656
                                if p2 != nil {
380✔
657
                                        cachedInPolicy =
190✔
658
                                                models.NewCachedPolicy(p2)
190✔
659
                                        cachedInPolicy.ToNodePubKey =
190✔
660
                                                toNodeCallback
190✔
661
                                        cachedInPolicy.ToNodeFeatures =
190✔
662
                                                toNodeFeatures
190✔
663
                                }
190✔
664

665
                                directedChannel := &DirectedChannel{
190✔
666
                                        ChannelID: e.ChannelID,
190✔
667
                                        IsNode1: node.PubKeyBytes ==
190✔
668
                                                e.NodeKey1Bytes,
190✔
669
                                        OtherNode:    e.NodeKey2Bytes,
190✔
670
                                        Capacity:     e.Capacity,
190✔
671
                                        OutPolicySet: p1 != nil,
190✔
672
                                        InPolicy:     cachedInPolicy,
190✔
673
                                }
190✔
674

190✔
675
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
676
                                        directedChannel.OtherNode =
95✔
677
                                                e.NodeKey1Bytes
95✔
678
                                }
95✔
679

680
                                channels[e.ChannelID] = directedChannel
190✔
681

190✔
682
                                return nil
190✔
683
                        })
684
                if err != nil {
20✔
UNCOV
685
                        return err
×
UNCOV
686
                }
×
687

688
                return cb(node.PubKeyBytes, channels)
20✔
689
        })
690
}
691

692
// DisabledChannelIDs returns the channel ids of disabled channels.
693
// A channel is disabled when two of the associated ChanelEdgePolicies
694
// have their disabled bit on.
695
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
6✔
696
        var disabledChanIDs []uint64
6✔
697
        var chanEdgeFound map[uint64]struct{}
6✔
698

6✔
699
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
700
                edges := tx.ReadBucket(edgeBucket)
6✔
701
                if edges == nil {
6✔
UNCOV
702
                        return ErrGraphNoEdgesFound
×
UNCOV
703
                }
×
704

705
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
706
                        disabledEdgePolicyBucket,
6✔
707
                )
6✔
708
                if disabledEdgePolicyIndex == nil {
7✔
709
                        return nil
1✔
710
                }
1✔
711

712
                // We iterate over all disabled policies and we add each channel
713
                // that has more than one disabled policy to disabledChanIDs
714
                // array.
715
                return disabledEdgePolicyIndex.ForEach(
5✔
716
                        func(k, v []byte) error {
16✔
717
                                chanID := byteOrder.Uint64(k[:8])
11✔
718
                                _, edgeFound := chanEdgeFound[chanID]
11✔
719
                                if edgeFound {
15✔
720
                                        delete(chanEdgeFound, chanID)
4✔
721
                                        disabledChanIDs = append(
4✔
722
                                                disabledChanIDs, chanID,
4✔
723
                                        )
4✔
724

4✔
725
                                        return nil
4✔
726
                                }
4✔
727

728
                                chanEdgeFound[chanID] = struct{}{}
7✔
729

7✔
730
                                return nil
7✔
731
                        },
732
                )
733
        }, func() {
6✔
734
                disabledChanIDs = nil
6✔
735
                chanEdgeFound = make(map[uint64]struct{})
6✔
736
        })
6✔
737
        if err != nil {
6✔
UNCOV
738
                return nil, err
×
UNCOV
739
        }
×
740

741
        return disabledChanIDs, nil
6✔
742
}
743

744
// ForEachNode iterates through all the stored vertices/nodes in the graph,
745
// executing the passed callback with each node encountered. If the callback
746
// returns an error, then the transaction is aborted and the iteration stops
747
// early. Any operations performed on the NodeTx passed to the call-back are
748
// executed under the same read transaction and so, methods on the NodeTx object
749
// _MUST_ only be called from within the call-back.
750
func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error {
131✔
751
        return c.forEachNode(func(tx kvdb.RTx,
131✔
752
                node *models.LightningNode) error {
1,292✔
753

1,161✔
754
                return cb(newChanGraphNodeTx(tx, c, node))
1,161✔
755
        })
1,161✔
756
}
757

758
// forEachNode iterates through all the stored vertices/nodes in the graph,
759
// executing the passed callback with each node encountered. If the callback
760
// returns an error, then the transaction is aborted and the iteration stops
761
// early.
762
//
763
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
764
// traversal when graph gets mega.
765
func (c *KVStore) forEachNode(
766
        cb func(kvdb.RTx, *models.LightningNode) error) error {
132✔
767

132✔
768
        traversal := func(tx kvdb.RTx) error {
264✔
769
                // First grab the nodes bucket which stores the mapping from
132✔
770
                // pubKey to node information.
132✔
771
                nodes := tx.ReadBucket(nodeBucket)
132✔
772
                if nodes == nil {
132✔
UNCOV
773
                        return ErrGraphNotFound
×
UNCOV
774
                }
×
775

776
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,574✔
777
                        // If this is the source key, then we skip this
1,442✔
778
                        // iteration as the value for this key is a pubKey
1,442✔
779
                        // rather than raw node information.
1,442✔
780
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,706✔
781
                                return nil
264✔
782
                        }
264✔
783

784
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
785
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
786
                        if err != nil {
1,181✔
787
                                return err
×
788
                        }
×
789

790
                        // Execute the callback, the transaction will abort if
791
                        // this returns an error.
792
                        return cb(tx, &node)
1,181✔
793
                })
794
        }
795

796
        return kvdb.View(c.db, traversal, func() {})
264✔
797
}
798

799
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
800
// graph, executing the passed callback with each node encountered. If the
801
// callback returns an error, then the transaction is aborted and the iteration
802
// stops early.
803
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
804
        *lnwire.FeatureVector) error) error {
141✔
805

141✔
806
        traversal := func(tx kvdb.RTx) error {
282✔
807
                // First grab the nodes bucket which stores the mapping from
141✔
808
                // pubKey to node information.
141✔
809
                nodes := tx.ReadBucket(nodeBucket)
141✔
810
                if nodes == nil {
141✔
811
                        return ErrGraphNotFound
×
812
                }
×
813

814
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
540✔
815
                        // If this is the source key, then we skip this
399✔
816
                        // iteration as the value for this key is a pubKey
399✔
817
                        // rather than raw node information.
399✔
818
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
678✔
819
                                return nil
279✔
820
                        }
279✔
821

822
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
823
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
123✔
824
                                nodeReader,
123✔
825
                        )
123✔
826
                        if err != nil {
123✔
UNCOV
827
                                return err
×
UNCOV
828
                        }
×
829

830
                        // Execute the callback, the transaction will abort if
831
                        // this returns an error.
832
                        return cb(node, features)
123✔
833
                })
834
        }
835

836
        return kvdb.View(c.db, traversal, func() {})
282✔
837
}
838

839
// SourceNode returns the source node of the graph. The source node is treated
840
// as the center node within a star-graph. This method may be used to kick off
841
// a path finding algorithm in order to explore the reachability of another
842
// node based off the source node.
843
func (c *KVStore) SourceNode() (*models.LightningNode, error) {
240✔
844
        var source *models.LightningNode
240✔
845
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
480✔
846
                // First grab the nodes bucket which stores the mapping from
240✔
847
                // pubKey to node information.
240✔
848
                nodes := tx.ReadBucket(nodeBucket)
240✔
849
                if nodes == nil {
240✔
UNCOV
850
                        return ErrGraphNotFound
×
UNCOV
851
                }
×
852

853
                node, err := c.sourceNode(nodes)
240✔
854
                if err != nil {
241✔
855
                        return err
1✔
856
                }
1✔
857
                source = node
239✔
858

239✔
859
                return nil
239✔
860
        }, func() {
240✔
861
                source = nil
240✔
862
        })
240✔
863
        if err != nil {
241✔
864
                return nil, err
1✔
865
        }
1✔
866

867
        return source, nil
239✔
868
}
869

870
// sourceNode uses an existing database transaction and returns the source node
871
// of the graph. The source node is treated as the center node within a
872
// star-graph. This method may be used to kick off a path finding algorithm in
873
// order to explore the reachability of another node based off the source node.
874
func (c *KVStore) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
875
        error) {
500✔
876

500✔
877
        selfPub := nodes.Get(sourceKey)
500✔
878
        if selfPub == nil {
501✔
879
                return nil, ErrSourceNodeNotSet
1✔
880
        }
1✔
881

882
        // With the pubKey of the source node retrieved, we're able to
883
        // fetch the full node information.
884
        node, err := fetchLightningNode(nodes, selfPub)
499✔
885
        if err != nil {
499✔
UNCOV
886
                return nil, err
×
UNCOV
887
        }
×
888

889
        return &node, nil
499✔
890
}
891

892
// SetSourceNode sets the source node within the graph database. The source
893
// node is to be used as the center of a star-graph within path finding
894
// algorithms.
895
func (c *KVStore) SetSourceNode(node *models.LightningNode) error {
117✔
896
        nodePubBytes := node.PubKeyBytes[:]
117✔
897

117✔
898
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
234✔
899
                // First grab the nodes bucket which stores the mapping from
117✔
900
                // pubKey to node information.
117✔
901
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
117✔
902
                if err != nil {
117✔
903
                        return err
×
UNCOV
904
                }
×
905

906
                // Next we create the mapping from source to the targeted
907
                // public key.
908
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
117✔
UNCOV
909
                        return err
×
UNCOV
910
                }
×
911

912
                // Finally, we commit the information of the lightning node
913
                // itself.
914
                return addLightningNode(tx, node)
117✔
915
        }, func() {})
117✔
916
}
917

918
// AddLightningNode adds a vertex/node to the graph database. If the node is not
919
// in the database from before, this will add a new, unconnected one to the
920
// graph. If it is present from before, this will update that node's
921
// information. Note that this method is expected to only be called to update an
922
// already present node from a node announcement, or to insert a node found in a
923
// channel update.
924
//
925
// TODO(roasbeef): also need sig of announcement.
926
func (c *KVStore) AddLightningNode(node *models.LightningNode,
927
        opts ...batch.SchedulerOption) error {
715✔
928

715✔
929
        ctx := context.TODO()
715✔
930

715✔
931
        r := &batch.Request[kvdb.RwTx]{
715✔
932
                Opts: batch.NewSchedulerOptions(opts...),
715✔
933
                Do: func(tx kvdb.RwTx) error {
1,430✔
934
                        return addLightningNode(tx, node)
715✔
935
                },
715✔
936
        }
937

938
        return c.nodeScheduler.Execute(ctx, r)
715✔
939
}
940

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

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

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

959
        return putLightningNode(nodes, aliases, updateIndex, node)
905✔
960
}
961

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

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

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

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

984
                // TODO(roasbeef): should actually be using the utf-8
985
                // package...
986
                alias = string(a)
4✔
987

4✔
988
                return nil
4✔
989
        }, func() {
5✔
990
                alias = ""
5✔
991
        })
5✔
992
        if err != nil {
6✔
993
                return "", err
1✔
994
        }
1✔
995

996
        return alias, nil
4✔
997
}
998

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

1009
                return c.deleteLightningNode(nodes, nodePub[:])
4✔
1010
        }, func() {})
4✔
1011
}
1012

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

65✔
1018
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
65✔
1019
        if aliases == nil {
65✔
1020
                return ErrGraphNodesNotFound
×
1021
        }
×
1022

1023
        if err := aliases.Delete(compressedPubKey); err != nil {
65✔
UNCOV
1024
                return err
×
UNCOV
1025
        }
×
1026

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

1035
        if err := nodes.Delete(compressedPubKey); err != nil {
64✔
UNCOV
1036
                return err
×
UNCOV
1037
        }
×
1038

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

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

64✔
1054
        return nodeUpdateIndex.Delete(indexKey[:])
64✔
1055
}
1056

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

1,720✔
1066
        ctx := context.TODO()
1,720✔
1067

1,720✔
1068
        var alreadyExists bool
1,720✔
1069
        r := &batch.Request[kvdb.RwTx]{
1,720✔
1070
                Opts: batch.NewSchedulerOptions(opts...),
1,720✔
1071
                Reset: func() {
3,440✔
1072
                        alreadyExists = false
1,720✔
1073
                },
1,720✔
1074
                Do: func(tx kvdb.RwTx) error {
1,720✔
1075
                        err := c.addChannelEdge(tx, edge)
1,720✔
1076

1,720✔
1077
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,720✔
1078
                        // succeed, but propagate the error via local state.
1,720✔
1079
                        if errors.Is(err, ErrEdgeAlreadyExist) {
1,957✔
1080
                                alreadyExists = true
237✔
1081
                                return nil
237✔
1082
                        }
237✔
1083

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

1100
        return c.chanScheduler.Execute(ctx, r)
1,720✔
1101
}
1102

1103
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1104
// utilize an existing db transaction.
1105
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1106
        edge *models.ChannelEdgeInfo) error {
1,720✔
1107

1,720✔
1108
        // Construct the channel's primary key which is the 8-byte channel ID.
1,720✔
1109
        var chanKey [8]byte
1,720✔
1110
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,720✔
1111

1,720✔
1112
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,720✔
1113
        if err != nil {
1,720✔
UNCOV
1114
                return err
×
UNCOV
1115
        }
×
1116
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,720✔
1117
        if err != nil {
1,720✔
UNCOV
1118
                return err
×
1119
        }
×
1120
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,720✔
1121
        if err != nil {
1,720✔
UNCOV
1122
                return err
×
UNCOV
1123
        }
×
1124
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,720✔
1125
        if err != nil {
1,720✔
UNCOV
1126
                return err
×
1127
        }
×
1128

1129
        // First, attempt to check if this edge has already been created. If
1130
        // so, then we can exit early as this method is meant to be idempotent.
1131
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,957✔
1132
                return ErrEdgeAlreadyExist
237✔
1133
        }
237✔
1134

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

1155
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,483✔
1156
        switch {
1,483✔
1157
        case errors.Is(node2Err, ErrGraphNodeNotFound):
59✔
1158
                node2Shell := models.LightningNode{
59✔
1159
                        PubKeyBytes:          edge.NodeKey2Bytes,
59✔
1160
                        HaveNodeAnnouncement: false,
59✔
1161
                }
59✔
1162
                err := addLightningNode(tx, &node2Shell)
59✔
1163
                if err != nil {
59✔
UNCOV
1164
                        return fmt.Errorf("unable to create shell node "+
×
UNCOV
1165
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
UNCOV
1166
                }
×
UNCOV
1167
        case node2Err != nil:
×
UNCOV
1168
                return node2Err
×
1169
        }
1170

1171
        // If the edge hasn't been created yet, then we'll first add it to the
1172
        // edge index in order to associate the edge between two nodes and also
1173
        // store the static components of the channel.
1174
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
1,483✔
UNCOV
1175
                return err
×
UNCOV
1176
        }
×
1177

1178
        // Mark edge policies for both sides as unknown. This is to enable
1179
        // efficient incoming channel lookup for a node.
1180
        keys := []*[33]byte{
1,483✔
1181
                &edge.NodeKey1Bytes,
1,483✔
1182
                &edge.NodeKey2Bytes,
1,483✔
1183
        }
1,483✔
1184
        for _, key := range keys {
4,446✔
1185
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,963✔
1186
                if err != nil {
2,963✔
UNCOV
1187
                        return err
×
UNCOV
1188
                }
×
1189
        }
1190

1191
        // Finally we add it to the channel index which maps channel points
1192
        // (outpoints) to the shorter channel ID's.
1193
        var b bytes.Buffer
1,483✔
1194
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,483✔
UNCOV
1195
                return err
×
UNCOV
1196
        }
×
1197

1198
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,483✔
1199
}
1200

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

215✔
1210
        var (
215✔
1211
                upd1Time time.Time
215✔
1212
                upd2Time time.Time
215✔
1213
                exists   bool
215✔
1214
                isZombie bool
215✔
1215
        )
215✔
1216

215✔
1217
        // We'll query the cache with the shared lock held to allow multiple
215✔
1218
        // readers to access values in the cache concurrently if they exist.
215✔
1219
        c.cacheMu.RLock()
215✔
1220
        if entry, ok := c.rejectCache.get(chanID); ok {
286✔
1221
                c.cacheMu.RUnlock()
71✔
1222
                upd1Time = time.Unix(entry.upd1Time, 0)
71✔
1223
                upd2Time = time.Unix(entry.upd2Time, 0)
71✔
1224
                exists, isZombie = entry.flags.unpack()
71✔
1225

71✔
1226
                return upd1Time, upd2Time, exists, isZombie, nil
71✔
1227
        }
71✔
1228
        c.cacheMu.RUnlock()
147✔
1229

147✔
1230
        c.cacheMu.Lock()
147✔
1231
        defer c.cacheMu.Unlock()
147✔
1232

147✔
1233
        // The item was not found with the shared lock, so we'll acquire the
147✔
1234
        // exclusive lock and check the cache again in case another method added
147✔
1235
        // the entry to the cache while no lock was held.
147✔
1236
        if entry, ok := c.rejectCache.get(chanID); ok {
152✔
1237
                upd1Time = time.Unix(entry.upd1Time, 0)
5✔
1238
                upd2Time = time.Unix(entry.upd2Time, 0)
5✔
1239
                exists, isZombie = entry.flags.unpack()
5✔
1240

5✔
1241
                return upd1Time, upd2Time, exists, isZombie, nil
5✔
1242
        }
5✔
1243

1244
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
290✔
1245
                edges := tx.ReadBucket(edgeBucket)
145✔
1246
                if edges == nil {
145✔
UNCOV
1247
                        return ErrGraphNoEdgesFound
×
UNCOV
1248
                }
×
1249
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
145✔
1250
                if edgeIndex == nil {
145✔
UNCOV
1251
                        return ErrGraphNoEdgesFound
×
UNCOV
1252
                }
×
1253

1254
                var channelID [8]byte
145✔
1255
                byteOrder.PutUint64(channelID[:], chanID)
145✔
1256

145✔
1257
                // If the edge doesn't exist, then we'll also check our zombie
145✔
1258
                // index.
145✔
1259
                if edgeIndex.Get(channelID[:]) == nil {
244✔
1260
                        exists = false
99✔
1261
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
99✔
1262
                        if zombieIndex != nil {
198✔
1263
                                isZombie, _, _ = isZombieEdge(
99✔
1264
                                        zombieIndex, chanID,
99✔
1265
                                )
99✔
1266
                        }
99✔
1267

1268
                        return nil
99✔
1269
                }
1270

1271
                exists = true
49✔
1272
                isZombie = false
49✔
1273

49✔
1274
                // If the channel has been found in the graph, then retrieve
49✔
1275
                // the edges itself so we can return the last updated
49✔
1276
                // timestamps.
49✔
1277
                nodes := tx.ReadBucket(nodeBucket)
49✔
1278
                if nodes == nil {
49✔
UNCOV
1279
                        return ErrGraphNodeNotFound
×
UNCOV
1280
                }
×
1281

1282
                e1, e2, err := fetchChanEdgePolicies(
49✔
1283
                        edgeIndex, edges, channelID[:],
49✔
1284
                )
49✔
1285
                if err != nil {
49✔
UNCOV
1286
                        return err
×
UNCOV
1287
                }
×
1288

1289
                // As we may have only one of the edges populated, only set the
1290
                // update time if the edge was found in the database.
1291
                if e1 != nil {
70✔
1292
                        upd1Time = e1.LastUpdate
21✔
1293
                }
21✔
1294
                if e2 != nil {
68✔
1295
                        upd2Time = e2.LastUpdate
19✔
1296
                }
19✔
1297

1298
                return nil
49✔
1299
        }, func() {}); err != nil {
145✔
UNCOV
1300
                return time.Time{}, time.Time{}, exists, isZombie, err
×
UNCOV
1301
        }
×
1302

1303
        c.rejectCache.insert(chanID, rejectCacheEntry{
145✔
1304
                upd1Time: upd1Time.Unix(),
145✔
1305
                upd2Time: upd2Time.Unix(),
145✔
1306
                flags:    packRejectFlags(exists, isZombie),
145✔
1307
        })
145✔
1308

145✔
1309
        return upd1Time, upd2Time, exists, isZombie, nil
145✔
1310
}
1311

1312
// AddEdgeProof sets the proof of an existing edge in the graph database.
1313
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1314
        proof *models.ChannelAuthProof) error {
5✔
1315

5✔
1316
        // Construct the channel's primary key which is the 8-byte channel ID.
5✔
1317
        var chanKey [8]byte
5✔
1318
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
5✔
1319

5✔
1320
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
10✔
1321
                edges := tx.ReadWriteBucket(edgeBucket)
5✔
1322
                if edges == nil {
5✔
UNCOV
1323
                        return ErrEdgeNotFound
×
UNCOV
1324
                }
×
1325

1326
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1327
                if edgeIndex == nil {
5✔
UNCOV
1328
                        return ErrEdgeNotFound
×
1329
                }
×
1330

1331
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
5✔
1332
                if err != nil {
5✔
UNCOV
1333
                        return err
×
UNCOV
1334
                }
×
1335

1336
                edge.AuthProof = proof
5✔
1337

5✔
1338
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
5✔
1339
        }, func() {})
5✔
1340
}
1341

1342
const (
1343
        // pruneTipBytes is the total size of the value which stores a prune
1344
        // entry of the graph in the prune log. The "prune tip" is the last
1345
        // entry in the prune log, and indicates if the channel graph is in
1346
        // sync with the current UTXO state. The structure of the value
1347
        // is: blockHash, taking 32 bytes total.
1348
        pruneTipBytes = 32
1349
)
1350

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

239✔
1363
        c.cacheMu.Lock()
239✔
1364
        defer c.cacheMu.Unlock()
239✔
1365

239✔
1366
        var (
239✔
1367
                chansClosed []*models.ChannelEdgeInfo
239✔
1368
                prunedNodes []route.Vertex
239✔
1369
        )
239✔
1370

239✔
1371
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
478✔
1372
                // First grab the edges bucket which houses the information
239✔
1373
                // we'd like to delete
239✔
1374
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
239✔
1375
                if err != nil {
239✔
1376
                        return err
×
1377
                }
×
1378

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

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

125✔
1407
                        var opBytes bytes.Buffer
125✔
1408
                        err := WriteOutpoint(&opBytes, chanPoint)
125✔
1409
                        if err != nil {
125✔
UNCOV
1410
                                return err
×
UNCOV
1411
                        }
×
1412

1413
                        // First attempt to see if the channel exists within
1414
                        // the database, if not, then we can exit early.
1415
                        chanID := chanIndex.Get(opBytes.Bytes())
125✔
1416
                        if chanID == nil {
228✔
1417
                                continue
103✔
1418
                        }
1419

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

1432
                        chansClosed = append(chansClosed, edgeInfo)
22✔
1433
                }
1434

1435
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
239✔
1436
                if err != nil {
239✔
UNCOV
1437
                        return err
×
1438
                }
×
1439

1440
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
239✔
1441
                        pruneLogBucket,
239✔
1442
                )
239✔
1443
                if err != nil {
239✔
UNCOV
1444
                        return err
×
UNCOV
1445
                }
×
1446

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

239✔
1453
                var newTip [pruneTipBytes]byte
239✔
1454
                copy(newTip[:], blockHash[:])
239✔
1455

239✔
1456
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
239✔
1457
                if err != nil {
239✔
UNCOV
1458
                        return err
×
UNCOV
1459
                }
×
1460

1461
                // Now that the graph has been pruned, we'll also attempt to
1462
                // prune any nodes that have had a channel closed within the
1463
                // latest block.
1464
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
239✔
1465

239✔
1466
                return err
239✔
1467
        }, func() {
239✔
1468
                chansClosed = nil
239✔
1469
                prunedNodes = nil
239✔
1470
        })
239✔
1471
        if err != nil {
239✔
UNCOV
1472
                return nil, nil, err
×
UNCOV
1473
        }
×
1474

1475
        for _, channel := range chansClosed {
261✔
1476
                c.rejectCache.remove(channel.ChannelID)
22✔
1477
                c.chanCache.remove(channel.ChannelID)
22✔
1478
        }
22✔
1479

1480
        return chansClosed, prunedNodes, nil
239✔
1481
}
1482

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

1503
                var err error
26✔
1504
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
26✔
1505
                if err != nil {
26✔
UNCOV
1506
                        return err
×
UNCOV
1507
                }
×
1508

1509
                return nil
26✔
1510
        }, func() {
26✔
1511
                prunedNodes = nil
26✔
1512
        })
26✔
1513

1514
        return prunedNodes, err
26✔
1515
}
1516

1517
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1518
// channel closed within the current block. If the node still has existing
1519
// channels in the graph, this will act as a no-op.
1520
func (c *KVStore) pruneGraphNodes(nodes kvdb.RwBucket,
1521
        edgeIndex kvdb.RwBucket) ([]route.Vertex, error) {
262✔
1522

262✔
1523
        log.Trace("Pruning nodes from graph with no open channels")
262✔
1524

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

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

1544
                var nodePub [33]byte
505✔
1545
                copy(nodePub[:], pubKey)
505✔
1546
                nodeRefCounts[nodePub] = 0
505✔
1547

505✔
1548
                return nil
505✔
1549
        })
1550
        if err != nil {
262✔
UNCOV
1551
                return nil, err
×
UNCOV
1552
        }
×
1553

1554
        // To ensure we never delete the source node, we'll start off by
1555
        // bumping its ref count to 1.
1556
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
262✔
1557

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

213✔
1569
                // With the nodes extracted, we'll increase the ref count of
213✔
1570
                // each of the nodes.
213✔
1571
                nodeRefCounts[node1]++
213✔
1572
                nodeRefCounts[node2]++
213✔
1573

213✔
1574
                return nil
213✔
1575
        })
213✔
1576
        if err != nil {
262✔
UNCOV
1577
                return nil, err
×
UNCOV
1578
        }
×
1579

1580
        // Finally, we'll make a second pass over the set of nodes, and delete
1581
        // any nodes that have a ref count of zero.
1582
        var pruned []route.Vertex
262✔
1583
        for nodePubKey, refCount := range nodeRefCounts {
767✔
1584
                // If the ref count of the node isn't zero, then we can safely
505✔
1585
                // skip it as it still has edges to or from it within the
505✔
1586
                // graph.
505✔
1587
                if refCount != 0 {
952✔
1588
                        continue
447✔
1589
                }
1590

1591
                // If we reach this point, then there are no longer any edges
1592
                // that connect this node, so we can delete it.
1593
                err := c.deleteLightningNode(nodes, nodePubKey[:])
61✔
1594
                if err != nil {
61✔
UNCOV
1595
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
UNCOV
1596
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1597

×
1598
                                log.Warnf("Unable to prune node %x from the "+
×
UNCOV
1599
                                        "graph: %v", nodePubKey, err)
×
UNCOV
1600
                                continue
×
1601
                        }
1602

UNCOV
1603
                        return nil, err
×
1604
                }
1605

1606
                log.Infof("Pruned unconnected node %x from channel graph",
61✔
1607
                        nodePubKey[:])
61✔
1608

61✔
1609
                pruned = append(pruned, nodePubKey)
61✔
1610
        }
1611

1612
        if len(pruned) > 0 {
307✔
1613
                log.Infof("Pruned %v unconnected nodes from the channel graph",
45✔
1614
                        len(pruned))
45✔
1615
        }
45✔
1616

1617
        return pruned, err
262✔
1618
}
1619

1620
// DisconnectBlockAtHeight is used to indicate that the block specified
1621
// by the passed height has been disconnected from the main chain. This
1622
// will "rewind" the graph back to the height below, deleting channels
1623
// that are no longer confirmed from the graph. The prune log will be
1624
// set to the last prune height valid for the remaining chain.
1625
// Channels that were removed from the graph resulting from the
1626
// disconnected block are returned.
1627
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1628
        []*models.ChannelEdgeInfo, error) {
160✔
1629

160✔
1630
        // Every channel having a ShortChannelID starting at 'height'
160✔
1631
        // will no longer be confirmed.
160✔
1632
        startShortChanID := lnwire.ShortChannelID{
160✔
1633
                BlockHeight: height,
160✔
1634
        }
160✔
1635

160✔
1636
        // Delete everything after this height from the db up until the
160✔
1637
        // SCID alias range.
160✔
1638
        endShortChanID := aliasmgr.StartingAlias
160✔
1639

160✔
1640
        // The block height will be the 3 first bytes of the channel IDs.
160✔
1641
        var chanIDStart [8]byte
160✔
1642
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
160✔
1643
        var chanIDEnd [8]byte
160✔
1644
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
160✔
1645

160✔
1646
        c.cacheMu.Lock()
160✔
1647
        defer c.cacheMu.Unlock()
160✔
1648

160✔
1649
        // Keep track of the channels that are removed from the graph.
160✔
1650
        var removedChans []*models.ChannelEdgeInfo
160✔
1651

160✔
1652
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
320✔
1653
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
160✔
1654
                if err != nil {
160✔
UNCOV
1655
                        return err
×
UNCOV
1656
                }
×
1657
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
160✔
1658
                if err != nil {
160✔
UNCOV
1659
                        return err
×
UNCOV
1660
                }
×
1661
                chanIndex, err := edges.CreateBucketIfNotExists(
160✔
1662
                        channelPointBucket,
160✔
1663
                )
160✔
1664
                if err != nil {
160✔
UNCOV
1665
                        return err
×
UNCOV
1666
                }
×
1667
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
160✔
1668
                if err != nil {
160✔
UNCOV
1669
                        return err
×
UNCOV
1670
                }
×
1671

1672
                // Scan from chanIDStart to chanIDEnd, deleting every
1673
                // found edge.
1674
                // NOTE: we must delete the edges after the cursor loop, since
1675
                // modifying the bucket while traversing is not safe.
1676
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1677
                // so that the StartingAlias itself isn't deleted.
1678
                var keys [][]byte
160✔
1679
                cursor := edgeIndex.ReadWriteCursor()
160✔
1680

160✔
1681
                //nolint:ll
160✔
1682
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
160✔
1683
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
254✔
1684
                        keys = append(keys, k)
94✔
1685
                }
94✔
1686

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

1696
                        removedChans = append(removedChans, edgeInfo)
94✔
1697
                }
1698

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

1706
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
160✔
1707
                        pruneLogBucket,
160✔
1708
                )
160✔
1709
                if err != nil {
160✔
UNCOV
1710
                        return err
×
UNCOV
1711
                }
×
1712

1713
                var pruneKeyStart [4]byte
160✔
1714
                byteOrder.PutUint32(pruneKeyStart[:], height)
160✔
1715

160✔
1716
                var pruneKeyEnd [4]byte
160✔
1717
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
160✔
1718

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

1729
                for _, k := range pruneKeys {
259✔
1730
                        if err := pruneBucket.Delete(k); err != nil {
99✔
UNCOV
1731
                                return err
×
UNCOV
1732
                        }
×
1733
                }
1734

1735
                return nil
160✔
1736
        }, func() {
160✔
1737
                removedChans = nil
160✔
1738
        }); err != nil {
160✔
UNCOV
1739
                return nil, err
×
UNCOV
1740
        }
×
1741

1742
        for _, channel := range removedChans {
254✔
1743
                c.rejectCache.remove(channel.ChannelID)
94✔
1744
                c.chanCache.remove(channel.ChannelID)
94✔
1745
        }
94✔
1746

1747
        return removedChans, nil
160✔
1748
}
1749

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

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

1770
                pruneCursor := pruneBucket.ReadCursor()
56✔
1771

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

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

38✔
1784
                return nil
38✔
1785
        }, func() {})
56✔
1786
        if err != nil {
77✔
1787
                return nil, 0, err
21✔
1788
        }
21✔
1789

1790
        return &tipHash, tipHeight, nil
38✔
1791
}
1792

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

142✔
1804
        // TODO(roasbeef): possibly delete from node bucket if node has no more
142✔
1805
        // channels
142✔
1806
        // TODO(roasbeef): don't delete both edges?
142✔
1807

142✔
1808
        c.cacheMu.Lock()
142✔
1809
        defer c.cacheMu.Unlock()
142✔
1810

142✔
1811
        var infos []*models.ChannelEdgeInfo
142✔
1812
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
284✔
1813
                edges := tx.ReadWriteBucket(edgeBucket)
142✔
1814
                if edges == nil {
142✔
UNCOV
1815
                        return ErrEdgeNotFound
×
UNCOV
1816
                }
×
1817
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
142✔
1818
                if edgeIndex == nil {
142✔
1819
                        return ErrEdgeNotFound
×
UNCOV
1820
                }
×
1821
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
142✔
1822
                if chanIndex == nil {
142✔
1823
                        return ErrEdgeNotFound
×
1824
                }
×
1825
                nodes := tx.ReadWriteBucket(nodeBucket)
142✔
1826
                if nodes == nil {
142✔
1827
                        return ErrGraphNodeNotFound
×
1828
                }
×
1829
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
142✔
1830
                if err != nil {
142✔
UNCOV
1831
                        return err
×
UNCOV
1832
                }
×
1833

1834
                var rawChanID [8]byte
142✔
1835
                for _, chanID := range chanIDs {
227✔
1836
                        byteOrder.PutUint64(rawChanID[:], chanID)
85✔
1837
                        edgeInfo, err := c.delChannelEdgeUnsafe(
85✔
1838
                                edges, edgeIndex, chanIndex, zombieIndex,
85✔
1839
                                rawChanID[:], markZombie, strictZombiePruning,
85✔
1840
                        )
85✔
1841
                        if err != nil {
145✔
1842
                                return err
60✔
1843
                        }
60✔
1844

1845
                        infos = append(infos, edgeInfo)
25✔
1846
                }
1847

1848
                return nil
82✔
1849
        }, func() {
142✔
1850
                infos = nil
142✔
1851
        })
142✔
1852
        if err != nil {
202✔
1853
                return nil, err
60✔
1854
        }
60✔
1855

1856
        for _, chanID := range chanIDs {
107✔
1857
                c.rejectCache.remove(chanID)
25✔
1858
                c.chanCache.remove(chanID)
25✔
1859
        }
25✔
1860

1861
        return infos, nil
82✔
1862
}
1863

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

1879
        return chanID, nil
4✔
1880
}
1881

1882
// getChanID returns the assigned channel ID for a given channel point.
1883
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
4✔
1884
        var b bytes.Buffer
4✔
1885
        if err := WriteOutpoint(&b, chanPoint); err != nil {
4✔
UNCOV
1886
                return 0, err
×
UNCOV
1887
        }
×
1888

1889
        edges := tx.ReadBucket(edgeBucket)
4✔
1890
        if edges == nil {
4✔
UNCOV
1891
                return 0, ErrGraphNoEdgesFound
×
UNCOV
1892
        }
×
1893
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1894
        if chanIndex == nil {
4✔
UNCOV
1895
                return 0, ErrGraphNoEdgesFound
×
UNCOV
1896
        }
×
1897

1898
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1899
        if chanIDBytes == nil {
7✔
1900
                return 0, ErrEdgeNotFound
3✔
1901
        }
3✔
1902

1903
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1904

4✔
1905
        return chanID, nil
4✔
1906
}
1907

1908
// TODO(roasbeef): allow updates to use Batch?
1909

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

6✔
1916
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
1917
                edges := tx.ReadBucket(edgeBucket)
6✔
1918
                if edges == nil {
6✔
UNCOV
1919
                        return ErrGraphNoEdgesFound
×
UNCOV
1920
                }
×
1921
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
6✔
1922
                if edgeIndex == nil {
6✔
UNCOV
1923
                        return ErrGraphNoEdgesFound
×
UNCOV
1924
                }
×
1925

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

6✔
1930
                lastChanID, _ := cidCursor.Last()
6✔
1931

6✔
1932
                // If there's no key, then this means that we don't actually
6✔
1933
                // know of any channels, so we'll return a predicable error.
6✔
1934
                if lastChanID == nil {
10✔
1935
                        return ErrGraphNoEdgesFound
4✔
1936
                }
4✔
1937

1938
                // Otherwise, we'll de serialize the channel ID and return it
1939
                // to the caller.
1940
                cid = byteOrder.Uint64(lastChanID)
5✔
1941

5✔
1942
                return nil
5✔
1943
        }, func() {
6✔
1944
                cid = 0
6✔
1945
        })
6✔
1946
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
6✔
UNCOV
1947
                return 0, err
×
UNCOV
1948
        }
×
1949

1950
        return cid, nil
6✔
1951
}
1952

1953
// ChannelEdge represents the complete set of information for a channel edge in
1954
// the known channel graph. This struct couples the core information of the
1955
// edge as well as each of the known advertised edge policies.
1956
type ChannelEdge struct {
1957
        // Info contains all the static information describing the channel.
1958
        Info *models.ChannelEdgeInfo
1959

1960
        // Policy1 points to the "first" edge policy of the channel containing
1961
        // the dynamic information required to properly route through the edge.
1962
        Policy1 *models.ChannelEdgePolicy
1963

1964
        // Policy2 points to the "second" edge policy of the channel containing
1965
        // the dynamic information required to properly route through the edge.
1966
        Policy2 *models.ChannelEdgePolicy
1967

1968
        // Node1 is "node 1" in the channel. This is the node that would have
1969
        // produced Policy1 if it exists.
1970
        Node1 *models.LightningNode
1971

1972
        // Node2 is "node 2" in the channel. This is the node that would have
1973
        // produced Policy2 if it exists.
1974
        Node2 *models.LightningNode
1975
}
1976

1977
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1978
// one edge that has an update timestamp within the specified horizon.
1979
func (c *KVStore) ChanUpdatesInHorizon(startTime,
1980
        endTime time.Time) ([]ChannelEdge, error) {
149✔
1981

149✔
1982
        // To ensure we don't return duplicate ChannelEdges, we'll use an
149✔
1983
        // additional map to keep track of the edges already seen to prevent
149✔
1984
        // re-adding it.
149✔
1985
        var edgesSeen map[uint64]struct{}
149✔
1986
        var edgesToCache map[uint64]ChannelEdge
149✔
1987
        var edgesInHorizon []ChannelEdge
149✔
1988

149✔
1989
        c.cacheMu.Lock()
149✔
1990
        defer c.cacheMu.Unlock()
149✔
1991

149✔
1992
        var hits int
149✔
1993
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
298✔
1994
                edges := tx.ReadBucket(edgeBucket)
149✔
1995
                if edges == nil {
149✔
UNCOV
1996
                        return ErrGraphNoEdgesFound
×
1997
                }
×
1998
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
149✔
1999
                if edgeIndex == nil {
149✔
2000
                        return ErrGraphNoEdgesFound
×
2001
                }
×
2002
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
149✔
2003
                if edgeUpdateIndex == nil {
149✔
UNCOV
2004
                        return ErrGraphNoEdgesFound
×
UNCOV
2005
                }
×
2006

2007
                nodes := tx.ReadBucket(nodeBucket)
149✔
2008
                if nodes == nil {
149✔
UNCOV
2009
                        return ErrGraphNodesNotFound
×
UNCOV
2010
                }
×
2011

2012
                // We'll now obtain a cursor to perform a range query within
2013
                // the index to find all channels within the horizon.
2014
                updateCursor := edgeUpdateIndex.ReadCursor()
149✔
2015

149✔
2016
                var startTimeBytes, endTimeBytes [8 + 8]byte
149✔
2017
                byteOrder.PutUint64(
149✔
2018
                        startTimeBytes[:8], uint64(startTime.Unix()),
149✔
2019
                )
149✔
2020
                byteOrder.PutUint64(
149✔
2021
                        endTimeBytes[:8], uint64(endTime.Unix()),
149✔
2022
                )
149✔
2023

149✔
2024
                // With our start and end times constructed, we'll step through
149✔
2025
                // the index collecting the info and policy of each update of
149✔
2026
                // each channel that has a last update within the time range.
149✔
2027
                //
149✔
2028
                //nolint:ll
149✔
2029
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
149✔
2030
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
198✔
2031
                        // We have a new eligible entry, so we'll slice of the
49✔
2032
                        // chan ID so we can query it in the DB.
49✔
2033
                        chanID := indexKey[8:]
49✔
2034

49✔
2035
                        // If we've already retrieved the info and policies for
49✔
2036
                        // this edge, then we can skip it as we don't need to do
49✔
2037
                        // so again.
49✔
2038
                        chanIDInt := byteOrder.Uint64(chanID)
49✔
2039
                        if _, ok := edgesSeen[chanIDInt]; ok {
68✔
2040
                                continue
19✔
2041
                        }
2042

2043
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
42✔
2044
                                hits++
12✔
2045
                                edgesSeen[chanIDInt] = struct{}{}
12✔
2046
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
2047

12✔
2048
                                continue
12✔
2049
                        }
2050

2051
                        // First, we'll fetch the static edge information.
2052
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
21✔
2053
                        if err != nil {
21✔
UNCOV
2054
                                chanID := byteOrder.Uint64(chanID)
×
UNCOV
2055
                                return fmt.Errorf("unable to fetch info for "+
×
UNCOV
2056
                                        "edge with chan_id=%v: %v", chanID, err)
×
UNCOV
2057
                        }
×
2058

2059
                        // With the static information obtained, we'll now
2060
                        // fetch the dynamic policy info.
2061
                        edge1, edge2, err := fetchChanEdgePolicies(
21✔
2062
                                edgeIndex, edges, chanID,
21✔
2063
                        )
21✔
2064
                        if err != nil {
21✔
UNCOV
2065
                                chanID := byteOrder.Uint64(chanID)
×
UNCOV
2066
                                return fmt.Errorf("unable to fetch policies "+
×
UNCOV
2067
                                        "for edge with chan_id=%v: %v", chanID,
×
UNCOV
2068
                                        err)
×
UNCOV
2069
                        }
×
2070

2071
                        node1, err := fetchLightningNode(
21✔
2072
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
2073
                        )
21✔
2074
                        if err != nil {
21✔
UNCOV
2075
                                return err
×
2076
                        }
×
2077

2078
                        node2, err := fetchLightningNode(
21✔
2079
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
2080
                        )
21✔
2081
                        if err != nil {
21✔
UNCOV
2082
                                return err
×
UNCOV
2083
                        }
×
2084

2085
                        // Finally, we'll collate this edge with the rest of
2086
                        // edges to be returned.
2087
                        edgesSeen[chanIDInt] = struct{}{}
21✔
2088
                        channel := ChannelEdge{
21✔
2089
                                Info:    &edgeInfo,
21✔
2090
                                Policy1: edge1,
21✔
2091
                                Policy2: edge2,
21✔
2092
                                Node1:   &node1,
21✔
2093
                                Node2:   &node2,
21✔
2094
                        }
21✔
2095
                        edgesInHorizon = append(edgesInHorizon, channel)
21✔
2096
                        edgesToCache[chanIDInt] = channel
21✔
2097
                }
2098

2099
                return nil
149✔
2100
        }, func() {
149✔
2101
                edgesSeen = make(map[uint64]struct{})
149✔
2102
                edgesToCache = make(map[uint64]ChannelEdge)
149✔
2103
                edgesInHorizon = nil
149✔
2104
        })
149✔
2105
        switch {
149✔
UNCOV
2106
        case errors.Is(err, ErrGraphNoEdgesFound):
×
UNCOV
2107
                fallthrough
×
UNCOV
2108
        case errors.Is(err, ErrGraphNodesNotFound):
×
UNCOV
2109
                break
×
2110

UNCOV
2111
        case err != nil:
×
2112
                return nil, err
×
2113
        }
2114

2115
        // Insert any edges loaded from disk into the cache.
2116
        for chanid, channel := range edgesToCache {
170✔
2117
                c.chanCache.insert(chanid, channel)
21✔
2118
        }
21✔
2119

2120
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
149✔
2121
                float64(hits)/float64(len(edgesInHorizon)), hits,
149✔
2122
                len(edgesInHorizon))
149✔
2123

149✔
2124
        return edgesInHorizon, nil
149✔
2125
}
2126

2127
// NodeUpdatesInHorizon returns all the known lightning node which have an
2128
// update timestamp within the passed range. This method can be used by two
2129
// nodes to quickly determine if they have the same set of up to date node
2130
// announcements.
2131
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2132
        endTime time.Time) ([]models.LightningNode, error) {
11✔
2133

11✔
2134
        var nodesInHorizon []models.LightningNode
11✔
2135

11✔
2136
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2137
                nodes := tx.ReadBucket(nodeBucket)
11✔
2138
                if nodes == nil {
11✔
UNCOV
2139
                        return ErrGraphNodesNotFound
×
UNCOV
2140
                }
×
2141

2142
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2143
                if nodeUpdateIndex == nil {
11✔
2144
                        return ErrGraphNodesNotFound
×
2145
                }
×
2146

2147
                // We'll now obtain a cursor to perform a range query within
2148
                // the index to find all node announcements within the horizon.
2149
                updateCursor := nodeUpdateIndex.ReadCursor()
11✔
2150

11✔
2151
                var startTimeBytes, endTimeBytes [8 + 33]byte
11✔
2152
                byteOrder.PutUint64(
11✔
2153
                        startTimeBytes[:8], uint64(startTime.Unix()),
11✔
2154
                )
11✔
2155
                byteOrder.PutUint64(
11✔
2156
                        endTimeBytes[:8], uint64(endTime.Unix()),
11✔
2157
                )
11✔
2158

11✔
2159
                // With our start and end times constructed, we'll step through
11✔
2160
                // the index collecting info for each node within the time
11✔
2161
                // range.
11✔
2162
                //
11✔
2163
                //nolint:ll
11✔
2164
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
11✔
2165
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
43✔
2166
                        nodePub := indexKey[8:]
32✔
2167
                        node, err := fetchLightningNode(nodes, nodePub)
32✔
2168
                        if err != nil {
32✔
UNCOV
2169
                                return err
×
UNCOV
2170
                        }
×
2171

2172
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2173
                }
2174

2175
                return nil
11✔
2176
        }, func() {
11✔
2177
                nodesInHorizon = nil
11✔
2178
        })
11✔
2179
        switch {
11✔
UNCOV
2180
        case errors.Is(err, ErrGraphNoEdgesFound):
×
UNCOV
2181
                fallthrough
×
UNCOV
2182
        case errors.Is(err, ErrGraphNodesNotFound):
×
UNCOV
2183
                break
×
2184

UNCOV
2185
        case err != nil:
×
UNCOV
2186
                return nil, err
×
2187
        }
2188

2189
        return nodesInHorizon, nil
11✔
2190
}
2191

2192
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2193
// ID's that we don't know and are not known zombies of the passed set. In other
2194
// words, we perform a set difference of our set of chan ID's and the ones
2195
// passed in. This method can be used by callers to determine the set of
2196
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2197
// known zombies is also returned.
2198
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2199
        []ChannelUpdateInfo, error) {
126✔
2200

126✔
2201
        var (
126✔
2202
                newChanIDs   []uint64
126✔
2203
                knownZombies []ChannelUpdateInfo
126✔
2204
        )
126✔
2205

126✔
2206
        c.cacheMu.Lock()
126✔
2207
        defer c.cacheMu.Unlock()
126✔
2208

126✔
2209
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
252✔
2210
                edges := tx.ReadBucket(edgeBucket)
126✔
2211
                if edges == nil {
126✔
UNCOV
2212
                        return ErrGraphNoEdgesFound
×
UNCOV
2213
                }
×
2214
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
126✔
2215
                if edgeIndex == nil {
126✔
UNCOV
2216
                        return ErrGraphNoEdgesFound
×
UNCOV
2217
                }
×
2218

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

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

115✔
2231
                        // If the edge is already known, skip it.
115✔
2232
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
136✔
2233
                                continue
21✔
2234
                        }
2235

2236
                        // If the edge is a known zombie, skip it.
2237
                        if zombieIndex != nil {
194✔
2238
                                isZombie, _, _ := isZombieEdge(
97✔
2239
                                        zombieIndex, scid,
97✔
2240
                                )
97✔
2241

97✔
2242
                                if isZombie {
148✔
2243
                                        knownZombies = append(
51✔
2244
                                                knownZombies, info,
51✔
2245
                                        )
51✔
2246

51✔
2247
                                        continue
51✔
2248
                                }
2249
                        }
2250

2251
                        newChanIDs = append(newChanIDs, scid)
46✔
2252
                }
2253

2254
                return nil
126✔
2255
        }, func() {
126✔
2256
                newChanIDs = nil
126✔
2257
                knownZombies = nil
126✔
2258
        })
126✔
2259
        switch {
126✔
2260
        // If we don't know of any edges yet, then we'll return the entire set
2261
        // of chan IDs specified.
UNCOV
2262
        case errors.Is(err, ErrGraphNoEdgesFound):
×
UNCOV
2263
                ogChanIDs := make([]uint64, len(chansInfo))
×
UNCOV
2264
                for i, info := range chansInfo {
×
UNCOV
2265
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
UNCOV
2266
                }
×
2267

UNCOV
2268
                return ogChanIDs, nil, nil
×
2269

UNCOV
2270
        case err != nil:
×
UNCOV
2271
                return nil, nil, err
×
2272
        }
2273

2274
        return newChanIDs, knownZombies, nil
126✔
2275
}
2276

2277
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2278
// latest received channel updates for the channel.
2279
type ChannelUpdateInfo struct {
2280
        // ShortChannelID is the SCID identifier of the channel.
2281
        ShortChannelID lnwire.ShortChannelID
2282

2283
        // Node1UpdateTimestamp is the timestamp of the latest received update
2284
        // from the node 1 channel peer. This will be set to zero time if no
2285
        // update has yet been received from this node.
2286
        Node1UpdateTimestamp time.Time
2287

2288
        // Node2UpdateTimestamp is the timestamp of the latest received update
2289
        // from the node 2 channel peer. This will be set to zero time if no
2290
        // update has yet been received from this node.
2291
        Node2UpdateTimestamp time.Time
2292
}
2293

2294
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2295
// timestamps with zero seconds unix timestamp which equals
2296
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2297
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2298
        node2Timestamp time.Time) ChannelUpdateInfo {
199✔
2299

199✔
2300
        chanInfo := ChannelUpdateInfo{
199✔
2301
                ShortChannelID:       scid,
199✔
2302
                Node1UpdateTimestamp: node1Timestamp,
199✔
2303
                Node2UpdateTimestamp: node2Timestamp,
199✔
2304
        }
199✔
2305

199✔
2306
        if node1Timestamp.IsZero() {
388✔
2307
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
189✔
2308
        }
189✔
2309

2310
        if node2Timestamp.IsZero() {
388✔
2311
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
189✔
2312
        }
189✔
2313

2314
        return chanInfo
199✔
2315
}
2316

2317
// BlockChannelRange represents a range of channels for a given block height.
2318
type BlockChannelRange struct {
2319
        // Height is the height of the block all of the channels below were
2320
        // included in.
2321
        Height uint32
2322

2323
        // Channels is the list of channels identified by their short ID
2324
        // representation known to us that were included in the block height
2325
        // above. The list may include channel update timestamp information if
2326
        // requested.
2327
        Channels []ChannelUpdateInfo
2328
}
2329

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

14✔
2340
        startChanID := &lnwire.ShortChannelID{
14✔
2341
                BlockHeight: startHeight,
14✔
2342
        }
14✔
2343

14✔
2344
        endChanID := lnwire.ShortChannelID{
14✔
2345
                BlockHeight: endHeight,
14✔
2346
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2347
                TxPosition:  math.MaxUint16,
14✔
2348
        }
14✔
2349

14✔
2350
        // As we need to perform a range scan, we'll convert the starting and
14✔
2351
        // ending height to their corresponding values when encoded using short
14✔
2352
        // channel ID's.
14✔
2353
        var chanIDStart, chanIDEnd [8]byte
14✔
2354
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
14✔
2355
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
14✔
2356

14✔
2357
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2358
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2359
                edges := tx.ReadBucket(edgeBucket)
14✔
2360
                if edges == nil {
14✔
UNCOV
2361
                        return ErrGraphNoEdgesFound
×
2362
                }
×
2363
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2364
                if edgeIndex == nil {
14✔
UNCOV
2365
                        return ErrGraphNoEdgesFound
×
UNCOV
2366
                }
×
2367

2368
                cursor := edgeIndex.ReadCursor()
14✔
2369

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

2383
                        if edgeInfo.AuthProof == nil {
50✔
2384
                                continue
3✔
2385
                        }
2386

2387
                        // This channel ID rests within the target range, so
2388
                        // we'll add it to our returned set.
2389
                        rawCid := byteOrder.Uint64(k)
47✔
2390
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2391

47✔
2392
                        chanInfo := NewChannelUpdateInfo(
47✔
2393
                                cid, time.Time{}, time.Time{},
47✔
2394
                        )
47✔
2395

47✔
2396
                        if !withTimestamps {
69✔
2397
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2398
                                        channelsPerBlock[cid.BlockHeight],
22✔
2399
                                        chanInfo,
22✔
2400
                                )
22✔
2401

22✔
2402
                                continue
22✔
2403
                        }
2404

2405
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2406

25✔
2407
                        rawPolicy := edges.Get(node1Key)
25✔
2408
                        if len(rawPolicy) != 0 {
34✔
2409
                                r := bytes.NewReader(rawPolicy)
9✔
2410

9✔
2411
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2412
                                if err != nil && !errors.Is(
9✔
2413
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2414
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
9✔
UNCOV
2415

×
UNCOV
2416
                                        return err
×
UNCOV
2417
                                }
×
2418

2419
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2420
                        }
2421

2422
                        rawPolicy = edges.Get(node2Key)
25✔
2423
                        if len(rawPolicy) != 0 {
39✔
2424
                                r := bytes.NewReader(rawPolicy)
14✔
2425

14✔
2426
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2427
                                if err != nil && !errors.Is(
14✔
2428
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2429
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
14✔
UNCOV
2430

×
UNCOV
2431
                                        return err
×
UNCOV
2432
                                }
×
2433

2434
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2435
                        }
2436

2437
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2438
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2439
                        )
25✔
2440
                }
2441

2442
                return nil
14✔
2443
        }, func() {
14✔
2444
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2445
        })
14✔
2446

2447
        switch {
14✔
2448
        // If we don't know of any channels yet, then there's nothing to
2449
        // filter, so we'll return an empty slice.
2450
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
6✔
2451
                return nil, nil
6✔
2452

UNCOV
2453
        case err != nil:
×
UNCOV
2454
                return nil, err
×
2455
        }
2456

2457
        // Return the channel ranges in ascending block height order.
2458
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2459
        for block := range channelsPerBlock {
36✔
2460
                blocks = append(blocks, block)
25✔
2461
        }
25✔
2462
        sort.Slice(blocks, func(i, j int) bool {
35✔
2463
                return blocks[i] < blocks[j]
24✔
2464
        })
24✔
2465

2466
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2467
        for _, block := range blocks {
36✔
2468
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2469
                        Height:   block,
25✔
2470
                        Channels: channelsPerBlock[block],
25✔
2471
                })
25✔
2472
        }
25✔
2473

2474
        return channelRanges, nil
11✔
2475
}
2476

2477
// FetchChanInfos returns the set of channel edges that correspond to the passed
2478
// channel ID's. If an edge is the query is unknown to the database, it will
2479
// skipped and the result will contain only those edges that exist at the time
2480
// of the query. This can be used to respond to peer queries that are seeking to
2481
// fill in gaps in their view of the channel graph.
2482
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
7✔
2483
        return c.fetchChanInfos(nil, chanIDs)
7✔
2484
}
7✔
2485

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

7✔
2498
        var (
7✔
2499
                chanEdges []ChannelEdge
7✔
2500
                cidBytes  [8]byte
7✔
2501
        )
7✔
2502

7✔
2503
        fetchChanInfos := func(tx kvdb.RTx) error {
14✔
2504
                edges := tx.ReadBucket(edgeBucket)
7✔
2505
                if edges == nil {
7✔
2506
                        return ErrGraphNoEdgesFound
×
UNCOV
2507
                }
×
2508
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
2509
                if edgeIndex == nil {
7✔
UNCOV
2510
                        return ErrGraphNoEdgesFound
×
2511
                }
×
2512
                nodes := tx.ReadBucket(nodeBucket)
7✔
2513
                if nodes == nil {
7✔
2514
                        return ErrGraphNotFound
×
UNCOV
2515
                }
×
2516

2517
                for _, cid := range chanIDs {
21✔
2518
                        byteOrder.PutUint64(cidBytes[:], cid)
14✔
2519

14✔
2520
                        // First, we'll fetch the static edge information. If
14✔
2521
                        // the edge is unknown, we will skip the edge and
14✔
2522
                        // continue gathering all known edges.
14✔
2523
                        edgeInfo, err := fetchChanEdgeInfo(
14✔
2524
                                edgeIndex, cidBytes[:],
14✔
2525
                        )
14✔
2526
                        switch {
14✔
2527
                        case errors.Is(err, ErrEdgeNotFound):
3✔
2528
                                continue
3✔
UNCOV
2529
                        case err != nil:
×
UNCOV
2530
                                return err
×
2531
                        }
2532

2533
                        // With the static information obtained, we'll now
2534
                        // fetch the dynamic policy info.
2535
                        edge1, edge2, err := fetchChanEdgePolicies(
11✔
2536
                                edgeIndex, edges, cidBytes[:],
11✔
2537
                        )
11✔
2538
                        if err != nil {
11✔
UNCOV
2539
                                return err
×
UNCOV
2540
                        }
×
2541

2542
                        node1, err := fetchLightningNode(
11✔
2543
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2544
                        )
11✔
2545
                        if err != nil {
11✔
UNCOV
2546
                                return err
×
UNCOV
2547
                        }
×
2548

2549
                        node2, err := fetchLightningNode(
11✔
2550
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2551
                        )
11✔
2552
                        if err != nil {
11✔
UNCOV
2553
                                return err
×
2554
                        }
×
2555

2556
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2557
                                Info:    &edgeInfo,
11✔
2558
                                Policy1: edge1,
11✔
2559
                                Policy2: edge2,
11✔
2560
                                Node1:   &node1,
11✔
2561
                                Node2:   &node2,
11✔
2562
                        })
11✔
2563
                }
2564

2565
                return nil
7✔
2566
        }
2567

2568
        if tx == nil {
14✔
2569
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2570
                        chanEdges = nil
7✔
2571
                })
7✔
2572
                if err != nil {
7✔
UNCOV
2573
                        return nil, err
×
2574
                }
×
2575

2576
                return chanEdges, nil
7✔
2577
        }
2578

UNCOV
2579
        err := fetchChanInfos(tx)
×
UNCOV
2580
        if err != nil {
×
UNCOV
2581
                return nil, err
×
UNCOV
2582
        }
×
2583

2584
        return chanEdges, nil
×
2585
}
2586

2587
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2588
        edge1, edge2 *models.ChannelEdgePolicy) error {
136✔
2589

136✔
2590
        // First, we'll fetch the edge update index bucket which currently
136✔
2591
        // stores an entry for the channel we're about to delete.
136✔
2592
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
136✔
2593
        if updateIndex == nil {
136✔
UNCOV
2594
                // No edges in bucket, return early.
×
UNCOV
2595
                return nil
×
UNCOV
2596
        }
×
2597

2598
        // Now that we have the bucket, we'll attempt to construct a template
2599
        // for the index key: updateTime || chanid.
2600
        var indexKey [8 + 8]byte
136✔
2601
        byteOrder.PutUint64(indexKey[8:], chanID)
136✔
2602

136✔
2603
        // With the template constructed, we'll attempt to delete an entry that
136✔
2604
        // would have been created by both edges: we'll alternate the update
136✔
2605
        // times, as one may had overridden the other.
136✔
2606
        if edge1 != nil {
149✔
2607
                byteOrder.PutUint64(
13✔
2608
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
13✔
2609
                )
13✔
2610
                if err := updateIndex.Delete(indexKey[:]); err != nil {
13✔
UNCOV
2611
                        return err
×
UNCOV
2612
                }
×
2613
        }
2614

2615
        // We'll also attempt to delete the entry that may have been created by
2616
        // the second edge.
2617
        if edge2 != nil {
151✔
2618
                byteOrder.PutUint64(
15✔
2619
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
15✔
2620
                )
15✔
2621
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
UNCOV
2622
                        return err
×
UNCOV
2623
                }
×
2624
        }
2625

2626
        return nil
136✔
2627
}
2628

2629
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2630
// cache. It then goes on to delete any policy info and edge info for this
2631
// channel from the DB and finally, if isZombie is true, it will add an entry
2632
// for this channel in the zombie index.
2633
//
2634
// NOTE: this method MUST only be called if the cacheMu has already been
2635
// acquired.
2636
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2637
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2638
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
196✔
2639

196✔
2640
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
196✔
2641
        if err != nil {
256✔
2642
                return nil, err
60✔
2643
        }
60✔
2644

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

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

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

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

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

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

2711
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
25✔
2712
        if strictZombie {
28✔
2713
                var e1UpdateTime, e2UpdateTime *time.Time
3✔
2714
                if edge1 != nil {
5✔
2715
                        e1UpdateTime = &edge1.LastUpdate
2✔
2716
                }
2✔
2717
                if edge2 != nil {
6✔
2718
                        e2UpdateTime = &edge2.LastUpdate
3✔
2719
                }
3✔
2720

2721
                nodeKey1, nodeKey2 = makeZombiePubkeys(
3✔
2722
                        &edgeInfo, e1UpdateTime, e2UpdateTime,
3✔
2723
                )
3✔
2724
        }
2725

2726
        return &edgeInfo, markEdgeZombie(
25✔
2727
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
25✔
2728
        )
25✔
2729
}
2730

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

3✔
2750
        switch {
3✔
2751
        // If we don't have either edge policy, we'll return both pubkeys so
2752
        // that the channel can be resurrected by either party.
UNCOV
2753
        case e1 == nil && e2 == nil:
×
UNCOV
2754
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2755

2756
        // If we're missing edge1, or if both edges are present but edge1 is
2757
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2758
        // means that only an update from edge1 will be able to resurrect the
2759
        // channel.
2760
        case e1 == nil || (e2 != nil && e1.Before(*e2)):
1✔
2761
                return info.NodeKey1Bytes, [33]byte{}
1✔
2762

2763
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2764
        // return a blank pubkey for edge1. In this case, only an update from
2765
        // edge2 can resurect the channel.
2766
        default:
2✔
2767
                return [33]byte{}, info.NodeKey2Bytes
2✔
2768
        }
2769
}
2770

2771
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2772
// within the database for the referenced channel. The `flags` attribute within
2773
// the ChannelEdgePolicy determines which of the directed edges are being
2774
// updated. If the flag is 1, then the first node's information is being
2775
// updated, otherwise it's the second node's information. The node ordering is
2776
// determined by the lexicographical ordering of the identity public keys of the
2777
// nodes on either side of the channel.
2778
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2779
        opts ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
2,668✔
2780

2,668✔
2781
        var (
2,668✔
2782
                ctx          = context.TODO()
2,668✔
2783
                isUpdate1    bool
2,668✔
2784
                edgeNotFound bool
2,668✔
2785
                from, to     route.Vertex
2,668✔
2786
        )
2,668✔
2787

2,668✔
2788
        r := &batch.Request[kvdb.RwTx]{
2,668✔
2789
                Opts: batch.NewSchedulerOptions(opts...),
2,668✔
2790
                Reset: func() {
5,337✔
2791
                        isUpdate1 = false
2,669✔
2792
                        edgeNotFound = false
2,669✔
2793
                },
2,669✔
2794
                Do: func(tx kvdb.RwTx) error {
2,669✔
2795
                        var err error
2,669✔
2796
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
2,669✔
2797
                        if err != nil {
2,674✔
2798
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
5✔
2799
                        }
5✔
2800

2801
                        // Silence ErrEdgeNotFound so that the batch can
2802
                        // succeed, but propagate the error via local state.
2803
                        if errors.Is(err, ErrEdgeNotFound) {
2,672✔
2804
                                edgeNotFound = true
3✔
2805
                                return nil
3✔
2806
                        }
3✔
2807

2808
                        return err
2,666✔
2809
                },
2810
                OnCommit: func(err error) error {
2,668✔
2811
                        switch {
2,668✔
2812
                        case err != nil:
1✔
2813
                                return err
1✔
2814
                        case edgeNotFound:
3✔
2815
                                return ErrEdgeNotFound
3✔
2816
                        default:
2,664✔
2817
                                c.updateEdgeCache(edge, isUpdate1)
2,664✔
2818
                                return nil
2,664✔
2819
                        }
2820
                },
2821
        }
2822

2823
        err := c.chanScheduler.Execute(ctx, r)
2,668✔
2824

2,668✔
2825
        return from, to, err
2,668✔
2826
}
2827

2828
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2829
        isUpdate1 bool) {
2,664✔
2830

2,664✔
2831
        // If an entry for this channel is found in reject cache, we'll modify
2,664✔
2832
        // the entry with the updated timestamp for the direction that was just
2,664✔
2833
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,664✔
2834
        // during the next query for this edge.
2,664✔
2835
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,672✔
2836
                if isUpdate1 {
14✔
2837
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2838
                } else {
11✔
2839
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2840
                }
5✔
2841
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2842
        }
2843

2844
        // If an entry for this channel is found in channel cache, we'll modify
2845
        // the entry with the updated policy for the direction that was just
2846
        // written. If the edge doesn't exist, we'll defer loading the info and
2847
        // policies and lazily read from disk during the next query.
2848
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,667✔
2849
                if isUpdate1 {
6✔
2850
                        channel.Policy1 = e
3✔
2851
                } else {
6✔
2852
                        channel.Policy2 = e
3✔
2853
                }
3✔
2854
                c.chanCache.insert(e.ChannelID, channel)
3✔
2855
        }
2856
}
2857

2858
// updateEdgePolicy attempts to update an edge's policy within the relevant
2859
// buckets using an existing database transaction. The returned boolean will be
2860
// true if the updated policy belongs to node1, and false if the policy belonged
2861
// to node2.
2862
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2863
        route.Vertex, route.Vertex, bool, error) {
2,669✔
2864

2,669✔
2865
        var noVertex route.Vertex
2,669✔
2866

2,669✔
2867
        edges := tx.ReadWriteBucket(edgeBucket)
2,669✔
2868
        if edges == nil {
2,669✔
UNCOV
2869
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2870
        }
×
2871
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,669✔
2872
        if edgeIndex == nil {
2,669✔
UNCOV
2873
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2874
        }
×
2875

2876
        // Create the channelID key be converting the channel ID
2877
        // integer into a byte slice.
2878
        var chanID [8]byte
2,669✔
2879
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,669✔
2880

2,669✔
2881
        // With the channel ID, we then fetch the value storing the two
2,669✔
2882
        // nodes which connect this channel edge.
2,669✔
2883
        nodeInfo := edgeIndex.Get(chanID[:])
2,669✔
2884
        if nodeInfo == nil {
2,672✔
2885
                return noVertex, noVertex, false, ErrEdgeNotFound
3✔
2886
        }
3✔
2887

2888
        // Depending on the flags value passed above, either the first
2889
        // or second edge policy is being updated.
2890
        var fromNode, toNode []byte
2,666✔
2891
        var isUpdate1 bool
2,666✔
2892
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,005✔
2893
                fromNode = nodeInfo[:33]
1,339✔
2894
                toNode = nodeInfo[33:66]
1,339✔
2895
                isUpdate1 = true
1,339✔
2896
        } else {
2,669✔
2897
                fromNode = nodeInfo[33:66]
1,330✔
2898
                toNode = nodeInfo[:33]
1,330✔
2899
                isUpdate1 = false
1,330✔
2900
        }
1,330✔
2901

2902
        // Finally, with the direction of the edge being updated
2903
        // identified, we update the on-disk edge representation.
2904
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,666✔
2905
        if err != nil {
2,668✔
2906
                return noVertex, noVertex, false, err
2✔
2907
        }
2✔
2908

2909
        var (
2,664✔
2910
                fromNodePubKey route.Vertex
2,664✔
2911
                toNodePubKey   route.Vertex
2,664✔
2912
        )
2,664✔
2913
        copy(fromNodePubKey[:], fromNode)
2,664✔
2914
        copy(toNodePubKey[:], toNode)
2,664✔
2915

2,664✔
2916
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
2,664✔
2917
}
2918

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

16✔
2925
        // In order to determine whether this node is publicly advertised within
16✔
2926
        // the graph, we'll need to look at all of its edges and check whether
16✔
2927
        // they extend to any other node than the source node. errDone will be
16✔
2928
        // used to terminate the check early.
16✔
2929
        nodeIsPublic := false
16✔
2930
        errDone := errors.New("done")
16✔
2931
        err := c.forEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
16✔
2932
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
16✔
2933
                _ *models.ChannelEdgePolicy) error {
29✔
2934

13✔
2935
                // If this edge doesn't extend to the source node, we'll
13✔
2936
                // terminate our search as we can now conclude that the node is
13✔
2937
                // publicly advertised within the graph due to the local node
13✔
2938
                // knowing of the current edge.
13✔
2939
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
2940
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
2941

6✔
2942
                        nodeIsPublic = true
6✔
2943
                        return errDone
6✔
2944
                }
6✔
2945

2946
                // Since the edge _does_ extend to the source node, we'll also
2947
                // need to ensure that this is a public edge.
2948
                if info.AuthProof != nil {
19✔
2949
                        nodeIsPublic = true
9✔
2950
                        return errDone
9✔
2951
                }
9✔
2952

2953
                // Otherwise, we'll continue our search.
2954
                return nil
4✔
2955
        })
2956
        if err != nil && !errors.Is(err, errDone) {
16✔
UNCOV
2957
                return false, err
×
UNCOV
2958
        }
×
2959

2960
        return nodeIsPublic, nil
16✔
2961
}
2962

2963
// FetchLightningNodeTx attempts to look up a target node by its identity
2964
// public key. If the node isn't found in the database, then
2965
// ErrGraphNodeNotFound is returned. An optional transaction may be provided.
2966
// If none is provided, then a new one will be created.
2967
func (c *KVStore) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
2968
        *models.LightningNode, error) {
3,654✔
2969

3,654✔
2970
        return c.fetchLightningNode(tx, nodePub)
3,654✔
2971
}
3,654✔
2972

2973
// FetchLightningNode attempts to look up a target node by its identity public
2974
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2975
// returned.
2976
func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
2977
        *models.LightningNode, error) {
162✔
2978

162✔
2979
        return c.fetchLightningNode(nil, nodePub)
162✔
2980
}
162✔
2981

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

3,813✔
2989
        var node *models.LightningNode
3,813✔
2990
        fetch := func(tx kvdb.RTx) error {
7,626✔
2991
                // First grab the nodes bucket which stores the mapping from
3,813✔
2992
                // pubKey to node information.
3,813✔
2993
                nodes := tx.ReadBucket(nodeBucket)
3,813✔
2994
                if nodes == nil {
3,813✔
UNCOV
2995
                        return ErrGraphNotFound
×
UNCOV
2996
                }
×
2997

2998
                // If a key for this serialized public key isn't found, then
2999
                // the target node doesn't exist within the database.
3000
                nodeBytes := nodes.Get(nodePub[:])
3,813✔
3001
                if nodeBytes == nil {
3,831✔
3002
                        return ErrGraphNodeNotFound
18✔
3003
                }
18✔
3004

3005
                // If the node is found, then we can de deserialize the node
3006
                // information to return to the user.
3007
                nodeReader := bytes.NewReader(nodeBytes)
3,798✔
3008
                n, err := deserializeLightningNode(nodeReader)
3,798✔
3009
                if err != nil {
3,798✔
UNCOV
3010
                        return err
×
UNCOV
3011
                }
×
3012

3013
                node = &n
3,798✔
3014

3,798✔
3015
                return nil
3,798✔
3016
        }
3017

3018
        if tx == nil {
3,999✔
3019
                err := kvdb.View(
186✔
3020
                        c.db, fetch, func() {
372✔
3021
                                node = nil
186✔
3022
                        },
186✔
3023
                )
3024
                if err != nil {
193✔
3025
                        return nil, err
7✔
3026
                }
7✔
3027

3028
                return node, nil
182✔
3029
        }
3030

3031
        err := fetch(tx)
3,627✔
3032
        if err != nil {
3,638✔
3033
                return nil, err
11✔
3034
        }
11✔
3035

3036
        return node, nil
3,616✔
3037
}
3038

3039
// HasLightningNode determines if the graph has a vertex identified by the
3040
// target node identity public key. If the node exists in the database, a
3041
// timestamp of when the data for the node was lasted updated is returned along
3042
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3043
// boolean.
3044
func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3045
        error) {
20✔
3046

20✔
3047
        var (
20✔
3048
                updateTime time.Time
20✔
3049
                exists     bool
20✔
3050
        )
20✔
3051

20✔
3052
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
40✔
3053
                // First grab the nodes bucket which stores the mapping from
20✔
3054
                // pubKey to node information.
20✔
3055
                nodes := tx.ReadBucket(nodeBucket)
20✔
3056
                if nodes == nil {
20✔
UNCOV
3057
                        return ErrGraphNotFound
×
UNCOV
3058
                }
×
3059

3060
                // If a key for this serialized public key isn't found, we can
3061
                // exit early.
3062
                nodeBytes := nodes.Get(nodePub[:])
20✔
3063
                if nodeBytes == nil {
26✔
3064
                        exists = false
6✔
3065
                        return nil
6✔
3066
                }
6✔
3067

3068
                // Otherwise we continue on to obtain the time stamp
3069
                // representing the last time the data for this node was
3070
                // updated.
3071
                nodeReader := bytes.NewReader(nodeBytes)
17✔
3072
                node, err := deserializeLightningNode(nodeReader)
17✔
3073
                if err != nil {
17✔
UNCOV
3074
                        return err
×
UNCOV
3075
                }
×
3076

3077
                exists = true
17✔
3078
                updateTime = node.LastUpdate
17✔
3079

17✔
3080
                return nil
17✔
3081
        }, func() {
20✔
3082
                updateTime = time.Time{}
20✔
3083
                exists = false
20✔
3084
        })
20✔
3085
        if err != nil {
20✔
UNCOV
3086
                return time.Time{}, exists, err
×
UNCOV
3087
        }
×
3088

3089
        return updateTime, exists, nil
20✔
3090
}
3091

3092
// nodeTraversal is used to traverse all channels of a node given by its
3093
// public key and passes channel information into the specified callback.
3094
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3095
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3096
                *models.ChannelEdgePolicy) error) error {
1,270✔
3097

1,270✔
3098
        traversal := func(tx kvdb.RTx) error {
2,540✔
3099
                edges := tx.ReadBucket(edgeBucket)
1,270✔
3100
                if edges == nil {
1,270✔
UNCOV
3101
                        return ErrGraphNotFound
×
UNCOV
3102
                }
×
3103
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,270✔
3104
                if edgeIndex == nil {
1,270✔
UNCOV
3105
                        return ErrGraphNoEdgesFound
×
UNCOV
3106
                }
×
3107

3108
                // In order to reach all the edges for this node, we take
3109
                // advantage of the construction of the key-space within the
3110
                // edge bucket. The keys are stored in the form: pubKey ||
3111
                // chanID. Therefore, starting from a chanID of zero, we can
3112
                // scan forward in the bucket, grabbing all the edges for the
3113
                // node. Once the prefix no longer matches, then we know we're
3114
                // done.
3115
                var nodeStart [33 + 8]byte
1,270✔
3116
                copy(nodeStart[:], nodePub)
1,270✔
3117
                copy(nodeStart[33:], chanStart[:])
1,270✔
3118

1,270✔
3119
                // Starting from the key pubKey || 0, we seek forward in the
1,270✔
3120
                // bucket until the retrieved key no longer has the public key
1,270✔
3121
                // as its prefix. This indicates that we've stepped over into
1,270✔
3122
                // another node's edges, so we can terminate our scan.
1,270✔
3123
                edgeCursor := edges.ReadCursor()
1,270✔
3124
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
5,115✔
3125
                        // If the prefix still matches, the channel id is
3,845✔
3126
                        // returned in nodeEdge. Channel id is used to lookup
3,845✔
3127
                        // the node at the other end of the channel and both
3,845✔
3128
                        // edge policies.
3,845✔
3129
                        chanID := nodeEdge[33:]
3,845✔
3130
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,845✔
3131
                        if err != nil {
3,845✔
UNCOV
3132
                                return err
×
UNCOV
3133
                        }
×
3134

3135
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,845✔
3136
                                edges, chanID, nodePub,
3,845✔
3137
                        )
3,845✔
3138
                        if err != nil {
3,845✔
UNCOV
3139
                                return err
×
UNCOV
3140
                        }
×
3141

3142
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,845✔
3143
                        if err != nil {
3,845✔
UNCOV
3144
                                return err
×
UNCOV
3145
                        }
×
3146

3147
                        incomingPolicy, err := fetchChanEdgePolicy(
3,845✔
3148
                                edges, chanID, otherNode[:],
3,845✔
3149
                        )
3,845✔
3150
                        if err != nil {
3,845✔
UNCOV
3151
                                return err
×
UNCOV
3152
                        }
×
3153

3154
                        // Finally, we execute the callback.
3155
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,845✔
3156
                        if err != nil {
3,857✔
3157
                                return err
12✔
3158
                        }
12✔
3159
                }
3160

3161
                return nil
1,261✔
3162
        }
3163

3164
        // If no transaction was provided, then we'll create a new transaction
3165
        // to execute the transaction within.
3166
        if tx == nil {
1,302✔
3167
                return kvdb.View(db, traversal, func() {})
64✔
3168
        }
3169

3170
        // Otherwise, we re-use the existing transaction to execute the graph
3171
        // traversal.
3172
        return traversal(tx)
1,241✔
3173
}
3174

3175
// ForEachNodeChannel iterates through all channels of the given node,
3176
// executing the passed callback with an edge info structure and the policies
3177
// of each end of the channel. The first edge policy is the outgoing edge *to*
3178
// the connecting node, while the second is the incoming edge *from* the
3179
// connecting node. If the callback returns an error, then the iteration is
3180
// halted with the error propagated back up to the caller.
3181
//
3182
// Unknown policies are passed into the callback as nil values.
3183
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3184
        cb func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3185
                *models.ChannelEdgePolicy) error) error {
9✔
3186

9✔
3187
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
9✔
3188
                info *models.ChannelEdgeInfo, policy,
9✔
3189
                policy2 *models.ChannelEdgePolicy) error {
22✔
3190

13✔
3191
                return cb(info, policy, policy2)
13✔
3192
        })
13✔
3193
}
3194

3195
// ForEachSourceNodeChannel iterates through all channels of the source node,
3196
// executing the passed callback on each. The callback is provided with the
3197
// channel's outpoint, whether we have a policy for the channel and the channel
3198
// peer's node information.
3199
func (c *KVStore) ForEachSourceNodeChannel(cb func(chanPoint wire.OutPoint,
3200
        havePolicy bool, otherNode *models.LightningNode) error) error {
4✔
3201

4✔
3202
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3203
                nodes := tx.ReadBucket(nodeBucket)
4✔
3204
                if nodes == nil {
4✔
UNCOV
3205
                        return ErrGraphNotFound
×
UNCOV
3206
                }
×
3207

3208
                node, err := c.sourceNode(nodes)
4✔
3209
                if err != nil {
4✔
UNCOV
3210
                        return err
×
3211
                }
×
3212

3213
                return nodeTraversal(
4✔
3214
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
4✔
3215
                                info *models.ChannelEdgeInfo,
4✔
3216
                                policy, _ *models.ChannelEdgePolicy) error {
9✔
3217

5✔
3218
                                peer, err := c.fetchOtherNode(
5✔
3219
                                        tx, info, node.PubKeyBytes[:],
5✔
3220
                                )
5✔
3221
                                if err != nil {
5✔
UNCOV
3222
                                        return err
×
UNCOV
3223
                                }
×
3224

3225
                                return cb(
5✔
3226
                                        info.ChannelPoint, policy != nil, peer,
5✔
3227
                                )
5✔
3228
                        },
3229
                )
3230
        }, func() {})
4✔
3231
}
3232

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

1,001✔
3251
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3252
}
1,001✔
3253

3254
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3255
// the target node in the channel. This is useful when one knows the pubkey of
3256
// one of the nodes, and wishes to obtain the full LightningNode for the other
3257
// end of the channel.
3258
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3259
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3260
        *models.LightningNode, error) {
5✔
3261

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

3273
        var targetNode *models.LightningNode
5✔
3274
        fetchNodeFunc := func(tx kvdb.RTx) error {
10✔
3275
                // First grab the nodes bucket which stores the mapping from
5✔
3276
                // pubKey to node information.
5✔
3277
                nodes := tx.ReadBucket(nodeBucket)
5✔
3278
                if nodes == nil {
5✔
UNCOV
3279
                        return ErrGraphNotFound
×
UNCOV
3280
                }
×
3281

3282
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
5✔
3283
                if err != nil {
5✔
3284
                        return err
×
3285
                }
×
3286

3287
                targetNode = &node
5✔
3288

5✔
3289
                return nil
5✔
3290
        }
3291

3292
        // If the transaction is nil, then we'll need to create a new one,
3293
        // otherwise we can use the existing db transaction.
3294
        var err error
5✔
3295
        if tx == nil {
5✔
3296
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
UNCOV
3297
                        targetNode = nil
×
UNCOV
3298
                })
×
3299
        } else {
5✔
3300
                err = fetchNodeFunc(tx)
5✔
3301
        }
5✔
3302

3303
        return targetNode, err
5✔
3304
}
3305

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

25✔
3315
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3316
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3317

25✔
3318
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3319
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3320

25✔
3321
        return node1Key[:], node2Key[:]
25✔
3322
}
25✔
3323

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

14✔
3333
        var (
14✔
3334
                edgeInfo *models.ChannelEdgeInfo
14✔
3335
                policy1  *models.ChannelEdgePolicy
14✔
3336
                policy2  *models.ChannelEdgePolicy
14✔
3337
        )
14✔
3338

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

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

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

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

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

3390
                policy1 = e1
4✔
3391
                policy2 = e2
4✔
3392

4✔
3393
                return nil
4✔
3394
        }, func() {
14✔
3395
                edgeInfo = nil
14✔
3396
                policy1 = nil
14✔
3397
                policy2 = nil
14✔
3398
        })
14✔
3399
        if err != nil {
27✔
3400
                return nil, nil, nil, err
13✔
3401
        }
13✔
3402

3403
        return edgeInfo, policy1, policy2, nil
4✔
3404
}
3405

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

2,686✔
3419
        var (
2,686✔
3420
                edgeInfo  *models.ChannelEdgeInfo
2,686✔
3421
                policy1   *models.ChannelEdgePolicy
2,686✔
3422
                policy2   *models.ChannelEdgePolicy
2,686✔
3423
                channelID [8]byte
2,686✔
3424
        )
2,686✔
3425

2,686✔
3426
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
5,372✔
3427
                // First, grab the node bucket. This will be used to populate
2,686✔
3428
                // the Node pointers in each edge read from disk.
2,686✔
3429
                nodes := tx.ReadBucket(nodeBucket)
2,686✔
3430
                if nodes == nil {
2,686✔
UNCOV
3431
                        return ErrGraphNotFound
×
UNCOV
3432
                }
×
3433

3434
                // Next, grab the edge bucket which stores the edges, and also
3435
                // the index itself so we can group the directed edges together
3436
                // logically.
3437
                edges := tx.ReadBucket(edgeBucket)
2,686✔
3438
                if edges == nil {
2,686✔
UNCOV
3439
                        return ErrGraphNoEdgesFound
×
UNCOV
3440
                }
×
3441
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
2,686✔
3442
                if edgeIndex == nil {
2,686✔
UNCOV
3443
                        return ErrGraphNoEdgesFound
×
UNCOV
3444
                }
×
3445

3446
                byteOrder.PutUint64(channelID[:], chanID)
2,686✔
3447

2,686✔
3448
                // Now, attempt to fetch edge.
2,686✔
3449
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
2,686✔
3450

2,686✔
3451
                // If it doesn't exist, we'll quickly check our zombie index to
2,686✔
3452
                // see if we've previously marked it as so.
2,686✔
3453
                if errors.Is(err, ErrEdgeNotFound) {
2,690✔
3454
                        // If the zombie index doesn't exist, or the edge is not
4✔
3455
                        // marked as a zombie within it, then we'll return the
4✔
3456
                        // original ErrEdgeNotFound error.
4✔
3457
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3458
                        if zombieIndex == nil {
4✔
UNCOV
3459
                                return ErrEdgeNotFound
×
3460
                        }
×
3461

3462
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3463
                                zombieIndex, chanID,
4✔
3464
                        )
4✔
3465
                        if !isZombie {
7✔
3466
                                return ErrEdgeNotFound
3✔
3467
                        }
3✔
3468

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

4✔
3478
                        return ErrZombieEdge
4✔
3479
                }
3480

3481
                // Otherwise, we'll just return the error if any.
3482
                if err != nil {
2,685✔
UNCOV
3483
                        return err
×
3484
                }
×
3485

3486
                edgeInfo = &edge
2,685✔
3487

2,685✔
3488
                // Then we'll attempt to fetch the accompanying policies of this
2,685✔
3489
                // edge.
2,685✔
3490
                e1, e2, err := fetchChanEdgePolicies(
2,685✔
3491
                        edgeIndex, edges, channelID[:],
2,685✔
3492
                )
2,685✔
3493
                if err != nil {
2,685✔
UNCOV
3494
                        return err
×
UNCOV
3495
                }
×
3496

3497
                policy1 = e1
2,685✔
3498
                policy2 = e2
2,685✔
3499

2,685✔
3500
                return nil
2,685✔
3501
        }, func() {
2,686✔
3502
                edgeInfo = nil
2,686✔
3503
                policy1 = nil
2,686✔
3504
                policy2 = nil
2,686✔
3505
        })
2,686✔
3506
        if errors.Is(err, ErrZombieEdge) {
2,690✔
3507
                return edgeInfo, nil, nil, err
4✔
3508
        }
4✔
3509
        if err != nil {
2,688✔
3510
                return nil, nil, nil, err
3✔
3511
        }
3✔
3512

3513
        return edgeInfo, policy1, policy2, nil
2,685✔
3514
}
3515

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

3535
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3536

16✔
3537
                return err
16✔
3538
        }, func() {
16✔
3539
                nodeIsPublic = false
16✔
3540
        })
16✔
3541
        if err != nil {
16✔
UNCOV
3542
                return false, err
×
UNCOV
3543
        }
×
3544

3545
        return nodeIsPublic, nil
16✔
3546
}
3547

3548
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3549
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
49✔
3550
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
49✔
3551
        if err != nil {
49✔
UNCOV
3552
                return nil, err
×
3553
        }
×
3554

3555
        // With the witness script generated, we'll now turn it into a p2wsh
3556
        // script:
3557
        //  * OP_0 <sha256(script)>
3558
        bldr := txscript.NewScriptBuilder(
49✔
3559
                txscript.WithScriptAllocSize(input.P2WSHSize),
49✔
3560
        )
49✔
3561
        bldr.AddOp(txscript.OP_0)
49✔
3562
        scriptHash := sha256.Sum256(witnessScript)
49✔
3563
        bldr.AddData(scriptHash[:])
49✔
3564

49✔
3565
        return bldr.Script()
49✔
3566
}
3567

3568
// EdgePoint couples the outpoint of a channel with the funding script that it
3569
// creates. The FilteredChainView will use this to watch for spends of this
3570
// edge point on chain. We require both of these values as depending on the
3571
// concrete implementation, either the pkScript, or the out point will be used.
3572
type EdgePoint struct {
3573
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3574
        FundingPkScript []byte
3575

3576
        // OutPoint is the outpoint of the target channel.
3577
        OutPoint wire.OutPoint
3578
}
3579

3580
// String returns a human readable version of the target EdgePoint. We return
3581
// the outpoint directly as it is enough to uniquely identify the edge point.
3582
func (e *EdgePoint) String() string {
×
3583
        return e.OutPoint.String()
×
UNCOV
3584
}
×
3585

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

3609
                // Once we have the proper bucket, we'll range over each key
3610
                // (which is the channel point for the channel) and decode it,
3611
                // accumulating each entry.
3612
                return chanIndex.ForEach(
25✔
3613
                        func(chanPointBytes, chanID []byte) error {
70✔
3614
                                chanPointReader := bytes.NewReader(
45✔
3615
                                        chanPointBytes,
45✔
3616
                                )
45✔
3617

45✔
3618
                                var chanPoint wire.OutPoint
45✔
3619
                                err := ReadOutpoint(chanPointReader, &chanPoint)
45✔
3620
                                if err != nil {
45✔
UNCOV
3621
                                        return err
×
UNCOV
3622
                                }
×
3623

3624
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3625
                                        edgeIndex, chanID,
45✔
3626
                                )
45✔
3627
                                if err != nil {
45✔
UNCOV
3628
                                        return err
×
UNCOV
3629
                                }
×
3630

3631
                                pkScript, err := genMultiSigP2WSH(
45✔
3632
                                        edgeInfo.BitcoinKey1Bytes[:],
45✔
3633
                                        edgeInfo.BitcoinKey2Bytes[:],
45✔
3634
                                )
45✔
3635
                                if err != nil {
45✔
UNCOV
3636
                                        return err
×
3637
                                }
×
3638

3639
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3640
                                        FundingPkScript: pkScript,
45✔
3641
                                        OutPoint:        chanPoint,
45✔
3642
                                })
45✔
3643

45✔
3644
                                return nil
45✔
3645
                        },
3646
                )
3647
        }, func() {
25✔
3648
                edgePoints = nil
25✔
3649
        }); err != nil {
25✔
3650
                return nil, err
×
3651
        }
×
3652

3653
        return edgePoints, nil
25✔
3654
}
3655

3656
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3657
// zombie. This method is used on an ad-hoc basis, when channels need to be
3658
// marked as zombies outside the normal pruning cycle.
3659
func (c *KVStore) MarkEdgeZombie(chanID uint64,
3660
        pubKey1, pubKey2 [33]byte) error {
134✔
3661

134✔
3662
        c.cacheMu.Lock()
134✔
3663
        defer c.cacheMu.Unlock()
134✔
3664

134✔
3665
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
268✔
3666
                edges := tx.ReadWriteBucket(edgeBucket)
134✔
3667
                if edges == nil {
134✔
3668
                        return ErrGraphNoEdgesFound
×
UNCOV
3669
                }
×
3670
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
134✔
3671
                if err != nil {
134✔
UNCOV
3672
                        return fmt.Errorf("unable to create zombie "+
×
3673
                                "bucket: %w", err)
×
3674
                }
×
3675

3676
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
134✔
3677
        })
3678
        if err != nil {
134✔
3679
                return err
×
3680
        }
×
3681

3682
        c.rejectCache.remove(chanID)
134✔
3683
        c.chanCache.remove(chanID)
134✔
3684

134✔
3685
        return nil
134✔
3686
}
3687

3688
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3689
// keys should represent the node public keys of the two parties involved in the
3690
// edge.
3691
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3692
        pubKey2 [33]byte) error {
159✔
3693

159✔
3694
        var k [8]byte
159✔
3695
        byteOrder.PutUint64(k[:], chanID)
159✔
3696

159✔
3697
        var v [66]byte
159✔
3698
        copy(v[:33], pubKey1[:])
159✔
3699
        copy(v[33:], pubKey2[:])
159✔
3700

159✔
3701
        return zombieIndex.Put(k[:], v[:])
159✔
3702
}
159✔
3703

3704
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3705
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
27✔
3706
        c.cacheMu.Lock()
27✔
3707
        defer c.cacheMu.Unlock()
27✔
3708

27✔
3709
        return c.markEdgeLiveUnsafe(nil, chanID)
27✔
3710
}
27✔
3711

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

3729
                var k [8]byte
27✔
3730
                byteOrder.PutUint64(k[:], chanID)
27✔
3731

27✔
3732
                if len(zombieIndex.Get(k[:])) == 0 {
28✔
3733
                        return ErrZombieEdgeNotFound
1✔
3734
                }
1✔
3735

3736
                return zombieIndex.Delete(k[:])
26✔
3737
        }
3738

3739
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3740
        // the existing transaction
3741
        var err error
27✔
3742
        if tx == nil {
54✔
3743
                err = kvdb.Update(c.db, dbFn, func() {})
54✔
UNCOV
3744
        } else {
×
3745
                err = dbFn(tx)
×
3746
        }
×
3747
        if err != nil {
28✔
3748
                return err
1✔
3749
        }
1✔
3750

3751
        c.rejectCache.remove(chanID)
26✔
3752
        c.chanCache.remove(chanID)
26✔
3753

26✔
3754
        return nil
26✔
3755
}
3756

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

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

3776
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
14✔
3777

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

3788
        return isZombie, pubKey1, pubKey2
14✔
3789
}
3790

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

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

208✔
3800
        v := zombieIndex.Get(k[:])
208✔
3801
        if v == nil {
317✔
3802
                return false, [33]byte{}, [33]byte{}
109✔
3803
        }
109✔
3804

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

102✔
3809
        return true, pubKey1, pubKey2
102✔
3810
}
3811

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

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

3836
        return numZombies, nil
4✔
3837
}
3838

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

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

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

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

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

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

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

3883
        return isClosed, nil
5✔
3884
}
3885

3886
// GraphSession will provide the call-back with access to a NodeTraverser
3887
// instance which can be used to perform queries against the channel graph.
3888
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
54✔
3889
        return c.db.View(func(tx walletdb.ReadTx) error {
108✔
3890
                return cb(&nodeTraverserSession{
54✔
3891
                        db: c,
54✔
3892
                        tx: tx,
54✔
3893
                })
54✔
3894
        }, func() {})
108✔
3895
}
3896

3897
// nodeTraverserSession implements the NodeTraverser interface but with a
3898
// backing read only transaction for a consistent view of the graph.
3899
type nodeTraverserSession struct {
3900
        tx kvdb.RTx
3901
        db *KVStore
3902
}
3903

3904
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3905
// node.
3906
//
3907
// NOTE: Part of the NodeTraverser interface.
3908
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3909
        cb func(channel *DirectedChannel) error) error {
239✔
3910

239✔
3911
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
239✔
3912
}
239✔
3913

3914
// FetchNodeFeatures returns the features of the given node. If the node is
3915
// unknown, assume no additional features are supported.
3916
//
3917
// NOTE: Part of the NodeTraverser interface.
3918
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
3919
        *lnwire.FeatureVector, error) {
254✔
3920

254✔
3921
        return c.db.fetchNodeFeatures(c.tx, nodePub)
254✔
3922
}
254✔
3923

3924
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3925
        node *models.LightningNode) error {
905✔
3926

905✔
3927
        var (
905✔
3928
                scratch [16]byte
905✔
3929
                b       bytes.Buffer
905✔
3930
        )
905✔
3931

905✔
3932
        pub, err := node.PubKey()
905✔
3933
        if err != nil {
905✔
UNCOV
3934
                return err
×
3935
        }
×
3936
        nodePub := pub.SerializeCompressed()
905✔
3937

905✔
3938
        // If the node has the update time set, write it, else write 0.
905✔
3939
        updateUnix := uint64(0)
905✔
3940
        if node.LastUpdate.Unix() > 0 {
1,680✔
3941
                updateUnix = uint64(node.LastUpdate.Unix())
775✔
3942
        }
775✔
3943

3944
        byteOrder.PutUint64(scratch[:8], updateUnix)
905✔
3945
        if _, err := b.Write(scratch[:8]); err != nil {
905✔
3946
                return err
×
UNCOV
3947
        }
×
3948

3949
        if _, err := b.Write(nodePub); err != nil {
905✔
3950
                return err
×
UNCOV
3951
        }
×
3952

3953
        // If we got a node announcement for this node, we will have the rest
3954
        // of the data available. If not we don't have more data to write.
3955
        if !node.HaveNodeAnnouncement {
985✔
3956
                // Write HaveNodeAnnouncement=0.
80✔
3957
                byteOrder.PutUint16(scratch[:2], 0)
80✔
3958
                if _, err := b.Write(scratch[:2]); err != nil {
80✔
UNCOV
3959
                        return err
×
UNCOV
3960
                }
×
3961

3962
                return nodeBucket.Put(nodePub, b.Bytes())
80✔
3963
        }
3964

3965
        // Write HaveNodeAnnouncement=1.
3966
        byteOrder.PutUint16(scratch[:2], 1)
828✔
3967
        if _, err := b.Write(scratch[:2]); err != nil {
828✔
UNCOV
3968
                return err
×
UNCOV
3969
        }
×
3970

3971
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
828✔
UNCOV
3972
                return err
×
UNCOV
3973
        }
×
3974
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
828✔
3975
                return err
×
UNCOV
3976
        }
×
3977
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
828✔
UNCOV
3978
                return err
×
3979
        }
×
3980

3981
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
828✔
UNCOV
3982
                return err
×
UNCOV
3983
        }
×
3984

3985
        if err := node.Features.Encode(&b); err != nil {
828✔
UNCOV
3986
                return err
×
UNCOV
3987
        }
×
3988

3989
        numAddresses := uint16(len(node.Addresses))
828✔
3990
        byteOrder.PutUint16(scratch[:2], numAddresses)
828✔
3991
        if _, err := b.Write(scratch[:2]); err != nil {
828✔
UNCOV
3992
                return err
×
UNCOV
3993
        }
×
3994

3995
        for _, address := range node.Addresses {
1,893✔
3996
                if err := SerializeAddr(&b, address); err != nil {
1,065✔
UNCOV
3997
                        return err
×
UNCOV
3998
                }
×
3999
        }
4000

4001
        sigLen := len(node.AuthSigBytes)
828✔
4002
        if sigLen > 80 {
828✔
UNCOV
4003
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
UNCOV
4004
                        sigLen)
×
UNCOV
4005
        }
×
4006

4007
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
828✔
4008
        if err != nil {
828✔
UNCOV
4009
                return err
×
4010
        }
×
4011

4012
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
828✔
UNCOV
4013
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4014
        }
×
4015
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
828✔
4016
        if err != nil {
828✔
UNCOV
4017
                return err
×
UNCOV
4018
        }
×
4019

4020
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
828✔
UNCOV
4021
                return err
×
UNCOV
4022
        }
×
4023

4024
        // With the alias bucket updated, we'll now update the index that
4025
        // tracks the time series of node updates.
4026
        var indexKey [8 + 33]byte
828✔
4027
        byteOrder.PutUint64(indexKey[:8], updateUnix)
828✔
4028
        copy(indexKey[8:], nodePub)
828✔
4029

828✔
4030
        // If there was already an old index entry for this node, then we'll
828✔
4031
        // delete the old one before we write the new entry.
828✔
4032
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
847✔
4033
                // Extract out the old update time to we can reconstruct the
19✔
4034
                // prior index key to delete it from the index.
19✔
4035
                oldUpdateTime := nodeBytes[:8]
19✔
4036

19✔
4037
                var oldIndexKey [8 + 33]byte
19✔
4038
                copy(oldIndexKey[:8], oldUpdateTime)
19✔
4039
                copy(oldIndexKey[8:], nodePub)
19✔
4040

19✔
4041
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
19✔
UNCOV
4042
                        return err
×
4043
                }
×
4044
        }
4045

4046
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
828✔
4047
                return err
×
4048
        }
×
4049

4050
        return nodeBucket.Put(nodePub, b.Bytes())
828✔
4051
}
4052

4053
func fetchLightningNode(nodeBucket kvdb.RBucket,
4054
        nodePub []byte) (models.LightningNode, error) {
3,617✔
4055

3,617✔
4056
        nodeBytes := nodeBucket.Get(nodePub)
3,617✔
4057
        if nodeBytes == nil {
3,697✔
4058
                return models.LightningNode{}, ErrGraphNodeNotFound
80✔
4059
        }
80✔
4060

4061
        nodeReader := bytes.NewReader(nodeBytes)
3,540✔
4062

3,540✔
4063
        return deserializeLightningNode(nodeReader)
3,540✔
4064
}
4065

4066
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4067
        *lnwire.FeatureVector, error) {
123✔
4068

123✔
4069
        var (
123✔
4070
                pubKey      route.Vertex
123✔
4071
                features    = lnwire.EmptyFeatureVector()
123✔
4072
                nodeScratch [8]byte
123✔
4073
        )
123✔
4074

123✔
4075
        // Skip ahead:
123✔
4076
        // - LastUpdate (8 bytes)
123✔
4077
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
UNCOV
4078
                return pubKey, nil, err
×
UNCOV
4079
        }
×
4080

4081
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
123✔
UNCOV
4082
                return pubKey, nil, err
×
UNCOV
4083
        }
×
4084

4085
        // Read the node announcement flag.
4086
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
UNCOV
4087
                return pubKey, nil, err
×
UNCOV
4088
        }
×
4089
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4090

123✔
4091
        // The rest of the data is optional, and will only be there if we got a
123✔
4092
        // node announcement for this node.
123✔
4093
        if hasNodeAnn == 0 {
126✔
4094
                return pubKey, features, nil
3✔
4095
        }
3✔
4096

4097
        // We did get a node announcement for this node, so we'll have the rest
4098
        // of the data available.
4099
        var rgb uint8
123✔
4100
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4101
                return pubKey, nil, err
×
4102
        }
×
4103
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
UNCOV
4104
                return pubKey, nil, err
×
UNCOV
4105
        }
×
4106
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4107
                return pubKey, nil, err
×
UNCOV
4108
        }
×
4109

4110
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4111
                return pubKey, nil, err
×
4112
        }
×
4113

4114
        if err := features.Decode(r); err != nil {
123✔
4115
                return pubKey, nil, err
×
4116
        }
×
4117

4118
        return pubKey, features, nil
123✔
4119
}
4120

4121
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,527✔
4122
        var (
8,527✔
4123
                node    models.LightningNode
8,527✔
4124
                scratch [8]byte
8,527✔
4125
                err     error
8,527✔
4126
        )
8,527✔
4127

8,527✔
4128
        // Always populate a feature vector, even if we don't have a node
8,527✔
4129
        // announcement and short circuit below.
8,527✔
4130
        node.Features = lnwire.EmptyFeatureVector()
8,527✔
4131

8,527✔
4132
        if _, err := r.Read(scratch[:]); err != nil {
8,527✔
UNCOV
4133
                return models.LightningNode{}, err
×
UNCOV
4134
        }
×
4135

4136
        unix := int64(byteOrder.Uint64(scratch[:]))
8,527✔
4137
        node.LastUpdate = time.Unix(unix, 0)
8,527✔
4138

8,527✔
4139
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,527✔
4140
                return models.LightningNode{}, err
×
4141
        }
×
4142

4143
        if _, err := r.Read(scratch[:2]); err != nil {
8,527✔
UNCOV
4144
                return models.LightningNode{}, err
×
UNCOV
4145
        }
×
4146

4147
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,527✔
4148
        if hasNodeAnn == 1 {
16,914✔
4149
                node.HaveNodeAnnouncement = true
8,387✔
4150
        } else {
8,530✔
4151
                node.HaveNodeAnnouncement = false
143✔
4152
        }
143✔
4153

4154
        // The rest of the data is optional, and will only be there if we got a
4155
        // node announcement for this node.
4156
        if !node.HaveNodeAnnouncement {
8,670✔
4157
                return node, nil
143✔
4158
        }
143✔
4159

4160
        // We did get a node announcement for this node, so we'll have the rest
4161
        // of the data available.
4162
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,387✔
4163
                return models.LightningNode{}, err
×
UNCOV
4164
        }
×
4165
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,387✔
4166
                return models.LightningNode{}, err
×
UNCOV
4167
        }
×
4168
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,387✔
4169
                return models.LightningNode{}, err
×
UNCOV
4170
        }
×
4171

4172
        node.Alias, err = wire.ReadVarString(r, 0)
8,387✔
4173
        if err != nil {
8,387✔
UNCOV
4174
                return models.LightningNode{}, err
×
UNCOV
4175
        }
×
4176

4177
        err = node.Features.Decode(r)
8,387✔
4178
        if err != nil {
8,387✔
UNCOV
4179
                return models.LightningNode{}, err
×
UNCOV
4180
        }
×
4181

4182
        if _, err := r.Read(scratch[:2]); err != nil {
8,387✔
UNCOV
4183
                return models.LightningNode{}, err
×
UNCOV
4184
        }
×
4185
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,387✔
4186

8,387✔
4187
        var addresses []net.Addr
8,387✔
4188
        for i := 0; i < numAddresses; i++ {
19,031✔
4189
                address, err := DeserializeAddr(r)
10,644✔
4190
                if err != nil {
10,644✔
4191
                        return models.LightningNode{}, err
×
4192
                }
×
4193
                addresses = append(addresses, address)
10,644✔
4194
        }
4195
        node.Addresses = addresses
8,387✔
4196

8,387✔
4197
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,387✔
4198
        if err != nil {
8,387✔
4199
                return models.LightningNode{}, err
×
UNCOV
4200
        }
×
4201

4202
        // We'll try and see if there are any opaque bytes left, if not, then
4203
        // we'll ignore the EOF error and return the node as is.
4204
        extraBytes, err := wire.ReadVarBytes(
8,387✔
4205
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,387✔
4206
        )
8,387✔
4207
        switch {
8,387✔
4208
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4209
        case errors.Is(err, io.EOF):
×
UNCOV
4210
        case err != nil:
×
UNCOV
4211
                return models.LightningNode{}, err
×
4212
        }
4213

4214
        if len(extraBytes) > 0 {
8,397✔
4215
                node.ExtraOpaqueData = extraBytes
10✔
4216
        }
10✔
4217

4218
        return node, nil
8,387✔
4219
}
4220

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

1,485✔
4224
        var b bytes.Buffer
1,485✔
4225

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

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

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

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

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

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

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

4290
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4291
        chanID []byte) (models.ChannelEdgeInfo, error) {
6,795✔
4292

6,795✔
4293
        edgeInfoBytes := edgeIndex.Get(chanID)
6,795✔
4294
        if edgeInfoBytes == nil {
6,862✔
4295
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
67✔
4296
        }
67✔
4297

4298
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
6,731✔
4299

6,731✔
4300
        return deserializeChanEdgeInfo(edgeInfoReader)
6,731✔
4301
}
4302

4303
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
7,270✔
4304
        var (
7,270✔
4305
                err      error
7,270✔
4306
                edgeInfo models.ChannelEdgeInfo
7,270✔
4307
        )
7,270✔
4308

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

4322
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
7,270✔
4323
        if err != nil {
7,270✔
UNCOV
4324
                return models.ChannelEdgeInfo{}, err
×
UNCOV
4325
        }
×
4326

4327
        proof := &models.ChannelAuthProof{}
7,270✔
4328

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

4346
        if !proof.IsEmpty() {
11,437✔
4347
                edgeInfo.AuthProof = proof
4,167✔
4348
        }
4,167✔
4349

4350
        edgeInfo.ChannelPoint = wire.OutPoint{}
7,270✔
4351
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
7,270✔
UNCOV
4352
                return models.ChannelEdgeInfo{}, err
×
UNCOV
4353
        }
×
4354
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
7,270✔
UNCOV
4355
                return models.ChannelEdgeInfo{}, err
×
UNCOV
4356
        }
×
4357
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
7,270✔
UNCOV
4358
                return models.ChannelEdgeInfo{}, err
×
UNCOV
4359
        }
×
4360

4361
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
7,270✔
4362
                return models.ChannelEdgeInfo{}, err
×
4363
        }
×
4364

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

4377
        return edgeInfo, nil
7,270✔
4378
}
4379

4380
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4381
        from, to []byte) error {
2,666✔
4382

2,666✔
4383
        var edgeKey [33 + 8]byte
2,666✔
4384
        copy(edgeKey[:], from)
2,666✔
4385
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,666✔
4386

2,666✔
4387
        var b bytes.Buffer
2,666✔
4388
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,668✔
4389
                return err
2✔
4390
        }
2✔
4391

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

2,664✔
4399
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,664✔
4400
        if err != nil {
2,664✔
UNCOV
4401
                return err
×
UNCOV
4402
        }
×
4403

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

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

×
UNCOV
4431
                        return err
×
UNCOV
4432
                }
×
4433

4434
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
26✔
4435

26✔
4436
                var oldIndexKey [8 + 8]byte
26✔
4437
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
26✔
4438
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
26✔
4439

26✔
4440
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
26✔
UNCOV
4441
                        return err
×
UNCOV
4442
                }
×
4443
        }
4444

4445
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,664✔
UNCOV
4446
                return err
×
UNCOV
4447
        }
×
4448

4449
        err = updateEdgePolicyDisabledIndex(
2,664✔
4450
                edges, edge.ChannelID,
2,664✔
4451
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,664✔
4452
                edge.IsDisabled(),
2,664✔
4453
        )
2,664✔
4454
        if err != nil {
2,664✔
UNCOV
4455
                return err
×
UNCOV
4456
        }
×
4457

4458
        return edges.Put(edgeKey[:], b.Bytes())
2,664✔
4459
}
4460

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

2,930✔
4473
        var disabledEdgeKey [8 + 1]byte
2,930✔
4474
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,930✔
4475
        if direction {
4,393✔
4476
                disabledEdgeKey[8] = 1
1,463✔
4477
        }
1,463✔
4478

4479
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,930✔
4480
                disabledEdgePolicyBucket,
2,930✔
4481
        )
2,930✔
4482
        if err != nil {
2,930✔
UNCOV
4483
                return err
×
UNCOV
4484
        }
×
4485

4486
        if disabled {
2,959✔
4487
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4488
        }
29✔
4489

4490
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,904✔
4491
}
4492

4493
// putChanEdgePolicyUnknown marks the edge policy as unknown
4494
// in the edges bucket.
4495
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4496
        from []byte) error {
2,963✔
4497

2,963✔
4498
        var edgeKey [33 + 8]byte
2,963✔
4499
        copy(edgeKey[:], from)
2,963✔
4500
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,963✔
4501

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

4507
        return edges.Put(edgeKey[:], unknownPolicy)
2,963✔
4508
}
4509

4510
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4511
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
13,463✔
4512

13,463✔
4513
        var edgeKey [33 + 8]byte
13,463✔
4514
        copy(edgeKey[:], nodePub)
13,463✔
4515
        copy(edgeKey[33:], chanID)
13,463✔
4516

13,463✔
4517
        edgeBytes := edges.Get(edgeKey[:])
13,463✔
4518
        if edgeBytes == nil {
13,463✔
UNCOV
4519
                return nil, ErrEdgeNotFound
×
UNCOV
4520
        }
×
4521

4522
        // No need to deserialize unknown policy.
4523
        if bytes.Equal(edgeBytes, unknownPolicy) {
14,878✔
4524
                return nil, nil
1,415✔
4525
        }
1,415✔
4526

4527
        edgeReader := bytes.NewReader(edgeBytes)
12,051✔
4528

12,051✔
4529
        ep, err := deserializeChanEdgePolicy(edgeReader)
12,051✔
4530
        switch {
12,051✔
4531
        // If the db policy was missing an expected optional field, we return
4532
        // nil as if the policy was unknown.
4533
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
2✔
4534
                return nil, nil
2✔
4535

4536
        // If the policy contains invalid TLV bytes, we return nil as if
4537
        // the policy was unknown.
4538
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4539
                return nil, nil
×
4540

4541
        case err != nil:
×
4542
                return nil, err
×
4543
        }
4544

4545
        return ep, nil
12,049✔
4546
}
4547

4548
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4549
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4550
        error) {
2,891✔
4551

2,891✔
4552
        edgeInfo := edgeIndex.Get(chanID)
2,891✔
4553
        if edgeInfo == nil {
2,891✔
UNCOV
4554
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4555
                        chanID)
×
4556
        }
×
4557

4558
        // The first node is contained within the first half of the edge
4559
        // information. We only propagate the error here and below if it's
4560
        // something other than edge non-existence.
4561
        node1Pub := edgeInfo[:33]
2,891✔
4562
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
2,891✔
4563
        if err != nil {
2,891✔
UNCOV
4564
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
UNCOV
4565
                        node1Pub)
×
4566
        }
×
4567

4568
        // Similarly, the second node is contained within the latter
4569
        // half of the edge information.
4570
        node2Pub := edgeInfo[33:66]
2,891✔
4571
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
2,891✔
4572
        if err != nil {
2,891✔
4573
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4574
                        node2Pub)
×
UNCOV
4575
        }
×
4576

4577
        return edge1, edge2, nil
2,891✔
4578
}
4579

4580
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4581
        to []byte) error {
2,668✔
4582

2,668✔
4583
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,668✔
4584
        if err != nil {
2,668✔
4585
                return err
×
UNCOV
4586
        }
×
4587

4588
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,668✔
UNCOV
4589
                return err
×
UNCOV
4590
        }
×
4591

4592
        var scratch [8]byte
2,668✔
4593
        updateUnix := uint64(edge.LastUpdate.Unix())
2,668✔
4594
        byteOrder.PutUint64(scratch[:], updateUnix)
2,668✔
4595
        if _, err := w.Write(scratch[:]); err != nil {
2,668✔
UNCOV
4596
                return err
×
UNCOV
4597
        }
×
4598

4599
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,668✔
4600
                return err
×
4601
        }
×
4602
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,668✔
UNCOV
4603
                return err
×
UNCOV
4604
        }
×
4605
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,668✔
UNCOV
4606
                return err
×
UNCOV
4607
        }
×
4608
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,668✔
UNCOV
4609
                return err
×
UNCOV
4610
        }
×
4611
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,668✔
4612
        if err != nil {
2,668✔
UNCOV
4613
                return err
×
4614
        }
×
4615
        err = binary.Write(
2,668✔
4616
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,668✔
4617
        )
2,668✔
4618
        if err != nil {
2,668✔
4619
                return err
×
UNCOV
4620
        }
×
4621

4622
        if _, err := w.Write(to); err != nil {
2,668✔
4623
                return err
×
4624
        }
×
4625

4626
        // If the max_htlc field is present, we write it. To be compatible with
4627
        // older versions that wasn't aware of this field, we write it as part
4628
        // of the opaque data.
4629
        // TODO(halseth): clean up when moving to TLV.
4630
        var opaqueBuf bytes.Buffer
2,668✔
4631
        if edge.MessageFlags.HasMaxHtlc() {
4,952✔
4632
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,284✔
4633
                if err != nil {
2,284✔
UNCOV
4634
                        return err
×
4635
                }
×
4636
        }
4637

4638
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
4639
        err = edge.ExtraOpaqueData.ValidateTLV()
2,668✔
4640
        if err != nil {
2,670✔
4641
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
2✔
4642
        }
2✔
4643

4644
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,666✔
4645
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4646
        }
×
4647
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,666✔
UNCOV
4648
                return err
×
UNCOV
4649
        }
×
4650

4651
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,666✔
UNCOV
4652
                return err
×
UNCOV
4653
        }
×
4654

4655
        return nil
2,666✔
4656
}
4657

4658
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
12,075✔
4659
        // Deserialize the policy. Note that in case an optional field is not
12,075✔
4660
        // found or if the edge has invalid TLV data, then both an error and a
12,075✔
4661
        // populated policy object are returned so that the caller can decide
12,075✔
4662
        // if it still wants to use the edge or not.
12,075✔
4663
        edge, err := deserializeChanEdgePolicyRaw(r)
12,075✔
4664
        if err != nil &&
12,075✔
4665
                !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
12,075✔
4666
                !errors.Is(err, ErrParsingExtraTLVBytes) {
12,075✔
4667

×
UNCOV
4668
                return nil, err
×
UNCOV
4669
        }
×
4670

4671
        return edge, err
12,075✔
4672
}
4673

4674
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4675
        error) {
13,082✔
4676

13,082✔
4677
        edge := &models.ChannelEdgePolicy{}
13,082✔
4678

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

4685
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
13,082✔
UNCOV
4686
                return nil, err
×
UNCOV
4687
        }
×
4688

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

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

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

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

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

13,082✔
4722
        if _, err := r.Read(edge.ToNode[:]); err != nil {
13,082✔
UNCOV
4723
                return nil, err
×
UNCOV
4724
        }
×
4725

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

4738
        // See if optional fields are present.
4739
        if edge.MessageFlags.HasMaxHtlc() {
25,207✔
4740
                // The max_htlc field should be at the beginning of the opaque
12,125✔
4741
                // bytes.
12,125✔
4742
                opq := edge.ExtraOpaqueData
12,125✔
4743

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

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

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

4758
        // Attempt to extract the inbound fee from the opaque data. If we fail
4759
        // to parse the TLV here, we return an error we also return the edge
4760
        // so that the caller can still use it. This is for backwards
4761
        // compatibility in case we have already persisted some policies that
4762
        // have invalid TLV data.
4763
        var inboundFee lnwire.Fee
13,078✔
4764
        typeMap, err := edge.ExtraOpaqueData.ExtractRecords(&inboundFee)
13,078✔
4765
        if err != nil {
13,078✔
UNCOV
4766
                return edge, fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
UNCOV
4767
        }
×
4768

4769
        val, ok := typeMap[lnwire.FeeRecordType]
13,078✔
4770
        if ok && val == nil {
14,781✔
4771
                edge.InboundFee = fn.Some(inboundFee)
1,703✔
4772
        }
1,703✔
4773

4774
        return edge, nil
13,078✔
4775
}
4776

4777
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4778
// KVStore and a kvdb.RTx.
4779
type chanGraphNodeTx struct {
4780
        tx   kvdb.RTx
4781
        db   *KVStore
4782
        node *models.LightningNode
4783
}
4784

4785
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4786
// interface.
4787
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4788

4789
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4790
        node *models.LightningNode) *chanGraphNodeTx {
4,105✔
4791

4,105✔
4792
        return &chanGraphNodeTx{
4,105✔
4793
                tx:   tx,
4,105✔
4794
                db:   db,
4,105✔
4795
                node: node,
4,105✔
4796
        }
4,105✔
4797
}
4,105✔
4798

4799
// Node returns the raw information of the node.
4800
//
4801
// NOTE: This is a part of the NodeRTx interface.
4802
func (c *chanGraphNodeTx) Node() *models.LightningNode {
5,022✔
4803
        return c.node
5,022✔
4804
}
5,022✔
4805

4806
// FetchNode fetches the node with the given pub key under the same transaction
4807
// used to fetch the current node. The returned node is also a NodeRTx and any
4808
// operations on that NodeRTx will also be done under the same transaction.
4809
//
4810
// NOTE: This is a part of the NodeRTx interface.
4811
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
2,944✔
4812
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
2,944✔
4813
        if err != nil {
2,944✔
UNCOV
4814
                return nil, err
×
UNCOV
4815
        }
×
4816

4817
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4818
}
4819

4820
// ForEachChannel can be used to iterate over the node's channels under
4821
// the same transaction used to fetch the node.
4822
//
4823
// NOTE: This is a part of the NodeRTx interface.
4824
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4825
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4826

965✔
4827
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4828
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4829
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4830

2,944✔
4831
                        return f(info, policy1, policy2)
2,944✔
4832
                },
2,944✔
4833
        )
4834
}
4835

4836
func (c *KVStore) forEachPruneLogEntry(cb func(height uint32,
NEW
4837
        hash *chainhash.Hash) error) error {
×
UNCOV
4838

×
NEW
4839
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
×
NEW
4840
                metaBucket := tx.ReadBucket(graphMetaBucket)
×
NEW
4841
                if metaBucket == nil {
×
NEW
4842
                        return ErrGraphNotFound
×
NEW
4843
                }
×
4844

NEW
4845
                pruneBucket := metaBucket.NestedReadBucket(pruneLogBucket)
×
NEW
4846
                if pruneBucket == nil {
×
NEW
4847
                        // Graph never been pruned. No entries to iterate over.
×
NEW
4848
                        return nil
×
NEW
4849
                }
×
4850

NEW
4851
                return pruneBucket.ForEach(func(k, v []byte) error {
×
NEW
4852
                        blockHeight := byteOrder.Uint32(k)
×
NEW
4853
                        var blockHash chainhash.Hash
×
NEW
4854
                        copy(blockHash[:], v)
×
UNCOV
4855

×
NEW
4856
                        return cb(blockHeight, &blockHash)
×
NEW
4857
                })
×
NEW
4858
        }, func() {})
×
4859
}
4860

4861
func (c *KVStore) forEachZombieEntry(cb func(chanID uint64, pubKey1,
NEW
4862
        pubKey2 [33]byte) error) error {
×
NEW
4863

×
NEW
4864
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
×
NEW
4865
                edges := tx.ReadBucket(edgeBucket)
×
NEW
4866
                if edges == nil {
×
NEW
4867
                        return ErrGraphNoEdgesFound
×
NEW
4868
                }
×
NEW
4869
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
NEW
4870
                if zombieIndex == nil {
×
NEW
4871
                        return nil
×
NEW
4872
                }
×
4873

NEW
4874
                return zombieIndex.ForEach(func(k, v []byte) error {
×
NEW
4875
                        var pubKey1, pubKey2 [33]byte
×
NEW
4876
                        copy(pubKey1[:], v[:33])
×
NEW
4877
                        copy(pubKey2[:], v[33:])
×
NEW
4878

×
NEW
4879
                        return cb(byteOrder.Uint64(k), pubKey1, pubKey2)
×
NEW
4880
                })
×
NEW
4881
        }, func() {})
×
4882
}
4883

4884
func (c *KVStore) forEachClosedSCID(
NEW
4885
        cb func(lnwire.ShortChannelID) error) error {
×
NEW
4886

×
NEW
4887
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
×
NEW
4888
                closedScids := tx.ReadBucket(closedScidBucket)
×
NEW
4889
                if closedScids == nil {
×
NEW
4890
                        return nil
×
NEW
4891
                }
×
4892

NEW
4893
                return closedScids.ForEach(func(k, _ []byte) error {
×
NEW
4894
                        return cb(lnwire.NewShortChanIDFromInt(
×
NEW
4895
                                byteOrder.Uint64(k),
×
NEW
4896
                        ))
×
NEW
4897
                })
×
NEW
4898
        }, func() {})
×
4899
}
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