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

lightningnetwork / lnd / 16152866413

08 Jul 2025 07:44PM UTC coverage: 57.72% (-9.8%) from 67.503%
16152866413

Pull #10015

github

web-flow
Merge f6affb695 into 47dce0894
Pull Request #10015: graph/db: add zombie channels cleanup routine

32 of 63 new or added lines in 2 files covered. (50.79%)

28432 existing lines in 455 files now uncovered.

98528 of 170699 relevant lines covered (57.72%)

1.79 hits per line

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

68.89
/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) {
3✔
207

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

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

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

3✔
233
        return g, nil
3✔
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
// String returns a human-readable representation of the key.
243
func (c channelMapKey) String() string {
×
244
        return fmt.Sprintf("node=%v, chanID=%x", c.nodeKey, c.chanID)
×
245
}
×
246

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

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

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

3✔
263
                        return nil
3✔
264
                }
3✔
265

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

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

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

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

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

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

298
                case err != nil:
×
299
                        return err
×
300
                }
301

302
                channelMap[key] = edge
3✔
303

3✔
304
                return nil
3✔
305
        })
306
        if err != nil {
3✔
307
                return nil, err
×
308
        }
×
309

310
        return channelMap, nil
3✔
311
}
312

313
var graphTopLevelBuckets = [][]byte{
314
        nodeBucket,
315
        edgeBucket,
316
        graphMetaBucket,
317
        closedScidBucket,
318
}
319

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

332
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
333
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
334
                if err != nil {
3✔
335
                        return err
×
336
                }
×
337
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
3✔
338
                if err != nil {
3✔
339
                        return err
×
340
                }
×
341

342
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
343
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
344
                if err != nil {
3✔
345
                        return err
×
346
                }
×
347
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
348
                if err != nil {
3✔
349
                        return err
×
350
                }
×
351
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
3✔
352
                if err != nil {
3✔
353
                        return err
×
354
                }
×
355
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
3✔
356
                if err != nil {
3✔
357
                        return err
×
358
                }
×
359

360
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
3✔
361
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
3✔
362

3✔
363
                return err
3✔
364
        }, func() {})
3✔
365
        if err != nil {
3✔
366
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
367
        }
×
368

369
        return nil
3✔
370
}
371

372
// AddrsForNode returns all known addresses for the target node public key that
373
// the graph DB is aware of. The returned boolean indicates if the given node is
374
// unknown to the graph DB or not.
375
//
376
// NOTE: this is part of the channeldb.AddrSource interface.
377
func (c *KVStore) AddrsForNode(ctx context.Context,
378
        nodePub *btcec.PublicKey) (bool, []net.Addr, error) {
3✔
379

3✔
380
        pubKey, err := route.NewVertexFromBytes(nodePub.SerializeCompressed())
3✔
381
        if err != nil {
3✔
382
                return false, nil, err
×
383
        }
×
384

385
        node, err := c.FetchLightningNode(ctx, pubKey)
3✔
386
        // We don't consider it an error if the graph is unaware of the node.
3✔
387
        switch {
3✔
388
        case err != nil && !errors.Is(err, ErrGraphNodeNotFound):
×
389
                return false, nil, err
×
390

391
        case errors.Is(err, ErrGraphNodeNotFound):
3✔
392
                return false, nil, nil
3✔
393
        }
394

395
        return true, node.Addresses, nil
3✔
396
}
397

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

3✔
410
        return forEachChannel(c.db, cb)
3✔
411
}
3✔
412

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

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

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

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

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

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

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

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

3✔
468
                                return cb(&info, policy1, policy2)
3✔
469
                        },
470
                )
471
        }, func() {})
3✔
472
}
473

474
// ForEachChannelCacheable iterates through all the channel edges stored within
475
// the graph and invokes the passed callback for each edge. The callback takes
476
// two edges as since this is a directed graph, both the in/out edges are
477
// visited. If the callback returns an error, then the transaction is aborted
478
// and the iteration stops early.
479
//
480
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
481
// for that particular channel edge routing policy will be passed into the
482
// callback.
483
//
484
// NOTE: this method is like ForEachChannel but fetches only the data required
485
// for the graph cache.
486
func (c *KVStore) ForEachChannelCacheable(cb func(*models.CachedEdgeInfo,
487
        *models.CachedEdgePolicy, *models.CachedEdgePolicy) error) error {
3✔
488

3✔
489
        return c.db.View(func(tx kvdb.RTx) error {
6✔
490
                edges := tx.ReadBucket(edgeBucket)
3✔
491
                if edges == nil {
3✔
492
                        return ErrGraphNoEdgesFound
×
493
                }
×
494

495
                // First, load all edges in memory indexed by node and channel
496
                // id.
497
                channelMap, err := getChannelMap(edges)
3✔
498
                if err != nil {
3✔
499
                        return err
×
500
                }
×
501

502
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
503
                if edgeIndex == nil {
3✔
504
                        return ErrGraphNoEdgesFound
×
505
                }
×
506

507
                // Load edge index, recombine each channel with the policies
508
                // loaded above and invoke the callback.
509
                return kvdb.ForAll(
3✔
510
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
6✔
511
                                var chanID [8]byte
3✔
512
                                copy(chanID[:], k)
3✔
513

3✔
514
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
515
                                info, err := deserializeChanEdgeInfo(
3✔
516
                                        edgeInfoReader,
3✔
517
                                )
3✔
518
                                if err != nil {
3✔
519
                                        return err
×
520
                                }
×
521

522
                                key1 := channelMapKey{
3✔
523
                                        nodeKey: info.NodeKey1Bytes,
3✔
524
                                        chanID:  chanID,
3✔
525
                                }
3✔
526
                                policy1 := channelMap[key1]
3✔
527

3✔
528
                                key2 := channelMapKey{
3✔
529
                                        nodeKey: info.NodeKey2Bytes,
3✔
530
                                        chanID:  chanID,
3✔
531
                                }
3✔
532
                                policy2 := channelMap[key2]
3✔
533

3✔
534
                                // We now create the cached edge policies, but
3✔
535
                                // only when the above policies are found in the
3✔
536
                                // `channelMap`.
3✔
537
                                var (
3✔
538
                                        cachedPolicy1 *models.CachedEdgePolicy
3✔
539
                                        cachedPolicy2 *models.CachedEdgePolicy
3✔
540
                                )
3✔
541

3✔
542
                                if policy1 != nil {
6✔
543
                                        cachedPolicy1 = models.NewCachedPolicy(
3✔
544
                                                policy1,
3✔
545
                                        )
3✔
546
                                }
3✔
547

548
                                if policy2 != nil {
6✔
549
                                        cachedPolicy2 = models.NewCachedPolicy(
3✔
550
                                                policy2,
3✔
551
                                        )
3✔
552
                                }
3✔
553

554
                                return cb(
3✔
555
                                        models.NewCachedEdge(&info),
3✔
556
                                        cachedPolicy1, cachedPolicy2,
3✔
557
                                )
3✔
558
                        },
559
                )
560
        }, func() {})
3✔
561
}
562

563
// forEachNodeDirectedChannel iterates through all channels of a given node,
564
// executing the passed callback on the directed edge representing the channel
565
// and its incoming policy. If the callback returns an error, then the iteration
566
// is halted with the error propagated back up to the caller. An optional read
567
// transaction may be provided. If none is provided, a new one will be created.
568
//
569
// Unknown policies are passed into the callback as nil values.
570
func (c *KVStore) forEachNodeDirectedChannel(tx kvdb.RTx,
571
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
3✔
572

3✔
573
        // Fallback that uses the database.
3✔
574
        toNodeCallback := func() route.Vertex {
6✔
575
                return node
3✔
576
        }
3✔
577
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
578
        if err != nil {
3✔
579
                return err
×
580
        }
×
581

582
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
3✔
583
                p2 *models.ChannelEdgePolicy) error {
6✔
584

3✔
585
                var cachedInPolicy *models.CachedEdgePolicy
3✔
586
                if p2 != nil {
6✔
587
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
588
                        cachedInPolicy.ToNodePubKey = toNodeCallback
3✔
589
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
3✔
590
                }
3✔
591

592
                directedChannel := &DirectedChannel{
3✔
593
                        ChannelID:    e.ChannelID,
3✔
594
                        IsNode1:      node == e.NodeKey1Bytes,
3✔
595
                        OtherNode:    e.NodeKey2Bytes,
3✔
596
                        Capacity:     e.Capacity,
3✔
597
                        OutPolicySet: p1 != nil,
3✔
598
                        InPolicy:     cachedInPolicy,
3✔
599
                }
3✔
600

3✔
601
                if p1 != nil {
6✔
602
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
UNCOV
603
                                directedChannel.InboundFee = fee
×
UNCOV
604
                        })
×
605
                }
606

607
                if node == e.NodeKey2Bytes {
6✔
608
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
609
                }
3✔
610

611
                return cb(directedChannel)
3✔
612
        }
613

614
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
615
}
616

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

3✔
623
        // Fallback that uses the database.
3✔
624
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
625
        switch {
3✔
626
        // If the node exists and has features, return them directly.
627
        case err == nil:
3✔
628
                return targetNode.Features, nil
3✔
629

630
        // If we couldn't find a node announcement, populate a blank feature
631
        // vector.
UNCOV
632
        case errors.Is(err, ErrGraphNodeNotFound):
×
UNCOV
633
                return lnwire.EmptyFeatureVector(), nil
×
634

635
        // Otherwise, bubble the error up.
636
        default:
×
637
                return nil, err
×
638
        }
639
}
640

641
// ForEachNodeDirectedChannel iterates through all channels of a given node,
642
// executing the passed callback on the directed edge representing the channel
643
// and its incoming policy. If the callback returns an error, then the iteration
644
// is halted with the error propagated back up to the caller.
645
//
646
// Unknown policies are passed into the callback as nil values.
647
//
648
// NOTE: this is part of the graphdb.NodeTraverser interface.
649
func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
650
        cb func(channel *DirectedChannel) error) error {
3✔
651

3✔
652
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
3✔
653
}
3✔
654

655
// FetchNodeFeatures returns the features of the given node. If no features are
656
// known for the node, an empty feature vector is returned.
657
//
658
// NOTE: this is part of the graphdb.NodeTraverser interface.
659
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
660
        *lnwire.FeatureVector, error) {
3✔
661

3✔
662
        return c.fetchNodeFeatures(nil, nodePub)
3✔
663
}
3✔
664

665
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
666
// data to the call-back.
667
//
668
// NOTE: The callback contents MUST not be modified.
669
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
UNCOV
670
        chans map[uint64]*DirectedChannel) error) error {
×
UNCOV
671

×
UNCOV
672
        // Otherwise call back to a version that uses the database directly.
×
UNCOV
673
        // We'll iterate over each node, then the set of channels for each
×
UNCOV
674
        // node, and construct a similar callback functiopn signature as the
×
UNCOV
675
        // main funcotin expects.
×
UNCOV
676
        return forEachNode(c.db, func(tx kvdb.RTx,
×
UNCOV
677
                node *models.LightningNode) error {
×
UNCOV
678

×
UNCOV
679
                channels := make(map[uint64]*DirectedChannel)
×
UNCOV
680

×
UNCOV
681
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
×
UNCOV
682
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
UNCOV
683
                                p1 *models.ChannelEdgePolicy,
×
UNCOV
684
                                p2 *models.ChannelEdgePolicy) error {
×
UNCOV
685

×
UNCOV
686
                                toNodeCallback := func() route.Vertex {
×
687
                                        return node.PubKeyBytes
×
688
                                }
×
UNCOV
689
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
UNCOV
690
                                        tx, node.PubKeyBytes,
×
UNCOV
691
                                )
×
UNCOV
692
                                if err != nil {
×
693
                                        return err
×
694
                                }
×
695

UNCOV
696
                                var cachedInPolicy *models.CachedEdgePolicy
×
UNCOV
697
                                if p2 != nil {
×
UNCOV
698
                                        cachedInPolicy =
×
UNCOV
699
                                                models.NewCachedPolicy(p2)
×
UNCOV
700
                                        cachedInPolicy.ToNodePubKey =
×
UNCOV
701
                                                toNodeCallback
×
UNCOV
702
                                        cachedInPolicy.ToNodeFeatures =
×
UNCOV
703
                                                toNodeFeatures
×
UNCOV
704
                                }
×
705

UNCOV
706
                                directedChannel := &DirectedChannel{
×
UNCOV
707
                                        ChannelID: e.ChannelID,
×
UNCOV
708
                                        IsNode1: node.PubKeyBytes ==
×
UNCOV
709
                                                e.NodeKey1Bytes,
×
UNCOV
710
                                        OtherNode:    e.NodeKey2Bytes,
×
UNCOV
711
                                        Capacity:     e.Capacity,
×
UNCOV
712
                                        OutPolicySet: p1 != nil,
×
UNCOV
713
                                        InPolicy:     cachedInPolicy,
×
UNCOV
714
                                }
×
UNCOV
715

×
UNCOV
716
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
UNCOV
717
                                        directedChannel.OtherNode =
×
UNCOV
718
                                                e.NodeKey1Bytes
×
UNCOV
719
                                }
×
720

UNCOV
721
                                channels[e.ChannelID] = directedChannel
×
UNCOV
722

×
UNCOV
723
                                return nil
×
724
                        })
UNCOV
725
                if err != nil {
×
726
                        return err
×
727
                }
×
728

UNCOV
729
                return cb(node.PubKeyBytes, channels)
×
730
        })
731
}
732

733
// DisabledChannelIDs returns the channel ids of disabled channels.
734
// A channel is disabled when two of the associated ChanelEdgePolicies
735
// have their disabled bit on.
UNCOV
736
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
×
UNCOV
737
        var disabledChanIDs []uint64
×
UNCOV
738
        var chanEdgeFound map[uint64]struct{}
×
UNCOV
739

×
UNCOV
740
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
741
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
742
                if edges == nil {
×
743
                        return ErrGraphNoEdgesFound
×
744
                }
×
745

UNCOV
746
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
UNCOV
747
                        disabledEdgePolicyBucket,
×
UNCOV
748
                )
×
UNCOV
749
                if disabledEdgePolicyIndex == nil {
×
UNCOV
750
                        return nil
×
UNCOV
751
                }
×
752

753
                // We iterate over all disabled policies and we add each channel
754
                // that has more than one disabled policy to disabledChanIDs
755
                // array.
UNCOV
756
                return disabledEdgePolicyIndex.ForEach(
×
UNCOV
757
                        func(k, v []byte) error {
×
UNCOV
758
                                chanID := byteOrder.Uint64(k[:8])
×
UNCOV
759
                                _, edgeFound := chanEdgeFound[chanID]
×
UNCOV
760
                                if edgeFound {
×
UNCOV
761
                                        delete(chanEdgeFound, chanID)
×
UNCOV
762
                                        disabledChanIDs = append(
×
UNCOV
763
                                                disabledChanIDs, chanID,
×
UNCOV
764
                                        )
×
UNCOV
765

×
UNCOV
766
                                        return nil
×
UNCOV
767
                                }
×
768

UNCOV
769
                                chanEdgeFound[chanID] = struct{}{}
×
UNCOV
770

×
UNCOV
771
                                return nil
×
772
                        },
773
                )
UNCOV
774
        }, func() {
×
UNCOV
775
                disabledChanIDs = nil
×
UNCOV
776
                chanEdgeFound = make(map[uint64]struct{})
×
UNCOV
777
        })
×
UNCOV
778
        if err != nil {
×
779
                return nil, err
×
780
        }
×
781

UNCOV
782
        return disabledChanIDs, nil
×
783
}
784

785
// ForEachNode iterates through all the stored vertices/nodes in the graph,
786
// executing the passed callback with each node encountered. If the callback
787
// returns an error, then the transaction is aborted and the iteration stops
788
// early. Any operations performed on the NodeTx passed to the call-back are
789
// executed under the same read transaction and so, methods on the NodeTx object
790
// _MUST_ only be called from within the call-back.
791
func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error {
3✔
792
        return forEachNode(c.db, func(tx kvdb.RTx,
3✔
793
                node *models.LightningNode) error {
6✔
794

3✔
795
                return cb(newChanGraphNodeTx(tx, c, node))
3✔
796
        })
3✔
797
}
798

799
// forEachNode iterates through all the stored vertices/nodes in the graph,
800
// executing the passed callback with each node encountered. If the callback
801
// returns an error, then the transaction is aborted and the iteration stops
802
// early.
803
//
804
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
805
// traversal when graph gets mega.
806
func forEachNode(db kvdb.Backend,
807
        cb func(kvdb.RTx, *models.LightningNode) error) error {
3✔
808

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

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

825
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
826
                        node, err := deserializeLightningNode(nodeReader)
3✔
827
                        if err != nil {
3✔
828
                                return err
×
829
                        }
×
830

831
                        // Execute the callback, the transaction will abort if
832
                        // this returns an error.
833
                        return cb(tx, &node)
3✔
834
                })
835
        }
836

837
        return kvdb.View(db, traversal, func() {})
6✔
838
}
839

840
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
841
// graph, executing the passed callback with each node encountered. If the
842
// callback returns an error, then the transaction is aborted and the iteration
843
// stops early.
844
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
845
        *lnwire.FeatureVector) error) error {
3✔
846

3✔
847
        traversal := func(tx kvdb.RTx) error {
6✔
848
                // First grab the nodes bucket which stores the mapping from
3✔
849
                // pubKey to node information.
3✔
850
                nodes := tx.ReadBucket(nodeBucket)
3✔
851
                if nodes == nil {
3✔
852
                        return ErrGraphNotFound
×
853
                }
×
854

855
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
856
                        // If this is the source key, then we skip this
3✔
857
                        // iteration as the value for this key is a pubKey
3✔
858
                        // rather than raw node information.
3✔
859
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
860
                                return nil
3✔
861
                        }
3✔
862

863
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
864
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
865
                                nodeReader,
3✔
866
                        )
3✔
867
                        if err != nil {
3✔
868
                                return err
×
869
                        }
×
870

871
                        // Execute the callback, the transaction will abort if
872
                        // this returns an error.
873
                        return cb(node, features)
3✔
874
                })
875
        }
876

877
        return kvdb.View(c.db, traversal, func() {})
6✔
878
}
879

880
// SourceNode returns the source node of the graph. The source node is treated
881
// as the center node within a star-graph. This method may be used to kick off
882
// a path finding algorithm in order to explore the reachability of another
883
// node based off the source node.
884
func (c *KVStore) SourceNode(_ context.Context) (*models.LightningNode, error) {
3✔
885
        return sourceNode(c.db)
3✔
886
}
3✔
887

888
// sourceNode fetches the source node of the graph. The source node is treated
889
// as the center node within a star-graph.
890
func sourceNode(db kvdb.Backend) (*models.LightningNode, error) {
3✔
891
        var source *models.LightningNode
3✔
892
        err := kvdb.View(db, func(tx kvdb.RTx) error {
6✔
893
                // First grab the nodes bucket which stores the mapping from
3✔
894
                // pubKey to node information.
3✔
895
                nodes := tx.ReadBucket(nodeBucket)
3✔
896
                if nodes == nil {
3✔
897
                        return ErrGraphNotFound
×
898
                }
×
899

900
                node, err := sourceNodeWithTx(nodes)
3✔
901
                if err != nil {
6✔
902
                        return err
3✔
903
                }
3✔
904
                source = node
3✔
905

3✔
906
                return nil
3✔
907
        }, func() {
3✔
908
                source = nil
3✔
909
        })
3✔
910
        if err != nil {
6✔
911
                return nil, err
3✔
912
        }
3✔
913

914
        return source, nil
3✔
915
}
916

917
// sourceNodeWithTx uses an existing database transaction and returns the source
918
// node of the graph. The source node is treated as the center node within a
919
// star-graph. This method may be used to kick off a path finding algorithm in
920
// order to explore the reachability of another node based off the source node.
921
func sourceNodeWithTx(nodes kvdb.RBucket) (*models.LightningNode, error) {
3✔
922
        selfPub := nodes.Get(sourceKey)
3✔
923
        if selfPub == nil {
6✔
924
                return nil, ErrSourceNodeNotSet
3✔
925
        }
3✔
926

927
        // With the pubKey of the source node retrieved, we're able to
928
        // fetch the full node information.
929
        node, err := fetchLightningNode(nodes, selfPub)
3✔
930
        if err != nil {
3✔
931
                return nil, err
×
932
        }
×
933

934
        return &node, nil
3✔
935
}
936

937
// SetSourceNode sets the source node within the graph database. The source
938
// node is to be used as the center of a star-graph within path finding
939
// algorithms.
940
func (c *KVStore) SetSourceNode(_ context.Context,
941
        node *models.LightningNode) error {
3✔
942

3✔
943
        nodePubBytes := node.PubKeyBytes[:]
3✔
944

3✔
945
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
946
                // First grab the nodes bucket which stores the mapping from
3✔
947
                // pubKey to node information.
3✔
948
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
949
                if err != nil {
3✔
950
                        return err
×
951
                }
×
952

953
                // Next we create the mapping from source to the targeted
954
                // public key.
955
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
3✔
956
                        return err
×
957
                }
×
958

959
                // Finally, we commit the information of the lightning node
960
                // itself.
961
                return addLightningNode(tx, node)
3✔
962
        }, func() {})
3✔
963
}
964

965
// AddLightningNode adds a vertex/node to the graph database. If the node is not
966
// in the database from before, this will add a new, unconnected one to the
967
// graph. If it is present from before, this will update that node's
968
// information. Note that this method is expected to only be called to update an
969
// already present node from a node announcement, or to insert a node found in a
970
// channel update.
971
//
972
// TODO(roasbeef): also need sig of announcement.
973
func (c *KVStore) AddLightningNode(ctx context.Context,
974
        node *models.LightningNode, opts ...batch.SchedulerOption) error {
3✔
975

3✔
976
        r := &batch.Request[kvdb.RwTx]{
3✔
977
                Opts: batch.NewSchedulerOptions(opts...),
3✔
978
                Do: func(tx kvdb.RwTx) error {
6✔
979
                        return addLightningNode(tx, node)
3✔
980
                },
3✔
981
        }
982

983
        return c.nodeScheduler.Execute(ctx, r)
3✔
984
}
985

986
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
987
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
988
        if err != nil {
3✔
989
                return err
×
990
        }
×
991

992
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
993
        if err != nil {
3✔
994
                return err
×
995
        }
×
996

997
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
998
                nodeUpdateIndexBucket,
3✔
999
        )
3✔
1000
        if err != nil {
3✔
1001
                return err
×
1002
        }
×
1003

1004
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
1005
}
1006

1007
// LookupAlias attempts to return the alias as advertised by the target node.
1008
// TODO(roasbeef): currently assumes that aliases are unique...
1009
func (c *KVStore) LookupAlias(_ context.Context,
1010
        pub *btcec.PublicKey) (string, error) {
3✔
1011

3✔
1012
        var alias string
3✔
1013

3✔
1014
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1015
                nodes := tx.ReadBucket(nodeBucket)
3✔
1016
                if nodes == nil {
3✔
1017
                        return ErrGraphNodesNotFound
×
1018
                }
×
1019

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

1025
                nodePub := pub.SerializeCompressed()
3✔
1026
                a := aliases.Get(nodePub)
3✔
1027
                if a == nil {
3✔
UNCOV
1028
                        return ErrNodeAliasNotFound
×
UNCOV
1029
                }
×
1030

1031
                // TODO(roasbeef): should actually be using the utf-8
1032
                // package...
1033
                alias = string(a)
3✔
1034

3✔
1035
                return nil
3✔
1036
        }, func() {
3✔
1037
                alias = ""
3✔
1038
        })
3✔
1039
        if err != nil {
3✔
UNCOV
1040
                return "", err
×
UNCOV
1041
        }
×
1042

1043
        return alias, nil
3✔
1044
}
1045

1046
// DeleteLightningNode starts a new database transaction to remove a vertex/node
1047
// from the database according to the node's public key.
1048
func (c *KVStore) DeleteLightningNode(_ context.Context,
UNCOV
1049
        nodePub route.Vertex) error {
×
UNCOV
1050

×
UNCOV
1051
        // TODO(roasbeef): ensure dangling edges are removed...
×
UNCOV
1052
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
1053
                nodes := tx.ReadWriteBucket(nodeBucket)
×
UNCOV
1054
                if nodes == nil {
×
1055
                        return ErrGraphNodeNotFound
×
1056
                }
×
1057

UNCOV
1058
                return c.deleteLightningNode(nodes, nodePub[:])
×
UNCOV
1059
        }, func() {})
×
1060
}
1061

1062
// deleteLightningNode uses an existing database transaction to remove a
1063
// vertex/node from the database according to the node's public key.
1064
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
1065
        compressedPubKey []byte) error {
3✔
1066

3✔
1067
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
3✔
1068
        if aliases == nil {
3✔
1069
                return ErrGraphNodesNotFound
×
1070
        }
×
1071

1072
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
1073
                return err
×
1074
        }
×
1075

1076
        // Before we delete the node, we'll fetch its current state so we can
1077
        // determine when its last update was to clear out the node update
1078
        // index.
1079
        node, err := fetchLightningNode(nodes, compressedPubKey)
3✔
1080
        if err != nil {
3✔
UNCOV
1081
                return err
×
UNCOV
1082
        }
×
1083

1084
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
1085
                return err
×
1086
        }
×
1087

1088
        // Finally, we'll delete the index entry for the node within the
1089
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1090
        // need to track its last update.
1091
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
1092
        if nodeUpdateIndex == nil {
3✔
1093
                return ErrGraphNodesNotFound
×
1094
        }
×
1095

1096
        // In order to delete the entry, we'll need to reconstruct the key for
1097
        // its last update.
1098
        updateUnix := uint64(node.LastUpdate.Unix())
3✔
1099
        var indexKey [8 + 33]byte
3✔
1100
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
1101
        copy(indexKey[8:], compressedPubKey)
3✔
1102

3✔
1103
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
1104
}
1105

1106
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1107
// undirected edge from the two target nodes are created. The information stored
1108
// denotes the static attributes of the channel, such as the channelID, the keys
1109
// involved in creation of the channel, and the set of features that the channel
1110
// supports. The chanPoint and chanID are used to uniquely identify the edge
1111
// globally within the database.
1112
func (c *KVStore) AddChannelEdge(ctx context.Context,
1113
        edge *models.ChannelEdgeInfo, opts ...batch.SchedulerOption) error {
3✔
1114

3✔
1115
        var alreadyExists bool
3✔
1116
        r := &batch.Request[kvdb.RwTx]{
3✔
1117
                Opts: batch.NewSchedulerOptions(opts...),
3✔
1118
                Reset: func() {
6✔
1119
                        alreadyExists = false
3✔
1120
                },
3✔
1121
                Do: func(tx kvdb.RwTx) error {
3✔
1122
                        err := c.addChannelEdge(tx, edge)
3✔
1123

3✔
1124
                        // Silence ErrEdgeAlreadyExist so that the batch can
3✔
1125
                        // succeed, but propagate the error via local state.
3✔
1126
                        if errors.Is(err, ErrEdgeAlreadyExist) {
3✔
UNCOV
1127
                                alreadyExists = true
×
UNCOV
1128
                                return nil
×
UNCOV
1129
                        }
×
1130

1131
                        return err
3✔
1132
                },
1133
                OnCommit: func(err error) error {
3✔
1134
                        switch {
3✔
1135
                        case err != nil:
×
1136
                                return err
×
UNCOV
1137
                        case alreadyExists:
×
UNCOV
1138
                                return ErrEdgeAlreadyExist
×
1139
                        default:
3✔
1140
                                c.rejectCache.remove(edge.ChannelID)
3✔
1141
                                c.chanCache.remove(edge.ChannelID)
3✔
1142
                                return nil
3✔
1143
                        }
1144
                },
1145
        }
1146

1147
        return c.chanScheduler.Execute(ctx, r)
3✔
1148
}
1149

1150
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1151
// utilize an existing db transaction.
1152
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1153
        edge *models.ChannelEdgeInfo) error {
3✔
1154

3✔
1155
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1156
        var chanKey [8]byte
3✔
1157
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1158

3✔
1159
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1160
        if err != nil {
3✔
1161
                return err
×
1162
        }
×
1163
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1164
        if err != nil {
3✔
1165
                return err
×
1166
        }
×
1167
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1168
        if err != nil {
3✔
1169
                return err
×
1170
        }
×
1171
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1172
        if err != nil {
3✔
1173
                return err
×
1174
        }
×
1175

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

1182
        // Before we insert the channel into the database, we'll ensure that
1183
        // both nodes already exist in the channel graph. If either node
1184
        // doesn't, then we'll insert a "shell" node that just includes its
1185
        // public key, so subsequent validation and queries can work properly.
1186
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
3✔
1187
        switch {
3✔
1188
        case errors.Is(node1Err, ErrGraphNodeNotFound):
3✔
1189
                node1Shell := models.LightningNode{
3✔
1190
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1191
                        HaveNodeAnnouncement: false,
3✔
1192
                }
3✔
1193
                err := addLightningNode(tx, &node1Shell)
3✔
1194
                if err != nil {
3✔
1195
                        return fmt.Errorf("unable to create shell node "+
×
1196
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1197
                }
×
1198
        case node1Err != nil:
×
1199
                return node1Err
×
1200
        }
1201

1202
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
1203
        switch {
3✔
1204
        case errors.Is(node2Err, ErrGraphNodeNotFound):
3✔
1205
                node2Shell := models.LightningNode{
3✔
1206
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1207
                        HaveNodeAnnouncement: false,
3✔
1208
                }
3✔
1209
                err := addLightningNode(tx, &node2Shell)
3✔
1210
                if err != nil {
3✔
1211
                        return fmt.Errorf("unable to create shell node "+
×
1212
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1213
                }
×
1214
        case node2Err != nil:
×
1215
                return node2Err
×
1216
        }
1217

1218
        // If the edge hasn't been created yet, then we'll first add it to the
1219
        // edge index in order to associate the edge between two nodes and also
1220
        // store the static components of the channel.
1221
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1222
                return err
×
1223
        }
×
1224

1225
        // Mark edge policies for both sides as unknown. This is to enable
1226
        // efficient incoming channel lookup for a node.
1227
        keys := []*[33]byte{
3✔
1228
                &edge.NodeKey1Bytes,
3✔
1229
                &edge.NodeKey2Bytes,
3✔
1230
        }
3✔
1231
        for _, key := range keys {
6✔
1232
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1233
                if err != nil {
3✔
1234
                        return err
×
1235
                }
×
1236
        }
1237

1238
        // Finally we add it to the channel index which maps channel points
1239
        // (outpoints) to the shorter channel ID's.
1240
        var b bytes.Buffer
3✔
1241
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1242
                return err
×
1243
        }
×
1244

1245
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1246
}
1247

1248
// HasChannelEdge returns true if the database knows of a channel edge with the
1249
// passed channel ID, and false otherwise. If an edge with that ID is found
1250
// within the graph, then two time stamps representing the last time the edge
1251
// was updated for both directed edges are returned along with the boolean. If
1252
// it is not found, then the zombie index is checked and its result is returned
1253
// as the second boolean.
1254
func (c *KVStore) HasChannelEdge(
1255
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1256

3✔
1257
        var (
3✔
1258
                upd1Time time.Time
3✔
1259
                upd2Time time.Time
3✔
1260
                exists   bool
3✔
1261
                isZombie bool
3✔
1262
        )
3✔
1263

3✔
1264
        // We'll query the cache with the shared lock held to allow multiple
3✔
1265
        // readers to access values in the cache concurrently if they exist.
3✔
1266
        c.cacheMu.RLock()
3✔
1267
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1268
                c.cacheMu.RUnlock()
3✔
1269
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1270
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1271
                exists, isZombie = entry.flags.unpack()
3✔
1272

3✔
1273
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1274
        }
3✔
1275
        c.cacheMu.RUnlock()
3✔
1276

3✔
1277
        c.cacheMu.Lock()
3✔
1278
        defer c.cacheMu.Unlock()
3✔
1279

3✔
1280
        // The item was not found with the shared lock, so we'll acquire the
3✔
1281
        // exclusive lock and check the cache again in case another method added
3✔
1282
        // the entry to the cache while no lock was held.
3✔
1283
        if entry, ok := c.rejectCache.get(chanID); ok {
5✔
1284
                upd1Time = time.Unix(entry.upd1Time, 0)
2✔
1285
                upd2Time = time.Unix(entry.upd2Time, 0)
2✔
1286
                exists, isZombie = entry.flags.unpack()
2✔
1287

2✔
1288
                return upd1Time, upd2Time, exists, isZombie, nil
2✔
1289
        }
2✔
1290

1291
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1292
                edges := tx.ReadBucket(edgeBucket)
3✔
1293
                if edges == nil {
3✔
1294
                        return ErrGraphNoEdgesFound
×
1295
                }
×
1296
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1297
                if edgeIndex == nil {
3✔
1298
                        return ErrGraphNoEdgesFound
×
1299
                }
×
1300

1301
                var channelID [8]byte
3✔
1302
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1303

3✔
1304
                // If the edge doesn't exist, then we'll also check our zombie
3✔
1305
                // index.
3✔
1306
                if edgeIndex.Get(channelID[:]) == nil {
6✔
1307
                        exists = false
3✔
1308
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1309
                        if zombieIndex != nil {
6✔
1310
                                isZombie, _, _ = isZombieEdge(
3✔
1311
                                        zombieIndex, chanID,
3✔
1312
                                )
3✔
1313
                        }
3✔
1314

1315
                        return nil
3✔
1316
                }
1317

1318
                exists = true
3✔
1319
                isZombie = false
3✔
1320

3✔
1321
                // If the channel has been found in the graph, then retrieve
3✔
1322
                // the edges itself so we can return the last updated
3✔
1323
                // timestamps.
3✔
1324
                nodes := tx.ReadBucket(nodeBucket)
3✔
1325
                if nodes == nil {
3✔
1326
                        return ErrGraphNodeNotFound
×
1327
                }
×
1328

1329
                e1, e2, err := fetchChanEdgePolicies(
3✔
1330
                        edgeIndex, edges, channelID[:],
3✔
1331
                )
3✔
1332
                if err != nil {
3✔
1333
                        return err
×
1334
                }
×
1335

1336
                // As we may have only one of the edges populated, only set the
1337
                // update time if the edge was found in the database.
1338
                if e1 != nil {
6✔
1339
                        upd1Time = e1.LastUpdate
3✔
1340
                }
3✔
1341
                if e2 != nil {
6✔
1342
                        upd2Time = e2.LastUpdate
3✔
1343
                }
3✔
1344

1345
                return nil
3✔
1346
        }, func() {}); err != nil {
3✔
1347
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1348
        }
×
1349

1350
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1351
                upd1Time: upd1Time.Unix(),
3✔
1352
                upd2Time: upd2Time.Unix(),
3✔
1353
                flags:    packRejectFlags(exists, isZombie),
3✔
1354
        })
3✔
1355

3✔
1356
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1357
}
1358

1359
// AddEdgeProof sets the proof of an existing edge in the graph database.
1360
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1361
        proof *models.ChannelAuthProof) error {
3✔
1362

3✔
1363
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1364
        var chanKey [8]byte
3✔
1365
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1366

3✔
1367
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1368
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1369
                if edges == nil {
3✔
1370
                        return ErrEdgeNotFound
×
1371
                }
×
1372

1373
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1374
                if edgeIndex == nil {
3✔
1375
                        return ErrEdgeNotFound
×
1376
                }
×
1377

1378
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1379
                if err != nil {
3✔
1380
                        return err
×
1381
                }
×
1382

1383
                edge.AuthProof = proof
3✔
1384

3✔
1385
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1386
        }, func() {})
3✔
1387
}
1388

1389
const (
1390
        // pruneTipBytes is the total size of the value which stores a prune
1391
        // entry of the graph in the prune log. The "prune tip" is the last
1392
        // entry in the prune log, and indicates if the channel graph is in
1393
        // sync with the current UTXO state. The structure of the value
1394
        // is: blockHash, taking 32 bytes total.
1395
        pruneTipBytes = 32
1396
)
1397

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

3✔
1410
        c.cacheMu.Lock()
3✔
1411
        defer c.cacheMu.Unlock()
3✔
1412

3✔
1413
        var (
3✔
1414
                chansClosed []*models.ChannelEdgeInfo
3✔
1415
                prunedNodes []route.Vertex
3✔
1416
        )
3✔
1417

3✔
1418
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1419
                // First grab the edges bucket which houses the information
3✔
1420
                // we'd like to delete
3✔
1421
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1422
                if err != nil {
3✔
1423
                        return err
×
1424
                }
×
1425

1426
                // Next grab the two edge indexes which will also need to be
1427
                // updated.
1428
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1429
                if err != nil {
3✔
1430
                        return err
×
1431
                }
×
1432
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1433
                        channelPointBucket,
3✔
1434
                )
3✔
1435
                if err != nil {
3✔
1436
                        return err
×
1437
                }
×
1438
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1439
                if nodes == nil {
3✔
1440
                        return ErrSourceNodeNotSet
×
1441
                }
×
1442
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1443
                if err != nil {
3✔
1444
                        return err
×
1445
                }
×
1446

1447
                // For each of the outpoints that have been spent within the
1448
                // block, we attempt to delete them from the graph as if that
1449
                // outpoint was a channel, then it has now been closed.
1450
                for _, chanPoint := range spentOutputs {
6✔
1451
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1452
                        // if NOT if filter
3✔
1453

3✔
1454
                        var opBytes bytes.Buffer
3✔
1455
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1456
                        if err != nil {
3✔
1457
                                return err
×
1458
                        }
×
1459

1460
                        // First attempt to see if the channel exists within
1461
                        // the database, if not, then we can exit early.
1462
                        chanID := chanIndex.Get(opBytes.Bytes())
3✔
1463
                        if chanID == nil {
3✔
UNCOV
1464
                                continue
×
1465
                        }
1466

1467
                        // Attempt to delete the channel, an ErrEdgeNotFound
1468
                        // will be returned if that outpoint isn't known to be
1469
                        // a channel. If no error is returned, then a channel
1470
                        // was successfully pruned.
1471
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1472
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1473
                                chanID, false, false,
3✔
1474
                        )
3✔
1475
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1476
                                return err
×
1477
                        }
×
1478

1479
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1480
                }
1481

1482
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1483
                if err != nil {
3✔
1484
                        return err
×
1485
                }
×
1486

1487
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1488
                        pruneLogBucket,
3✔
1489
                )
3✔
1490
                if err != nil {
3✔
1491
                        return err
×
1492
                }
×
1493

1494
                // With the graph pruned, add a new entry to the prune log,
1495
                // which can be used to check if the graph is fully synced with
1496
                // the current UTXO state.
1497
                var blockHeightBytes [4]byte
3✔
1498
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
3✔
1499

3✔
1500
                var newTip [pruneTipBytes]byte
3✔
1501
                copy(newTip[:], blockHash[:])
3✔
1502

3✔
1503
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1504
                if err != nil {
3✔
1505
                        return err
×
1506
                }
×
1507

1508
                // Now that the graph has been pruned, we'll also attempt to
1509
                // prune any nodes that have had a channel closed within the
1510
                // latest block.
1511
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1512

3✔
1513
                return err
3✔
1514
        }, func() {
3✔
1515
                chansClosed = nil
3✔
1516
                prunedNodes = nil
3✔
1517
        })
3✔
1518
        if err != nil {
3✔
1519
                return nil, nil, err
×
1520
        }
×
1521

1522
        for _, channel := range chansClosed {
6✔
1523
                c.rejectCache.remove(channel.ChannelID)
3✔
1524
                c.chanCache.remove(channel.ChannelID)
3✔
1525
        }
3✔
1526

1527
        return chansClosed, prunedNodes, nil
3✔
1528
}
1529

1530
// PruneGraphNodes is a garbage collection method which attempts to prune out
1531
// any nodes from the channel graph that are currently unconnected. This ensure
1532
// that we only maintain a graph of reachable nodes. In the event that a pruned
1533
// node gains more channels, it will be re-added back to the graph.
1534
func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error) {
3✔
1535
        var prunedNodes []route.Vertex
3✔
1536
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1537
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1538
                if nodes == nil {
3✔
1539
                        return ErrGraphNodesNotFound
×
1540
                }
×
1541
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1542
                if edges == nil {
3✔
1543
                        return ErrGraphNotFound
×
1544
                }
×
1545
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1546
                if edgeIndex == nil {
3✔
1547
                        return ErrGraphNoEdgesFound
×
1548
                }
×
1549

1550
                var err error
3✔
1551
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1552
                if err != nil {
3✔
1553
                        return err
×
1554
                }
×
1555

1556
                return nil
3✔
1557
        }, func() {
3✔
1558
                prunedNodes = nil
3✔
1559
        })
3✔
1560

1561
        return prunedNodes, err
3✔
1562
}
1563

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

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

3✔
1572
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1573
        // even if it no longer has any open channels.
3✔
1574
        sourceNode, err := sourceNodeWithTx(nodes)
3✔
1575
        if err != nil {
3✔
1576
                return nil, err
×
1577
        }
×
1578

1579
        // We'll use this map to keep count the number of references to a node
1580
        // in the graph. A node should only be removed once it has no more
1581
        // references in the graph.
1582
        nodeRefCounts := make(map[[33]byte]int)
3✔
1583
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1584
                // If this is the source key, then we skip this
3✔
1585
                // iteration as the value for this key is a pubKey
3✔
1586
                // rather than raw node information.
3✔
1587
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1588
                        return nil
3✔
1589
                }
3✔
1590

1591
                var nodePub [33]byte
3✔
1592
                copy(nodePub[:], pubKey)
3✔
1593
                nodeRefCounts[nodePub] = 0
3✔
1594

3✔
1595
                return nil
3✔
1596
        })
1597
        if err != nil {
3✔
1598
                return nil, err
×
1599
        }
×
1600

1601
        // To ensure we never delete the source node, we'll start off by
1602
        // bumping its ref count to 1.
1603
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1604

3✔
1605
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1606
        // edge info. We'll use this scan to populate our reference count map
3✔
1607
        // above.
3✔
1608
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
6✔
1609
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1610
                // the nodes that this edge attaches. We'll extract them, and
3✔
1611
                // add them to the ref count map.
3✔
1612
                var node1, node2 [33]byte
3✔
1613
                copy(node1[:], edgeInfoBytes[:33])
3✔
1614
                copy(node2[:], edgeInfoBytes[33:])
3✔
1615

3✔
1616
                // With the nodes extracted, we'll increase the ref count of
3✔
1617
                // each of the nodes.
3✔
1618
                nodeRefCounts[node1]++
3✔
1619
                nodeRefCounts[node2]++
3✔
1620

3✔
1621
                return nil
3✔
1622
        })
3✔
1623
        if err != nil {
3✔
1624
                return nil, err
×
1625
        }
×
1626

1627
        // Finally, we'll make a second pass over the set of nodes, and delete
1628
        // any nodes that have a ref count of zero.
1629
        var pruned []route.Vertex
3✔
1630
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1631
                // If the ref count of the node isn't zero, then we can safely
3✔
1632
                // skip it as it still has edges to or from it within the
3✔
1633
                // graph.
3✔
1634
                if refCount != 0 {
6✔
1635
                        continue
3✔
1636
                }
1637

1638
                // If we reach this point, then there are no longer any edges
1639
                // that connect this node, so we can delete it.
1640
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1641
                if err != nil {
3✔
1642
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1643
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1644

×
1645
                                log.Warnf("Unable to prune node %x from the "+
×
1646
                                        "graph: %v", nodePubKey, err)
×
1647
                                continue
×
1648
                        }
1649

1650
                        return nil, err
×
1651
                }
1652

1653
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1654
                        nodePubKey[:])
3✔
1655

3✔
1656
                pruned = append(pruned, nodePubKey)
3✔
1657
        }
1658

1659
        if len(pruned) > 0 {
6✔
1660
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1661
                        len(pruned))
3✔
1662
        }
3✔
1663

1664
        return pruned, err
3✔
1665
}
1666

1667
// DisconnectBlockAtHeight is used to indicate that the block specified
1668
// by the passed height has been disconnected from the main chain. This
1669
// will "rewind" the graph back to the height below, deleting channels
1670
// that are no longer confirmed from the graph. The prune log will be
1671
// set to the last prune height valid for the remaining chain.
1672
// Channels that were removed from the graph resulting from the
1673
// disconnected block are returned.
1674
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1675
        []*models.ChannelEdgeInfo, error) {
2✔
1676

2✔
1677
        // Every channel having a ShortChannelID starting at 'height'
2✔
1678
        // will no longer be confirmed.
2✔
1679
        startShortChanID := lnwire.ShortChannelID{
2✔
1680
                BlockHeight: height,
2✔
1681
        }
2✔
1682

2✔
1683
        // Delete everything after this height from the db up until the
2✔
1684
        // SCID alias range.
2✔
1685
        endShortChanID := aliasmgr.StartingAlias
2✔
1686

2✔
1687
        // The block height will be the 3 first bytes of the channel IDs.
2✔
1688
        var chanIDStart [8]byte
2✔
1689
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
2✔
1690
        var chanIDEnd [8]byte
2✔
1691
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
2✔
1692

2✔
1693
        c.cacheMu.Lock()
2✔
1694
        defer c.cacheMu.Unlock()
2✔
1695

2✔
1696
        // Keep track of the channels that are removed from the graph.
2✔
1697
        var removedChans []*models.ChannelEdgeInfo
2✔
1698

2✔
1699
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
4✔
1700
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
2✔
1701
                if err != nil {
2✔
1702
                        return err
×
1703
                }
×
1704
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
2✔
1705
                if err != nil {
2✔
1706
                        return err
×
1707
                }
×
1708
                chanIndex, err := edges.CreateBucketIfNotExists(
2✔
1709
                        channelPointBucket,
2✔
1710
                )
2✔
1711
                if err != nil {
2✔
1712
                        return err
×
1713
                }
×
1714
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
2✔
1715
                if err != nil {
2✔
1716
                        return err
×
1717
                }
×
1718

1719
                // Scan from chanIDStart to chanIDEnd, deleting every
1720
                // found edge.
1721
                // NOTE: we must delete the edges after the cursor loop, since
1722
                // modifying the bucket while traversing is not safe.
1723
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1724
                // so that the StartingAlias itself isn't deleted.
1725
                var keys [][]byte
2✔
1726
                cursor := edgeIndex.ReadWriteCursor()
2✔
1727

2✔
1728
                //nolint:ll
2✔
1729
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
2✔
1730
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
4✔
1731
                        keys = append(keys, k)
2✔
1732
                }
2✔
1733

1734
                for _, k := range keys {
4✔
1735
                        edgeInfo, err := c.delChannelEdgeUnsafe(
2✔
1736
                                edges, edgeIndex, chanIndex, zombieIndex,
2✔
1737
                                k, false, false,
2✔
1738
                        )
2✔
1739
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
2✔
1740
                                return err
×
1741
                        }
×
1742

1743
                        removedChans = append(removedChans, edgeInfo)
2✔
1744
                }
1745

1746
                // Delete all the entries in the prune log having a height
1747
                // greater or equal to the block disconnected.
1748
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
2✔
1749
                if err != nil {
2✔
1750
                        return err
×
1751
                }
×
1752

1753
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1754
                        pruneLogBucket,
2✔
1755
                )
2✔
1756
                if err != nil {
2✔
1757
                        return err
×
1758
                }
×
1759

1760
                var pruneKeyStart [4]byte
2✔
1761
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1762

2✔
1763
                var pruneKeyEnd [4]byte
2✔
1764
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1765

2✔
1766
                // To avoid modifying the bucket while traversing, we delete
2✔
1767
                // the keys in a second loop.
2✔
1768
                var pruneKeys [][]byte
2✔
1769
                pruneCursor := pruneBucket.ReadWriteCursor()
2✔
1770
                //nolint:ll
2✔
1771
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
2✔
1772
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
4✔
1773
                        pruneKeys = append(pruneKeys, k)
2✔
1774
                }
2✔
1775

1776
                for _, k := range pruneKeys {
4✔
1777
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1778
                                return err
×
1779
                        }
×
1780
                }
1781

1782
                return nil
2✔
1783
        }, func() {
2✔
1784
                removedChans = nil
2✔
1785
        }); err != nil {
2✔
1786
                return nil, err
×
1787
        }
×
1788

1789
        for _, channel := range removedChans {
4✔
1790
                c.rejectCache.remove(channel.ChannelID)
2✔
1791
                c.chanCache.remove(channel.ChannelID)
2✔
1792
        }
2✔
1793

1794
        return removedChans, nil
2✔
1795
}
1796

1797
// PruneTip returns the block height and hash of the latest block that has been
1798
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1799
// to tell if the graph is currently in sync with the current best known UTXO
1800
// state.
1801
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
3✔
1802
        var (
3✔
1803
                tipHash   chainhash.Hash
3✔
1804
                tipHeight uint32
3✔
1805
        )
3✔
1806

3✔
1807
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1808
                graphMeta := tx.ReadBucket(graphMetaBucket)
3✔
1809
                if graphMeta == nil {
3✔
1810
                        return ErrGraphNotFound
×
1811
                }
×
1812
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
3✔
1813
                if pruneBucket == nil {
3✔
1814
                        return ErrGraphNeverPruned
×
1815
                }
×
1816

1817
                pruneCursor := pruneBucket.ReadCursor()
3✔
1818

3✔
1819
                // The prune key with the largest block height will be our
3✔
1820
                // prune tip.
3✔
1821
                k, v := pruneCursor.Last()
3✔
1822
                if k == nil {
6✔
1823
                        return ErrGraphNeverPruned
3✔
1824
                }
3✔
1825

1826
                // Once we have the prune tip, the value will be the block hash,
1827
                // and the key the block height.
1828
                copy(tipHash[:], v)
3✔
1829
                tipHeight = byteOrder.Uint32(k)
3✔
1830

3✔
1831
                return nil
3✔
1832
        }, func() {})
3✔
1833
        if err != nil {
6✔
1834
                return nil, 0, err
3✔
1835
        }
3✔
1836

1837
        return &tipHash, tipHeight, nil
3✔
1838
}
1839

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

3✔
1851
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1852
        // channels
3✔
1853
        // TODO(roasbeef): don't delete both edges?
3✔
1854

3✔
1855
        c.cacheMu.Lock()
3✔
1856
        defer c.cacheMu.Unlock()
3✔
1857

3✔
1858
        var infos []*models.ChannelEdgeInfo
3✔
1859
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1860
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1861
                if edges == nil {
3✔
1862
                        return ErrEdgeNotFound
×
1863
                }
×
1864
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1865
                if edgeIndex == nil {
3✔
1866
                        return ErrEdgeNotFound
×
1867
                }
×
1868
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
3✔
1869
                if chanIndex == nil {
3✔
1870
                        return ErrEdgeNotFound
×
1871
                }
×
1872
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1873
                if nodes == nil {
3✔
1874
                        return ErrGraphNodeNotFound
×
1875
                }
×
1876
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1877
                if err != nil {
3✔
1878
                        return err
×
1879
                }
×
1880

1881
                var rawChanID [8]byte
3✔
1882
                for _, chanID := range chanIDs {
6✔
1883
                        byteOrder.PutUint64(rawChanID[:], chanID)
3✔
1884
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1885
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1886
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1887
                        )
3✔
1888
                        if err != nil {
3✔
UNCOV
1889
                                return err
×
UNCOV
1890
                        }
×
1891

1892
                        infos = append(infos, edgeInfo)
3✔
1893
                }
1894

1895
                return nil
3✔
1896
        }, func() {
3✔
1897
                infos = nil
3✔
1898
        })
3✔
1899
        if err != nil {
3✔
UNCOV
1900
                return nil, err
×
UNCOV
1901
        }
×
1902

1903
        for _, chanID := range chanIDs {
6✔
1904
                c.rejectCache.remove(chanID)
3✔
1905
                c.chanCache.remove(chanID)
3✔
1906
        }
3✔
1907

1908
        return infos, nil
3✔
1909
}
1910

1911
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1912
// passed channel point (outpoint). If the passed channel doesn't exist within
1913
// the database, then ErrEdgeNotFound is returned.
1914
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1915
        var chanID uint64
3✔
1916
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1917
                var err error
3✔
1918
                chanID, err = getChanID(tx, chanPoint)
3✔
1919
                return err
3✔
1920
        }, func() {
6✔
1921
                chanID = 0
3✔
1922
        }); err != nil {
6✔
1923
                return 0, err
3✔
1924
        }
3✔
1925

1926
        return chanID, nil
3✔
1927
}
1928

1929
// getChanID returns the assigned channel ID for a given channel point.
1930
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1931
        var b bytes.Buffer
3✔
1932
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1933
                return 0, err
×
1934
        }
×
1935

1936
        edges := tx.ReadBucket(edgeBucket)
3✔
1937
        if edges == nil {
3✔
1938
                return 0, ErrGraphNoEdgesFound
×
1939
        }
×
1940
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1941
        if chanIndex == nil {
3✔
1942
                return 0, ErrGraphNoEdgesFound
×
1943
        }
×
1944

1945
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1946
        if chanIDBytes == nil {
6✔
1947
                return 0, ErrEdgeNotFound
3✔
1948
        }
3✔
1949

1950
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1951

3✔
1952
        return chanID, nil
3✔
1953
}
1954

1955
// TODO(roasbeef): allow updates to use Batch?
1956

1957
// HighestChanID returns the "highest" known channel ID in the channel graph.
1958
// This represents the "newest" channel from the PoV of the chain. This method
1959
// can be used by peers to quickly determine if they're graphs are in sync.
1960
func (c *KVStore) HighestChanID(_ context.Context) (uint64, error) {
3✔
1961
        var cid uint64
3✔
1962

3✔
1963
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1964
                edges := tx.ReadBucket(edgeBucket)
3✔
1965
                if edges == nil {
3✔
1966
                        return ErrGraphNoEdgesFound
×
1967
                }
×
1968
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1969
                if edgeIndex == nil {
3✔
1970
                        return ErrGraphNoEdgesFound
×
1971
                }
×
1972

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

3✔
1977
                lastChanID, _ := cidCursor.Last()
3✔
1978

3✔
1979
                // If there's no key, then this means that we don't actually
3✔
1980
                // know of any channels, so we'll return a predicable error.
3✔
1981
                if lastChanID == nil {
6✔
1982
                        return ErrGraphNoEdgesFound
3✔
1983
                }
3✔
1984

1985
                // Otherwise, we'll de serialize the channel ID and return it
1986
                // to the caller.
1987
                cid = byteOrder.Uint64(lastChanID)
3✔
1988

3✔
1989
                return nil
3✔
1990
        }, func() {
3✔
1991
                cid = 0
3✔
1992
        })
3✔
1993
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
3✔
1994
                return 0, err
×
1995
        }
×
1996

1997
        return cid, nil
3✔
1998
}
1999

2000
// ChannelEdge represents the complete set of information for a channel edge in
2001
// the known channel graph. This struct couples the core information of the
2002
// edge as well as each of the known advertised edge policies.
2003
type ChannelEdge struct {
2004
        // Info contains all the static information describing the channel.
2005
        Info *models.ChannelEdgeInfo
2006

2007
        // Policy1 points to the "first" edge policy of the channel containing
2008
        // the dynamic information required to properly route through the edge.
2009
        Policy1 *models.ChannelEdgePolicy
2010

2011
        // Policy2 points to the "second" edge policy of the channel containing
2012
        // the dynamic information required to properly route through the edge.
2013
        Policy2 *models.ChannelEdgePolicy
2014

2015
        // Node1 is "node 1" in the channel. This is the node that would have
2016
        // produced Policy1 if it exists.
2017
        Node1 *models.LightningNode
2018

2019
        // Node2 is "node 2" in the channel. This is the node that would have
2020
        // produced Policy2 if it exists.
2021
        Node2 *models.LightningNode
2022
}
2023

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

3✔
2029
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
2030
        // additional map to keep track of the edges already seen to prevent
3✔
2031
        // re-adding it.
3✔
2032
        var edgesSeen map[uint64]struct{}
3✔
2033
        var edgesToCache map[uint64]ChannelEdge
3✔
2034
        var edgesInHorizon []ChannelEdge
3✔
2035

3✔
2036
        c.cacheMu.Lock()
3✔
2037
        defer c.cacheMu.Unlock()
3✔
2038

3✔
2039
        var hits int
3✔
2040
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2041
                edges := tx.ReadBucket(edgeBucket)
3✔
2042
                if edges == nil {
3✔
2043
                        return ErrGraphNoEdgesFound
×
2044
                }
×
2045
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2046
                if edgeIndex == nil {
3✔
2047
                        return ErrGraphNoEdgesFound
×
2048
                }
×
2049
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
3✔
2050
                if edgeUpdateIndex == nil {
3✔
2051
                        return ErrGraphNoEdgesFound
×
2052
                }
×
2053

2054
                nodes := tx.ReadBucket(nodeBucket)
3✔
2055
                if nodes == nil {
3✔
2056
                        return ErrGraphNodesNotFound
×
2057
                }
×
2058

2059
                // We'll now obtain a cursor to perform a range query within
2060
                // the index to find all channels within the horizon.
2061
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
2062

3✔
2063
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
2064
                byteOrder.PutUint64(
3✔
2065
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2066
                )
3✔
2067
                byteOrder.PutUint64(
3✔
2068
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2069
                )
3✔
2070

3✔
2071
                // With our start and end times constructed, we'll step through
3✔
2072
                // the index collecting the info and policy of each update of
3✔
2073
                // each channel that has a last update within the time range.
3✔
2074
                //
3✔
2075
                //nolint:ll
3✔
2076
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2077
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2078
                        // We have a new eligible entry, so we'll slice of the
3✔
2079
                        // chan ID so we can query it in the DB.
3✔
2080
                        chanID := indexKey[8:]
3✔
2081

3✔
2082
                        // If we've already retrieved the info and policies for
3✔
2083
                        // this edge, then we can skip it as we don't need to do
3✔
2084
                        // so again.
3✔
2085
                        chanIDInt := byteOrder.Uint64(chanID)
3✔
2086
                        if _, ok := edgesSeen[chanIDInt]; ok {
3✔
UNCOV
2087
                                continue
×
2088
                        }
2089

2090
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
2091
                                hits++
3✔
2092
                                edgesSeen[chanIDInt] = struct{}{}
3✔
2093
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
2094

3✔
2095
                                continue
3✔
2096
                        }
2097

2098
                        // First, we'll fetch the static edge information.
2099
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2100
                        if err != nil {
3✔
2101
                                chanID := byteOrder.Uint64(chanID)
×
2102
                                return fmt.Errorf("unable to fetch info for "+
×
2103
                                        "edge with chan_id=%v: %v", chanID, err)
×
2104
                        }
×
2105

2106
                        // With the static information obtained, we'll now
2107
                        // fetch the dynamic policy info.
2108
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2109
                                edgeIndex, edges, chanID,
3✔
2110
                        )
3✔
2111
                        if err != nil {
3✔
2112
                                chanID := byteOrder.Uint64(chanID)
×
2113
                                return fmt.Errorf("unable to fetch policies "+
×
2114
                                        "for edge with chan_id=%v: %v", chanID,
×
2115
                                        err)
×
2116
                        }
×
2117

2118
                        node1, err := fetchLightningNode(
3✔
2119
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2120
                        )
3✔
2121
                        if err != nil {
3✔
2122
                                return err
×
2123
                        }
×
2124

2125
                        node2, err := fetchLightningNode(
3✔
2126
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2127
                        )
3✔
2128
                        if err != nil {
3✔
2129
                                return err
×
2130
                        }
×
2131

2132
                        // Finally, we'll collate this edge with the rest of
2133
                        // edges to be returned.
2134
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2135
                        channel := ChannelEdge{
3✔
2136
                                Info:    &edgeInfo,
3✔
2137
                                Policy1: edge1,
3✔
2138
                                Policy2: edge2,
3✔
2139
                                Node1:   &node1,
3✔
2140
                                Node2:   &node2,
3✔
2141
                        }
3✔
2142
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2143
                        edgesToCache[chanIDInt] = channel
3✔
2144
                }
2145

2146
                return nil
3✔
2147
        }, func() {
3✔
2148
                edgesSeen = make(map[uint64]struct{})
3✔
2149
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2150
                edgesInHorizon = nil
3✔
2151
        })
3✔
2152
        switch {
3✔
2153
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2154
                fallthrough
×
2155
        case errors.Is(err, ErrGraphNodesNotFound):
×
2156
                break
×
2157

2158
        case err != nil:
×
2159
                return nil, err
×
2160
        }
2161

2162
        // Insert any edges loaded from disk into the cache.
2163
        for chanid, channel := range edgesToCache {
6✔
2164
                c.chanCache.insert(chanid, channel)
3✔
2165
        }
3✔
2166

2167
        if len(edgesInHorizon) > 0 {
6✔
2168
                log.Debugf("ChanUpdatesInHorizon hit percentage: %.2f (%d/%d)",
3✔
2169
                        float64(hits)*100/float64(len(edgesInHorizon)), hits,
3✔
2170
                        len(edgesInHorizon))
3✔
2171
        } else {
6✔
2172
                log.Debugf("ChanUpdatesInHorizon returned no edges in "+
3✔
2173
                        "horizon (%s, %s)", startTime, endTime)
3✔
2174
        }
3✔
2175

2176
        return edgesInHorizon, nil
3✔
2177
}
2178

2179
// NodeUpdatesInHorizon returns all the known lightning node which have an
2180
// update timestamp within the passed range. This method can be used by two
2181
// nodes to quickly determine if they have the same set of up to date node
2182
// announcements.
2183
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2184
        endTime time.Time) ([]models.LightningNode, error) {
3✔
2185

3✔
2186
        var nodesInHorizon []models.LightningNode
3✔
2187

3✔
2188
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2189
                nodes := tx.ReadBucket(nodeBucket)
3✔
2190
                if nodes == nil {
3✔
2191
                        return ErrGraphNodesNotFound
×
2192
                }
×
2193

2194
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2195
                if nodeUpdateIndex == nil {
3✔
2196
                        return ErrGraphNodesNotFound
×
2197
                }
×
2198

2199
                // We'll now obtain a cursor to perform a range query within
2200
                // the index to find all node announcements within the horizon.
2201
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2202

3✔
2203
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2204
                byteOrder.PutUint64(
3✔
2205
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2206
                )
3✔
2207
                byteOrder.PutUint64(
3✔
2208
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2209
                )
3✔
2210

3✔
2211
                // With our start and end times constructed, we'll step through
3✔
2212
                // the index collecting info for each node within the time
3✔
2213
                // range.
3✔
2214
                //
3✔
2215
                //nolint:ll
3✔
2216
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2217
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2218
                        nodePub := indexKey[8:]
3✔
2219
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2220
                        if err != nil {
3✔
2221
                                return err
×
2222
                        }
×
2223

2224
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2225
                }
2226

2227
                return nil
3✔
2228
        }, func() {
3✔
2229
                nodesInHorizon = nil
3✔
2230
        })
3✔
2231
        switch {
3✔
2232
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2233
                fallthrough
×
2234
        case errors.Is(err, ErrGraphNodesNotFound):
×
2235
                break
×
2236

2237
        case err != nil:
×
2238
                return nil, err
×
2239
        }
2240

2241
        return nodesInHorizon, nil
3✔
2242
}
2243

2244
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2245
// ID's that we don't know and are not known zombies of the passed set. In other
2246
// words, we perform a set difference of our set of chan ID's and the ones
2247
// passed in. This method can be used by callers to determine the set of
2248
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2249
// known zombies is also returned.
2250
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2251
        []ChannelUpdateInfo, error) {
3✔
2252

3✔
2253
        var (
3✔
2254
                newChanIDs   []uint64
3✔
2255
                knownZombies []ChannelUpdateInfo
3✔
2256
        )
3✔
2257

3✔
2258
        c.cacheMu.Lock()
3✔
2259
        defer c.cacheMu.Unlock()
3✔
2260

3✔
2261
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2262
                edges := tx.ReadBucket(edgeBucket)
3✔
2263
                if edges == nil {
3✔
2264
                        return ErrGraphNoEdgesFound
×
2265
                }
×
2266
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2267
                if edgeIndex == nil {
3✔
2268
                        return ErrGraphNoEdgesFound
×
2269
                }
×
2270

2271
                // Fetch the zombie index, it may not exist if no edges have
2272
                // ever been marked as zombies. If the index has been
2273
                // initialized, we will use it later to skip known zombie edges.
2274
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2275

3✔
2276
                // We'll run through the set of chanIDs and collate only the
3✔
2277
                // set of channel that are unable to be found within our db.
3✔
2278
                var cidBytes [8]byte
3✔
2279
                for _, info := range chansInfo {
6✔
2280
                        scid := info.ShortChannelID.ToUint64()
3✔
2281
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2282

3✔
2283
                        // If the edge is already known, skip it.
3✔
2284
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
6✔
2285
                                continue
3✔
2286
                        }
2287

2288
                        // If the edge is a known zombie, skip it.
2289
                        if zombieIndex != nil {
6✔
2290
                                isZombie, _, _ := isZombieEdge(
3✔
2291
                                        zombieIndex, scid,
3✔
2292
                                )
3✔
2293

3✔
2294
                                if isZombie {
3✔
UNCOV
2295
                                        knownZombies = append(
×
UNCOV
2296
                                                knownZombies, info,
×
UNCOV
2297
                                        )
×
UNCOV
2298

×
UNCOV
2299
                                        continue
×
2300
                                }
2301
                        }
2302

2303
                        newChanIDs = append(newChanIDs, scid)
3✔
2304
                }
2305

2306
                return nil
3✔
2307
        }, func() {
3✔
2308
                newChanIDs = nil
3✔
2309
                knownZombies = nil
3✔
2310
        })
3✔
2311
        switch {
3✔
2312
        // If we don't know of any edges yet, then we'll return the entire set
2313
        // of chan IDs specified.
2314
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2315
                ogChanIDs := make([]uint64, len(chansInfo))
×
2316
                for i, info := range chansInfo {
×
2317
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2318
                }
×
2319

2320
                return ogChanIDs, nil, nil
×
2321

2322
        case err != nil:
×
2323
                return nil, nil, err
×
2324
        }
2325

2326
        return newChanIDs, knownZombies, nil
3✔
2327
}
2328

2329
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2330
// latest received channel updates for the channel.
2331
type ChannelUpdateInfo struct {
2332
        // ShortChannelID is the SCID identifier of the channel.
2333
        ShortChannelID lnwire.ShortChannelID
2334

2335
        // Node1UpdateTimestamp is the timestamp of the latest received update
2336
        // from the node 1 channel peer. This will be set to zero time if no
2337
        // update has yet been received from this node.
2338
        Node1UpdateTimestamp time.Time
2339

2340
        // Node2UpdateTimestamp is the timestamp of the latest received update
2341
        // from the node 2 channel peer. This will be set to zero time if no
2342
        // update has yet been received from this node.
2343
        Node2UpdateTimestamp time.Time
2344
}
2345

2346
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2347
// timestamps with zero seconds unix timestamp which equals
2348
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2349
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2350
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2351

3✔
2352
        chanInfo := ChannelUpdateInfo{
3✔
2353
                ShortChannelID:       scid,
3✔
2354
                Node1UpdateTimestamp: node1Timestamp,
3✔
2355
                Node2UpdateTimestamp: node2Timestamp,
3✔
2356
        }
3✔
2357

3✔
2358
        if node1Timestamp.IsZero() {
6✔
2359
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2360
        }
3✔
2361

2362
        if node2Timestamp.IsZero() {
6✔
2363
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2364
        }
3✔
2365

2366
        return chanInfo
3✔
2367
}
2368

2369
// BlockChannelRange represents a range of channels for a given block height.
2370
type BlockChannelRange struct {
2371
        // Height is the height of the block all of the channels below were
2372
        // included in.
2373
        Height uint32
2374

2375
        // Channels is the list of channels identified by their short ID
2376
        // representation known to us that were included in the block height
2377
        // above. The list may include channel update timestamp information if
2378
        // requested.
2379
        Channels []ChannelUpdateInfo
2380
}
2381

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

3✔
2392
        startChanID := &lnwire.ShortChannelID{
3✔
2393
                BlockHeight: startHeight,
3✔
2394
        }
3✔
2395

3✔
2396
        endChanID := lnwire.ShortChannelID{
3✔
2397
                BlockHeight: endHeight,
3✔
2398
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2399
                TxPosition:  math.MaxUint16,
3✔
2400
        }
3✔
2401

3✔
2402
        // As we need to perform a range scan, we'll convert the starting and
3✔
2403
        // ending height to their corresponding values when encoded using short
3✔
2404
        // channel ID's.
3✔
2405
        var chanIDStart, chanIDEnd [8]byte
3✔
2406
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
3✔
2407
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
3✔
2408

3✔
2409
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
3✔
2410
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2411
                edges := tx.ReadBucket(edgeBucket)
3✔
2412
                if edges == nil {
3✔
2413
                        return ErrGraphNoEdgesFound
×
2414
                }
×
2415
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2416
                if edgeIndex == nil {
3✔
2417
                        return ErrGraphNoEdgesFound
×
2418
                }
×
2419

2420
                cursor := edgeIndex.ReadCursor()
3✔
2421

3✔
2422
                // We'll now iterate through the database, and find each
3✔
2423
                // channel ID that resides within the specified range.
3✔
2424
                //
3✔
2425
                //nolint:ll
3✔
2426
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
2427
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
6✔
2428
                        // Don't send alias SCIDs during gossip sync.
3✔
2429
                        edgeReader := bytes.NewReader(v)
3✔
2430
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
3✔
2431
                        if err != nil {
3✔
2432
                                return err
×
2433
                        }
×
2434

2435
                        if edgeInfo.AuthProof == nil {
6✔
2436
                                continue
3✔
2437
                        }
2438

2439
                        // This channel ID rests within the target range, so
2440
                        // we'll add it to our returned set.
2441
                        rawCid := byteOrder.Uint64(k)
3✔
2442
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2443

3✔
2444
                        chanInfo := NewChannelUpdateInfo(
3✔
2445
                                cid, time.Time{}, time.Time{},
3✔
2446
                        )
3✔
2447

3✔
2448
                        if !withTimestamps {
3✔
UNCOV
2449
                                channelsPerBlock[cid.BlockHeight] = append(
×
UNCOV
2450
                                        channelsPerBlock[cid.BlockHeight],
×
UNCOV
2451
                                        chanInfo,
×
UNCOV
2452
                                )
×
UNCOV
2453

×
UNCOV
2454
                                continue
×
2455
                        }
2456

2457
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2458

3✔
2459
                        rawPolicy := edges.Get(node1Key)
3✔
2460
                        if len(rawPolicy) != 0 {
6✔
2461
                                r := bytes.NewReader(rawPolicy)
3✔
2462

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

×
2468
                                        return err
×
2469
                                }
×
2470

2471
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2472
                        }
2473

2474
                        rawPolicy = edges.Get(node2Key)
3✔
2475
                        if len(rawPolicy) != 0 {
6✔
2476
                                r := bytes.NewReader(rawPolicy)
3✔
2477

3✔
2478
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2479
                                if err != nil && !errors.Is(
3✔
2480
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2481
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2482

×
2483
                                        return err
×
2484
                                }
×
2485

2486
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2487
                        }
2488

2489
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2490
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2491
                        )
3✔
2492
                }
2493

2494
                return nil
3✔
2495
        }, func() {
3✔
2496
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2497
        })
3✔
2498

2499
        switch {
3✔
2500
        // If we don't know of any channels yet, then there's nothing to
2501
        // filter, so we'll return an empty slice.
2502
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
3✔
2503
                return nil, nil
3✔
2504

2505
        case err != nil:
×
2506
                return nil, err
×
2507
        }
2508

2509
        // Return the channel ranges in ascending block height order.
2510
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2511
        for block := range channelsPerBlock {
6✔
2512
                blocks = append(blocks, block)
3✔
2513
        }
3✔
2514
        sort.Slice(blocks, func(i, j int) bool {
6✔
2515
                return blocks[i] < blocks[j]
3✔
2516
        })
3✔
2517

2518
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2519
        for _, block := range blocks {
6✔
2520
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2521
                        Height:   block,
3✔
2522
                        Channels: channelsPerBlock[block],
3✔
2523
                })
3✔
2524
        }
3✔
2525

2526
        return channelRanges, nil
3✔
2527
}
2528

2529
// FetchChanInfos returns the set of channel edges that correspond to the passed
2530
// channel ID's. If an edge is the query is unknown to the database, it will
2531
// skipped and the result will contain only those edges that exist at the time
2532
// of the query. This can be used to respond to peer queries that are seeking to
2533
// fill in gaps in their view of the channel graph.
2534
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
2535
        return c.fetchChanInfos(nil, chanIDs)
3✔
2536
}
3✔
2537

2538
// fetchChanInfos returns the set of channel edges that correspond to the passed
2539
// channel ID's. If an edge is the query is unknown to the database, it will
2540
// skipped and the result will contain only those edges that exist at the time
2541
// of the query. This can be used to respond to peer queries that are seeking to
2542
// fill in gaps in their view of the channel graph.
2543
//
2544
// NOTE: An optional transaction may be provided. If none is provided, then a
2545
// new one will be created.
2546
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2547
        []ChannelEdge, error) {
3✔
2548
        // TODO(roasbeef): sort cids?
3✔
2549

3✔
2550
        var (
3✔
2551
                chanEdges []ChannelEdge
3✔
2552
                cidBytes  [8]byte
3✔
2553
        )
3✔
2554

3✔
2555
        fetchChanInfos := func(tx kvdb.RTx) error {
6✔
2556
                edges := tx.ReadBucket(edgeBucket)
3✔
2557
                if edges == nil {
3✔
2558
                        return ErrGraphNoEdgesFound
×
2559
                }
×
2560
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2561
                if edgeIndex == nil {
3✔
2562
                        return ErrGraphNoEdgesFound
×
2563
                }
×
2564
                nodes := tx.ReadBucket(nodeBucket)
3✔
2565
                if nodes == nil {
3✔
2566
                        return ErrGraphNotFound
×
2567
                }
×
2568

2569
                for _, cid := range chanIDs {
6✔
2570
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2571

3✔
2572
                        // First, we'll fetch the static edge information. If
3✔
2573
                        // the edge is unknown, we will skip the edge and
3✔
2574
                        // continue gathering all known edges.
3✔
2575
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2576
                                edgeIndex, cidBytes[:],
3✔
2577
                        )
3✔
2578
                        switch {
3✔
UNCOV
2579
                        case errors.Is(err, ErrEdgeNotFound):
×
UNCOV
2580
                                continue
×
2581
                        case err != nil:
×
2582
                                return err
×
2583
                        }
2584

2585
                        // With the static information obtained, we'll now
2586
                        // fetch the dynamic policy info.
2587
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2588
                                edgeIndex, edges, cidBytes[:],
3✔
2589
                        )
3✔
2590
                        if err != nil {
3✔
2591
                                return err
×
2592
                        }
×
2593

2594
                        node1, err := fetchLightningNode(
3✔
2595
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2596
                        )
3✔
2597
                        if err != nil {
3✔
2598
                                return err
×
2599
                        }
×
2600

2601
                        node2, err := fetchLightningNode(
3✔
2602
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2603
                        )
3✔
2604
                        if err != nil {
3✔
2605
                                return err
×
2606
                        }
×
2607

2608
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2609
                                Info:    &edgeInfo,
3✔
2610
                                Policy1: edge1,
3✔
2611
                                Policy2: edge2,
3✔
2612
                                Node1:   &node1,
3✔
2613
                                Node2:   &node2,
3✔
2614
                        })
3✔
2615
                }
2616

2617
                return nil
3✔
2618
        }
2619

2620
        if tx == nil {
6✔
2621
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2622
                        chanEdges = nil
3✔
2623
                })
3✔
2624
                if err != nil {
3✔
2625
                        return nil, err
×
2626
                }
×
2627

2628
                return chanEdges, nil
3✔
2629
        }
2630

2631
        err := fetchChanInfos(tx)
×
2632
        if err != nil {
×
2633
                return nil, err
×
2634
        }
×
2635

2636
        return chanEdges, nil
×
2637
}
2638

2639
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2640
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2641

3✔
2642
        // First, we'll fetch the edge update index bucket which currently
3✔
2643
        // stores an entry for the channel we're about to delete.
3✔
2644
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2645
        if updateIndex == nil {
3✔
2646
                // No edges in bucket, return early.
×
2647
                return nil
×
2648
        }
×
2649

2650
        // Now that we have the bucket, we'll attempt to construct a template
2651
        // for the index key: updateTime || chanid.
2652
        var indexKey [8 + 8]byte
3✔
2653
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2654

3✔
2655
        // With the template constructed, we'll attempt to delete an entry that
3✔
2656
        // would have been created by both edges: we'll alternate the update
3✔
2657
        // times, as one may had overridden the other.
3✔
2658
        if edge1 != nil {
6✔
2659
                byteOrder.PutUint64(
3✔
2660
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
3✔
2661
                )
3✔
2662
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2663
                        return err
×
2664
                }
×
2665
        }
2666

2667
        // We'll also attempt to delete the entry that may have been created by
2668
        // the second edge.
2669
        if edge2 != nil {
6✔
2670
                byteOrder.PutUint64(
3✔
2671
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2672
                )
3✔
2673
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2674
                        return err
×
2675
                }
×
2676
        }
2677

2678
        return nil
3✔
2679
}
2680

2681
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2682
// cache. It then goes on to delete any policy info and edge info for this
2683
// channel from the DB and finally, if isZombie is true, it will add an entry
2684
// for this channel in the zombie index.
2685
//
2686
// NOTE: this method MUST only be called if the cacheMu has already been
2687
// acquired.
2688
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2689
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2690
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
3✔
2691

3✔
2692
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2693
        if err != nil {
3✔
UNCOV
2694
                return nil, err
×
UNCOV
2695
        }
×
2696

2697
        // We'll also remove the entry in the edge update index bucket before
2698
        // we delete the edges themselves so we can access their last update
2699
        // times.
2700
        cid := byteOrder.Uint64(chanID)
3✔
2701
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2702
        if err != nil {
3✔
2703
                return nil, err
×
2704
        }
×
2705
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2706
        if err != nil {
3✔
2707
                return nil, err
×
2708
        }
×
2709

2710
        // The edge key is of the format pubKey || chanID. First we construct
2711
        // the latter half, populating the channel ID.
2712
        var edgeKey [33 + 8]byte
3✔
2713
        copy(edgeKey[33:], chanID)
3✔
2714

3✔
2715
        // With the latter half constructed, copy over the first public key to
3✔
2716
        // delete the edge in this direction, then the second to delete the
3✔
2717
        // edge in the opposite direction.
3✔
2718
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2719
        if edges.Get(edgeKey[:]) != nil {
6✔
2720
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2721
                        return nil, err
×
2722
                }
×
2723
        }
2724
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2725
        if edges.Get(edgeKey[:]) != nil {
6✔
2726
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2727
                        return nil, err
×
2728
                }
×
2729
        }
2730

2731
        // As part of deleting the edge we also remove all disabled entries
2732
        // from the edgePolicyDisabledIndex bucket. We do that for both
2733
        // directions.
2734
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
3✔
2735
        if err != nil {
3✔
2736
                return nil, err
×
2737
        }
×
2738
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2739
        if err != nil {
3✔
2740
                return nil, err
×
2741
        }
×
2742

2743
        // With the edge data deleted, we can purge the information from the two
2744
        // edge indexes.
2745
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2746
                return nil, err
×
2747
        }
×
2748
        var b bytes.Buffer
3✔
2749
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2750
                return nil, err
×
2751
        }
×
2752
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
2753
                return nil, err
×
2754
        }
×
2755

2756
        // Finally, we'll mark the edge as a zombie within our index if it's
2757
        // being removed due to the channel becoming a zombie. We do this to
2758
        // ensure we don't store unnecessary data for spent channels.
2759
        if !isZombie {
6✔
2760
                return &edgeInfo, nil
3✔
2761
        }
3✔
2762

2763
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2764
        if strictZombie {
3✔
UNCOV
2765
                var e1UpdateTime, e2UpdateTime *time.Time
×
UNCOV
2766
                if edge1 != nil {
×
UNCOV
2767
                        e1UpdateTime = &edge1.LastUpdate
×
UNCOV
2768
                }
×
UNCOV
2769
                if edge2 != nil {
×
UNCOV
2770
                        e2UpdateTime = &edge2.LastUpdate
×
UNCOV
2771
                }
×
2772

UNCOV
2773
                nodeKey1, nodeKey2 = makeZombiePubkeys(
×
UNCOV
2774
                        &edgeInfo, e1UpdateTime, e2UpdateTime,
×
UNCOV
2775
                )
×
2776
        }
2777

2778
        return &edgeInfo, markEdgeZombie(
3✔
2779
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2780
        )
3✔
2781
}
2782

2783
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2784
// particular pair of channel policies. The return values are one of:
2785
//  1. (pubkey1, pubkey2)
2786
//  2. (pubkey1, blank)
2787
//  3. (blank, pubkey2)
2788
//
2789
// A blank pubkey means that corresponding node will be unable to resurrect a
2790
// channel on its own. For example, node1 may continue to publish recent
2791
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2792
// we don't want another fresh update from node1 to resurrect, as the edge can
2793
// only become live once node2 finally sends something recent.
2794
//
2795
// In the case where we have neither update, we allow either party to resurrect
2796
// the channel. If the channel were to be marked zombie again, it would be
2797
// marked with the correct lagging channel since we received an update from only
2798
// one side.
2799
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
UNCOV
2800
        e1, e2 *time.Time) ([33]byte, [33]byte) {
×
UNCOV
2801

×
UNCOV
2802
        switch {
×
2803
        // If we don't have either edge policy, we'll return both pubkeys so
2804
        // that the channel can be resurrected by either party.
2805
        case e1 == nil && e2 == nil:
×
2806
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2807

2808
        // If we're missing edge1, or if both edges are present but edge1 is
2809
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2810
        // means that only an update from edge1 will be able to resurrect the
2811
        // channel.
UNCOV
2812
        case e1 == nil || (e2 != nil && e1.Before(*e2)):
×
UNCOV
2813
                return info.NodeKey1Bytes, [33]byte{}
×
2814

2815
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2816
        // return a blank pubkey for edge1. In this case, only an update from
2817
        // edge2 can resurect the channel.
UNCOV
2818
        default:
×
UNCOV
2819
                return [33]byte{}, info.NodeKey2Bytes
×
2820
        }
2821
}
2822

2823
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2824
// within the database for the referenced channel. The `flags` attribute within
2825
// the ChannelEdgePolicy determines which of the directed edges are being
2826
// updated. If the flag is 1, then the first node's information is being
2827
// updated, otherwise it's the second node's information. The node ordering is
2828
// determined by the lexicographical ordering of the identity public keys of the
2829
// nodes on either side of the channel.
2830
func (c *KVStore) UpdateEdgePolicy(ctx context.Context,
2831
        edge *models.ChannelEdgePolicy,
2832
        opts ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
3✔
2833

3✔
2834
        var (
3✔
2835
                isUpdate1    bool
3✔
2836
                edgeNotFound bool
3✔
2837
                from, to     route.Vertex
3✔
2838
        )
3✔
2839

3✔
2840
        r := &batch.Request[kvdb.RwTx]{
3✔
2841
                Opts: batch.NewSchedulerOptions(opts...),
3✔
2842
                Reset: func() {
6✔
2843
                        isUpdate1 = false
3✔
2844
                        edgeNotFound = false
3✔
2845
                },
3✔
2846
                Do: func(tx kvdb.RwTx) error {
3✔
2847
                        var err error
3✔
2848
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
3✔
2849
                        if err != nil {
3✔
UNCOV
2850
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
×
UNCOV
2851
                        }
×
2852

2853
                        // Silence ErrEdgeNotFound so that the batch can
2854
                        // succeed, but propagate the error via local state.
2855
                        if errors.Is(err, ErrEdgeNotFound) {
3✔
UNCOV
2856
                                edgeNotFound = true
×
UNCOV
2857
                                return nil
×
UNCOV
2858
                        }
×
2859

2860
                        return err
3✔
2861
                },
2862
                OnCommit: func(err error) error {
3✔
2863
                        switch {
3✔
UNCOV
2864
                        case err != nil:
×
UNCOV
2865
                                return err
×
UNCOV
2866
                        case edgeNotFound:
×
UNCOV
2867
                                return ErrEdgeNotFound
×
2868
                        default:
3✔
2869
                                c.updateEdgeCache(edge, isUpdate1)
3✔
2870
                                return nil
3✔
2871
                        }
2872
                },
2873
        }
2874

2875
        err := c.chanScheduler.Execute(ctx, r)
3✔
2876

3✔
2877
        return from, to, err
3✔
2878
}
2879

2880
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2881
        isUpdate1 bool) {
3✔
2882

3✔
2883
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2884
        // the entry with the updated timestamp for the direction that was just
3✔
2885
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2886
        // during the next query for this edge.
3✔
2887
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2888
                if isUpdate1 {
6✔
2889
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2890
                } else {
6✔
2891
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2892
                }
3✔
2893
                c.rejectCache.insert(e.ChannelID, entry)
3✔
2894
        }
2895

2896
        // If an entry for this channel is found in channel cache, we'll modify
2897
        // the entry with the updated policy for the direction that was just
2898
        // written. If the edge doesn't exist, we'll defer loading the info and
2899
        // policies and lazily read from disk during the next query.
2900
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
6✔
2901
                if isUpdate1 {
6✔
2902
                        channel.Policy1 = e
3✔
2903
                } else {
6✔
2904
                        channel.Policy2 = e
3✔
2905
                }
3✔
2906
                c.chanCache.insert(e.ChannelID, channel)
3✔
2907
        }
2908
}
2909

2910
// updateEdgePolicy attempts to update an edge's policy within the relevant
2911
// buckets using an existing database transaction. The returned boolean will be
2912
// true if the updated policy belongs to node1, and false if the policy belonged
2913
// to node2.
2914
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2915
        route.Vertex, route.Vertex, bool, error) {
3✔
2916

3✔
2917
        var noVertex route.Vertex
3✔
2918

3✔
2919
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2920
        if edges == nil {
3✔
2921
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2922
        }
×
2923
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2924
        if edgeIndex == nil {
3✔
2925
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2926
        }
×
2927

2928
        // Create the channelID key be converting the channel ID
2929
        // integer into a byte slice.
2930
        var chanID [8]byte
3✔
2931
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2932

3✔
2933
        // With the channel ID, we then fetch the value storing the two
3✔
2934
        // nodes which connect this channel edge.
3✔
2935
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2936
        if nodeInfo == nil {
3✔
UNCOV
2937
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2938
        }
×
2939

2940
        // Depending on the flags value passed above, either the first
2941
        // or second edge policy is being updated.
2942
        var fromNode, toNode []byte
3✔
2943
        var isUpdate1 bool
3✔
2944
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2945
                fromNode = nodeInfo[:33]
3✔
2946
                toNode = nodeInfo[33:66]
3✔
2947
                isUpdate1 = true
3✔
2948
        } else {
6✔
2949
                fromNode = nodeInfo[33:66]
3✔
2950
                toNode = nodeInfo[:33]
3✔
2951
                isUpdate1 = false
3✔
2952
        }
3✔
2953

2954
        // Finally, with the direction of the edge being updated
2955
        // identified, we update the on-disk edge representation.
2956
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
3✔
2957
        if err != nil {
3✔
UNCOV
2958
                return noVertex, noVertex, false, err
×
UNCOV
2959
        }
×
2960

2961
        var (
3✔
2962
                fromNodePubKey route.Vertex
3✔
2963
                toNodePubKey   route.Vertex
3✔
2964
        )
3✔
2965
        copy(fromNodePubKey[:], fromNode)
3✔
2966
        copy(toNodePubKey[:], toNode)
3✔
2967

3✔
2968
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
3✔
2969
}
2970

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

3✔
2977
        // In order to determine whether this node is publicly advertised within
3✔
2978
        // the graph, we'll need to look at all of its edges and check whether
3✔
2979
        // they extend to any other node than the source node. errDone will be
3✔
2980
        // used to terminate the check early.
3✔
2981
        nodeIsPublic := false
3✔
2982
        errDone := errors.New("done")
3✔
2983
        err := c.forEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
3✔
2984
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
3✔
2985
                _ *models.ChannelEdgePolicy) error {
6✔
2986

3✔
2987
                // If this edge doesn't extend to the source node, we'll
3✔
2988
                // terminate our search as we can now conclude that the node is
3✔
2989
                // publicly advertised within the graph due to the local node
3✔
2990
                // knowing of the current edge.
3✔
2991
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
3✔
2992
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
6✔
2993

3✔
2994
                        nodeIsPublic = true
3✔
2995
                        return errDone
3✔
2996
                }
3✔
2997

2998
                // Since the edge _does_ extend to the source node, we'll also
2999
                // need to ensure that this is a public edge.
3000
                if info.AuthProof != nil {
6✔
3001
                        nodeIsPublic = true
3✔
3002
                        return errDone
3✔
3003
                }
3✔
3004

3005
                // Otherwise, we'll continue our search.
3006
                return nil
3✔
3007
        })
3008
        if err != nil && !errors.Is(err, errDone) {
3✔
3009
                return false, err
×
3010
        }
×
3011

3012
        return nodeIsPublic, nil
3✔
3013
}
3014

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

3✔
3022
        return c.fetchLightningNode(tx, nodePub)
3✔
3023
}
3✔
3024

3025
// FetchLightningNode attempts to look up a target node by its identity public
3026
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3027
// returned.
3028
func (c *KVStore) FetchLightningNode(_ context.Context,
3029
        nodePub route.Vertex) (*models.LightningNode, error) {
3✔
3030

3✔
3031
        return c.fetchLightningNode(nil, nodePub)
3✔
3032
}
3✔
3033

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

3✔
3041
        var node *models.LightningNode
3✔
3042
        fetch := func(tx kvdb.RTx) error {
6✔
3043
                // First grab the nodes bucket which stores the mapping from
3✔
3044
                // pubKey to node information.
3✔
3045
                nodes := tx.ReadBucket(nodeBucket)
3✔
3046
                if nodes == nil {
3✔
3047
                        return ErrGraphNotFound
×
3048
                }
×
3049

3050
                // If a key for this serialized public key isn't found, then
3051
                // the target node doesn't exist within the database.
3052
                nodeBytes := nodes.Get(nodePub[:])
3✔
3053
                if nodeBytes == nil {
6✔
3054
                        return ErrGraphNodeNotFound
3✔
3055
                }
3✔
3056

3057
                // If the node is found, then we can de deserialize the node
3058
                // information to return to the user.
3059
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3060
                n, err := deserializeLightningNode(nodeReader)
3✔
3061
                if err != nil {
3✔
3062
                        return err
×
3063
                }
×
3064

3065
                node = &n
3✔
3066

3✔
3067
                return nil
3✔
3068
        }
3069

3070
        if tx == nil {
6✔
3071
                err := kvdb.View(
3✔
3072
                        c.db, fetch, func() {
6✔
3073
                                node = nil
3✔
3074
                        },
3✔
3075
                )
3076
                if err != nil {
6✔
3077
                        return nil, err
3✔
3078
                }
3✔
3079

3080
                return node, nil
3✔
3081
        }
3082

UNCOV
3083
        err := fetch(tx)
×
UNCOV
3084
        if err != nil {
×
UNCOV
3085
                return nil, err
×
UNCOV
3086
        }
×
3087

UNCOV
3088
        return node, nil
×
3089
}
3090

3091
// HasLightningNode determines if the graph has a vertex identified by the
3092
// target node identity public key. If the node exists in the database, a
3093
// timestamp of when the data for the node was lasted updated is returned along
3094
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3095
// boolean.
3096
func (c *KVStore) HasLightningNode(_ context.Context,
3097
        nodePub [33]byte) (time.Time, bool, error) {
3✔
3098

3✔
3099
        var (
3✔
3100
                updateTime time.Time
3✔
3101
                exists     bool
3✔
3102
        )
3✔
3103

3✔
3104
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3105
                // First grab the nodes bucket which stores the mapping from
3✔
3106
                // pubKey to node information.
3✔
3107
                nodes := tx.ReadBucket(nodeBucket)
3✔
3108
                if nodes == nil {
3✔
3109
                        return ErrGraphNotFound
×
3110
                }
×
3111

3112
                // If a key for this serialized public key isn't found, we can
3113
                // exit early.
3114
                nodeBytes := nodes.Get(nodePub[:])
3✔
3115
                if nodeBytes == nil {
6✔
3116
                        exists = false
3✔
3117
                        return nil
3✔
3118
                }
3✔
3119

3120
                // Otherwise we continue on to obtain the time stamp
3121
                // representing the last time the data for this node was
3122
                // updated.
3123
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3124
                node, err := deserializeLightningNode(nodeReader)
3✔
3125
                if err != nil {
3✔
3126
                        return err
×
3127
                }
×
3128

3129
                exists = true
3✔
3130
                updateTime = node.LastUpdate
3✔
3131

3✔
3132
                return nil
3✔
3133
        }, func() {
3✔
3134
                updateTime = time.Time{}
3✔
3135
                exists = false
3✔
3136
        })
3✔
3137
        if err != nil {
3✔
3138
                return time.Time{}, exists, err
×
3139
        }
×
3140

3141
        return updateTime, exists, nil
3✔
3142
}
3143

3144
// nodeTraversal is used to traverse all channels of a node given by its
3145
// public key and passes channel information into the specified callback.
3146
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3147
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3148
                *models.ChannelEdgePolicy) error) error {
3✔
3149

3✔
3150
        traversal := func(tx kvdb.RTx) error {
6✔
3151
                edges := tx.ReadBucket(edgeBucket)
3✔
3152
                if edges == nil {
3✔
3153
                        return ErrGraphNotFound
×
3154
                }
×
3155
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3156
                if edgeIndex == nil {
3✔
3157
                        return ErrGraphNoEdgesFound
×
3158
                }
×
3159

3160
                // In order to reach all the edges for this node, we take
3161
                // advantage of the construction of the key-space within the
3162
                // edge bucket. The keys are stored in the form: pubKey ||
3163
                // chanID. Therefore, starting from a chanID of zero, we can
3164
                // scan forward in the bucket, grabbing all the edges for the
3165
                // node. Once the prefix no longer matches, then we know we're
3166
                // done.
3167
                var nodeStart [33 + 8]byte
3✔
3168
                copy(nodeStart[:], nodePub)
3✔
3169
                copy(nodeStart[33:], chanStart[:])
3✔
3170

3✔
3171
                // Starting from the key pubKey || 0, we seek forward in the
3✔
3172
                // bucket until the retrieved key no longer has the public key
3✔
3173
                // as its prefix. This indicates that we've stepped over into
3✔
3174
                // another node's edges, so we can terminate our scan.
3✔
3175
                edgeCursor := edges.ReadCursor()
3✔
3176
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
6✔
3177
                        // If the prefix still matches, the channel id is
3✔
3178
                        // returned in nodeEdge. Channel id is used to lookup
3✔
3179
                        // the node at the other end of the channel and both
3✔
3180
                        // edge policies.
3✔
3181
                        chanID := nodeEdge[33:]
3✔
3182
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3183
                        if err != nil {
3✔
3184
                                return err
×
3185
                        }
×
3186

3187
                        outgoingPolicy, err := fetchChanEdgePolicy(
3✔
3188
                                edges, chanID, nodePub,
3✔
3189
                        )
3✔
3190
                        if err != nil {
3✔
3191
                                return err
×
3192
                        }
×
3193

3194
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3195
                        if err != nil {
3✔
3196
                                return err
×
3197
                        }
×
3198

3199
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3200
                                edges, chanID, otherNode[:],
3✔
3201
                        )
3✔
3202
                        if err != nil {
3✔
3203
                                return err
×
3204
                        }
×
3205

3206
                        // Finally, we execute the callback.
3207
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3208
                        if err != nil {
6✔
3209
                                return err
3✔
3210
                        }
3✔
3211
                }
3212

3213
                return nil
3✔
3214
        }
3215

3216
        // If no transaction was provided, then we'll create a new transaction
3217
        // to execute the transaction within.
3218
        if tx == nil {
6✔
3219
                return kvdb.View(db, traversal, func() {})
6✔
3220
        }
3221

3222
        // Otherwise, we re-use the existing transaction to execute the graph
3223
        // traversal.
3224
        return traversal(tx)
3✔
3225
}
3226

3227
// ForEachNodeChannel iterates through all channels of the given node,
3228
// executing the passed callback with an edge info structure and the policies
3229
// of each end of the channel. The first edge policy is the outgoing edge *to*
3230
// the connecting node, while the second is the incoming edge *from* the
3231
// connecting node. If the callback returns an error, then the iteration is
3232
// halted with the error propagated back up to the caller.
3233
//
3234
// Unknown policies are passed into the callback as nil values.
3235
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3236
        cb func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3237
                *models.ChannelEdgePolicy) error) error {
3✔
3238

3✔
3239
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
3✔
3240
                info *models.ChannelEdgeInfo, policy,
3✔
3241
                policy2 *models.ChannelEdgePolicy) error {
6✔
3242

3✔
3243
                return cb(info, policy, policy2)
3✔
3244
        })
3✔
3245
}
3246

3247
// ForEachSourceNodeChannel iterates through all channels of the source node,
3248
// executing the passed callback on each. The callback is provided with the
3249
// channel's outpoint, whether we have a policy for the channel and the channel
3250
// peer's node information.
3251
func (c *KVStore) ForEachSourceNodeChannel(cb func(chanPoint wire.OutPoint,
3252
        havePolicy bool, otherNode *models.LightningNode) error) error {
3✔
3253

3✔
3254
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3255
                nodes := tx.ReadBucket(nodeBucket)
3✔
3256
                if nodes == nil {
3✔
3257
                        return ErrGraphNotFound
×
3258
                }
×
3259

3260
                node, err := sourceNodeWithTx(nodes)
3✔
3261
                if err != nil {
3✔
3262
                        return err
×
3263
                }
×
3264

3265
                return nodeTraversal(
3✔
3266
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
3✔
3267
                                info *models.ChannelEdgeInfo,
3✔
3268
                                policy, _ *models.ChannelEdgePolicy) error {
6✔
3269

3✔
3270
                                peer, err := c.fetchOtherNode(
3✔
3271
                                        tx, info, node.PubKeyBytes[:],
3✔
3272
                                )
3✔
3273
                                if err != nil {
3✔
3274
                                        return err
×
3275
                                }
×
3276

3277
                                return cb(
3✔
3278
                                        info.ChannelPoint, policy != nil, peer,
3✔
3279
                                )
3✔
3280
                        },
3281
                )
3282
        }, func() {})
3✔
3283
}
3284

3285
// forEachNodeChannelTx iterates through all channels of the given node,
3286
// executing the passed callback with an edge info structure and the policies
3287
// of each end of the channel. The first edge policy is the outgoing edge *to*
3288
// the connecting node, while the second is the incoming edge *from* the
3289
// connecting node. If the callback returns an error, then the iteration is
3290
// halted with the error propagated back up to the caller.
3291
//
3292
// Unknown policies are passed into the callback as nil values.
3293
//
3294
// If the caller wishes to re-use an existing boltdb transaction, then it
3295
// should be passed as the first argument.  Otherwise, the first argument should
3296
// be nil and a fresh transaction will be created to execute the graph
3297
// traversal.
3298
func (c *KVStore) forEachNodeChannelTx(tx kvdb.RTx,
3299
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3300
                *models.ChannelEdgePolicy,
3301
                *models.ChannelEdgePolicy) error) error {
3✔
3302

3✔
3303
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3304
}
3✔
3305

3306
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3307
// the target node in the channel. This is useful when one knows the pubkey of
3308
// one of the nodes, and wishes to obtain the full LightningNode for the other
3309
// end of the channel.
3310
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3311
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3312
        *models.LightningNode, error) {
3✔
3313

3✔
3314
        // Ensure that the node passed in is actually a member of the channel.
3✔
3315
        var targetNodeBytes [33]byte
3✔
3316
        switch {
3✔
3317
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3318
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3319
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3320
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3321
        default:
×
3322
                return nil, fmt.Errorf("node not participating in this channel")
×
3323
        }
3324

3325
        var targetNode *models.LightningNode
3✔
3326
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3327
                // First grab the nodes bucket which stores the mapping from
3✔
3328
                // pubKey to node information.
3✔
3329
                nodes := tx.ReadBucket(nodeBucket)
3✔
3330
                if nodes == nil {
3✔
3331
                        return ErrGraphNotFound
×
3332
                }
×
3333

3334
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3335
                if err != nil {
3✔
3336
                        return err
×
3337
                }
×
3338

3339
                targetNode = &node
3✔
3340

3✔
3341
                return nil
3✔
3342
        }
3343

3344
        // If the transaction is nil, then we'll need to create a new one,
3345
        // otherwise we can use the existing db transaction.
3346
        var err error
3✔
3347
        if tx == nil {
3✔
3348
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3349
                        targetNode = nil
×
3350
                })
×
3351
        } else {
3✔
3352
                err = fetchNodeFunc(tx)
3✔
3353
        }
3✔
3354

3355
        return targetNode, err
3✔
3356
}
3357

3358
// computeEdgePolicyKeys is a helper function that can be used to compute the
3359
// keys used to index the channel edge policy info for the two nodes of the
3360
// edge. The keys for node 1 and node 2 are returned respectively.
3361
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3✔
3362
        var (
3✔
3363
                node1Key [33 + 8]byte
3✔
3364
                node2Key [33 + 8]byte
3✔
3365
        )
3✔
3366

3✔
3367
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3368
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3369

3✔
3370
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3371
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3372

3✔
3373
        return node1Key[:], node2Key[:]
3✔
3374
}
3✔
3375

3376
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3377
// the channel identified by the funding outpoint. If the channel can't be
3378
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3379
// information for the channel itself is returned as well as two structs that
3380
// contain the routing policies for the channel in either direction.
3381
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3382
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3383
        *models.ChannelEdgePolicy, error) {
3✔
3384

3✔
3385
        var (
3✔
3386
                edgeInfo *models.ChannelEdgeInfo
3✔
3387
                policy1  *models.ChannelEdgePolicy
3✔
3388
                policy2  *models.ChannelEdgePolicy
3✔
3389
        )
3✔
3390

3✔
3391
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3392
                // First, grab the node bucket. This will be used to populate
3✔
3393
                // the Node pointers in each edge read from disk.
3✔
3394
                nodes := tx.ReadBucket(nodeBucket)
3✔
3395
                if nodes == nil {
3✔
3396
                        return ErrGraphNotFound
×
3397
                }
×
3398

3399
                // Next, grab the edge bucket which stores the edges, and also
3400
                // the index itself so we can group the directed edges together
3401
                // logically.
3402
                edges := tx.ReadBucket(edgeBucket)
3✔
3403
                if edges == nil {
3✔
3404
                        return ErrGraphNoEdgesFound
×
3405
                }
×
3406
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3407
                if edgeIndex == nil {
3✔
3408
                        return ErrGraphNoEdgesFound
×
3409
                }
×
3410

3411
                // If the channel's outpoint doesn't exist within the outpoint
3412
                // index, then the edge does not exist.
3413
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3414
                if chanIndex == nil {
3✔
3415
                        return ErrGraphNoEdgesFound
×
3416
                }
×
3417
                var b bytes.Buffer
3✔
3418
                if err := WriteOutpoint(&b, op); err != nil {
3✔
3419
                        return err
×
3420
                }
×
3421
                chanID := chanIndex.Get(b.Bytes())
3✔
3422
                if chanID == nil {
6✔
3423
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3424
                }
3✔
3425

3426
                // If the channel is found to exists, then we'll first retrieve
3427
                // the general information for the channel.
3428
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3429
                if err != nil {
3✔
3430
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3431
                }
×
3432
                edgeInfo = &edge
3✔
3433

3✔
3434
                // Once we have the information about the channels' parameters,
3✔
3435
                // we'll fetch the routing policies for each for the directed
3✔
3436
                // edges.
3✔
3437
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3438
                if err != nil {
3✔
3439
                        return fmt.Errorf("failed to find policy: %w", err)
×
3440
                }
×
3441

3442
                policy1 = e1
3✔
3443
                policy2 = e2
3✔
3444

3✔
3445
                return nil
3✔
3446
        }, func() {
3✔
3447
                edgeInfo = nil
3✔
3448
                policy1 = nil
3✔
3449
                policy2 = nil
3✔
3450
        })
3✔
3451
        if err != nil {
6✔
3452
                return nil, nil, nil, err
3✔
3453
        }
3✔
3454

3455
        return edgeInfo, policy1, policy2, nil
3✔
3456
}
3457

3458
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3459
// channel identified by the channel ID. If the channel can't be found, then
3460
// ErrEdgeNotFound is returned. A struct which houses the general information
3461
// for the channel itself is returned as well as two structs that contain the
3462
// routing policies for the channel in either direction.
3463
//
3464
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3465
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3466
// the ChannelEdgeInfo will only include the public keys of each node.
3467
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3468
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3469
        *models.ChannelEdgePolicy, error) {
3✔
3470

3✔
3471
        var (
3✔
3472
                edgeInfo  *models.ChannelEdgeInfo
3✔
3473
                policy1   *models.ChannelEdgePolicy
3✔
3474
                policy2   *models.ChannelEdgePolicy
3✔
3475
                channelID [8]byte
3✔
3476
        )
3✔
3477

3✔
3478
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3479
                // First, grab the node bucket. This will be used to populate
3✔
3480
                // the Node pointers in each edge read from disk.
3✔
3481
                nodes := tx.ReadBucket(nodeBucket)
3✔
3482
                if nodes == nil {
3✔
3483
                        return ErrGraphNotFound
×
3484
                }
×
3485

3486
                // Next, grab the edge bucket which stores the edges, and also
3487
                // the index itself so we can group the directed edges together
3488
                // logically.
3489
                edges := tx.ReadBucket(edgeBucket)
3✔
3490
                if edges == nil {
3✔
3491
                        return ErrGraphNoEdgesFound
×
3492
                }
×
3493
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3494
                if edgeIndex == nil {
3✔
3495
                        return ErrGraphNoEdgesFound
×
3496
                }
×
3497

3498
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3499

3✔
3500
                // Now, attempt to fetch edge.
3✔
3501
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3502

3✔
3503
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3504
                // see if we've previously marked it as so.
3✔
3505
                if errors.Is(err, ErrEdgeNotFound) {
6✔
3506
                        // If the zombie index doesn't exist, or the edge is not
3✔
3507
                        // marked as a zombie within it, then we'll return the
3✔
3508
                        // original ErrEdgeNotFound error.
3✔
3509
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3510
                        if zombieIndex == nil {
3✔
3511
                                return ErrEdgeNotFound
×
3512
                        }
×
3513

3514
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3515
                                zombieIndex, chanID,
3✔
3516
                        )
3✔
3517
                        if !isZombie {
6✔
3518
                                return ErrEdgeNotFound
3✔
3519
                        }
3✔
3520

3521
                        // Otherwise, the edge is marked as a zombie, so we'll
3522
                        // populate the edge info with the public keys of each
3523
                        // party as this is the only information we have about
3524
                        // it and return an error signaling so.
3525
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3526
                                NodeKey1Bytes: pubKey1,
3✔
3527
                                NodeKey2Bytes: pubKey2,
3✔
3528
                        }
3✔
3529

3✔
3530
                        return ErrZombieEdge
3✔
3531
                }
3532

3533
                // Otherwise, we'll just return the error if any.
3534
                if err != nil {
3✔
3535
                        return err
×
3536
                }
×
3537

3538
                edgeInfo = &edge
3✔
3539

3✔
3540
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3541
                // edge.
3✔
3542
                e1, e2, err := fetchChanEdgePolicies(
3✔
3543
                        edgeIndex, edges, channelID[:],
3✔
3544
                )
3✔
3545
                if err != nil {
3✔
3546
                        return err
×
3547
                }
×
3548

3549
                policy1 = e1
3✔
3550
                policy2 = e2
3✔
3551

3✔
3552
                return nil
3✔
3553
        }, func() {
3✔
3554
                edgeInfo = nil
3✔
3555
                policy1 = nil
3✔
3556
                policy2 = nil
3✔
3557
        })
3✔
3558
        if errors.Is(err, ErrZombieEdge) {
6✔
3559
                return edgeInfo, nil, nil, err
3✔
3560
        }
3✔
3561
        if err != nil {
6✔
3562
                return nil, nil, nil, err
3✔
3563
        }
3✔
3564

3565
        return edgeInfo, policy1, policy2, nil
3✔
3566
}
3567

3568
// IsPublicNode is a helper method that determines whether the node with the
3569
// given public key is seen as a public node in the graph from the graph's
3570
// source node's point of view.
3571
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3572
        var nodeIsPublic bool
3✔
3573
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3574
                nodes := tx.ReadBucket(nodeBucket)
3✔
3575
                if nodes == nil {
3✔
3576
                        return ErrGraphNodesNotFound
×
3577
                }
×
3578
                ourPubKey := nodes.Get(sourceKey)
3✔
3579
                if ourPubKey == nil {
3✔
3580
                        return ErrSourceNodeNotSet
×
3581
                }
×
3582
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3583
                if err != nil {
3✔
3584
                        return err
×
3585
                }
×
3586

3587
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3588

3✔
3589
                return err
3✔
3590
        }, func() {
3✔
3591
                nodeIsPublic = false
3✔
3592
        })
3✔
3593
        if err != nil {
3✔
3594
                return false, err
×
3595
        }
×
3596

3597
        return nodeIsPublic, nil
3✔
3598
}
3599

3600
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3601
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3602
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3603
        if err != nil {
3✔
3604
                return nil, err
×
3605
        }
×
3606

3607
        // With the witness script generated, we'll now turn it into a p2wsh
3608
        // script:
3609
        //  * OP_0 <sha256(script)>
3610
        bldr := txscript.NewScriptBuilder(
3✔
3611
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3612
        )
3✔
3613
        bldr.AddOp(txscript.OP_0)
3✔
3614
        scriptHash := sha256.Sum256(witnessScript)
3✔
3615
        bldr.AddData(scriptHash[:])
3✔
3616

3✔
3617
        return bldr.Script()
3✔
3618
}
3619

3620
// EdgePoint couples the outpoint of a channel with the funding script that it
3621
// creates. The FilteredChainView will use this to watch for spends of this
3622
// edge point on chain. We require both of these values as depending on the
3623
// concrete implementation, either the pkScript, or the out point will be used.
3624
type EdgePoint struct {
3625
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3626
        FundingPkScript []byte
3627

3628
        // OutPoint is the outpoint of the target channel.
3629
        OutPoint wire.OutPoint
3630
}
3631

3632
// String returns a human readable version of the target EdgePoint. We return
3633
// the outpoint directly as it is enough to uniquely identify the edge point.
3634
func (e *EdgePoint) String() string {
×
3635
        return e.OutPoint.String()
×
3636
}
×
3637

3638
// ChannelView returns the verifiable edge information for each active channel
3639
// within the known channel graph. The set of UTXO's (along with their scripts)
3640
// returned are the ones that need to be watched on chain to detect channel
3641
// closes on the resident blockchain.
3642
func (c *KVStore) ChannelView() ([]EdgePoint, error) {
3✔
3643
        var edgePoints []EdgePoint
3✔
3644
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3645
                // We're going to iterate over the entire channel index, so
3✔
3646
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3647
                // it's a sub-bucket.
3✔
3648
                edges := tx.ReadBucket(edgeBucket)
3✔
3649
                if edges == nil {
3✔
3650
                        return ErrGraphNoEdgesFound
×
3651
                }
×
3652
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3653
                if chanIndex == nil {
3✔
3654
                        return ErrGraphNoEdgesFound
×
3655
                }
×
3656
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3657
                if edgeIndex == nil {
3✔
3658
                        return ErrGraphNoEdgesFound
×
3659
                }
×
3660

3661
                // Once we have the proper bucket, we'll range over each key
3662
                // (which is the channel point for the channel) and decode it,
3663
                // accumulating each entry.
3664
                return chanIndex.ForEach(
3✔
3665
                        func(chanPointBytes, chanID []byte) error {
6✔
3666
                                chanPointReader := bytes.NewReader(
3✔
3667
                                        chanPointBytes,
3✔
3668
                                )
3✔
3669

3✔
3670
                                var chanPoint wire.OutPoint
3✔
3671
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3672
                                if err != nil {
3✔
3673
                                        return err
×
3674
                                }
×
3675

3676
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3677
                                        edgeIndex, chanID,
3✔
3678
                                )
3✔
3679
                                if err != nil {
3✔
3680
                                        return err
×
3681
                                }
×
3682

3683
                                pkScript, err := genMultiSigP2WSH(
3✔
3684
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3685
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3686
                                )
3✔
3687
                                if err != nil {
3✔
3688
                                        return err
×
3689
                                }
×
3690

3691
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3692
                                        FundingPkScript: pkScript,
3✔
3693
                                        OutPoint:        chanPoint,
3✔
3694
                                })
3✔
3695

3✔
3696
                                return nil
3✔
3697
                        },
3698
                )
3699
        }, func() {
3✔
3700
                edgePoints = nil
3✔
3701
        }); err != nil {
3✔
3702
                return nil, err
×
3703
        }
×
3704

3705
        return edgePoints, nil
3✔
3706
}
3707

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

×
UNCOV
3714
        c.cacheMu.Lock()
×
UNCOV
3715
        defer c.cacheMu.Unlock()
×
UNCOV
3716

×
UNCOV
3717
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3718
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3719
                if edges == nil {
×
3720
                        return ErrGraphNoEdgesFound
×
3721
                }
×
UNCOV
3722
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
UNCOV
3723
                if err != nil {
×
3724
                        return fmt.Errorf("unable to create zombie "+
×
3725
                                "bucket: %w", err)
×
3726
                }
×
3727

UNCOV
3728
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3729
        })
UNCOV
3730
        if err != nil {
×
3731
                return err
×
3732
        }
×
3733

UNCOV
3734
        c.rejectCache.remove(chanID)
×
UNCOV
3735
        c.chanCache.remove(chanID)
×
UNCOV
3736

×
UNCOV
3737
        return nil
×
3738
}
3739

3740
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3741
// keys should represent the node public keys of the two parties involved in the
3742
// edge.
3743
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3744
        pubKey2 [33]byte) error {
3✔
3745

3✔
3746
        var k [8]byte
3✔
3747
        byteOrder.PutUint64(k[:], chanID)
3✔
3748

3✔
3749
        var v [66]byte
3✔
3750
        copy(v[:33], pubKey1[:])
3✔
3751
        copy(v[33:], pubKey2[:])
3✔
3752

3✔
3753
        return zombieIndex.Put(k[:], v[:])
3✔
3754
}
3✔
3755

3756
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
UNCOV
3757
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
UNCOV
3758
        c.cacheMu.Lock()
×
UNCOV
3759
        defer c.cacheMu.Unlock()
×
UNCOV
3760

×
UNCOV
3761
        return c.markEdgeLiveUnsafe(nil, chanID)
×
UNCOV
3762
}
×
3763

3764
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3765
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3766
// case a new transaction will be created.
3767
//
3768
// NOTE: this method MUST only be called if the cacheMu has already been
3769
// acquired.
UNCOV
3770
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
UNCOV
3771
        dbFn := func(tx kvdb.RwTx) error {
×
UNCOV
3772
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3773
                if edges == nil {
×
3774
                        return ErrGraphNoEdgesFound
×
3775
                }
×
UNCOV
3776
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
×
UNCOV
3777
                if zombieIndex == nil {
×
3778
                        return nil
×
3779
                }
×
3780

UNCOV
3781
                var k [8]byte
×
UNCOV
3782
                byteOrder.PutUint64(k[:], chanID)
×
UNCOV
3783

×
UNCOV
3784
                if len(zombieIndex.Get(k[:])) == 0 {
×
UNCOV
3785
                        return ErrZombieEdgeNotFound
×
UNCOV
3786
                }
×
3787

UNCOV
3788
                return zombieIndex.Delete(k[:])
×
3789
        }
3790

3791
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3792
        // the existing transaction
UNCOV
3793
        var err error
×
UNCOV
3794
        if tx == nil {
×
UNCOV
3795
                err = kvdb.Update(c.db, dbFn, func() {})
×
3796
        } else {
×
3797
                err = dbFn(tx)
×
3798
        }
×
UNCOV
3799
        if err != nil {
×
UNCOV
3800
                return err
×
UNCOV
3801
        }
×
3802

UNCOV
3803
        c.rejectCache.remove(chanID)
×
UNCOV
3804
        c.chanCache.remove(chanID)
×
UNCOV
3805

×
UNCOV
3806
        return nil
×
3807
}
3808

3809
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3810
// zombie, then the two node public keys corresponding to this edge are also
3811
// returned.
3812
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte,
UNCOV
3813
        error) {
×
UNCOV
3814

×
UNCOV
3815
        var (
×
UNCOV
3816
                isZombie         bool
×
UNCOV
3817
                pubKey1, pubKey2 [33]byte
×
UNCOV
3818
        )
×
UNCOV
3819

×
UNCOV
3820
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3821
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3822
                if edges == nil {
×
3823
                        return ErrGraphNoEdgesFound
×
3824
                }
×
UNCOV
3825
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3826
                if zombieIndex == nil {
×
3827
                        return nil
×
3828
                }
×
3829

UNCOV
3830
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
UNCOV
3831

×
UNCOV
3832
                return nil
×
UNCOV
3833
        }, func() {
×
UNCOV
3834
                isZombie = false
×
UNCOV
3835
                pubKey1 = [33]byte{}
×
UNCOV
3836
                pubKey2 = [33]byte{}
×
UNCOV
3837
        })
×
UNCOV
3838
        if err != nil {
×
3839
                return false, [33]byte{}, [33]byte{}, fmt.Errorf("%w: %w "+
×
3840
                        "(chanID=%d)", ErrCantCheckIfZombieEdgeStr, err, chanID)
×
3841
        }
×
3842

UNCOV
3843
        return isZombie, pubKey1, pubKey2, nil
×
3844
}
3845

3846
// isZombieEdge returns whether an entry exists for the given channel in the
3847
// zombie index. If an entry exists, then the two node public keys corresponding
3848
// to this edge are also returned.
3849
func isZombieEdge(zombieIndex kvdb.RBucket,
3850
        chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3851

3✔
3852
        var k [8]byte
3✔
3853
        byteOrder.PutUint64(k[:], chanID)
3✔
3854

3✔
3855
        v := zombieIndex.Get(k[:])
3✔
3856
        if v == nil {
6✔
3857
                return false, [33]byte{}, [33]byte{}
3✔
3858
        }
3✔
3859

3860
        var pubKey1, pubKey2 [33]byte
3✔
3861
        copy(pubKey1[:], v[:33])
3✔
3862
        copy(pubKey2[:], v[33:])
3✔
3863

3✔
3864
        return true, pubKey1, pubKey2
3✔
3865
}
3866

3867
// NumZombies returns the current number of zombie channels in the graph.
UNCOV
3868
func (c *KVStore) NumZombies() (uint64, error) {
×
UNCOV
3869
        var numZombies uint64
×
UNCOV
3870
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3871
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3872
                if edges == nil {
×
3873
                        return nil
×
3874
                }
×
UNCOV
3875
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3876
                if zombieIndex == nil {
×
3877
                        return nil
×
3878
                }
×
3879

UNCOV
3880
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
UNCOV
3881
                        numZombies++
×
UNCOV
3882
                        return nil
×
UNCOV
3883
                })
×
UNCOV
3884
        }, func() {
×
UNCOV
3885
                numZombies = 0
×
UNCOV
3886
        })
×
UNCOV
3887
        if err != nil {
×
3888
                return 0, err
×
3889
        }
×
3890

UNCOV
3891
        return numZombies, nil
×
3892
}
3893

3894
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3895
// that we can ignore channel announcements that we know to be closed without
3896
// having to validate them and fetch a block.
UNCOV
3897
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
×
UNCOV
3898
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3899
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
UNCOV
3900
                if err != nil {
×
3901
                        return err
×
3902
                }
×
3903

UNCOV
3904
                var k [8]byte
×
UNCOV
3905
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
UNCOV
3906

×
UNCOV
3907
                return closedScids.Put(k[:], []byte{})
×
UNCOV
3908
        }, func() {})
×
3909
}
3910

3911
// IsClosedScid checks whether a channel identified by the passed in scid is
3912
// closed. This helps avoid having to perform expensive validation checks.
3913
// TODO: Add an LRU cache to cut down on disc reads.
3914
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3915
        var isClosed bool
3✔
3916
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3917
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3918
                if closedScids == nil {
3✔
3919
                        return ErrClosedScidsNotFound
×
3920
                }
×
3921

3922
                var k [8]byte
3✔
3923
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3924

3✔
3925
                if closedScids.Get(k[:]) != nil {
3✔
UNCOV
3926
                        isClosed = true
×
UNCOV
3927
                        return nil
×
UNCOV
3928
                }
×
3929

3930
                return nil
3✔
3931
        }, func() {
3✔
3932
                isClosed = false
3✔
3933
        })
3✔
3934
        if err != nil {
3✔
3935
                return false, err
×
3936
        }
×
3937

3938
        return isClosed, nil
3✔
3939
}
3940

3941
// GraphSession will provide the call-back with access to a NodeTraverser
3942
// instance which can be used to perform queries against the channel graph.
UNCOV
3943
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
×
UNCOV
3944
        return c.db.View(func(tx walletdb.ReadTx) error {
×
UNCOV
3945
                return cb(&nodeTraverserSession{
×
UNCOV
3946
                        db: c,
×
UNCOV
3947
                        tx: tx,
×
UNCOV
3948
                })
×
UNCOV
3949
        }, func() {})
×
3950
}
3951

3952
// nodeTraverserSession implements the NodeTraverser interface but with a
3953
// backing read only transaction for a consistent view of the graph.
3954
type nodeTraverserSession struct {
3955
        tx kvdb.RTx
3956
        db *KVStore
3957
}
3958

3959
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3960
// node.
3961
//
3962
// NOTE: Part of the NodeTraverser interface.
3963
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
UNCOV
3964
        cb func(channel *DirectedChannel) error) error {
×
UNCOV
3965

×
UNCOV
3966
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
×
UNCOV
3967
}
×
3968

3969
// FetchNodeFeatures returns the features of the given node. If the node is
3970
// unknown, assume no additional features are supported.
3971
//
3972
// NOTE: Part of the NodeTraverser interface.
3973
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
UNCOV
3974
        *lnwire.FeatureVector, error) {
×
UNCOV
3975

×
UNCOV
3976
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
UNCOV
3977
}
×
3978

3979
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3980
        node *models.LightningNode) error {
3✔
3981

3✔
3982
        var (
3✔
3983
                scratch [16]byte
3✔
3984
                b       bytes.Buffer
3✔
3985
        )
3✔
3986

3✔
3987
        pub, err := node.PubKey()
3✔
3988
        if err != nil {
3✔
3989
                return err
×
3990
        }
×
3991
        nodePub := pub.SerializeCompressed()
3✔
3992

3✔
3993
        // If the node has the update time set, write it, else write 0.
3✔
3994
        updateUnix := uint64(0)
3✔
3995
        if node.LastUpdate.Unix() > 0 {
6✔
3996
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
3997
        }
3✔
3998

3999
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
4000
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
4001
                return err
×
4002
        }
×
4003

4004
        if _, err := b.Write(nodePub); err != nil {
3✔
4005
                return err
×
4006
        }
×
4007

4008
        // If we got a node announcement for this node, we will have the rest
4009
        // of the data available. If not we don't have more data to write.
4010
        if !node.HaveNodeAnnouncement {
6✔
4011
                // Write HaveNodeAnnouncement=0.
3✔
4012
                byteOrder.PutUint16(scratch[:2], 0)
3✔
4013
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
4014
                        return err
×
4015
                }
×
4016

4017
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
4018
        }
4019

4020
        // Write HaveNodeAnnouncement=1.
4021
        byteOrder.PutUint16(scratch[:2], 1)
3✔
4022
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4023
                return err
×
4024
        }
×
4025

4026
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
4027
                return err
×
4028
        }
×
4029
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
4030
                return err
×
4031
        }
×
4032
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
4033
                return err
×
4034
        }
×
4035

4036
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
4037
                return err
×
4038
        }
×
4039

4040
        if err := node.Features.Encode(&b); err != nil {
3✔
4041
                return err
×
4042
        }
×
4043

4044
        numAddresses := uint16(len(node.Addresses))
3✔
4045
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
4046
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4047
                return err
×
4048
        }
×
4049

4050
        for _, address := range node.Addresses {
6✔
4051
                if err := SerializeAddr(&b, address); err != nil {
3✔
4052
                        return err
×
4053
                }
×
4054
        }
4055

4056
        sigLen := len(node.AuthSigBytes)
3✔
4057
        if sigLen > 80 {
3✔
4058
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4059
                        sigLen)
×
4060
        }
×
4061

4062
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
4063
        if err != nil {
3✔
4064
                return err
×
4065
        }
×
4066

4067
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4068
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4069
        }
×
4070
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
4071
        if err != nil {
3✔
4072
                return err
×
4073
        }
×
4074

4075
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
4076
                return err
×
4077
        }
×
4078

4079
        // With the alias bucket updated, we'll now update the index that
4080
        // tracks the time series of node updates.
4081
        var indexKey [8 + 33]byte
3✔
4082
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4083
        copy(indexKey[8:], nodePub)
3✔
4084

3✔
4085
        // If there was already an old index entry for this node, then we'll
3✔
4086
        // delete the old one before we write the new entry.
3✔
4087
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
6✔
4088
                // Extract out the old update time to we can reconstruct the
3✔
4089
                // prior index key to delete it from the index.
3✔
4090
                oldUpdateTime := nodeBytes[:8]
3✔
4091

3✔
4092
                var oldIndexKey [8 + 33]byte
3✔
4093
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
4094
                copy(oldIndexKey[8:], nodePub)
3✔
4095

3✔
4096
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4097
                        return err
×
4098
                }
×
4099
        }
4100

4101
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4102
                return err
×
4103
        }
×
4104

4105
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
4106
}
4107

4108
func fetchLightningNode(nodeBucket kvdb.RBucket,
4109
        nodePub []byte) (models.LightningNode, error) {
3✔
4110

3✔
4111
        nodeBytes := nodeBucket.Get(nodePub)
3✔
4112
        if nodeBytes == nil {
6✔
4113
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
4114
        }
3✔
4115

4116
        nodeReader := bytes.NewReader(nodeBytes)
3✔
4117

3✔
4118
        return deserializeLightningNode(nodeReader)
3✔
4119
}
4120

4121
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4122
        *lnwire.FeatureVector, error) {
3✔
4123

3✔
4124
        var (
3✔
4125
                pubKey      route.Vertex
3✔
4126
                features    = lnwire.EmptyFeatureVector()
3✔
4127
                nodeScratch [8]byte
3✔
4128
        )
3✔
4129

3✔
4130
        // Skip ahead:
3✔
4131
        // - LastUpdate (8 bytes)
3✔
4132
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
4133
                return pubKey, nil, err
×
4134
        }
×
4135

4136
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
4137
                return pubKey, nil, err
×
4138
        }
×
4139

4140
        // Read the node announcement flag.
4141
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
4142
                return pubKey, nil, err
×
4143
        }
×
4144
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4145

3✔
4146
        // The rest of the data is optional, and will only be there if we got a
3✔
4147
        // node announcement for this node.
3✔
4148
        if hasNodeAnn == 0 {
6✔
4149
                return pubKey, features, nil
3✔
4150
        }
3✔
4151

4152
        // We did get a node announcement for this node, so we'll have the rest
4153
        // of the data available.
4154
        var rgb uint8
3✔
4155
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4156
                return pubKey, nil, err
×
4157
        }
×
4158
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4159
                return pubKey, nil, err
×
4160
        }
×
4161
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4162
                return pubKey, nil, err
×
4163
        }
×
4164

4165
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4166
                return pubKey, nil, err
×
4167
        }
×
4168

4169
        if err := features.Decode(r); err != nil {
3✔
4170
                return pubKey, nil, err
×
4171
        }
×
4172

4173
        return pubKey, features, nil
3✔
4174
}
4175

4176
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4177
        var (
3✔
4178
                node    models.LightningNode
3✔
4179
                scratch [8]byte
3✔
4180
                err     error
3✔
4181
        )
3✔
4182

3✔
4183
        // Always populate a feature vector, even if we don't have a node
3✔
4184
        // announcement and short circuit below.
3✔
4185
        node.Features = lnwire.EmptyFeatureVector()
3✔
4186

3✔
4187
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4188
                return models.LightningNode{}, err
×
4189
        }
×
4190

4191
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4192
        node.LastUpdate = time.Unix(unix, 0)
3✔
4193

3✔
4194
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4195
                return models.LightningNode{}, err
×
4196
        }
×
4197

4198
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4199
                return models.LightningNode{}, err
×
4200
        }
×
4201

4202
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4203
        if hasNodeAnn == 1 {
6✔
4204
                node.HaveNodeAnnouncement = true
3✔
4205
        } else {
6✔
4206
                node.HaveNodeAnnouncement = false
3✔
4207
        }
3✔
4208

4209
        // The rest of the data is optional, and will only be there if we got a
4210
        // node announcement for this node.
4211
        if !node.HaveNodeAnnouncement {
6✔
4212
                return node, nil
3✔
4213
        }
3✔
4214

4215
        // We did get a node announcement for this node, so we'll have the rest
4216
        // of the data available.
4217
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
3✔
4218
                return models.LightningNode{}, err
×
4219
        }
×
4220
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
3✔
4221
                return models.LightningNode{}, err
×
4222
        }
×
4223
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4224
                return models.LightningNode{}, err
×
4225
        }
×
4226

4227
        node.Alias, err = wire.ReadVarString(r, 0)
3✔
4228
        if err != nil {
3✔
4229
                return models.LightningNode{}, err
×
4230
        }
×
4231

4232
        err = node.Features.Decode(r)
3✔
4233
        if err != nil {
3✔
4234
                return models.LightningNode{}, err
×
4235
        }
×
4236

4237
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4238
                return models.LightningNode{}, err
×
4239
        }
×
4240
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4241

3✔
4242
        var addresses []net.Addr
3✔
4243
        for i := 0; i < numAddresses; i++ {
6✔
4244
                address, err := DeserializeAddr(r)
3✔
4245
                if err != nil {
3✔
4246
                        return models.LightningNode{}, err
×
4247
                }
×
4248
                addresses = append(addresses, address)
3✔
4249
        }
4250
        node.Addresses = addresses
3✔
4251

3✔
4252
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4253
        if err != nil {
3✔
4254
                return models.LightningNode{}, err
×
4255
        }
×
4256

4257
        // We'll try and see if there are any opaque bytes left, if not, then
4258
        // we'll ignore the EOF error and return the node as is.
4259
        extraBytes, err := wire.ReadVarBytes(
3✔
4260
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4261
        )
3✔
4262
        switch {
3✔
4263
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4264
        case errors.Is(err, io.EOF):
×
4265
        case err != nil:
×
4266
                return models.LightningNode{}, err
×
4267
        }
4268

4269
        if len(extraBytes) > 0 {
3✔
UNCOV
4270
                node.ExtraOpaqueData = extraBytes
×
UNCOV
4271
        }
×
4272

4273
        return node, nil
3✔
4274
}
4275

4276
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4277
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4278

3✔
4279
        var b bytes.Buffer
3✔
4280

3✔
4281
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4282
                return err
×
4283
        }
×
4284
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4285
                return err
×
4286
        }
×
4287
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4288
                return err
×
4289
        }
×
4290
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4291
                return err
×
4292
        }
×
4293

4294
        var featureBuf bytes.Buffer
3✔
4295
        if err := edgeInfo.Features.Encode(&featureBuf); err != nil {
3✔
4296
                return fmt.Errorf("unable to encode features: %w", err)
×
4297
        }
×
4298

4299
        if err := wire.WriteVarBytes(&b, 0, featureBuf.Bytes()); err != nil {
3✔
4300
                return err
×
4301
        }
×
4302

4303
        authProof := edgeInfo.AuthProof
3✔
4304
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4305
        if authProof != nil {
6✔
4306
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4307
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4308
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4309
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4310
        }
3✔
4311

4312
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4313
                return err
×
4314
        }
×
4315
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4316
                return err
×
4317
        }
×
4318
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4319
                return err
×
4320
        }
×
4321
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4322
                return err
×
4323
        }
×
4324

4325
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4326
                return err
×
4327
        }
×
4328
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
3✔
4329
        if err != nil {
3✔
4330
                return err
×
4331
        }
×
4332
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4333
                return err
×
4334
        }
×
4335
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4336
                return err
×
4337
        }
×
4338

4339
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4340
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4341
        }
×
4342
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4343
        if err != nil {
3✔
4344
                return err
×
4345
        }
×
4346

4347
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4348
}
4349

4350
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4351
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4352

3✔
4353
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4354
        if edgeInfoBytes == nil {
6✔
4355
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4356
        }
3✔
4357

4358
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4359

3✔
4360
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4361
}
4362

4363
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4364
        var (
3✔
4365
                err      error
3✔
4366
                edgeInfo models.ChannelEdgeInfo
3✔
4367
        )
3✔
4368

3✔
4369
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4370
                return models.ChannelEdgeInfo{}, err
×
4371
        }
×
4372
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4373
                return models.ChannelEdgeInfo{}, err
×
4374
        }
×
4375
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4376
                return models.ChannelEdgeInfo{}, err
×
4377
        }
×
4378
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4379
                return models.ChannelEdgeInfo{}, err
×
4380
        }
×
4381

4382
        featureBytes, err := wire.ReadVarBytes(r, 0, 900, "features")
3✔
4383
        if err != nil {
3✔
4384
                return models.ChannelEdgeInfo{}, err
×
4385
        }
×
4386

4387
        features := lnwire.NewRawFeatureVector()
3✔
4388
        err = features.Decode(bytes.NewReader(featureBytes))
3✔
4389
        if err != nil {
3✔
4390
                return models.ChannelEdgeInfo{}, fmt.Errorf("unable to decode "+
×
4391
                        "features: %w", err)
×
4392
        }
×
4393
        edgeInfo.Features = lnwire.NewFeatureVector(features, lnwire.Features)
3✔
4394

3✔
4395
        proof := &models.ChannelAuthProof{}
3✔
4396

3✔
4397
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4398
        if err != nil {
3✔
4399
                return models.ChannelEdgeInfo{}, err
×
4400
        }
×
4401
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4402
        if err != nil {
3✔
4403
                return models.ChannelEdgeInfo{}, err
×
4404
        }
×
4405
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4406
        if err != nil {
3✔
4407
                return models.ChannelEdgeInfo{}, err
×
4408
        }
×
4409
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4410
        if err != nil {
3✔
4411
                return models.ChannelEdgeInfo{}, err
×
4412
        }
×
4413

4414
        if !proof.IsEmpty() {
6✔
4415
                edgeInfo.AuthProof = proof
3✔
4416
        }
3✔
4417

4418
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4419
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4420
                return models.ChannelEdgeInfo{}, err
×
4421
        }
×
4422
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4423
                return models.ChannelEdgeInfo{}, err
×
4424
        }
×
4425
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4426
                return models.ChannelEdgeInfo{}, err
×
4427
        }
×
4428

4429
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4430
                return models.ChannelEdgeInfo{}, err
×
4431
        }
×
4432

4433
        // We'll try and see if there are any opaque bytes left, if not, then
4434
        // we'll ignore the EOF error and return the edge as is.
4435
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4436
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4437
        )
3✔
4438
        switch {
3✔
4439
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4440
        case errors.Is(err, io.EOF):
×
4441
        case err != nil:
×
4442
                return models.ChannelEdgeInfo{}, err
×
4443
        }
4444

4445
        return edgeInfo, nil
3✔
4446
}
4447

4448
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4449
        from, to []byte) error {
3✔
4450

3✔
4451
        var edgeKey [33 + 8]byte
3✔
4452
        copy(edgeKey[:], from)
3✔
4453
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4454

3✔
4455
        var b bytes.Buffer
3✔
4456
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
UNCOV
4457
                return err
×
UNCOV
4458
        }
×
4459

4460
        // Before we write out the new edge, we'll create a new entry in the
4461
        // update index in order to keep it fresh.
4462
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4463
        var indexKey [8 + 8]byte
3✔
4464
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4465
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4466

3✔
4467
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4468
        if err != nil {
3✔
4469
                return err
×
4470
        }
×
4471

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

3✔
4479
                // In order to delete the old entry, we'll need to obtain the
3✔
4480
                // *prior* update time in order to delete it. To do this, we'll
3✔
4481
                // need to deserialize the existing policy within the database
3✔
4482
                // (now outdated by the new one), and delete its corresponding
3✔
4483
                // entry within the update index. We'll ignore any
3✔
4484
                // ErrEdgePolicyOptionalFieldNotFound or ErrParsingExtraTLVBytes
3✔
4485
                // errors, as we only need the channel ID and update time to
3✔
4486
                // delete the entry.
3✔
4487
                //
3✔
4488
                // TODO(halseth): get rid of these invalid policies in a
3✔
4489
                // migration.
3✔
4490
                // TODO(elle): complete the above TODO in migration from kvdb
3✔
4491
                // to SQL.
3✔
4492
                oldEdgePolicy, err := deserializeChanEdgePolicy(
3✔
4493
                        bytes.NewReader(edgeBytes),
3✔
4494
                )
3✔
4495
                if err != nil &&
3✔
4496
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4497
                        !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4498

×
4499
                        return err
×
4500
                }
×
4501

4502
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4503

3✔
4504
                var oldIndexKey [8 + 8]byte
3✔
4505
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4506
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4507

3✔
4508
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4509
                        return err
×
4510
                }
×
4511
        }
4512

4513
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4514
                return err
×
4515
        }
×
4516

4517
        err = updateEdgePolicyDisabledIndex(
3✔
4518
                edges, edge.ChannelID,
3✔
4519
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4520
                edge.IsDisabled(),
3✔
4521
        )
3✔
4522
        if err != nil {
3✔
4523
                return err
×
4524
        }
×
4525

4526
        return edges.Put(edgeKey[:], b.Bytes())
3✔
4527
}
4528

4529
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4530
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4531
// one.
4532
// The direction represents the direction of the edge and disabled is used for
4533
// deciding whether to remove or add an entry to the bucket.
4534
// In general a channel is disabled if two entries for the same chanID exist
4535
// in this bucket.
4536
// Maintaining the bucket this way allows a fast retrieval of disabled
4537
// channels, for example when prune is needed.
4538
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4539
        direction bool, disabled bool) error {
3✔
4540

3✔
4541
        var disabledEdgeKey [8 + 1]byte
3✔
4542
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4543
        if direction {
6✔
4544
                disabledEdgeKey[8] = 1
3✔
4545
        }
3✔
4546

4547
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4548
                disabledEdgePolicyBucket,
3✔
4549
        )
3✔
4550
        if err != nil {
3✔
4551
                return err
×
4552
        }
×
4553

4554
        if disabled {
6✔
4555
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4556
        }
3✔
4557

4558
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4559
}
4560

4561
// putChanEdgePolicyUnknown marks the edge policy as unknown
4562
// in the edges bucket.
4563
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4564
        from []byte) error {
3✔
4565

3✔
4566
        var edgeKey [33 + 8]byte
3✔
4567
        copy(edgeKey[:], from)
3✔
4568
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4569

3✔
4570
        if edges.Get(edgeKey[:]) != nil {
3✔
4571
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4572
                        " when there is already a policy present", channelID)
×
4573
        }
×
4574

4575
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4576
}
4577

4578
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4579
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
3✔
4580

3✔
4581
        var edgeKey [33 + 8]byte
3✔
4582
        copy(edgeKey[:], nodePub)
3✔
4583
        copy(edgeKey[33:], chanID)
3✔
4584

3✔
4585
        edgeBytes := edges.Get(edgeKey[:])
3✔
4586
        if edgeBytes == nil {
3✔
4587
                return nil, ErrEdgeNotFound
×
4588
        }
×
4589

4590
        // No need to deserialize unknown policy.
4591
        if bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4592
                return nil, nil
3✔
4593
        }
3✔
4594

4595
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4596

3✔
4597
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4598
        switch {
3✔
4599
        // If the db policy was missing an expected optional field, we return
4600
        // nil as if the policy was unknown.
UNCOV
4601
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
UNCOV
4602
                return nil, nil
×
4603

4604
        // If the policy contains invalid TLV bytes, we return nil as if
4605
        // the policy was unknown.
4606
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4607
                return nil, nil
×
4608

4609
        case err != nil:
×
4610
                return nil, err
×
4611
        }
4612

4613
        return ep, nil
3✔
4614
}
4615

4616
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4617
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4618
        error) {
3✔
4619

3✔
4620
        edgeInfo := edgeIndex.Get(chanID)
3✔
4621
        if edgeInfo == nil {
3✔
4622
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4623
                        chanID)
×
4624
        }
×
4625

4626
        // The first node is contained within the first half of the edge
4627
        // information. We only propagate the error here and below if it's
4628
        // something other than edge non-existence.
4629
        node1Pub := edgeInfo[:33]
3✔
4630
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4631
        if err != nil {
3✔
4632
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4633
                        node1Pub)
×
4634
        }
×
4635

4636
        // Similarly, the second node is contained within the latter
4637
        // half of the edge information.
4638
        node2Pub := edgeInfo[33:66]
3✔
4639
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4640
        if err != nil {
3✔
4641
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4642
                        node2Pub)
×
4643
        }
×
4644

4645
        return edge1, edge2, nil
3✔
4646
}
4647

4648
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4649
        to []byte) error {
3✔
4650

3✔
4651
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4652
        if err != nil {
3✔
4653
                return err
×
4654
        }
×
4655

4656
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4657
                return err
×
4658
        }
×
4659

4660
        var scratch [8]byte
3✔
4661
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4662
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4663
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4664
                return err
×
4665
        }
×
4666

4667
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
3✔
4668
                return err
×
4669
        }
×
4670
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
3✔
4671
                return err
×
4672
        }
×
4673
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
3✔
4674
                return err
×
4675
        }
×
4676
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
3✔
4677
                return err
×
4678
        }
×
4679
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
3✔
4680
        if err != nil {
3✔
4681
                return err
×
4682
        }
×
4683
        err = binary.Write(
3✔
4684
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
3✔
4685
        )
3✔
4686
        if err != nil {
3✔
4687
                return err
×
4688
        }
×
4689

4690
        if _, err := w.Write(to); err != nil {
3✔
4691
                return err
×
4692
        }
×
4693

4694
        // If the max_htlc field is present, we write it. To be compatible with
4695
        // older versions that wasn't aware of this field, we write it as part
4696
        // of the opaque data.
4697
        // TODO(halseth): clean up when moving to TLV.
4698
        var opaqueBuf bytes.Buffer
3✔
4699
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4700
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4701
                if err != nil {
3✔
4702
                        return err
×
4703
                }
×
4704
        }
4705

4706
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
4707
        err = edge.ExtraOpaqueData.ValidateTLV()
3✔
4708
        if err != nil {
3✔
UNCOV
4709
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
UNCOV
4710
        }
×
4711

4712
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4713
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4714
        }
×
4715
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4716
                return err
×
4717
        }
×
4718

4719
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4720
                return err
×
4721
        }
×
4722

4723
        return nil
3✔
4724
}
4725

4726
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
3✔
4727
        // Deserialize the policy. Note that in case an optional field is not
3✔
4728
        // found or if the edge has invalid TLV data, then both an error and a
3✔
4729
        // populated policy object are returned so that the caller can decide
3✔
4730
        // if it still wants to use the edge or not.
3✔
4731
        edge, err := deserializeChanEdgePolicyRaw(r)
3✔
4732
        if err != nil &&
3✔
4733
                !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4734
                !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4735

×
4736
                return nil, err
×
4737
        }
×
4738

4739
        return edge, err
3✔
4740
}
4741

4742
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4743
        error) {
3✔
4744

3✔
4745
        edge := &models.ChannelEdgePolicy{}
3✔
4746

3✔
4747
        var err error
3✔
4748
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4749
        if err != nil {
3✔
4750
                return nil, err
×
4751
        }
×
4752

4753
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4754
                return nil, err
×
4755
        }
×
4756

4757
        var scratch [8]byte
3✔
4758
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4759
                return nil, err
×
4760
        }
×
4761
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4762
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4763

3✔
4764
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4765
                return nil, err
×
4766
        }
×
4767
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4768
                return nil, err
×
4769
        }
×
4770
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4771
                return nil, err
×
4772
        }
×
4773

4774
        var n uint64
3✔
4775
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4776
                return nil, err
×
4777
        }
×
4778
        edge.MinHTLC = lnwire.MilliSatoshi(n)
3✔
4779

3✔
4780
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4781
                return nil, err
×
4782
        }
×
4783
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
4784

3✔
4785
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4786
                return nil, err
×
4787
        }
×
4788
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4789

3✔
4790
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4791
                return nil, err
×
4792
        }
×
4793

4794
        // We'll try and see if there are any opaque bytes left, if not, then
4795
        // we'll ignore the EOF error and return the edge as is.
4796
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4797
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4798
        )
3✔
4799
        switch {
3✔
4800
        case errors.Is(err, io.ErrUnexpectedEOF):
×
UNCOV
4801
        case errors.Is(err, io.EOF):
×
4802
        case err != nil:
×
4803
                return nil, err
×
4804
        }
4805

4806
        // See if optional fields are present.
4807
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4808
                // The max_htlc field should be at the beginning of the opaque
3✔
4809
                // bytes.
3✔
4810
                opq := edge.ExtraOpaqueData
3✔
4811

3✔
4812
                // If the max_htlc field is not present, it might be old data
3✔
4813
                // stored before this field was validated. We'll return the
3✔
4814
                // edge along with an error.
3✔
4815
                if len(opq) < 8 {
3✔
UNCOV
4816
                        return edge, ErrEdgePolicyOptionalFieldNotFound
×
UNCOV
4817
                }
×
4818

4819
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4820
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4821

3✔
4822
                // Exclude the parsed field from the rest of the opaque data.
3✔
4823
                edge.ExtraOpaqueData = opq[8:]
3✔
4824
        }
4825

4826
        // Attempt to extract the inbound fee from the opaque data. If we fail
4827
        // to parse the TLV here, we return an error we also return the edge
4828
        // so that the caller can still use it. This is for backwards
4829
        // compatibility in case we have already persisted some policies that
4830
        // have invalid TLV data.
4831
        var inboundFee lnwire.Fee
3✔
4832
        typeMap, err := edge.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
4833
        if err != nil {
3✔
4834
                return edge, fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
4835
        }
×
4836

4837
        val, ok := typeMap[lnwire.FeeRecordType]
3✔
4838
        if ok && val == nil {
6✔
4839
                edge.InboundFee = fn.Some(inboundFee)
3✔
4840
        }
3✔
4841

4842
        return edge, nil
3✔
4843
}
4844

4845
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4846
// KVStore and a kvdb.RTx.
4847
type chanGraphNodeTx struct {
4848
        tx   kvdb.RTx
4849
        db   *KVStore
4850
        node *models.LightningNode
4851
}
4852

4853
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4854
// interface.
4855
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4856

4857
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4858
        node *models.LightningNode) *chanGraphNodeTx {
3✔
4859

3✔
4860
        return &chanGraphNodeTx{
3✔
4861
                tx:   tx,
3✔
4862
                db:   db,
3✔
4863
                node: node,
3✔
4864
        }
3✔
4865
}
3✔
4866

4867
// Node returns the raw information of the node.
4868
//
4869
// NOTE: This is a part of the NodeRTx interface.
4870
func (c *chanGraphNodeTx) Node() *models.LightningNode {
3✔
4871
        return c.node
3✔
4872
}
3✔
4873

4874
// FetchNode fetches the node with the given pub key under the same transaction
4875
// used to fetch the current node. The returned node is also a NodeRTx and any
4876
// operations on that NodeRTx will also be done under the same transaction.
4877
//
4878
// NOTE: This is a part of the NodeRTx interface.
UNCOV
4879
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
×
UNCOV
4880
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
×
UNCOV
4881
        if err != nil {
×
4882
                return nil, err
×
4883
        }
×
4884

UNCOV
4885
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4886
}
4887

4888
// ForEachChannel can be used to iterate over the node's channels under
4889
// the same transaction used to fetch the node.
4890
//
4891
// NOTE: This is a part of the NodeRTx interface.
4892
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
UNCOV
4893
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
×
UNCOV
4894

×
UNCOV
4895
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
×
UNCOV
4896
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
×
UNCOV
4897
                        policy2 *models.ChannelEdgePolicy) error {
×
UNCOV
4898

×
UNCOV
4899
                        return f(info, policy1, policy2)
×
UNCOV
4900
                },
×
4901
        )
4902
}
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