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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 hits per line

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

68.32
/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
        "testing"
16
        "time"
17

18
        "github.com/btcsuite/btcd/btcec/v2"
19
        "github.com/btcsuite/btcd/chaincfg/chainhash"
20
        "github.com/btcsuite/btcd/txscript"
21
        "github.com/btcsuite/btcd/wire"
22
        "github.com/btcsuite/btcwallet/walletdb"
23
        "github.com/lightningnetwork/lnd/aliasmgr"
24
        "github.com/lightningnetwork/lnd/batch"
25
        "github.com/lightningnetwork/lnd/fn/v2"
26
        "github.com/lightningnetwork/lnd/graph/db/models"
27
        "github.com/lightningnetwork/lnd/input"
28
        "github.com/lightningnetwork/lnd/kvdb"
29
        "github.com/lightningnetwork/lnd/lnwire"
30
        "github.com/lightningnetwork/lnd/routing/route"
31
        "github.com/stretchr/testify/require"
32
)
33

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

197
        chanScheduler batch.Scheduler[kvdb.RwTx]
198
        nodeScheduler batch.Scheduler[kvdb.RwTx]
199
}
200

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

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

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

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

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

3✔
235
        return g, nil
3✔
236
}
237

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

244
// String returns a human-readable representation of the key.
245
func (c channelMapKey) String() string {
×
246
        return fmt.Sprintf("node=%v, chanID=%x", c.nodeKey, c.chanID)
×
247
}
×
248

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

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

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

3✔
265
                        return nil
3✔
266
                }
3✔
267

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

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

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

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

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

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

300
                case err != nil:
×
301
                        return err
×
302
                }
303

304
                channelMap[key] = edge
3✔
305

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

312
        return channelMap, nil
3✔
313
}
314

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

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

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

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

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

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

371
        return nil
3✔
372
}
373

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

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

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

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

397
        return true, node.Addresses, nil
3✔
398
}
399

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

3✔
412
        return c.db.View(func(tx kvdb.RTx) error {
6✔
413
                edges := tx.ReadBucket(edgeBucket)
3✔
414
                if edges == nil {
3✔
415
                        return ErrGraphNoEdgesFound
×
416
                }
×
417

418
                // First, load all edges in memory indexed by node and channel
419
                // id.
420
                channelMap, err := c.getChannelMap(edges)
3✔
421
                if err != nil {
3✔
422
                        return err
×
423
                }
×
424

425
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
426
                if edgeIndex == nil {
3✔
427
                        return ErrGraphNoEdgesFound
×
428
                }
×
429

430
                // Load edge index, recombine each channel with the policies
431
                // loaded above and invoke the callback.
432
                return kvdb.ForAll(
3✔
433
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
6✔
434
                                var chanID [8]byte
3✔
435
                                copy(chanID[:], k)
3✔
436

3✔
437
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
438
                                info, err := deserializeChanEdgeInfo(
3✔
439
                                        edgeInfoReader,
3✔
440
                                )
3✔
441
                                if err != nil {
3✔
442
                                        return err
×
443
                                }
×
444

445
                                policy1 := channelMap[channelMapKey{
3✔
446
                                        nodeKey: info.NodeKey1Bytes,
3✔
447
                                        chanID:  chanID,
3✔
448
                                }]
3✔
449

3✔
450
                                policy2 := channelMap[channelMapKey{
3✔
451
                                        nodeKey: info.NodeKey2Bytes,
3✔
452
                                        chanID:  chanID,
3✔
453
                                }]
3✔
454

3✔
455
                                return cb(&info, policy1, policy2)
3✔
456
                        },
457
                )
458
        }, func() {})
3✔
459
}
460

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

3✔
476
        return c.db.View(func(tx kvdb.RTx) error {
6✔
477
                edges := tx.ReadBucket(edgeBucket)
3✔
478
                if edges == nil {
3✔
479
                        return ErrGraphNoEdgesFound
×
480
                }
×
481

482
                // First, load all edges in memory indexed by node and channel
483
                // id.
484
                channelMap, err := c.getChannelMap(edges)
3✔
485
                if err != nil {
3✔
486
                        return err
×
487
                }
×
488

489
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
490
                if edgeIndex == nil {
3✔
491
                        return ErrGraphNoEdgesFound
×
492
                }
×
493

494
                // Load edge index, recombine each channel with the policies
495
                // loaded above and invoke the callback.
496
                return kvdb.ForAll(
3✔
497
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
6✔
498
                                var chanID [8]byte
3✔
499
                                copy(chanID[:], k)
3✔
500

3✔
501
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
502
                                info, err := deserializeChanEdgeInfo(
3✔
503
                                        edgeInfoReader,
3✔
504
                                )
3✔
505
                                if err != nil {
3✔
506
                                        return err
×
507
                                }
×
508

509
                                key1 := channelMapKey{
3✔
510
                                        nodeKey: info.NodeKey1Bytes,
3✔
511
                                        chanID:  chanID,
3✔
512
                                }
3✔
513
                                policy1 := channelMap[key1]
3✔
514

3✔
515
                                key2 := channelMapKey{
3✔
516
                                        nodeKey: info.NodeKey2Bytes,
3✔
517
                                        chanID:  chanID,
3✔
518
                                }
3✔
519
                                policy2 := channelMap[key2]
3✔
520

3✔
521
                                // We now create the cached edge policies, but
3✔
522
                                // only when the above policies are found in the
3✔
523
                                // `channelMap`.
3✔
524
                                var (
3✔
525
                                        cachedPolicy1 *models.CachedEdgePolicy
3✔
526
                                        cachedPolicy2 *models.CachedEdgePolicy
3✔
527
                                )
3✔
528

3✔
529
                                if policy1 != nil {
6✔
530
                                        cachedPolicy1 = models.NewCachedPolicy(
3✔
531
                                                policy1,
3✔
532
                                        )
3✔
533
                                } else {
3✔
534
                                        log.Warnf("ChannelEdgePolicy not "+
×
535
                                                "found using %v", key1)
×
536
                                }
×
537

538
                                if policy2 != nil {
6✔
539
                                        cachedPolicy2 = models.NewCachedPolicy(
3✔
540
                                                policy2,
3✔
541
                                        )
3✔
542
                                } else {
3✔
543
                                        log.Warnf("ChannelEdgePolicy not "+
×
544
                                                "found using %v", key2)
×
545
                                }
×
546

547
                                return cb(
3✔
548
                                        models.NewCachedEdge(&info),
3✔
549
                                        cachedPolicy1, cachedPolicy2,
3✔
550
                                )
3✔
551
                        },
552
                )
553
        }, func() {})
3✔
554
}
555

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

3✔
566
        // Fallback that uses the database.
3✔
567
        toNodeCallback := func() route.Vertex {
6✔
568
                return node
3✔
569
        }
3✔
570
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
571
        if err != nil {
3✔
572
                return err
×
573
        }
×
574

575
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
3✔
576
                p2 *models.ChannelEdgePolicy) error {
6✔
577

3✔
578
                var cachedInPolicy *models.CachedEdgePolicy
3✔
579
                if p2 != nil {
6✔
580
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
581
                        cachedInPolicy.ToNodePubKey = toNodeCallback
3✔
582
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
3✔
583
                }
3✔
584

585
                directedChannel := &DirectedChannel{
3✔
586
                        ChannelID:    e.ChannelID,
3✔
587
                        IsNode1:      node == e.NodeKey1Bytes,
3✔
588
                        OtherNode:    e.NodeKey2Bytes,
3✔
589
                        Capacity:     e.Capacity,
3✔
590
                        OutPolicySet: p1 != nil,
3✔
591
                        InPolicy:     cachedInPolicy,
3✔
592
                }
3✔
593

3✔
594
                if p1 != nil {
6✔
595
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
UNCOV
596
                                directedChannel.InboundFee = fee
×
UNCOV
597
                        })
×
598
                }
599

600
                if node == e.NodeKey2Bytes {
6✔
601
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
602
                }
3✔
603

604
                return cb(directedChannel)
3✔
605
        }
606

607
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
608
}
609

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

3✔
616
        // Fallback that uses the database.
3✔
617
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
618
        switch {
3✔
619
        // If the node exists and has features, return them directly.
620
        case err == nil:
3✔
621
                return targetNode.Features, nil
3✔
622

623
        // If we couldn't find a node announcement, populate a blank feature
624
        // vector.
UNCOV
625
        case errors.Is(err, ErrGraphNodeNotFound):
×
UNCOV
626
                return lnwire.EmptyFeatureVector(), nil
×
627

628
        // Otherwise, bubble the error up.
629
        default:
×
630
                return nil, err
×
631
        }
632
}
633

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

3✔
645
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
3✔
646
}
3✔
647

648
// FetchNodeFeatures returns the features of the given node. If no features are
649
// known for the node, an empty feature vector is returned.
650
//
651
// NOTE: this is part of the graphdb.NodeTraverser interface.
652
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
653
        *lnwire.FeatureVector, error) {
3✔
654

3✔
655
        return c.fetchNodeFeatures(nil, nodePub)
3✔
656
}
3✔
657

658
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
659
// data to the call-back.
660
//
661
// NOTE: The callback contents MUST not be modified.
662
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
UNCOV
663
        chans map[uint64]*DirectedChannel) error) error {
×
UNCOV
664

×
UNCOV
665
        // Otherwise call back to a version that uses the database directly.
×
UNCOV
666
        // We'll iterate over each node, then the set of channels for each
×
UNCOV
667
        // node, and construct a similar callback functiopn signature as the
×
UNCOV
668
        // main funcotin expects.
×
UNCOV
669
        return c.forEachNode(func(tx kvdb.RTx,
×
UNCOV
670
                node *models.LightningNode) error {
×
UNCOV
671

×
UNCOV
672
                channels := make(map[uint64]*DirectedChannel)
×
UNCOV
673

×
UNCOV
674
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
×
UNCOV
675
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
UNCOV
676
                                p1 *models.ChannelEdgePolicy,
×
UNCOV
677
                                p2 *models.ChannelEdgePolicy) error {
×
UNCOV
678

×
UNCOV
679
                                toNodeCallback := func() route.Vertex {
×
680
                                        return node.PubKeyBytes
×
681
                                }
×
UNCOV
682
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
UNCOV
683
                                        tx, node.PubKeyBytes,
×
UNCOV
684
                                )
×
UNCOV
685
                                if err != nil {
×
686
                                        return err
×
687
                                }
×
688

UNCOV
689
                                var cachedInPolicy *models.CachedEdgePolicy
×
UNCOV
690
                                if p2 != nil {
×
UNCOV
691
                                        cachedInPolicy =
×
UNCOV
692
                                                models.NewCachedPolicy(p2)
×
UNCOV
693
                                        cachedInPolicy.ToNodePubKey =
×
UNCOV
694
                                                toNodeCallback
×
UNCOV
695
                                        cachedInPolicy.ToNodeFeatures =
×
UNCOV
696
                                                toNodeFeatures
×
UNCOV
697
                                }
×
698

UNCOV
699
                                directedChannel := &DirectedChannel{
×
UNCOV
700
                                        ChannelID: e.ChannelID,
×
UNCOV
701
                                        IsNode1: node.PubKeyBytes ==
×
UNCOV
702
                                                e.NodeKey1Bytes,
×
UNCOV
703
                                        OtherNode:    e.NodeKey2Bytes,
×
UNCOV
704
                                        Capacity:     e.Capacity,
×
UNCOV
705
                                        OutPolicySet: p1 != nil,
×
UNCOV
706
                                        InPolicy:     cachedInPolicy,
×
UNCOV
707
                                }
×
UNCOV
708

×
UNCOV
709
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
UNCOV
710
                                        directedChannel.OtherNode =
×
UNCOV
711
                                                e.NodeKey1Bytes
×
UNCOV
712
                                }
×
713

UNCOV
714
                                channels[e.ChannelID] = directedChannel
×
UNCOV
715

×
UNCOV
716
                                return nil
×
717
                        })
UNCOV
718
                if err != nil {
×
719
                        return err
×
720
                }
×
721

UNCOV
722
                return cb(node.PubKeyBytes, channels)
×
723
        })
724
}
725

726
// DisabledChannelIDs returns the channel ids of disabled channels.
727
// A channel is disabled when two of the associated ChanelEdgePolicies
728
// have their disabled bit on.
UNCOV
729
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
×
UNCOV
730
        var disabledChanIDs []uint64
×
UNCOV
731
        var chanEdgeFound map[uint64]struct{}
×
UNCOV
732

×
UNCOV
733
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
734
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
735
                if edges == nil {
×
736
                        return ErrGraphNoEdgesFound
×
737
                }
×
738

UNCOV
739
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
UNCOV
740
                        disabledEdgePolicyBucket,
×
UNCOV
741
                )
×
UNCOV
742
                if disabledEdgePolicyIndex == nil {
×
UNCOV
743
                        return nil
×
UNCOV
744
                }
×
745

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

×
UNCOV
759
                                        return nil
×
UNCOV
760
                                }
×
761

UNCOV
762
                                chanEdgeFound[chanID] = struct{}{}
×
UNCOV
763

×
UNCOV
764
                                return nil
×
765
                        },
766
                )
UNCOV
767
        }, func() {
×
UNCOV
768
                disabledChanIDs = nil
×
UNCOV
769
                chanEdgeFound = make(map[uint64]struct{})
×
UNCOV
770
        })
×
UNCOV
771
        if err != nil {
×
772
                return nil, err
×
773
        }
×
774

UNCOV
775
        return disabledChanIDs, nil
×
776
}
777

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

3✔
788
                return cb(newChanGraphNodeTx(tx, c, node))
3✔
789
        })
3✔
790
}
791

792
// forEachNode iterates through all the stored vertices/nodes in the graph,
793
// executing the passed callback with each node encountered. If the callback
794
// returns an error, then the transaction is aborted and the iteration stops
795
// early.
796
//
797
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
798
// traversal when graph gets mega.
799
func (c *KVStore) forEachNode(
800
        cb func(kvdb.RTx, *models.LightningNode) error) error {
3✔
801

3✔
802
        traversal := func(tx kvdb.RTx) error {
6✔
803
                // First grab the nodes bucket which stores the mapping from
3✔
804
                // pubKey to node information.
3✔
805
                nodes := tx.ReadBucket(nodeBucket)
3✔
806
                if nodes == nil {
3✔
807
                        return ErrGraphNotFound
×
808
                }
×
809

810
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
811
                        // If this is the source key, then we skip this
3✔
812
                        // iteration as the value for this key is a pubKey
3✔
813
                        // rather than raw node information.
3✔
814
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
815
                                return nil
3✔
816
                        }
3✔
817

818
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
819
                        node, err := deserializeLightningNode(nodeReader)
3✔
820
                        if err != nil {
3✔
821
                                return err
×
822
                        }
×
823

824
                        // Execute the callback, the transaction will abort if
825
                        // this returns an error.
826
                        return cb(tx, &node)
3✔
827
                })
828
        }
829

830
        return kvdb.View(c.db, traversal, func() {})
6✔
831
}
832

833
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
834
// graph, executing the passed callback with each node encountered. If the
835
// callback returns an error, then the transaction is aborted and the iteration
836
// stops early.
837
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
838
        *lnwire.FeatureVector) error) error {
3✔
839

3✔
840
        traversal := func(tx kvdb.RTx) error {
6✔
841
                // First grab the nodes bucket which stores the mapping from
3✔
842
                // pubKey to node information.
3✔
843
                nodes := tx.ReadBucket(nodeBucket)
3✔
844
                if nodes == nil {
3✔
845
                        return ErrGraphNotFound
×
846
                }
×
847

848
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
849
                        // If this is the source key, then we skip this
3✔
850
                        // iteration as the value for this key is a pubKey
3✔
851
                        // rather than raw node information.
3✔
852
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
853
                                return nil
3✔
854
                        }
3✔
855

856
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
857
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
858
                                nodeReader,
3✔
859
                        )
3✔
860
                        if err != nil {
3✔
861
                                return err
×
862
                        }
×
863

864
                        // Execute the callback, the transaction will abort if
865
                        // this returns an error.
866
                        return cb(node, features)
3✔
867
                })
868
        }
869

870
        return kvdb.View(c.db, traversal, func() {})
6✔
871
}
872

873
// SourceNode returns the source node of the graph. The source node is treated
874
// as the center node within a star-graph. This method may be used to kick off
875
// a path finding algorithm in order to explore the reachability of another
876
// node based off the source node.
877
func (c *KVStore) SourceNode() (*models.LightningNode, error) {
3✔
878
        var source *models.LightningNode
3✔
879
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
880
                // First grab the nodes bucket which stores the mapping from
3✔
881
                // pubKey to node information.
3✔
882
                nodes := tx.ReadBucket(nodeBucket)
3✔
883
                if nodes == nil {
3✔
884
                        return ErrGraphNotFound
×
885
                }
×
886

887
                node, err := c.sourceNode(nodes)
3✔
888
                if err != nil {
3✔
UNCOV
889
                        return err
×
UNCOV
890
                }
×
891
                source = node
3✔
892

3✔
893
                return nil
3✔
894
        }, func() {
3✔
895
                source = nil
3✔
896
        })
3✔
897
        if err != nil {
3✔
UNCOV
898
                return nil, err
×
UNCOV
899
        }
×
900

901
        return source, nil
3✔
902
}
903

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

3✔
911
        selfPub := nodes.Get(sourceKey)
3✔
912
        if selfPub == nil {
3✔
UNCOV
913
                return nil, ErrSourceNodeNotSet
×
UNCOV
914
        }
×
915

916
        // With the pubKey of the source node retrieved, we're able to
917
        // fetch the full node information.
918
        node, err := fetchLightningNode(nodes, selfPub)
3✔
919
        if err != nil {
3✔
920
                return nil, err
×
921
        }
×
922

923
        return &node, nil
3✔
924
}
925

926
// SetSourceNode sets the source node within the graph database. The source
927
// node is to be used as the center of a star-graph within path finding
928
// algorithms.
929
func (c *KVStore) SetSourceNode(node *models.LightningNode) error {
3✔
930
        nodePubBytes := node.PubKeyBytes[:]
3✔
931

3✔
932
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
933
                // First grab the nodes bucket which stores the mapping from
3✔
934
                // pubKey to node information.
3✔
935
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
936
                if err != nil {
3✔
937
                        return err
×
938
                }
×
939

940
                // Next we create the mapping from source to the targeted
941
                // public key.
942
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
3✔
943
                        return err
×
944
                }
×
945

946
                // Finally, we commit the information of the lightning node
947
                // itself.
948
                return addLightningNode(tx, node)
3✔
949
        }, func() {})
3✔
950
}
951

952
// AddLightningNode adds a vertex/node to the graph database. If the node is not
953
// in the database from before, this will add a new, unconnected one to the
954
// graph. If it is present from before, this will update that node's
955
// information. Note that this method is expected to only be called to update an
956
// already present node from a node announcement, or to insert a node found in a
957
// channel update.
958
//
959
// TODO(roasbeef): also need sig of announcement.
960
func (c *KVStore) AddLightningNode(ctx context.Context,
961
        node *models.LightningNode, opts ...batch.SchedulerOption) error {
3✔
962

3✔
963
        r := &batch.Request[kvdb.RwTx]{
3✔
964
                Opts: batch.NewSchedulerOptions(opts...),
3✔
965
                Do: func(tx kvdb.RwTx) error {
6✔
966
                        return addLightningNode(tx, node)
3✔
967
                },
3✔
968
        }
969

970
        return c.nodeScheduler.Execute(ctx, r)
3✔
971
}
972

973
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
974
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
975
        if err != nil {
3✔
976
                return err
×
977
        }
×
978

979
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
980
        if err != nil {
3✔
981
                return err
×
982
        }
×
983

984
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
985
                nodeUpdateIndexBucket,
3✔
986
        )
3✔
987
        if err != nil {
3✔
988
                return err
×
989
        }
×
990

991
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
992
}
993

994
// LookupAlias attempts to return the alias as advertised by the target node.
995
// TODO(roasbeef): currently assumes that aliases are unique...
996
func (c *KVStore) LookupAlias(pub *btcec.PublicKey) (string, error) {
3✔
997
        var alias string
3✔
998

3✔
999
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1000
                nodes := tx.ReadBucket(nodeBucket)
3✔
1001
                if nodes == nil {
3✔
1002
                        return ErrGraphNodesNotFound
×
1003
                }
×
1004

1005
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
3✔
1006
                if aliases == nil {
3✔
1007
                        return ErrGraphNodesNotFound
×
1008
                }
×
1009

1010
                nodePub := pub.SerializeCompressed()
3✔
1011
                a := aliases.Get(nodePub)
3✔
1012
                if a == nil {
3✔
UNCOV
1013
                        return ErrNodeAliasNotFound
×
UNCOV
1014
                }
×
1015

1016
                // TODO(roasbeef): should actually be using the utf-8
1017
                // package...
1018
                alias = string(a)
3✔
1019

3✔
1020
                return nil
3✔
1021
        }, func() {
3✔
1022
                alias = ""
3✔
1023
        })
3✔
1024
        if err != nil {
3✔
UNCOV
1025
                return "", err
×
UNCOV
1026
        }
×
1027

1028
        return alias, nil
3✔
1029
}
1030

1031
// DeleteLightningNode starts a new database transaction to remove a vertex/node
1032
// from the database according to the node's public key.
1033
func (c *KVStore) DeleteLightningNode(_ context.Context,
UNCOV
1034
        nodePub route.Vertex) error {
×
UNCOV
1035

×
UNCOV
1036
        // TODO(roasbeef): ensure dangling edges are removed...
×
UNCOV
1037
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
1038
                nodes := tx.ReadWriteBucket(nodeBucket)
×
UNCOV
1039
                if nodes == nil {
×
1040
                        return ErrGraphNodeNotFound
×
1041
                }
×
1042

UNCOV
1043
                return c.deleteLightningNode(nodes, nodePub[:])
×
UNCOV
1044
        }, func() {})
×
1045
}
1046

1047
// deleteLightningNode uses an existing database transaction to remove a
1048
// vertex/node from the database according to the node's public key.
1049
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
1050
        compressedPubKey []byte) error {
3✔
1051

3✔
1052
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
3✔
1053
        if aliases == nil {
3✔
1054
                return ErrGraphNodesNotFound
×
1055
        }
×
1056

1057
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
1058
                return err
×
1059
        }
×
1060

1061
        // Before we delete the node, we'll fetch its current state so we can
1062
        // determine when its last update was to clear out the node update
1063
        // index.
1064
        node, err := fetchLightningNode(nodes, compressedPubKey)
3✔
1065
        if err != nil {
3✔
UNCOV
1066
                return err
×
UNCOV
1067
        }
×
1068

1069
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
1070
                return err
×
1071
        }
×
1072

1073
        // Finally, we'll delete the index entry for the node within the
1074
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1075
        // need to track its last update.
1076
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
1077
        if nodeUpdateIndex == nil {
3✔
1078
                return ErrGraphNodesNotFound
×
1079
        }
×
1080

1081
        // In order to delete the entry, we'll need to reconstruct the key for
1082
        // its last update.
1083
        updateUnix := uint64(node.LastUpdate.Unix())
3✔
1084
        var indexKey [8 + 33]byte
3✔
1085
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
1086
        copy(indexKey[8:], compressedPubKey)
3✔
1087

3✔
1088
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
1089
}
1090

1091
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1092
// undirected edge from the two target nodes are created. The information stored
1093
// denotes the static attributes of the channel, such as the channelID, the keys
1094
// involved in creation of the channel, and the set of features that the channel
1095
// supports. The chanPoint and chanID are used to uniquely identify the edge
1096
// globally within the database.
1097
func (c *KVStore) AddChannelEdge(edge *models.ChannelEdgeInfo,
1098
        opts ...batch.SchedulerOption) error {
3✔
1099

3✔
1100
        ctx := context.TODO()
3✔
1101

3✔
1102
        var alreadyExists bool
3✔
1103
        r := &batch.Request[kvdb.RwTx]{
3✔
1104
                Opts: batch.NewSchedulerOptions(opts...),
3✔
1105
                Reset: func() {
6✔
1106
                        alreadyExists = false
3✔
1107
                },
3✔
1108
                Do: func(tx kvdb.RwTx) error {
3✔
1109
                        err := c.addChannelEdge(tx, edge)
3✔
1110

3✔
1111
                        // Silence ErrEdgeAlreadyExist so that the batch can
3✔
1112
                        // succeed, but propagate the error via local state.
3✔
1113
                        if errors.Is(err, ErrEdgeAlreadyExist) {
3✔
UNCOV
1114
                                alreadyExists = true
×
UNCOV
1115
                                return nil
×
UNCOV
1116
                        }
×
1117

1118
                        return err
3✔
1119
                },
1120
                OnCommit: func(err error) error {
3✔
1121
                        switch {
3✔
1122
                        case err != nil:
×
1123
                                return err
×
UNCOV
1124
                        case alreadyExists:
×
UNCOV
1125
                                return ErrEdgeAlreadyExist
×
1126
                        default:
3✔
1127
                                c.rejectCache.remove(edge.ChannelID)
3✔
1128
                                c.chanCache.remove(edge.ChannelID)
3✔
1129
                                return nil
3✔
1130
                        }
1131
                },
1132
        }
1133

1134
        return c.chanScheduler.Execute(ctx, r)
3✔
1135
}
1136

1137
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1138
// utilize an existing db transaction.
1139
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1140
        edge *models.ChannelEdgeInfo) error {
3✔
1141

3✔
1142
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1143
        var chanKey [8]byte
3✔
1144
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1145

3✔
1146
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1147
        if err != nil {
3✔
1148
                return err
×
1149
        }
×
1150
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1151
        if err != nil {
3✔
1152
                return err
×
1153
        }
×
1154
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1155
        if err != nil {
3✔
1156
                return err
×
1157
        }
×
1158
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1159
        if err != nil {
3✔
1160
                return err
×
1161
        }
×
1162

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

1169
        // Before we insert the channel into the database, we'll ensure that
1170
        // both nodes already exist in the channel graph. If either node
1171
        // doesn't, then we'll insert a "shell" node that just includes its
1172
        // public key, so subsequent validation and queries can work properly.
1173
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
3✔
1174
        switch {
3✔
1175
        case errors.Is(node1Err, ErrGraphNodeNotFound):
3✔
1176
                node1Shell := models.LightningNode{
3✔
1177
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1178
                        HaveNodeAnnouncement: false,
3✔
1179
                }
3✔
1180
                err := addLightningNode(tx, &node1Shell)
3✔
1181
                if err != nil {
3✔
1182
                        return fmt.Errorf("unable to create shell node "+
×
1183
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1184
                }
×
1185
        case node1Err != nil:
×
1186
                return node1Err
×
1187
        }
1188

1189
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
1190
        switch {
3✔
1191
        case errors.Is(node2Err, ErrGraphNodeNotFound):
3✔
1192
                node2Shell := models.LightningNode{
3✔
1193
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1194
                        HaveNodeAnnouncement: false,
3✔
1195
                }
3✔
1196
                err := addLightningNode(tx, &node2Shell)
3✔
1197
                if err != nil {
3✔
1198
                        return fmt.Errorf("unable to create shell node "+
×
1199
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1200
                }
×
1201
        case node2Err != nil:
×
1202
                return node2Err
×
1203
        }
1204

1205
        // If the edge hasn't been created yet, then we'll first add it to the
1206
        // edge index in order to associate the edge between two nodes and also
1207
        // store the static components of the channel.
1208
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1209
                return err
×
1210
        }
×
1211

1212
        // Mark edge policies for both sides as unknown. This is to enable
1213
        // efficient incoming channel lookup for a node.
1214
        keys := []*[33]byte{
3✔
1215
                &edge.NodeKey1Bytes,
3✔
1216
                &edge.NodeKey2Bytes,
3✔
1217
        }
3✔
1218
        for _, key := range keys {
6✔
1219
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1220
                if err != nil {
3✔
1221
                        return err
×
1222
                }
×
1223
        }
1224

1225
        // Finally we add it to the channel index which maps channel points
1226
        // (outpoints) to the shorter channel ID's.
1227
        var b bytes.Buffer
3✔
1228
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1229
                return err
×
1230
        }
×
1231

1232
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1233
}
1234

1235
// HasChannelEdge returns true if the database knows of a channel edge with the
1236
// passed channel ID, and false otherwise. If an edge with that ID is found
1237
// within the graph, then two time stamps representing the last time the edge
1238
// was updated for both directed edges are returned along with the boolean. If
1239
// it is not found, then the zombie index is checked and its result is returned
1240
// as the second boolean.
1241
func (c *KVStore) HasChannelEdge(
1242
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1243

3✔
1244
        var (
3✔
1245
                upd1Time time.Time
3✔
1246
                upd2Time time.Time
3✔
1247
                exists   bool
3✔
1248
                isZombie bool
3✔
1249
        )
3✔
1250

3✔
1251
        // We'll query the cache with the shared lock held to allow multiple
3✔
1252
        // readers to access values in the cache concurrently if they exist.
3✔
1253
        c.cacheMu.RLock()
3✔
1254
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1255
                c.cacheMu.RUnlock()
3✔
1256
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1257
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1258
                exists, isZombie = entry.flags.unpack()
3✔
1259

3✔
1260
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1261
        }
3✔
1262
        c.cacheMu.RUnlock()
3✔
1263

3✔
1264
        c.cacheMu.Lock()
3✔
1265
        defer c.cacheMu.Unlock()
3✔
1266

3✔
1267
        // The item was not found with the shared lock, so we'll acquire the
3✔
1268
        // exclusive lock and check the cache again in case another method added
3✔
1269
        // the entry to the cache while no lock was held.
3✔
1270
        if entry, ok := c.rejectCache.get(chanID); ok {
5✔
1271
                upd1Time = time.Unix(entry.upd1Time, 0)
2✔
1272
                upd2Time = time.Unix(entry.upd2Time, 0)
2✔
1273
                exists, isZombie = entry.flags.unpack()
2✔
1274

2✔
1275
                return upd1Time, upd2Time, exists, isZombie, nil
2✔
1276
        }
2✔
1277

1278
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1279
                edges := tx.ReadBucket(edgeBucket)
3✔
1280
                if edges == nil {
3✔
1281
                        return ErrGraphNoEdgesFound
×
1282
                }
×
1283
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1284
                if edgeIndex == nil {
3✔
1285
                        return ErrGraphNoEdgesFound
×
1286
                }
×
1287

1288
                var channelID [8]byte
3✔
1289
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1290

3✔
1291
                // If the edge doesn't exist, then we'll also check our zombie
3✔
1292
                // index.
3✔
1293
                if edgeIndex.Get(channelID[:]) == nil {
6✔
1294
                        exists = false
3✔
1295
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1296
                        if zombieIndex != nil {
6✔
1297
                                isZombie, _, _ = isZombieEdge(
3✔
1298
                                        zombieIndex, chanID,
3✔
1299
                                )
3✔
1300
                        }
3✔
1301

1302
                        return nil
3✔
1303
                }
1304

1305
                exists = true
3✔
1306
                isZombie = false
3✔
1307

3✔
1308
                // If the channel has been found in the graph, then retrieve
3✔
1309
                // the edges itself so we can return the last updated
3✔
1310
                // timestamps.
3✔
1311
                nodes := tx.ReadBucket(nodeBucket)
3✔
1312
                if nodes == nil {
3✔
1313
                        return ErrGraphNodeNotFound
×
1314
                }
×
1315

1316
                e1, e2, err := fetchChanEdgePolicies(
3✔
1317
                        edgeIndex, edges, channelID[:],
3✔
1318
                )
3✔
1319
                if err != nil {
3✔
1320
                        return err
×
1321
                }
×
1322

1323
                // As we may have only one of the edges populated, only set the
1324
                // update time if the edge was found in the database.
1325
                if e1 != nil {
6✔
1326
                        upd1Time = e1.LastUpdate
3✔
1327
                }
3✔
1328
                if e2 != nil {
6✔
1329
                        upd2Time = e2.LastUpdate
3✔
1330
                }
3✔
1331

1332
                return nil
3✔
1333
        }, func() {}); err != nil {
3✔
1334
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1335
        }
×
1336

1337
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1338
                upd1Time: upd1Time.Unix(),
3✔
1339
                upd2Time: upd2Time.Unix(),
3✔
1340
                flags:    packRejectFlags(exists, isZombie),
3✔
1341
        })
3✔
1342

3✔
1343
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1344
}
1345

1346
// AddEdgeProof sets the proof of an existing edge in the graph database.
1347
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1348
        proof *models.ChannelAuthProof) error {
3✔
1349

3✔
1350
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1351
        var chanKey [8]byte
3✔
1352
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1353

3✔
1354
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1355
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1356
                if edges == nil {
3✔
1357
                        return ErrEdgeNotFound
×
1358
                }
×
1359

1360
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1361
                if edgeIndex == nil {
3✔
1362
                        return ErrEdgeNotFound
×
1363
                }
×
1364

1365
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1366
                if err != nil {
3✔
1367
                        return err
×
1368
                }
×
1369

1370
                edge.AuthProof = proof
3✔
1371

3✔
1372
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1373
        }, func() {})
3✔
1374
}
1375

1376
const (
1377
        // pruneTipBytes is the total size of the value which stores a prune
1378
        // entry of the graph in the prune log. The "prune tip" is the last
1379
        // entry in the prune log, and indicates if the channel graph is in
1380
        // sync with the current UTXO state. The structure of the value
1381
        // is: blockHash, taking 32 bytes total.
1382
        pruneTipBytes = 32
1383
)
1384

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

3✔
1397
        c.cacheMu.Lock()
3✔
1398
        defer c.cacheMu.Unlock()
3✔
1399

3✔
1400
        var (
3✔
1401
                chansClosed []*models.ChannelEdgeInfo
3✔
1402
                prunedNodes []route.Vertex
3✔
1403
        )
3✔
1404

3✔
1405
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1406
                // First grab the edges bucket which houses the information
3✔
1407
                // we'd like to delete
3✔
1408
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1409
                if err != nil {
3✔
1410
                        return err
×
1411
                }
×
1412

1413
                // Next grab the two edge indexes which will also need to be
1414
                // updated.
1415
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1416
                if err != nil {
3✔
1417
                        return err
×
1418
                }
×
1419
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1420
                        channelPointBucket,
3✔
1421
                )
3✔
1422
                if err != nil {
3✔
1423
                        return err
×
1424
                }
×
1425
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1426
                if nodes == nil {
3✔
1427
                        return ErrSourceNodeNotSet
×
1428
                }
×
1429
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1430
                if err != nil {
3✔
1431
                        return err
×
1432
                }
×
1433

1434
                // For each of the outpoints that have been spent within the
1435
                // block, we attempt to delete them from the graph as if that
1436
                // outpoint was a channel, then it has now been closed.
1437
                for _, chanPoint := range spentOutputs {
6✔
1438
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1439
                        // if NOT if filter
3✔
1440

3✔
1441
                        var opBytes bytes.Buffer
3✔
1442
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1443
                        if err != nil {
3✔
1444
                                return err
×
1445
                        }
×
1446

1447
                        // First attempt to see if the channel exists within
1448
                        // the database, if not, then we can exit early.
1449
                        chanID := chanIndex.Get(opBytes.Bytes())
3✔
1450
                        if chanID == nil {
3✔
UNCOV
1451
                                continue
×
1452
                        }
1453

1454
                        // Attempt to delete the channel, an ErrEdgeNotFound
1455
                        // will be returned if that outpoint isn't known to be
1456
                        // a channel. If no error is returned, then a channel
1457
                        // was successfully pruned.
1458
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1459
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1460
                                chanID, false, false,
3✔
1461
                        )
3✔
1462
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1463
                                return err
×
1464
                        }
×
1465

1466
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1467
                }
1468

1469
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1470
                if err != nil {
3✔
1471
                        return err
×
1472
                }
×
1473

1474
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1475
                        pruneLogBucket,
3✔
1476
                )
3✔
1477
                if err != nil {
3✔
1478
                        return err
×
1479
                }
×
1480

1481
                // With the graph pruned, add a new entry to the prune log,
1482
                // which can be used to check if the graph is fully synced with
1483
                // the current UTXO state.
1484
                var blockHeightBytes [4]byte
3✔
1485
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
3✔
1486

3✔
1487
                var newTip [pruneTipBytes]byte
3✔
1488
                copy(newTip[:], blockHash[:])
3✔
1489

3✔
1490
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1491
                if err != nil {
3✔
1492
                        return err
×
1493
                }
×
1494

1495
                // Now that the graph has been pruned, we'll also attempt to
1496
                // prune any nodes that have had a channel closed within the
1497
                // latest block.
1498
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1499

3✔
1500
                return err
3✔
1501
        }, func() {
3✔
1502
                chansClosed = nil
3✔
1503
                prunedNodes = nil
3✔
1504
        })
3✔
1505
        if err != nil {
3✔
1506
                return nil, nil, err
×
1507
        }
×
1508

1509
        for _, channel := range chansClosed {
6✔
1510
                c.rejectCache.remove(channel.ChannelID)
3✔
1511
                c.chanCache.remove(channel.ChannelID)
3✔
1512
        }
3✔
1513

1514
        return chansClosed, prunedNodes, nil
3✔
1515
}
1516

1517
// PruneGraphNodes is a garbage collection method which attempts to prune out
1518
// any nodes from the channel graph that are currently unconnected. This ensure
1519
// that we only maintain a graph of reachable nodes. In the event that a pruned
1520
// node gains more channels, it will be re-added back to the graph.
1521
func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error) {
3✔
1522
        var prunedNodes []route.Vertex
3✔
1523
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1524
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1525
                if nodes == nil {
3✔
1526
                        return ErrGraphNodesNotFound
×
1527
                }
×
1528
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1529
                if edges == nil {
3✔
1530
                        return ErrGraphNotFound
×
1531
                }
×
1532
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1533
                if edgeIndex == nil {
3✔
1534
                        return ErrGraphNoEdgesFound
×
1535
                }
×
1536

1537
                var err error
3✔
1538
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1539
                if err != nil {
3✔
1540
                        return err
×
1541
                }
×
1542

1543
                return nil
3✔
1544
        }, func() {
3✔
1545
                prunedNodes = nil
3✔
1546
        })
3✔
1547

1548
        return prunedNodes, err
3✔
1549
}
1550

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

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

3✔
1559
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1560
        // even if it no longer has any open channels.
3✔
1561
        sourceNode, err := c.sourceNode(nodes)
3✔
1562
        if err != nil {
3✔
1563
                return nil, err
×
1564
        }
×
1565

1566
        // We'll use this map to keep count the number of references to a node
1567
        // in the graph. A node should only be removed once it has no more
1568
        // references in the graph.
1569
        nodeRefCounts := make(map[[33]byte]int)
3✔
1570
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1571
                // If this is the source key, then we skip this
3✔
1572
                // iteration as the value for this key is a pubKey
3✔
1573
                // rather than raw node information.
3✔
1574
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1575
                        return nil
3✔
1576
                }
3✔
1577

1578
                var nodePub [33]byte
3✔
1579
                copy(nodePub[:], pubKey)
3✔
1580
                nodeRefCounts[nodePub] = 0
3✔
1581

3✔
1582
                return nil
3✔
1583
        })
1584
        if err != nil {
3✔
1585
                return nil, err
×
1586
        }
×
1587

1588
        // To ensure we never delete the source node, we'll start off by
1589
        // bumping its ref count to 1.
1590
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1591

3✔
1592
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1593
        // edge info. We'll use this scan to populate our reference count map
3✔
1594
        // above.
3✔
1595
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
6✔
1596
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1597
                // the nodes that this edge attaches. We'll extract them, and
3✔
1598
                // add them to the ref count map.
3✔
1599
                var node1, node2 [33]byte
3✔
1600
                copy(node1[:], edgeInfoBytes[:33])
3✔
1601
                copy(node2[:], edgeInfoBytes[33:])
3✔
1602

3✔
1603
                // With the nodes extracted, we'll increase the ref count of
3✔
1604
                // each of the nodes.
3✔
1605
                nodeRefCounts[node1]++
3✔
1606
                nodeRefCounts[node2]++
3✔
1607

3✔
1608
                return nil
3✔
1609
        })
3✔
1610
        if err != nil {
3✔
1611
                return nil, err
×
1612
        }
×
1613

1614
        // Finally, we'll make a second pass over the set of nodes, and delete
1615
        // any nodes that have a ref count of zero.
1616
        var pruned []route.Vertex
3✔
1617
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1618
                // If the ref count of the node isn't zero, then we can safely
3✔
1619
                // skip it as it still has edges to or from it within the
3✔
1620
                // graph.
3✔
1621
                if refCount != 0 {
6✔
1622
                        continue
3✔
1623
                }
1624

1625
                // If we reach this point, then there are no longer any edges
1626
                // that connect this node, so we can delete it.
1627
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1628
                if err != nil {
3✔
1629
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1630
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1631

×
1632
                                log.Warnf("Unable to prune node %x from the "+
×
1633
                                        "graph: %v", nodePubKey, err)
×
1634
                                continue
×
1635
                        }
1636

1637
                        return nil, err
×
1638
                }
1639

1640
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1641
                        nodePubKey[:])
3✔
1642

3✔
1643
                pruned = append(pruned, nodePubKey)
3✔
1644
        }
1645

1646
        if len(pruned) > 0 {
6✔
1647
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1648
                        len(pruned))
3✔
1649
        }
3✔
1650

1651
        return pruned, err
3✔
1652
}
1653

1654
// DisconnectBlockAtHeight is used to indicate that the block specified
1655
// by the passed height has been disconnected from the main chain. This
1656
// will "rewind" the graph back to the height below, deleting channels
1657
// that are no longer confirmed from the graph. The prune log will be
1658
// set to the last prune height valid for the remaining chain.
1659
// Channels that were removed from the graph resulting from the
1660
// disconnected block are returned.
1661
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1662
        []*models.ChannelEdgeInfo, error) {
2✔
1663

2✔
1664
        // Every channel having a ShortChannelID starting at 'height'
2✔
1665
        // will no longer be confirmed.
2✔
1666
        startShortChanID := lnwire.ShortChannelID{
2✔
1667
                BlockHeight: height,
2✔
1668
        }
2✔
1669

2✔
1670
        // Delete everything after this height from the db up until the
2✔
1671
        // SCID alias range.
2✔
1672
        endShortChanID := aliasmgr.StartingAlias
2✔
1673

2✔
1674
        // The block height will be the 3 first bytes of the channel IDs.
2✔
1675
        var chanIDStart [8]byte
2✔
1676
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
2✔
1677
        var chanIDEnd [8]byte
2✔
1678
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
2✔
1679

2✔
1680
        c.cacheMu.Lock()
2✔
1681
        defer c.cacheMu.Unlock()
2✔
1682

2✔
1683
        // Keep track of the channels that are removed from the graph.
2✔
1684
        var removedChans []*models.ChannelEdgeInfo
2✔
1685

2✔
1686
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
4✔
1687
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
2✔
1688
                if err != nil {
2✔
1689
                        return err
×
1690
                }
×
1691
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
2✔
1692
                if err != nil {
2✔
1693
                        return err
×
1694
                }
×
1695
                chanIndex, err := edges.CreateBucketIfNotExists(
2✔
1696
                        channelPointBucket,
2✔
1697
                )
2✔
1698
                if err != nil {
2✔
1699
                        return err
×
1700
                }
×
1701
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
2✔
1702
                if err != nil {
2✔
1703
                        return err
×
1704
                }
×
1705

1706
                // Scan from chanIDStart to chanIDEnd, deleting every
1707
                // found edge.
1708
                // NOTE: we must delete the edges after the cursor loop, since
1709
                // modifying the bucket while traversing is not safe.
1710
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1711
                // so that the StartingAlias itself isn't deleted.
1712
                var keys [][]byte
2✔
1713
                cursor := edgeIndex.ReadWriteCursor()
2✔
1714

2✔
1715
                //nolint:ll
2✔
1716
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
2✔
1717
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
4✔
1718
                        keys = append(keys, k)
2✔
1719
                }
2✔
1720

1721
                for _, k := range keys {
4✔
1722
                        edgeInfo, err := c.delChannelEdgeUnsafe(
2✔
1723
                                edges, edgeIndex, chanIndex, zombieIndex,
2✔
1724
                                k, false, false,
2✔
1725
                        )
2✔
1726
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
2✔
1727
                                return err
×
1728
                        }
×
1729

1730
                        removedChans = append(removedChans, edgeInfo)
2✔
1731
                }
1732

1733
                // Delete all the entries in the prune log having a height
1734
                // greater or equal to the block disconnected.
1735
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
2✔
1736
                if err != nil {
2✔
1737
                        return err
×
1738
                }
×
1739

1740
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1741
                        pruneLogBucket,
2✔
1742
                )
2✔
1743
                if err != nil {
2✔
1744
                        return err
×
1745
                }
×
1746

1747
                var pruneKeyStart [4]byte
2✔
1748
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1749

2✔
1750
                var pruneKeyEnd [4]byte
2✔
1751
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1752

2✔
1753
                // To avoid modifying the bucket while traversing, we delete
2✔
1754
                // the keys in a second loop.
2✔
1755
                var pruneKeys [][]byte
2✔
1756
                pruneCursor := pruneBucket.ReadWriteCursor()
2✔
1757
                //nolint:ll
2✔
1758
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
2✔
1759
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
4✔
1760
                        pruneKeys = append(pruneKeys, k)
2✔
1761
                }
2✔
1762

1763
                for _, k := range pruneKeys {
4✔
1764
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1765
                                return err
×
1766
                        }
×
1767
                }
1768

1769
                return nil
2✔
1770
        }, func() {
2✔
1771
                removedChans = nil
2✔
1772
        }); err != nil {
2✔
1773
                return nil, err
×
1774
        }
×
1775

1776
        for _, channel := range removedChans {
4✔
1777
                c.rejectCache.remove(channel.ChannelID)
2✔
1778
                c.chanCache.remove(channel.ChannelID)
2✔
1779
        }
2✔
1780

1781
        return removedChans, nil
2✔
1782
}
1783

1784
// PruneTip returns the block height and hash of the latest block that has been
1785
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1786
// to tell if the graph is currently in sync with the current best known UTXO
1787
// state.
1788
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
3✔
1789
        var (
3✔
1790
                tipHash   chainhash.Hash
3✔
1791
                tipHeight uint32
3✔
1792
        )
3✔
1793

3✔
1794
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1795
                graphMeta := tx.ReadBucket(graphMetaBucket)
3✔
1796
                if graphMeta == nil {
3✔
1797
                        return ErrGraphNotFound
×
1798
                }
×
1799
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
3✔
1800
                if pruneBucket == nil {
3✔
1801
                        return ErrGraphNeverPruned
×
1802
                }
×
1803

1804
                pruneCursor := pruneBucket.ReadCursor()
3✔
1805

3✔
1806
                // The prune key with the largest block height will be our
3✔
1807
                // prune tip.
3✔
1808
                k, v := pruneCursor.Last()
3✔
1809
                if k == nil {
6✔
1810
                        return ErrGraphNeverPruned
3✔
1811
                }
3✔
1812

1813
                // Once we have the prune tip, the value will be the block hash,
1814
                // and the key the block height.
1815
                copy(tipHash[:], v)
3✔
1816
                tipHeight = byteOrder.Uint32(k)
3✔
1817

3✔
1818
                return nil
3✔
1819
        }, func() {})
3✔
1820
        if err != nil {
6✔
1821
                return nil, 0, err
3✔
1822
        }
3✔
1823

1824
        return &tipHash, tipHeight, nil
3✔
1825
}
1826

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

3✔
1838
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1839
        // channels
3✔
1840
        // TODO(roasbeef): don't delete both edges?
3✔
1841

3✔
1842
        c.cacheMu.Lock()
3✔
1843
        defer c.cacheMu.Unlock()
3✔
1844

3✔
1845
        var infos []*models.ChannelEdgeInfo
3✔
1846
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1847
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1848
                if edges == nil {
3✔
1849
                        return ErrEdgeNotFound
×
1850
                }
×
1851
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1852
                if edgeIndex == nil {
3✔
1853
                        return ErrEdgeNotFound
×
1854
                }
×
1855
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
3✔
1856
                if chanIndex == nil {
3✔
1857
                        return ErrEdgeNotFound
×
1858
                }
×
1859
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1860
                if nodes == nil {
3✔
1861
                        return ErrGraphNodeNotFound
×
1862
                }
×
1863
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1864
                if err != nil {
3✔
1865
                        return err
×
1866
                }
×
1867

1868
                var rawChanID [8]byte
3✔
1869
                for _, chanID := range chanIDs {
6✔
1870
                        byteOrder.PutUint64(rawChanID[:], chanID)
3✔
1871
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1872
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1873
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1874
                        )
3✔
1875
                        if err != nil {
3✔
UNCOV
1876
                                return err
×
UNCOV
1877
                        }
×
1878

1879
                        infos = append(infos, edgeInfo)
3✔
1880
                }
1881

1882
                return nil
3✔
1883
        }, func() {
3✔
1884
                infos = nil
3✔
1885
        })
3✔
1886
        if err != nil {
3✔
UNCOV
1887
                return nil, err
×
UNCOV
1888
        }
×
1889

1890
        for _, chanID := range chanIDs {
6✔
1891
                c.rejectCache.remove(chanID)
3✔
1892
                c.chanCache.remove(chanID)
3✔
1893
        }
3✔
1894

1895
        return infos, nil
3✔
1896
}
1897

1898
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1899
// passed channel point (outpoint). If the passed channel doesn't exist within
1900
// the database, then ErrEdgeNotFound is returned.
1901
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1902
        var chanID uint64
3✔
1903
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1904
                var err error
3✔
1905
                chanID, err = getChanID(tx, chanPoint)
3✔
1906
                return err
3✔
1907
        }, func() {
6✔
1908
                chanID = 0
3✔
1909
        }); err != nil {
6✔
1910
                return 0, err
3✔
1911
        }
3✔
1912

1913
        return chanID, nil
3✔
1914
}
1915

1916
// getChanID returns the assigned channel ID for a given channel point.
1917
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1918
        var b bytes.Buffer
3✔
1919
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1920
                return 0, err
×
1921
        }
×
1922

1923
        edges := tx.ReadBucket(edgeBucket)
3✔
1924
        if edges == nil {
3✔
1925
                return 0, ErrGraphNoEdgesFound
×
1926
        }
×
1927
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1928
        if chanIndex == nil {
3✔
1929
                return 0, ErrGraphNoEdgesFound
×
1930
        }
×
1931

1932
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1933
        if chanIDBytes == nil {
6✔
1934
                return 0, ErrEdgeNotFound
3✔
1935
        }
3✔
1936

1937
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1938

3✔
1939
        return chanID, nil
3✔
1940
}
1941

1942
// TODO(roasbeef): allow updates to use Batch?
1943

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

3✔
1950
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1951
                edges := tx.ReadBucket(edgeBucket)
3✔
1952
                if edges == nil {
3✔
1953
                        return ErrGraphNoEdgesFound
×
1954
                }
×
1955
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1956
                if edgeIndex == nil {
3✔
1957
                        return ErrGraphNoEdgesFound
×
1958
                }
×
1959

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

3✔
1964
                lastChanID, _ := cidCursor.Last()
3✔
1965

3✔
1966
                // If there's no key, then this means that we don't actually
3✔
1967
                // know of any channels, so we'll return a predicable error.
3✔
1968
                if lastChanID == nil {
6✔
1969
                        return ErrGraphNoEdgesFound
3✔
1970
                }
3✔
1971

1972
                // Otherwise, we'll de serialize the channel ID and return it
1973
                // to the caller.
1974
                cid = byteOrder.Uint64(lastChanID)
3✔
1975

3✔
1976
                return nil
3✔
1977
        }, func() {
3✔
1978
                cid = 0
3✔
1979
        })
3✔
1980
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
3✔
1981
                return 0, err
×
1982
        }
×
1983

1984
        return cid, nil
3✔
1985
}
1986

1987
// ChannelEdge represents the complete set of information for a channel edge in
1988
// the known channel graph. This struct couples the core information of the
1989
// edge as well as each of the known advertised edge policies.
1990
type ChannelEdge struct {
1991
        // Info contains all the static information describing the channel.
1992
        Info *models.ChannelEdgeInfo
1993

1994
        // Policy1 points to the "first" edge policy of the channel containing
1995
        // the dynamic information required to properly route through the edge.
1996
        Policy1 *models.ChannelEdgePolicy
1997

1998
        // Policy2 points to the "second" edge policy of the channel containing
1999
        // the dynamic information required to properly route through the edge.
2000
        Policy2 *models.ChannelEdgePolicy
2001

2002
        // Node1 is "node 1" in the channel. This is the node that would have
2003
        // produced Policy1 if it exists.
2004
        Node1 *models.LightningNode
2005

2006
        // Node2 is "node 2" in the channel. This is the node that would have
2007
        // produced Policy2 if it exists.
2008
        Node2 *models.LightningNode
2009
}
2010

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

3✔
2016
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
2017
        // additional map to keep track of the edges already seen to prevent
3✔
2018
        // re-adding it.
3✔
2019
        var edgesSeen map[uint64]struct{}
3✔
2020
        var edgesToCache map[uint64]ChannelEdge
3✔
2021
        var edgesInHorizon []ChannelEdge
3✔
2022

3✔
2023
        c.cacheMu.Lock()
3✔
2024
        defer c.cacheMu.Unlock()
3✔
2025

3✔
2026
        var hits int
3✔
2027
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2028
                edges := tx.ReadBucket(edgeBucket)
3✔
2029
                if edges == nil {
3✔
2030
                        return ErrGraphNoEdgesFound
×
2031
                }
×
2032
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2033
                if edgeIndex == nil {
3✔
2034
                        return ErrGraphNoEdgesFound
×
2035
                }
×
2036
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
3✔
2037
                if edgeUpdateIndex == nil {
3✔
2038
                        return ErrGraphNoEdgesFound
×
2039
                }
×
2040

2041
                nodes := tx.ReadBucket(nodeBucket)
3✔
2042
                if nodes == nil {
3✔
2043
                        return ErrGraphNodesNotFound
×
2044
                }
×
2045

2046
                // We'll now obtain a cursor to perform a range query within
2047
                // the index to find all channels within the horizon.
2048
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
2049

3✔
2050
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
2051
                byteOrder.PutUint64(
3✔
2052
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2053
                )
3✔
2054
                byteOrder.PutUint64(
3✔
2055
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2056
                )
3✔
2057

3✔
2058
                // With our start and end times constructed, we'll step through
3✔
2059
                // the index collecting the info and policy of each update of
3✔
2060
                // each channel that has a last update within the time range.
3✔
2061
                //
3✔
2062
                //nolint:ll
3✔
2063
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2064
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2065
                        // We have a new eligible entry, so we'll slice of the
3✔
2066
                        // chan ID so we can query it in the DB.
3✔
2067
                        chanID := indexKey[8:]
3✔
2068

3✔
2069
                        // If we've already retrieved the info and policies for
3✔
2070
                        // this edge, then we can skip it as we don't need to do
3✔
2071
                        // so again.
3✔
2072
                        chanIDInt := byteOrder.Uint64(chanID)
3✔
2073
                        if _, ok := edgesSeen[chanIDInt]; ok {
3✔
UNCOV
2074
                                continue
×
2075
                        }
2076

2077
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
2078
                                hits++
3✔
2079
                                edgesSeen[chanIDInt] = struct{}{}
3✔
2080
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
2081

3✔
2082
                                continue
3✔
2083
                        }
2084

2085
                        // First, we'll fetch the static edge information.
2086
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2087
                        if err != nil {
3✔
2088
                                chanID := byteOrder.Uint64(chanID)
×
2089
                                return fmt.Errorf("unable to fetch info for "+
×
2090
                                        "edge with chan_id=%v: %v", chanID, err)
×
2091
                        }
×
2092

2093
                        // With the static information obtained, we'll now
2094
                        // fetch the dynamic policy info.
2095
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2096
                                edgeIndex, edges, chanID,
3✔
2097
                        )
3✔
2098
                        if err != nil {
3✔
2099
                                chanID := byteOrder.Uint64(chanID)
×
2100
                                return fmt.Errorf("unable to fetch policies "+
×
2101
                                        "for edge with chan_id=%v: %v", chanID,
×
2102
                                        err)
×
2103
                        }
×
2104

2105
                        node1, err := fetchLightningNode(
3✔
2106
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2107
                        )
3✔
2108
                        if err != nil {
3✔
2109
                                return err
×
2110
                        }
×
2111

2112
                        node2, err := fetchLightningNode(
3✔
2113
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2114
                        )
3✔
2115
                        if err != nil {
3✔
2116
                                return err
×
2117
                        }
×
2118

2119
                        // Finally, we'll collate this edge with the rest of
2120
                        // edges to be returned.
2121
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2122
                        channel := ChannelEdge{
3✔
2123
                                Info:    &edgeInfo,
3✔
2124
                                Policy1: edge1,
3✔
2125
                                Policy2: edge2,
3✔
2126
                                Node1:   &node1,
3✔
2127
                                Node2:   &node2,
3✔
2128
                        }
3✔
2129
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2130
                        edgesToCache[chanIDInt] = channel
3✔
2131
                }
2132

2133
                return nil
3✔
2134
        }, func() {
3✔
2135
                edgesSeen = make(map[uint64]struct{})
3✔
2136
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2137
                edgesInHorizon = nil
3✔
2138
        })
3✔
2139
        switch {
3✔
2140
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2141
                fallthrough
×
2142
        case errors.Is(err, ErrGraphNodesNotFound):
×
2143
                break
×
2144

2145
        case err != nil:
×
2146
                return nil, err
×
2147
        }
2148

2149
        // Insert any edges loaded from disk into the cache.
2150
        for chanid, channel := range edgesToCache {
6✔
2151
                c.chanCache.insert(chanid, channel)
3✔
2152
        }
3✔
2153

2154
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
3✔
2155
                float64(hits)/float64(len(edgesInHorizon)), hits,
3✔
2156
                len(edgesInHorizon))
3✔
2157

3✔
2158
        return edgesInHorizon, nil
3✔
2159
}
2160

2161
// NodeUpdatesInHorizon returns all the known lightning node which have an
2162
// update timestamp within the passed range. This method can be used by two
2163
// nodes to quickly determine if they have the same set of up to date node
2164
// announcements.
2165
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2166
        endTime time.Time) ([]models.LightningNode, error) {
3✔
2167

3✔
2168
        var nodesInHorizon []models.LightningNode
3✔
2169

3✔
2170
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2171
                nodes := tx.ReadBucket(nodeBucket)
3✔
2172
                if nodes == nil {
3✔
2173
                        return ErrGraphNodesNotFound
×
2174
                }
×
2175

2176
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2177
                if nodeUpdateIndex == nil {
3✔
2178
                        return ErrGraphNodesNotFound
×
2179
                }
×
2180

2181
                // We'll now obtain a cursor to perform a range query within
2182
                // the index to find all node announcements within the horizon.
2183
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2184

3✔
2185
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2186
                byteOrder.PutUint64(
3✔
2187
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2188
                )
3✔
2189
                byteOrder.PutUint64(
3✔
2190
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2191
                )
3✔
2192

3✔
2193
                // With our start and end times constructed, we'll step through
3✔
2194
                // the index collecting info for each node within the time
3✔
2195
                // range.
3✔
2196
                //
3✔
2197
                //nolint:ll
3✔
2198
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2199
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2200
                        nodePub := indexKey[8:]
3✔
2201
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2202
                        if err != nil {
3✔
2203
                                return err
×
2204
                        }
×
2205

2206
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2207
                }
2208

2209
                return nil
3✔
2210
        }, func() {
3✔
2211
                nodesInHorizon = nil
3✔
2212
        })
3✔
2213
        switch {
3✔
2214
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2215
                fallthrough
×
2216
        case errors.Is(err, ErrGraphNodesNotFound):
×
2217
                break
×
2218

2219
        case err != nil:
×
2220
                return nil, err
×
2221
        }
2222

2223
        return nodesInHorizon, nil
3✔
2224
}
2225

2226
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2227
// ID's that we don't know and are not known zombies of the passed set. In other
2228
// words, we perform a set difference of our set of chan ID's and the ones
2229
// passed in. This method can be used by callers to determine the set of
2230
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2231
// known zombies is also returned.
2232
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2233
        []ChannelUpdateInfo, error) {
3✔
2234

3✔
2235
        var (
3✔
2236
                newChanIDs   []uint64
3✔
2237
                knownZombies []ChannelUpdateInfo
3✔
2238
        )
3✔
2239

3✔
2240
        c.cacheMu.Lock()
3✔
2241
        defer c.cacheMu.Unlock()
3✔
2242

3✔
2243
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2244
                edges := tx.ReadBucket(edgeBucket)
3✔
2245
                if edges == nil {
3✔
2246
                        return ErrGraphNoEdgesFound
×
2247
                }
×
2248
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2249
                if edgeIndex == nil {
3✔
2250
                        return ErrGraphNoEdgesFound
×
2251
                }
×
2252

2253
                // Fetch the zombie index, it may not exist if no edges have
2254
                // ever been marked as zombies. If the index has been
2255
                // initialized, we will use it later to skip known zombie edges.
2256
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2257

3✔
2258
                // We'll run through the set of chanIDs and collate only the
3✔
2259
                // set of channel that are unable to be found within our db.
3✔
2260
                var cidBytes [8]byte
3✔
2261
                for _, info := range chansInfo {
6✔
2262
                        scid := info.ShortChannelID.ToUint64()
3✔
2263
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2264

3✔
2265
                        // If the edge is already known, skip it.
3✔
2266
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
6✔
2267
                                continue
3✔
2268
                        }
2269

2270
                        // If the edge is a known zombie, skip it.
2271
                        if zombieIndex != nil {
6✔
2272
                                isZombie, _, _ := isZombieEdge(
3✔
2273
                                        zombieIndex, scid,
3✔
2274
                                )
3✔
2275

3✔
2276
                                if isZombie {
3✔
UNCOV
2277
                                        knownZombies = append(
×
UNCOV
2278
                                                knownZombies, info,
×
UNCOV
2279
                                        )
×
UNCOV
2280

×
UNCOV
2281
                                        continue
×
2282
                                }
2283
                        }
2284

2285
                        newChanIDs = append(newChanIDs, scid)
3✔
2286
                }
2287

2288
                return nil
3✔
2289
        }, func() {
3✔
2290
                newChanIDs = nil
3✔
2291
                knownZombies = nil
3✔
2292
        })
3✔
2293
        switch {
3✔
2294
        // If we don't know of any edges yet, then we'll return the entire set
2295
        // of chan IDs specified.
2296
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2297
                ogChanIDs := make([]uint64, len(chansInfo))
×
2298
                for i, info := range chansInfo {
×
2299
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2300
                }
×
2301

2302
                return ogChanIDs, nil, nil
×
2303

2304
        case err != nil:
×
2305
                return nil, nil, err
×
2306
        }
2307

2308
        return newChanIDs, knownZombies, nil
3✔
2309
}
2310

2311
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2312
// latest received channel updates for the channel.
2313
type ChannelUpdateInfo struct {
2314
        // ShortChannelID is the SCID identifier of the channel.
2315
        ShortChannelID lnwire.ShortChannelID
2316

2317
        // Node1UpdateTimestamp is the timestamp of the latest received update
2318
        // from the node 1 channel peer. This will be set to zero time if no
2319
        // update has yet been received from this node.
2320
        Node1UpdateTimestamp time.Time
2321

2322
        // Node2UpdateTimestamp is the timestamp of the latest received update
2323
        // from the node 2 channel peer. This will be set to zero time if no
2324
        // update has yet been received from this node.
2325
        Node2UpdateTimestamp time.Time
2326
}
2327

2328
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2329
// timestamps with zero seconds unix timestamp which equals
2330
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2331
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2332
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2333

3✔
2334
        chanInfo := ChannelUpdateInfo{
3✔
2335
                ShortChannelID:       scid,
3✔
2336
                Node1UpdateTimestamp: node1Timestamp,
3✔
2337
                Node2UpdateTimestamp: node2Timestamp,
3✔
2338
        }
3✔
2339

3✔
2340
        if node1Timestamp.IsZero() {
6✔
2341
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2342
        }
3✔
2343

2344
        if node2Timestamp.IsZero() {
6✔
2345
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2346
        }
3✔
2347

2348
        return chanInfo
3✔
2349
}
2350

2351
// BlockChannelRange represents a range of channels for a given block height.
2352
type BlockChannelRange struct {
2353
        // Height is the height of the block all of the channels below were
2354
        // included in.
2355
        Height uint32
2356

2357
        // Channels is the list of channels identified by their short ID
2358
        // representation known to us that were included in the block height
2359
        // above. The list may include channel update timestamp information if
2360
        // requested.
2361
        Channels []ChannelUpdateInfo
2362
}
2363

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

3✔
2374
        startChanID := &lnwire.ShortChannelID{
3✔
2375
                BlockHeight: startHeight,
3✔
2376
        }
3✔
2377

3✔
2378
        endChanID := lnwire.ShortChannelID{
3✔
2379
                BlockHeight: endHeight,
3✔
2380
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2381
                TxPosition:  math.MaxUint16,
3✔
2382
        }
3✔
2383

3✔
2384
        // As we need to perform a range scan, we'll convert the starting and
3✔
2385
        // ending height to their corresponding values when encoded using short
3✔
2386
        // channel ID's.
3✔
2387
        var chanIDStart, chanIDEnd [8]byte
3✔
2388
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
3✔
2389
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
3✔
2390

3✔
2391
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
3✔
2392
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2393
                edges := tx.ReadBucket(edgeBucket)
3✔
2394
                if edges == nil {
3✔
2395
                        return ErrGraphNoEdgesFound
×
2396
                }
×
2397
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2398
                if edgeIndex == nil {
3✔
2399
                        return ErrGraphNoEdgesFound
×
2400
                }
×
2401

2402
                cursor := edgeIndex.ReadCursor()
3✔
2403

3✔
2404
                // We'll now iterate through the database, and find each
3✔
2405
                // channel ID that resides within the specified range.
3✔
2406
                //
3✔
2407
                //nolint:ll
3✔
2408
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
2409
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
6✔
2410
                        // Don't send alias SCIDs during gossip sync.
3✔
2411
                        edgeReader := bytes.NewReader(v)
3✔
2412
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
3✔
2413
                        if err != nil {
3✔
2414
                                return err
×
2415
                        }
×
2416

2417
                        if edgeInfo.AuthProof == nil {
6✔
2418
                                continue
3✔
2419
                        }
2420

2421
                        // This channel ID rests within the target range, so
2422
                        // we'll add it to our returned set.
2423
                        rawCid := byteOrder.Uint64(k)
3✔
2424
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2425

3✔
2426
                        chanInfo := NewChannelUpdateInfo(
3✔
2427
                                cid, time.Time{}, time.Time{},
3✔
2428
                        )
3✔
2429

3✔
2430
                        if !withTimestamps {
3✔
UNCOV
2431
                                channelsPerBlock[cid.BlockHeight] = append(
×
UNCOV
2432
                                        channelsPerBlock[cid.BlockHeight],
×
UNCOV
2433
                                        chanInfo,
×
UNCOV
2434
                                )
×
UNCOV
2435

×
UNCOV
2436
                                continue
×
2437
                        }
2438

2439
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2440

3✔
2441
                        rawPolicy := edges.Get(node1Key)
3✔
2442
                        if len(rawPolicy) != 0 {
6✔
2443
                                r := bytes.NewReader(rawPolicy)
3✔
2444

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

×
2450
                                        return err
×
2451
                                }
×
2452

2453
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2454
                        }
2455

2456
                        rawPolicy = edges.Get(node2Key)
3✔
2457
                        if len(rawPolicy) != 0 {
6✔
2458
                                r := bytes.NewReader(rawPolicy)
3✔
2459

3✔
2460
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2461
                                if err != nil && !errors.Is(
3✔
2462
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2463
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2464

×
2465
                                        return err
×
2466
                                }
×
2467

2468
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2469
                        }
2470

2471
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2472
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2473
                        )
3✔
2474
                }
2475

2476
                return nil
3✔
2477
        }, func() {
3✔
2478
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2479
        })
3✔
2480

2481
        switch {
3✔
2482
        // If we don't know of any channels yet, then there's nothing to
2483
        // filter, so we'll return an empty slice.
2484
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
3✔
2485
                return nil, nil
3✔
2486

2487
        case err != nil:
×
2488
                return nil, err
×
2489
        }
2490

2491
        // Return the channel ranges in ascending block height order.
2492
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2493
        for block := range channelsPerBlock {
6✔
2494
                blocks = append(blocks, block)
3✔
2495
        }
3✔
2496
        sort.Slice(blocks, func(i, j int) bool {
6✔
2497
                return blocks[i] < blocks[j]
3✔
2498
        })
3✔
2499

2500
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2501
        for _, block := range blocks {
6✔
2502
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2503
                        Height:   block,
3✔
2504
                        Channels: channelsPerBlock[block],
3✔
2505
                })
3✔
2506
        }
3✔
2507

2508
        return channelRanges, nil
3✔
2509
}
2510

2511
// FetchChanInfos returns the set of channel edges that correspond to the passed
2512
// channel ID's. If an edge is the query is unknown to the database, it will
2513
// skipped and the result will contain only those edges that exist at the time
2514
// of the query. This can be used to respond to peer queries that are seeking to
2515
// fill in gaps in their view of the channel graph.
2516
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
2517
        return c.fetchChanInfos(nil, chanIDs)
3✔
2518
}
3✔
2519

2520
// fetchChanInfos returns the set of channel edges that correspond to the passed
2521
// channel ID's. If an edge is the query is unknown to the database, it will
2522
// skipped and the result will contain only those edges that exist at the time
2523
// of the query. This can be used to respond to peer queries that are seeking to
2524
// fill in gaps in their view of the channel graph.
2525
//
2526
// NOTE: An optional transaction may be provided. If none is provided, then a
2527
// new one will be created.
2528
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2529
        []ChannelEdge, error) {
3✔
2530
        // TODO(roasbeef): sort cids?
3✔
2531

3✔
2532
        var (
3✔
2533
                chanEdges []ChannelEdge
3✔
2534
                cidBytes  [8]byte
3✔
2535
        )
3✔
2536

3✔
2537
        fetchChanInfos := func(tx kvdb.RTx) error {
6✔
2538
                edges := tx.ReadBucket(edgeBucket)
3✔
2539
                if edges == nil {
3✔
2540
                        return ErrGraphNoEdgesFound
×
2541
                }
×
2542
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2543
                if edgeIndex == nil {
3✔
2544
                        return ErrGraphNoEdgesFound
×
2545
                }
×
2546
                nodes := tx.ReadBucket(nodeBucket)
3✔
2547
                if nodes == nil {
3✔
2548
                        return ErrGraphNotFound
×
2549
                }
×
2550

2551
                for _, cid := range chanIDs {
6✔
2552
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2553

3✔
2554
                        // First, we'll fetch the static edge information. If
3✔
2555
                        // the edge is unknown, we will skip the edge and
3✔
2556
                        // continue gathering all known edges.
3✔
2557
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2558
                                edgeIndex, cidBytes[:],
3✔
2559
                        )
3✔
2560
                        switch {
3✔
UNCOV
2561
                        case errors.Is(err, ErrEdgeNotFound):
×
UNCOV
2562
                                continue
×
2563
                        case err != nil:
×
2564
                                return err
×
2565
                        }
2566

2567
                        // With the static information obtained, we'll now
2568
                        // fetch the dynamic policy info.
2569
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2570
                                edgeIndex, edges, cidBytes[:],
3✔
2571
                        )
3✔
2572
                        if err != nil {
3✔
2573
                                return err
×
2574
                        }
×
2575

2576
                        node1, err := fetchLightningNode(
3✔
2577
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2578
                        )
3✔
2579
                        if err != nil {
3✔
2580
                                return err
×
2581
                        }
×
2582

2583
                        node2, err := fetchLightningNode(
3✔
2584
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2585
                        )
3✔
2586
                        if err != nil {
3✔
2587
                                return err
×
2588
                        }
×
2589

2590
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2591
                                Info:    &edgeInfo,
3✔
2592
                                Policy1: edge1,
3✔
2593
                                Policy2: edge2,
3✔
2594
                                Node1:   &node1,
3✔
2595
                                Node2:   &node2,
3✔
2596
                        })
3✔
2597
                }
2598

2599
                return nil
3✔
2600
        }
2601

2602
        if tx == nil {
6✔
2603
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2604
                        chanEdges = nil
3✔
2605
                })
3✔
2606
                if err != nil {
3✔
2607
                        return nil, err
×
2608
                }
×
2609

2610
                return chanEdges, nil
3✔
2611
        }
2612

2613
        err := fetchChanInfos(tx)
×
2614
        if err != nil {
×
2615
                return nil, err
×
2616
        }
×
2617

2618
        return chanEdges, nil
×
2619
}
2620

2621
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2622
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2623

3✔
2624
        // First, we'll fetch the edge update index bucket which currently
3✔
2625
        // stores an entry for the channel we're about to delete.
3✔
2626
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2627
        if updateIndex == nil {
3✔
2628
                // No edges in bucket, return early.
×
2629
                return nil
×
2630
        }
×
2631

2632
        // Now that we have the bucket, we'll attempt to construct a template
2633
        // for the index key: updateTime || chanid.
2634
        var indexKey [8 + 8]byte
3✔
2635
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2636

3✔
2637
        // With the template constructed, we'll attempt to delete an entry that
3✔
2638
        // would have been created by both edges: we'll alternate the update
3✔
2639
        // times, as one may had overridden the other.
3✔
2640
        if edge1 != nil {
6✔
2641
                byteOrder.PutUint64(
3✔
2642
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
3✔
2643
                )
3✔
2644
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2645
                        return err
×
2646
                }
×
2647
        }
2648

2649
        // We'll also attempt to delete the entry that may have been created by
2650
        // the second edge.
2651
        if edge2 != nil {
6✔
2652
                byteOrder.PutUint64(
3✔
2653
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2654
                )
3✔
2655
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2656
                        return err
×
2657
                }
×
2658
        }
2659

2660
        return nil
3✔
2661
}
2662

2663
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2664
// cache. It then goes on to delete any policy info and edge info for this
2665
// channel from the DB and finally, if isZombie is true, it will add an entry
2666
// for this channel in the zombie index.
2667
//
2668
// NOTE: this method MUST only be called if the cacheMu has already been
2669
// acquired.
2670
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2671
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2672
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
3✔
2673

3✔
2674
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2675
        if err != nil {
3✔
UNCOV
2676
                return nil, err
×
UNCOV
2677
        }
×
2678

2679
        // We'll also remove the entry in the edge update index bucket before
2680
        // we delete the edges themselves so we can access their last update
2681
        // times.
2682
        cid := byteOrder.Uint64(chanID)
3✔
2683
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2684
        if err != nil {
3✔
2685
                return nil, err
×
2686
        }
×
2687
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2688
        if err != nil {
3✔
2689
                return nil, err
×
2690
        }
×
2691

2692
        // The edge key is of the format pubKey || chanID. First we construct
2693
        // the latter half, populating the channel ID.
2694
        var edgeKey [33 + 8]byte
3✔
2695
        copy(edgeKey[33:], chanID)
3✔
2696

3✔
2697
        // With the latter half constructed, copy over the first public key to
3✔
2698
        // delete the edge in this direction, then the second to delete the
3✔
2699
        // edge in the opposite direction.
3✔
2700
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2701
        if edges.Get(edgeKey[:]) != nil {
6✔
2702
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2703
                        return nil, err
×
2704
                }
×
2705
        }
2706
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2707
        if edges.Get(edgeKey[:]) != nil {
6✔
2708
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2709
                        return nil, err
×
2710
                }
×
2711
        }
2712

2713
        // As part of deleting the edge we also remove all disabled entries
2714
        // from the edgePolicyDisabledIndex bucket. We do that for both
2715
        // directions.
2716
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
3✔
2717
        if err != nil {
3✔
2718
                return nil, err
×
2719
        }
×
2720
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2721
        if err != nil {
3✔
2722
                return nil, err
×
2723
        }
×
2724

2725
        // With the edge data deleted, we can purge the information from the two
2726
        // edge indexes.
2727
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2728
                return nil, err
×
2729
        }
×
2730
        var b bytes.Buffer
3✔
2731
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2732
                return nil, err
×
2733
        }
×
2734
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
2735
                return nil, err
×
2736
        }
×
2737

2738
        // Finally, we'll mark the edge as a zombie within our index if it's
2739
        // being removed due to the channel becoming a zombie. We do this to
2740
        // ensure we don't store unnecessary data for spent channels.
2741
        if !isZombie {
6✔
2742
                return &edgeInfo, nil
3✔
2743
        }
3✔
2744

2745
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2746
        if strictZombie {
3✔
UNCOV
2747
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
×
UNCOV
2748
        }
×
2749

2750
        return &edgeInfo, markEdgeZombie(
3✔
2751
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2752
        )
3✔
2753
}
2754

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

×
UNCOV
2774
        switch {
×
2775
        // If we don't have either edge policy, we'll return both pubkeys so
2776
        // that the channel can be resurrected by either party.
2777
        case e1 == nil && e2 == nil:
×
2778
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2779

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

2787
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2788
        // return a blank pubkey for edge1. In this case, only an update from
2789
        // edge2 can resurect the channel.
UNCOV
2790
        default:
×
UNCOV
2791
                return [33]byte{}, info.NodeKey2Bytes
×
2792
        }
2793
}
2794

2795
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2796
// within the database for the referenced channel. The `flags` attribute within
2797
// the ChannelEdgePolicy determines which of the directed edges are being
2798
// updated. If the flag is 1, then the first node's information is being
2799
// updated, otherwise it's the second node's information. The node ordering is
2800
// determined by the lexicographical ordering of the identity public keys of the
2801
// nodes on either side of the channel.
2802
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2803
        opts ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
3✔
2804

3✔
2805
        var (
3✔
2806
                ctx          = context.TODO()
3✔
2807
                isUpdate1    bool
3✔
2808
                edgeNotFound bool
3✔
2809
                from, to     route.Vertex
3✔
2810
        )
3✔
2811

3✔
2812
        r := &batch.Request[kvdb.RwTx]{
3✔
2813
                Opts: batch.NewSchedulerOptions(opts...),
3✔
2814
                Reset: func() {
6✔
2815
                        isUpdate1 = false
3✔
2816
                        edgeNotFound = false
3✔
2817
                },
3✔
2818
                Do: func(tx kvdb.RwTx) error {
3✔
2819
                        var err error
3✔
2820
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
3✔
2821
                        if err != nil {
3✔
UNCOV
2822
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
×
UNCOV
2823
                        }
×
2824

2825
                        // Silence ErrEdgeNotFound so that the batch can
2826
                        // succeed, but propagate the error via local state.
2827
                        if errors.Is(err, ErrEdgeNotFound) {
3✔
UNCOV
2828
                                edgeNotFound = true
×
UNCOV
2829
                                return nil
×
UNCOV
2830
                        }
×
2831

2832
                        return err
3✔
2833
                },
2834
                OnCommit: func(err error) error {
3✔
2835
                        switch {
3✔
UNCOV
2836
                        case err != nil:
×
UNCOV
2837
                                return err
×
UNCOV
2838
                        case edgeNotFound:
×
UNCOV
2839
                                return ErrEdgeNotFound
×
2840
                        default:
3✔
2841
                                c.updateEdgeCache(edge, isUpdate1)
3✔
2842
                                return nil
3✔
2843
                        }
2844
                },
2845
        }
2846

2847
        err := c.chanScheduler.Execute(ctx, r)
3✔
2848

3✔
2849
        return from, to, err
3✔
2850
}
2851

2852
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2853
        isUpdate1 bool) {
3✔
2854

3✔
2855
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2856
        // the entry with the updated timestamp for the direction that was just
3✔
2857
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2858
        // during the next query for this edge.
3✔
2859
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2860
                if isUpdate1 {
6✔
2861
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2862
                } else {
6✔
2863
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2864
                }
3✔
2865
                c.rejectCache.insert(e.ChannelID, entry)
3✔
2866
        }
2867

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

2882
// updateEdgePolicy attempts to update an edge's policy within the relevant
2883
// buckets using an existing database transaction. The returned boolean will be
2884
// true if the updated policy belongs to node1, and false if the policy belonged
2885
// to node2.
2886
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2887
        route.Vertex, route.Vertex, bool, error) {
3✔
2888

3✔
2889
        var noVertex route.Vertex
3✔
2890

3✔
2891
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2892
        if edges == nil {
3✔
2893
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2894
        }
×
2895
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2896
        if edgeIndex == nil {
3✔
2897
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2898
        }
×
2899

2900
        // Create the channelID key be converting the channel ID
2901
        // integer into a byte slice.
2902
        var chanID [8]byte
3✔
2903
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2904

3✔
2905
        // With the channel ID, we then fetch the value storing the two
3✔
2906
        // nodes which connect this channel edge.
3✔
2907
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2908
        if nodeInfo == nil {
3✔
UNCOV
2909
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2910
        }
×
2911

2912
        // Depending on the flags value passed above, either the first
2913
        // or second edge policy is being updated.
2914
        var fromNode, toNode []byte
3✔
2915
        var isUpdate1 bool
3✔
2916
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2917
                fromNode = nodeInfo[:33]
3✔
2918
                toNode = nodeInfo[33:66]
3✔
2919
                isUpdate1 = true
3✔
2920
        } else {
6✔
2921
                fromNode = nodeInfo[33:66]
3✔
2922
                toNode = nodeInfo[:33]
3✔
2923
                isUpdate1 = false
3✔
2924
        }
3✔
2925

2926
        // Finally, with the direction of the edge being updated
2927
        // identified, we update the on-disk edge representation.
2928
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
3✔
2929
        if err != nil {
3✔
UNCOV
2930
                return noVertex, noVertex, false, err
×
UNCOV
2931
        }
×
2932

2933
        var (
3✔
2934
                fromNodePubKey route.Vertex
3✔
2935
                toNodePubKey   route.Vertex
3✔
2936
        )
3✔
2937
        copy(fromNodePubKey[:], fromNode)
3✔
2938
        copy(toNodePubKey[:], toNode)
3✔
2939

3✔
2940
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
3✔
2941
}
2942

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

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

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

3✔
2966
                        nodeIsPublic = true
3✔
2967
                        return errDone
3✔
2968
                }
3✔
2969

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

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

2984
        return nodeIsPublic, nil
3✔
2985
}
2986

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

3✔
2994
        return c.fetchLightningNode(tx, nodePub)
3✔
2995
}
3✔
2996

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

3✔
3003
        return c.fetchLightningNode(nil, nodePub)
3✔
3004
}
3✔
3005

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

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

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

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

3037
                node = &n
3✔
3038

3✔
3039
                return nil
3✔
3040
        }
3041

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

3052
                return node, nil
3✔
3053
        }
3054

UNCOV
3055
        err := fetch(tx)
×
UNCOV
3056
        if err != nil {
×
UNCOV
3057
                return nil, err
×
UNCOV
3058
        }
×
3059

UNCOV
3060
        return node, nil
×
3061
}
3062

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

3✔
3071
        var (
3✔
3072
                updateTime time.Time
3✔
3073
                exists     bool
3✔
3074
        )
3✔
3075

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

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

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

3101
                exists = true
3✔
3102
                updateTime = node.LastUpdate
3✔
3103

3✔
3104
                return nil
3✔
3105
        }, func() {
3✔
3106
                updateTime = time.Time{}
3✔
3107
                exists = false
3✔
3108
        })
3✔
3109
        if err != nil {
3✔
3110
                return time.Time{}, exists, err
×
3111
        }
×
3112

3113
        return updateTime, exists, nil
3✔
3114
}
3115

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

3✔
3122
        traversal := func(tx kvdb.RTx) error {
6✔
3123
                edges := tx.ReadBucket(edgeBucket)
3✔
3124
                if edges == nil {
3✔
3125
                        return ErrGraphNotFound
×
3126
                }
×
3127
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3128
                if edgeIndex == nil {
3✔
3129
                        return ErrGraphNoEdgesFound
×
3130
                }
×
3131

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

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

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

3166
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3167
                        if err != nil {
3✔
3168
                                return err
×
3169
                        }
×
3170

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

3178
                        // Finally, we execute the callback.
3179
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3180
                        if err != nil {
6✔
3181
                                return err
3✔
3182
                        }
3✔
3183
                }
3184

3185
                return nil
3✔
3186
        }
3187

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

3194
        // Otherwise, we re-use the existing transaction to execute the graph
3195
        // traversal.
3196
        return traversal(tx)
3✔
3197
}
3198

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

3✔
3211
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
3✔
3212
                info *models.ChannelEdgeInfo, policy,
3✔
3213
                policy2 *models.ChannelEdgePolicy) error {
6✔
3214

3✔
3215
                return cb(info, policy, policy2)
3✔
3216
        })
3✔
3217
}
3218

3219
// ForEachSourceNodeChannel iterates through all channels of the source node,
3220
// executing the passed callback on each. The callback is provided with the
3221
// channel's outpoint, whether we have a policy for the channel and the channel
3222
// peer's node information.
3223
func (c *KVStore) ForEachSourceNodeChannel(cb func(chanPoint wire.OutPoint,
3224
        havePolicy bool, otherNode *models.LightningNode) error) error {
3✔
3225

3✔
3226
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3227
                nodes := tx.ReadBucket(nodeBucket)
3✔
3228
                if nodes == nil {
3✔
3229
                        return ErrGraphNotFound
×
3230
                }
×
3231

3232
                node, err := c.sourceNode(nodes)
3✔
3233
                if err != nil {
3✔
3234
                        return err
×
3235
                }
×
3236

3237
                return nodeTraversal(
3✔
3238
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
3✔
3239
                                info *models.ChannelEdgeInfo,
3✔
3240
                                policy, _ *models.ChannelEdgePolicy) error {
6✔
3241

3✔
3242
                                peer, err := c.fetchOtherNode(
3✔
3243
                                        tx, info, node.PubKeyBytes[:],
3✔
3244
                                )
3✔
3245
                                if err != nil {
3✔
3246
                                        return err
×
3247
                                }
×
3248

3249
                                return cb(
3✔
3250
                                        info.ChannelPoint, policy != nil, peer,
3✔
3251
                                )
3✔
3252
                        },
3253
                )
3254
        }, func() {})
3✔
3255
}
3256

3257
// forEachNodeChannelTx iterates through all channels of the given node,
3258
// executing the passed callback with an edge info structure and the policies
3259
// of each end of the channel. The first edge policy is the outgoing edge *to*
3260
// the connecting node, while the second is the incoming edge *from* the
3261
// connecting node. If the callback returns an error, then the iteration is
3262
// halted with the error propagated back up to the caller.
3263
//
3264
// Unknown policies are passed into the callback as nil values.
3265
//
3266
// If the caller wishes to re-use an existing boltdb transaction, then it
3267
// should be passed as the first argument.  Otherwise, the first argument should
3268
// be nil and a fresh transaction will be created to execute the graph
3269
// traversal.
3270
func (c *KVStore) forEachNodeChannelTx(tx kvdb.RTx,
3271
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3272
                *models.ChannelEdgePolicy,
3273
                *models.ChannelEdgePolicy) error) error {
3✔
3274

3✔
3275
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3276
}
3✔
3277

3278
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3279
// the target node in the channel. This is useful when one knows the pubkey of
3280
// one of the nodes, and wishes to obtain the full LightningNode for the other
3281
// end of the channel.
3282
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3283
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3284
        *models.LightningNode, error) {
3✔
3285

3✔
3286
        // Ensure that the node passed in is actually a member of the channel.
3✔
3287
        var targetNodeBytes [33]byte
3✔
3288
        switch {
3✔
3289
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3290
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3291
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3292
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3293
        default:
×
3294
                return nil, fmt.Errorf("node not participating in this channel")
×
3295
        }
3296

3297
        var targetNode *models.LightningNode
3✔
3298
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3299
                // First grab the nodes bucket which stores the mapping from
3✔
3300
                // pubKey to node information.
3✔
3301
                nodes := tx.ReadBucket(nodeBucket)
3✔
3302
                if nodes == nil {
3✔
3303
                        return ErrGraphNotFound
×
3304
                }
×
3305

3306
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3307
                if err != nil {
3✔
3308
                        return err
×
3309
                }
×
3310

3311
                targetNode = &node
3✔
3312

3✔
3313
                return nil
3✔
3314
        }
3315

3316
        // If the transaction is nil, then we'll need to create a new one,
3317
        // otherwise we can use the existing db transaction.
3318
        var err error
3✔
3319
        if tx == nil {
3✔
3320
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3321
                        targetNode = nil
×
3322
                })
×
3323
        } else {
3✔
3324
                err = fetchNodeFunc(tx)
3✔
3325
        }
3✔
3326

3327
        return targetNode, err
3✔
3328
}
3329

3330
// computeEdgePolicyKeys is a helper function that can be used to compute the
3331
// keys used to index the channel edge policy info for the two nodes of the
3332
// edge. The keys for node 1 and node 2 are returned respectively.
3333
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3✔
3334
        var (
3✔
3335
                node1Key [33 + 8]byte
3✔
3336
                node2Key [33 + 8]byte
3✔
3337
        )
3✔
3338

3✔
3339
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3340
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3341

3✔
3342
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3343
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3344

3✔
3345
        return node1Key[:], node2Key[:]
3✔
3346
}
3✔
3347

3348
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3349
// the channel identified by the funding outpoint. If the channel can't be
3350
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3351
// information for the channel itself is returned as well as two structs that
3352
// contain the routing policies for the channel in either direction.
3353
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3354
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3355
        *models.ChannelEdgePolicy, error) {
3✔
3356

3✔
3357
        var (
3✔
3358
                edgeInfo *models.ChannelEdgeInfo
3✔
3359
                policy1  *models.ChannelEdgePolicy
3✔
3360
                policy2  *models.ChannelEdgePolicy
3✔
3361
        )
3✔
3362

3✔
3363
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3364
                // First, grab the node bucket. This will be used to populate
3✔
3365
                // the Node pointers in each edge read from disk.
3✔
3366
                nodes := tx.ReadBucket(nodeBucket)
3✔
3367
                if nodes == nil {
3✔
3368
                        return ErrGraphNotFound
×
3369
                }
×
3370

3371
                // Next, grab the edge bucket which stores the edges, and also
3372
                // the index itself so we can group the directed edges together
3373
                // logically.
3374
                edges := tx.ReadBucket(edgeBucket)
3✔
3375
                if edges == nil {
3✔
3376
                        return ErrGraphNoEdgesFound
×
3377
                }
×
3378
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3379
                if edgeIndex == nil {
3✔
3380
                        return ErrGraphNoEdgesFound
×
3381
                }
×
3382

3383
                // If the channel's outpoint doesn't exist within the outpoint
3384
                // index, then the edge does not exist.
3385
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3386
                if chanIndex == nil {
3✔
3387
                        return ErrGraphNoEdgesFound
×
3388
                }
×
3389
                var b bytes.Buffer
3✔
3390
                if err := WriteOutpoint(&b, op); err != nil {
3✔
3391
                        return err
×
3392
                }
×
3393
                chanID := chanIndex.Get(b.Bytes())
3✔
3394
                if chanID == nil {
6✔
3395
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3396
                }
3✔
3397

3398
                // If the channel is found to exists, then we'll first retrieve
3399
                // the general information for the channel.
3400
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3401
                if err != nil {
3✔
3402
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3403
                }
×
3404
                edgeInfo = &edge
3✔
3405

3✔
3406
                // Once we have the information about the channels' parameters,
3✔
3407
                // we'll fetch the routing policies for each for the directed
3✔
3408
                // edges.
3✔
3409
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3410
                if err != nil {
3✔
3411
                        return fmt.Errorf("failed to find policy: %w", err)
×
3412
                }
×
3413

3414
                policy1 = e1
3✔
3415
                policy2 = e2
3✔
3416

3✔
3417
                return nil
3✔
3418
        }, func() {
3✔
3419
                edgeInfo = nil
3✔
3420
                policy1 = nil
3✔
3421
                policy2 = nil
3✔
3422
        })
3✔
3423
        if err != nil {
6✔
3424
                return nil, nil, nil, err
3✔
3425
        }
3✔
3426

3427
        return edgeInfo, policy1, policy2, nil
3✔
3428
}
3429

3430
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3431
// channel identified by the channel ID. If the channel can't be found, then
3432
// ErrEdgeNotFound is returned. A struct which houses the general information
3433
// for the channel itself is returned as well as two structs that contain the
3434
// routing policies for the channel in either direction.
3435
//
3436
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3437
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3438
// the ChannelEdgeInfo will only include the public keys of each node.
3439
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3440
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3441
        *models.ChannelEdgePolicy, error) {
3✔
3442

3✔
3443
        var (
3✔
3444
                edgeInfo  *models.ChannelEdgeInfo
3✔
3445
                policy1   *models.ChannelEdgePolicy
3✔
3446
                policy2   *models.ChannelEdgePolicy
3✔
3447
                channelID [8]byte
3✔
3448
        )
3✔
3449

3✔
3450
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3451
                // First, grab the node bucket. This will be used to populate
3✔
3452
                // the Node pointers in each edge read from disk.
3✔
3453
                nodes := tx.ReadBucket(nodeBucket)
3✔
3454
                if nodes == nil {
3✔
3455
                        return ErrGraphNotFound
×
3456
                }
×
3457

3458
                // Next, grab the edge bucket which stores the edges, and also
3459
                // the index itself so we can group the directed edges together
3460
                // logically.
3461
                edges := tx.ReadBucket(edgeBucket)
3✔
3462
                if edges == nil {
3✔
3463
                        return ErrGraphNoEdgesFound
×
3464
                }
×
3465
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3466
                if edgeIndex == nil {
3✔
3467
                        return ErrGraphNoEdgesFound
×
3468
                }
×
3469

3470
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3471

3✔
3472
                // Now, attempt to fetch edge.
3✔
3473
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3474

3✔
3475
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3476
                // see if we've previously marked it as so.
3✔
3477
                if errors.Is(err, ErrEdgeNotFound) {
6✔
3478
                        // If the zombie index doesn't exist, or the edge is not
3✔
3479
                        // marked as a zombie within it, then we'll return the
3✔
3480
                        // original ErrEdgeNotFound error.
3✔
3481
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3482
                        if zombieIndex == nil {
3✔
3483
                                return ErrEdgeNotFound
×
3484
                        }
×
3485

3486
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3487
                                zombieIndex, chanID,
3✔
3488
                        )
3✔
3489
                        if !isZombie {
6✔
3490
                                return ErrEdgeNotFound
3✔
3491
                        }
3✔
3492

3493
                        // Otherwise, the edge is marked as a zombie, so we'll
3494
                        // populate the edge info with the public keys of each
3495
                        // party as this is the only information we have about
3496
                        // it and return an error signaling so.
3497
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3498
                                NodeKey1Bytes: pubKey1,
3✔
3499
                                NodeKey2Bytes: pubKey2,
3✔
3500
                        }
3✔
3501

3✔
3502
                        return ErrZombieEdge
3✔
3503
                }
3504

3505
                // Otherwise, we'll just return the error if any.
3506
                if err != nil {
3✔
3507
                        return err
×
3508
                }
×
3509

3510
                edgeInfo = &edge
3✔
3511

3✔
3512
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3513
                // edge.
3✔
3514
                e1, e2, err := fetchChanEdgePolicies(
3✔
3515
                        edgeIndex, edges, channelID[:],
3✔
3516
                )
3✔
3517
                if err != nil {
3✔
3518
                        return err
×
3519
                }
×
3520

3521
                policy1 = e1
3✔
3522
                policy2 = e2
3✔
3523

3✔
3524
                return nil
3✔
3525
        }, func() {
3✔
3526
                edgeInfo = nil
3✔
3527
                policy1 = nil
3✔
3528
                policy2 = nil
3✔
3529
        })
3✔
3530
        if errors.Is(err, ErrZombieEdge) {
6✔
3531
                return edgeInfo, nil, nil, err
3✔
3532
        }
3✔
3533
        if err != nil {
6✔
3534
                return nil, nil, nil, err
3✔
3535
        }
3✔
3536

3537
        return edgeInfo, policy1, policy2, nil
3✔
3538
}
3539

3540
// IsPublicNode is a helper method that determines whether the node with the
3541
// given public key is seen as a public node in the graph from the graph's
3542
// source node's point of view.
3543
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3544
        var nodeIsPublic bool
3✔
3545
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3546
                nodes := tx.ReadBucket(nodeBucket)
3✔
3547
                if nodes == nil {
3✔
3548
                        return ErrGraphNodesNotFound
×
3549
                }
×
3550
                ourPubKey := nodes.Get(sourceKey)
3✔
3551
                if ourPubKey == nil {
3✔
3552
                        return ErrSourceNodeNotSet
×
3553
                }
×
3554
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3555
                if err != nil {
3✔
3556
                        return err
×
3557
                }
×
3558

3559
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3560

3✔
3561
                return err
3✔
3562
        }, func() {
3✔
3563
                nodeIsPublic = false
3✔
3564
        })
3✔
3565
        if err != nil {
3✔
3566
                return false, err
×
3567
        }
×
3568

3569
        return nodeIsPublic, nil
3✔
3570
}
3571

3572
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3573
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3574
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3575
        if err != nil {
3✔
3576
                return nil, err
×
3577
        }
×
3578

3579
        // With the witness script generated, we'll now turn it into a p2wsh
3580
        // script:
3581
        //  * OP_0 <sha256(script)>
3582
        bldr := txscript.NewScriptBuilder(
3✔
3583
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3584
        )
3✔
3585
        bldr.AddOp(txscript.OP_0)
3✔
3586
        scriptHash := sha256.Sum256(witnessScript)
3✔
3587
        bldr.AddData(scriptHash[:])
3✔
3588

3✔
3589
        return bldr.Script()
3✔
3590
}
3591

3592
// EdgePoint couples the outpoint of a channel with the funding script that it
3593
// creates. The FilteredChainView will use this to watch for spends of this
3594
// edge point on chain. We require both of these values as depending on the
3595
// concrete implementation, either the pkScript, or the out point will be used.
3596
type EdgePoint struct {
3597
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3598
        FundingPkScript []byte
3599

3600
        // OutPoint is the outpoint of the target channel.
3601
        OutPoint wire.OutPoint
3602
}
3603

3604
// String returns a human readable version of the target EdgePoint. We return
3605
// the outpoint directly as it is enough to uniquely identify the edge point.
3606
func (e *EdgePoint) String() string {
×
3607
        return e.OutPoint.String()
×
3608
}
×
3609

3610
// ChannelView returns the verifiable edge information for each active channel
3611
// within the known channel graph. The set of UTXO's (along with their scripts)
3612
// returned are the ones that need to be watched on chain to detect channel
3613
// closes on the resident blockchain.
3614
func (c *KVStore) ChannelView() ([]EdgePoint, error) {
3✔
3615
        var edgePoints []EdgePoint
3✔
3616
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3617
                // We're going to iterate over the entire channel index, so
3✔
3618
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3619
                // it's a sub-bucket.
3✔
3620
                edges := tx.ReadBucket(edgeBucket)
3✔
3621
                if edges == nil {
3✔
3622
                        return ErrGraphNoEdgesFound
×
3623
                }
×
3624
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3625
                if chanIndex == nil {
3✔
3626
                        return ErrGraphNoEdgesFound
×
3627
                }
×
3628
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3629
                if edgeIndex == nil {
3✔
3630
                        return ErrGraphNoEdgesFound
×
3631
                }
×
3632

3633
                // Once we have the proper bucket, we'll range over each key
3634
                // (which is the channel point for the channel) and decode it,
3635
                // accumulating each entry.
3636
                return chanIndex.ForEach(
3✔
3637
                        func(chanPointBytes, chanID []byte) error {
6✔
3638
                                chanPointReader := bytes.NewReader(
3✔
3639
                                        chanPointBytes,
3✔
3640
                                )
3✔
3641

3✔
3642
                                var chanPoint wire.OutPoint
3✔
3643
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3644
                                if err != nil {
3✔
3645
                                        return err
×
3646
                                }
×
3647

3648
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3649
                                        edgeIndex, chanID,
3✔
3650
                                )
3✔
3651
                                if err != nil {
3✔
3652
                                        return err
×
3653
                                }
×
3654

3655
                                pkScript, err := genMultiSigP2WSH(
3✔
3656
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3657
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3658
                                )
3✔
3659
                                if err != nil {
3✔
3660
                                        return err
×
3661
                                }
×
3662

3663
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3664
                                        FundingPkScript: pkScript,
3✔
3665
                                        OutPoint:        chanPoint,
3✔
3666
                                })
3✔
3667

3✔
3668
                                return nil
3✔
3669
                        },
3670
                )
3671
        }, func() {
3✔
3672
                edgePoints = nil
3✔
3673
        }); err != nil {
3✔
3674
                return nil, err
×
3675
        }
×
3676

3677
        return edgePoints, nil
3✔
3678
}
3679

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

×
UNCOV
3686
        c.cacheMu.Lock()
×
UNCOV
3687
        defer c.cacheMu.Unlock()
×
UNCOV
3688

×
UNCOV
3689
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3690
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3691
                if edges == nil {
×
3692
                        return ErrGraphNoEdgesFound
×
3693
                }
×
UNCOV
3694
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
UNCOV
3695
                if err != nil {
×
3696
                        return fmt.Errorf("unable to create zombie "+
×
3697
                                "bucket: %w", err)
×
3698
                }
×
3699

UNCOV
3700
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3701
        })
UNCOV
3702
        if err != nil {
×
3703
                return err
×
3704
        }
×
3705

UNCOV
3706
        c.rejectCache.remove(chanID)
×
UNCOV
3707
        c.chanCache.remove(chanID)
×
UNCOV
3708

×
UNCOV
3709
        return nil
×
3710
}
3711

3712
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3713
// keys should represent the node public keys of the two parties involved in the
3714
// edge.
3715
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3716
        pubKey2 [33]byte) error {
3✔
3717

3✔
3718
        var k [8]byte
3✔
3719
        byteOrder.PutUint64(k[:], chanID)
3✔
3720

3✔
3721
        var v [66]byte
3✔
3722
        copy(v[:33], pubKey1[:])
3✔
3723
        copy(v[33:], pubKey2[:])
3✔
3724

3✔
3725
        return zombieIndex.Put(k[:], v[:])
3✔
3726
}
3✔
3727

3728
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
UNCOV
3729
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
UNCOV
3730
        c.cacheMu.Lock()
×
UNCOV
3731
        defer c.cacheMu.Unlock()
×
UNCOV
3732

×
UNCOV
3733
        return c.markEdgeLiveUnsafe(nil, chanID)
×
UNCOV
3734
}
×
3735

3736
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3737
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3738
// case a new transaction will be created.
3739
//
3740
// NOTE: this method MUST only be called if the cacheMu has already been
3741
// acquired.
UNCOV
3742
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
UNCOV
3743
        dbFn := func(tx kvdb.RwTx) error {
×
UNCOV
3744
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3745
                if edges == nil {
×
3746
                        return ErrGraphNoEdgesFound
×
3747
                }
×
UNCOV
3748
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
×
UNCOV
3749
                if zombieIndex == nil {
×
3750
                        return nil
×
3751
                }
×
3752

UNCOV
3753
                var k [8]byte
×
UNCOV
3754
                byteOrder.PutUint64(k[:], chanID)
×
UNCOV
3755

×
UNCOV
3756
                if len(zombieIndex.Get(k[:])) == 0 {
×
UNCOV
3757
                        return ErrZombieEdgeNotFound
×
UNCOV
3758
                }
×
3759

UNCOV
3760
                return zombieIndex.Delete(k[:])
×
3761
        }
3762

3763
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3764
        // the existing transaction
UNCOV
3765
        var err error
×
UNCOV
3766
        if tx == nil {
×
UNCOV
3767
                err = kvdb.Update(c.db, dbFn, func() {})
×
3768
        } else {
×
3769
                err = dbFn(tx)
×
3770
        }
×
UNCOV
3771
        if err != nil {
×
UNCOV
3772
                return err
×
UNCOV
3773
        }
×
3774

UNCOV
3775
        c.rejectCache.remove(chanID)
×
UNCOV
3776
        c.chanCache.remove(chanID)
×
UNCOV
3777

×
UNCOV
3778
        return nil
×
3779
}
3780

3781
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3782
// zombie, then the two node public keys corresponding to this edge are also
3783
// returned.
UNCOV
3784
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
×
UNCOV
3785
        var (
×
UNCOV
3786
                isZombie         bool
×
UNCOV
3787
                pubKey1, pubKey2 [33]byte
×
UNCOV
3788
        )
×
UNCOV
3789

×
UNCOV
3790
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3791
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3792
                if edges == nil {
×
3793
                        return ErrGraphNoEdgesFound
×
3794
                }
×
UNCOV
3795
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3796
                if zombieIndex == nil {
×
3797
                        return nil
×
3798
                }
×
3799

UNCOV
3800
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
UNCOV
3801

×
UNCOV
3802
                return nil
×
UNCOV
3803
        }, func() {
×
UNCOV
3804
                isZombie = false
×
UNCOV
3805
                pubKey1 = [33]byte{}
×
UNCOV
3806
                pubKey2 = [33]byte{}
×
UNCOV
3807
        })
×
UNCOV
3808
        if err != nil {
×
3809
                return false, [33]byte{}, [33]byte{}
×
3810
        }
×
3811

UNCOV
3812
        return isZombie, pubKey1, pubKey2
×
3813
}
3814

3815
// isZombieEdge returns whether an entry exists for the given channel in the
3816
// zombie index. If an entry exists, then the two node public keys corresponding
3817
// to this edge are also returned.
3818
func isZombieEdge(zombieIndex kvdb.RBucket,
3819
        chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3820

3✔
3821
        var k [8]byte
3✔
3822
        byteOrder.PutUint64(k[:], chanID)
3✔
3823

3✔
3824
        v := zombieIndex.Get(k[:])
3✔
3825
        if v == nil {
6✔
3826
                return false, [33]byte{}, [33]byte{}
3✔
3827
        }
3✔
3828

3829
        var pubKey1, pubKey2 [33]byte
3✔
3830
        copy(pubKey1[:], v[:33])
3✔
3831
        copy(pubKey2[:], v[33:])
3✔
3832

3✔
3833
        return true, pubKey1, pubKey2
3✔
3834
}
3835

3836
// NumZombies returns the current number of zombie channels in the graph.
UNCOV
3837
func (c *KVStore) NumZombies() (uint64, error) {
×
UNCOV
3838
        var numZombies uint64
×
UNCOV
3839
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3840
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3841
                if edges == nil {
×
3842
                        return nil
×
3843
                }
×
UNCOV
3844
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3845
                if zombieIndex == nil {
×
3846
                        return nil
×
3847
                }
×
3848

UNCOV
3849
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
UNCOV
3850
                        numZombies++
×
UNCOV
3851
                        return nil
×
UNCOV
3852
                })
×
UNCOV
3853
        }, func() {
×
UNCOV
3854
                numZombies = 0
×
UNCOV
3855
        })
×
UNCOV
3856
        if err != nil {
×
3857
                return 0, err
×
3858
        }
×
3859

UNCOV
3860
        return numZombies, nil
×
3861
}
3862

3863
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3864
// that we can ignore channel announcements that we know to be closed without
3865
// having to validate them and fetch a block.
UNCOV
3866
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
×
UNCOV
3867
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3868
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
UNCOV
3869
                if err != nil {
×
3870
                        return err
×
3871
                }
×
3872

UNCOV
3873
                var k [8]byte
×
UNCOV
3874
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
UNCOV
3875

×
UNCOV
3876
                return closedScids.Put(k[:], []byte{})
×
UNCOV
3877
        }, func() {})
×
3878
}
3879

3880
// IsClosedScid checks whether a channel identified by the passed in scid is
3881
// closed. This helps avoid having to perform expensive validation checks.
3882
// TODO: Add an LRU cache to cut down on disc reads.
3883
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3884
        var isClosed bool
3✔
3885
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3886
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3887
                if closedScids == nil {
3✔
3888
                        return ErrClosedScidsNotFound
×
3889
                }
×
3890

3891
                var k [8]byte
3✔
3892
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3893

3✔
3894
                if closedScids.Get(k[:]) != nil {
3✔
UNCOV
3895
                        isClosed = true
×
UNCOV
3896
                        return nil
×
UNCOV
3897
                }
×
3898

3899
                return nil
3✔
3900
        }, func() {
3✔
3901
                isClosed = false
3✔
3902
        })
3✔
3903
        if err != nil {
3✔
3904
                return false, err
×
3905
        }
×
3906

3907
        return isClosed, nil
3✔
3908
}
3909

3910
// GraphSession will provide the call-back with access to a NodeTraverser
3911
// instance which can be used to perform queries against the channel graph.
UNCOV
3912
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
×
UNCOV
3913
        return c.db.View(func(tx walletdb.ReadTx) error {
×
UNCOV
3914
                return cb(&nodeTraverserSession{
×
UNCOV
3915
                        db: c,
×
UNCOV
3916
                        tx: tx,
×
UNCOV
3917
                })
×
UNCOV
3918
        }, func() {})
×
3919
}
3920

3921
// nodeTraverserSession implements the NodeTraverser interface but with a
3922
// backing read only transaction for a consistent view of the graph.
3923
type nodeTraverserSession struct {
3924
        tx kvdb.RTx
3925
        db *KVStore
3926
}
3927

3928
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3929
// node.
3930
//
3931
// NOTE: Part of the NodeTraverser interface.
3932
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
UNCOV
3933
        cb func(channel *DirectedChannel) error) error {
×
UNCOV
3934

×
UNCOV
3935
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
×
UNCOV
3936
}
×
3937

3938
// FetchNodeFeatures returns the features of the given node. If the node is
3939
// unknown, assume no additional features are supported.
3940
//
3941
// NOTE: Part of the NodeTraverser interface.
3942
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
UNCOV
3943
        *lnwire.FeatureVector, error) {
×
UNCOV
3944

×
UNCOV
3945
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
UNCOV
3946
}
×
3947

3948
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3949
        node *models.LightningNode) error {
3✔
3950

3✔
3951
        var (
3✔
3952
                scratch [16]byte
3✔
3953
                b       bytes.Buffer
3✔
3954
        )
3✔
3955

3✔
3956
        pub, err := node.PubKey()
3✔
3957
        if err != nil {
3✔
3958
                return err
×
3959
        }
×
3960
        nodePub := pub.SerializeCompressed()
3✔
3961

3✔
3962
        // If the node has the update time set, write it, else write 0.
3✔
3963
        updateUnix := uint64(0)
3✔
3964
        if node.LastUpdate.Unix() > 0 {
6✔
3965
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
3966
        }
3✔
3967

3968
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
3969
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
3970
                return err
×
3971
        }
×
3972

3973
        if _, err := b.Write(nodePub); err != nil {
3✔
3974
                return err
×
3975
        }
×
3976

3977
        // If we got a node announcement for this node, we will have the rest
3978
        // of the data available. If not we don't have more data to write.
3979
        if !node.HaveNodeAnnouncement {
6✔
3980
                // Write HaveNodeAnnouncement=0.
3✔
3981
                byteOrder.PutUint16(scratch[:2], 0)
3✔
3982
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
3983
                        return err
×
3984
                }
×
3985

3986
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
3987
        }
3988

3989
        // Write HaveNodeAnnouncement=1.
3990
        byteOrder.PutUint16(scratch[:2], 1)
3✔
3991
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
3992
                return err
×
3993
        }
×
3994

3995
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
3996
                return err
×
3997
        }
×
3998
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
3999
                return err
×
4000
        }
×
4001
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
4002
                return err
×
4003
        }
×
4004

4005
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
4006
                return err
×
4007
        }
×
4008

4009
        if err := node.Features.Encode(&b); err != nil {
3✔
4010
                return err
×
4011
        }
×
4012

4013
        numAddresses := uint16(len(node.Addresses))
3✔
4014
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
4015
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4016
                return err
×
4017
        }
×
4018

4019
        for _, address := range node.Addresses {
6✔
4020
                if err := SerializeAddr(&b, address); err != nil {
3✔
4021
                        return err
×
4022
                }
×
4023
        }
4024

4025
        sigLen := len(node.AuthSigBytes)
3✔
4026
        if sigLen > 80 {
3✔
4027
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4028
                        sigLen)
×
4029
        }
×
4030

4031
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
4032
        if err != nil {
3✔
4033
                return err
×
4034
        }
×
4035

4036
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4037
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4038
        }
×
4039
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
4040
        if err != nil {
3✔
4041
                return err
×
4042
        }
×
4043

4044
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
4045
                return err
×
4046
        }
×
4047

4048
        // With the alias bucket updated, we'll now update the index that
4049
        // tracks the time series of node updates.
4050
        var indexKey [8 + 33]byte
3✔
4051
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4052
        copy(indexKey[8:], nodePub)
3✔
4053

3✔
4054
        // If there was already an old index entry for this node, then we'll
3✔
4055
        // delete the old one before we write the new entry.
3✔
4056
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
6✔
4057
                // Extract out the old update time to we can reconstruct the
3✔
4058
                // prior index key to delete it from the index.
3✔
4059
                oldUpdateTime := nodeBytes[:8]
3✔
4060

3✔
4061
                var oldIndexKey [8 + 33]byte
3✔
4062
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
4063
                copy(oldIndexKey[8:], nodePub)
3✔
4064

3✔
4065
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4066
                        return err
×
4067
                }
×
4068
        }
4069

4070
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4071
                return err
×
4072
        }
×
4073

4074
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
4075
}
4076

4077
func fetchLightningNode(nodeBucket kvdb.RBucket,
4078
        nodePub []byte) (models.LightningNode, error) {
3✔
4079

3✔
4080
        nodeBytes := nodeBucket.Get(nodePub)
3✔
4081
        if nodeBytes == nil {
6✔
4082
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
4083
        }
3✔
4084

4085
        nodeReader := bytes.NewReader(nodeBytes)
3✔
4086

3✔
4087
        return deserializeLightningNode(nodeReader)
3✔
4088
}
4089

4090
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4091
        *lnwire.FeatureVector, error) {
3✔
4092

3✔
4093
        var (
3✔
4094
                pubKey      route.Vertex
3✔
4095
                features    = lnwire.EmptyFeatureVector()
3✔
4096
                nodeScratch [8]byte
3✔
4097
        )
3✔
4098

3✔
4099
        // Skip ahead:
3✔
4100
        // - LastUpdate (8 bytes)
3✔
4101
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
4102
                return pubKey, nil, err
×
4103
        }
×
4104

4105
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
4106
                return pubKey, nil, err
×
4107
        }
×
4108

4109
        // Read the node announcement flag.
4110
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
4111
                return pubKey, nil, err
×
4112
        }
×
4113
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4114

3✔
4115
        // The rest of the data is optional, and will only be there if we got a
3✔
4116
        // node announcement for this node.
3✔
4117
        if hasNodeAnn == 0 {
6✔
4118
                return pubKey, features, nil
3✔
4119
        }
3✔
4120

4121
        // We did get a node announcement for this node, so we'll have the rest
4122
        // of the data available.
4123
        var rgb uint8
3✔
4124
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4125
                return pubKey, nil, err
×
4126
        }
×
4127
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4128
                return pubKey, nil, err
×
4129
        }
×
4130
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4131
                return pubKey, nil, err
×
4132
        }
×
4133

4134
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4135
                return pubKey, nil, err
×
4136
        }
×
4137

4138
        if err := features.Decode(r); err != nil {
3✔
4139
                return pubKey, nil, err
×
4140
        }
×
4141

4142
        return pubKey, features, nil
3✔
4143
}
4144

4145
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4146
        var (
3✔
4147
                node    models.LightningNode
3✔
4148
                scratch [8]byte
3✔
4149
                err     error
3✔
4150
        )
3✔
4151

3✔
4152
        // Always populate a feature vector, even if we don't have a node
3✔
4153
        // announcement and short circuit below.
3✔
4154
        node.Features = lnwire.EmptyFeatureVector()
3✔
4155

3✔
4156
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4157
                return models.LightningNode{}, err
×
4158
        }
×
4159

4160
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4161
        node.LastUpdate = time.Unix(unix, 0)
3✔
4162

3✔
4163
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4164
                return models.LightningNode{}, err
×
4165
        }
×
4166

4167
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4168
                return models.LightningNode{}, err
×
4169
        }
×
4170

4171
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4172
        if hasNodeAnn == 1 {
6✔
4173
                node.HaveNodeAnnouncement = true
3✔
4174
        } else {
6✔
4175
                node.HaveNodeAnnouncement = false
3✔
4176
        }
3✔
4177

4178
        // The rest of the data is optional, and will only be there if we got a
4179
        // node announcement for this node.
4180
        if !node.HaveNodeAnnouncement {
6✔
4181
                return node, nil
3✔
4182
        }
3✔
4183

4184
        // We did get a node announcement for this node, so we'll have the rest
4185
        // of the data available.
4186
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
3✔
4187
                return models.LightningNode{}, err
×
4188
        }
×
4189
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
3✔
4190
                return models.LightningNode{}, err
×
4191
        }
×
4192
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4193
                return models.LightningNode{}, err
×
4194
        }
×
4195

4196
        node.Alias, err = wire.ReadVarString(r, 0)
3✔
4197
        if err != nil {
3✔
4198
                return models.LightningNode{}, err
×
4199
        }
×
4200

4201
        err = node.Features.Decode(r)
3✔
4202
        if err != nil {
3✔
4203
                return models.LightningNode{}, err
×
4204
        }
×
4205

4206
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4207
                return models.LightningNode{}, err
×
4208
        }
×
4209
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4210

3✔
4211
        var addresses []net.Addr
3✔
4212
        for i := 0; i < numAddresses; i++ {
6✔
4213
                address, err := DeserializeAddr(r)
3✔
4214
                if err != nil {
3✔
4215
                        return models.LightningNode{}, err
×
4216
                }
×
4217
                addresses = append(addresses, address)
3✔
4218
        }
4219
        node.Addresses = addresses
3✔
4220

3✔
4221
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4222
        if err != nil {
3✔
4223
                return models.LightningNode{}, err
×
4224
        }
×
4225

4226
        // We'll try and see if there are any opaque bytes left, if not, then
4227
        // we'll ignore the EOF error and return the node as is.
4228
        extraBytes, err := wire.ReadVarBytes(
3✔
4229
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4230
        )
3✔
4231
        switch {
3✔
4232
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4233
        case errors.Is(err, io.EOF):
×
4234
        case err != nil:
×
4235
                return models.LightningNode{}, err
×
4236
        }
4237

4238
        if len(extraBytes) > 0 {
3✔
UNCOV
4239
                node.ExtraOpaqueData = extraBytes
×
UNCOV
4240
        }
×
4241

4242
        return node, nil
3✔
4243
}
4244

4245
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4246
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4247

3✔
4248
        var b bytes.Buffer
3✔
4249

3✔
4250
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4251
                return err
×
4252
        }
×
4253
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4254
                return err
×
4255
        }
×
4256
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4257
                return err
×
4258
        }
×
4259
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4260
                return err
×
4261
        }
×
4262

4263
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
3✔
4264
                return err
×
4265
        }
×
4266

4267
        authProof := edgeInfo.AuthProof
3✔
4268
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4269
        if authProof != nil {
6✔
4270
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4271
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4272
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4273
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4274
        }
3✔
4275

4276
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4277
                return err
×
4278
        }
×
4279
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4280
                return err
×
4281
        }
×
4282
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4283
                return err
×
4284
        }
×
4285
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4286
                return err
×
4287
        }
×
4288

4289
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4290
                return err
×
4291
        }
×
4292
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
3✔
4293
        if err != nil {
3✔
4294
                return err
×
4295
        }
×
4296
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4297
                return err
×
4298
        }
×
4299
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4300
                return err
×
4301
        }
×
4302

4303
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4304
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4305
        }
×
4306
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4307
        if err != nil {
3✔
4308
                return err
×
4309
        }
×
4310

4311
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4312
}
4313

4314
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4315
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4316

3✔
4317
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4318
        if edgeInfoBytes == nil {
6✔
4319
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4320
        }
3✔
4321

4322
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4323

3✔
4324
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4325
}
4326

4327
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4328
        var (
3✔
4329
                err      error
3✔
4330
                edgeInfo models.ChannelEdgeInfo
3✔
4331
        )
3✔
4332

3✔
4333
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4334
                return models.ChannelEdgeInfo{}, err
×
4335
        }
×
4336
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4337
                return models.ChannelEdgeInfo{}, err
×
4338
        }
×
4339
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4340
                return models.ChannelEdgeInfo{}, err
×
4341
        }
×
4342
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4343
                return models.ChannelEdgeInfo{}, err
×
4344
        }
×
4345

4346
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
3✔
4347
        if err != nil {
3✔
4348
                return models.ChannelEdgeInfo{}, err
×
4349
        }
×
4350

4351
        proof := &models.ChannelAuthProof{}
3✔
4352

3✔
4353
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4354
        if err != nil {
3✔
4355
                return models.ChannelEdgeInfo{}, err
×
4356
        }
×
4357
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4358
        if err != nil {
3✔
4359
                return models.ChannelEdgeInfo{}, err
×
4360
        }
×
4361
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4362
        if err != nil {
3✔
4363
                return models.ChannelEdgeInfo{}, err
×
4364
        }
×
4365
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4366
        if err != nil {
3✔
4367
                return models.ChannelEdgeInfo{}, err
×
4368
        }
×
4369

4370
        if !proof.IsEmpty() {
6✔
4371
                edgeInfo.AuthProof = proof
3✔
4372
        }
3✔
4373

4374
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4375
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4376
                return models.ChannelEdgeInfo{}, err
×
4377
        }
×
4378
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4379
                return models.ChannelEdgeInfo{}, err
×
4380
        }
×
4381
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4382
                return models.ChannelEdgeInfo{}, err
×
4383
        }
×
4384

4385
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4386
                return models.ChannelEdgeInfo{}, err
×
4387
        }
×
4388

4389
        // We'll try and see if there are any opaque bytes left, if not, then
4390
        // we'll ignore the EOF error and return the edge as is.
4391
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4392
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4393
        )
3✔
4394
        switch {
3✔
4395
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4396
        case errors.Is(err, io.EOF):
×
4397
        case err != nil:
×
4398
                return models.ChannelEdgeInfo{}, err
×
4399
        }
4400

4401
        return edgeInfo, nil
3✔
4402
}
4403

4404
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4405
        from, to []byte) error {
3✔
4406

3✔
4407
        var edgeKey [33 + 8]byte
3✔
4408
        copy(edgeKey[:], from)
3✔
4409
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4410

3✔
4411
        var b bytes.Buffer
3✔
4412
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
UNCOV
4413
                return err
×
UNCOV
4414
        }
×
4415

4416
        // Before we write out the new edge, we'll create a new entry in the
4417
        // update index in order to keep it fresh.
4418
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4419
        var indexKey [8 + 8]byte
3✔
4420
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4421
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4422

3✔
4423
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4424
        if err != nil {
3✔
4425
                return err
×
4426
        }
×
4427

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

3✔
4435
                // In order to delete the old entry, we'll need to obtain the
3✔
4436
                // *prior* update time in order to delete it. To do this, we'll
3✔
4437
                // need to deserialize the existing policy within the database
3✔
4438
                // (now outdated by the new one), and delete its corresponding
3✔
4439
                // entry within the update index. We'll ignore any
3✔
4440
                // ErrEdgePolicyOptionalFieldNotFound or ErrParsingExtraTLVBytes
3✔
4441
                // errors, as we only need the channel ID and update time to
3✔
4442
                // delete the entry.
3✔
4443
                //
3✔
4444
                // TODO(halseth): get rid of these invalid policies in a
3✔
4445
                // migration.
3✔
4446
                // TODO(elle): complete the above TODO in migration from kvdb
3✔
4447
                // to SQL.
3✔
4448
                oldEdgePolicy, err := deserializeChanEdgePolicy(
3✔
4449
                        bytes.NewReader(edgeBytes),
3✔
4450
                )
3✔
4451
                if err != nil &&
3✔
4452
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4453
                        !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4454

×
4455
                        return err
×
4456
                }
×
4457

4458
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4459

3✔
4460
                var oldIndexKey [8 + 8]byte
3✔
4461
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4462
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4463

3✔
4464
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4465
                        return err
×
4466
                }
×
4467
        }
4468

4469
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4470
                return err
×
4471
        }
×
4472

4473
        err = updateEdgePolicyDisabledIndex(
3✔
4474
                edges, edge.ChannelID,
3✔
4475
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4476
                edge.IsDisabled(),
3✔
4477
        )
3✔
4478
        if err != nil {
3✔
4479
                return err
×
4480
        }
×
4481

4482
        return edges.Put(edgeKey[:], b.Bytes())
3✔
4483
}
4484

4485
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4486
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4487
// one.
4488
// The direction represents the direction of the edge and disabled is used for
4489
// deciding whether to remove or add an entry to the bucket.
4490
// In general a channel is disabled if two entries for the same chanID exist
4491
// in this bucket.
4492
// Maintaining the bucket this way allows a fast retrieval of disabled
4493
// channels, for example when prune is needed.
4494
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4495
        direction bool, disabled bool) error {
3✔
4496

3✔
4497
        var disabledEdgeKey [8 + 1]byte
3✔
4498
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4499
        if direction {
6✔
4500
                disabledEdgeKey[8] = 1
3✔
4501
        }
3✔
4502

4503
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4504
                disabledEdgePolicyBucket,
3✔
4505
        )
3✔
4506
        if err != nil {
3✔
4507
                return err
×
4508
        }
×
4509

4510
        if disabled {
6✔
4511
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4512
        }
3✔
4513

4514
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4515
}
4516

4517
// putChanEdgePolicyUnknown marks the edge policy as unknown
4518
// in the edges bucket.
4519
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4520
        from []byte) error {
3✔
4521

3✔
4522
        var edgeKey [33 + 8]byte
3✔
4523
        copy(edgeKey[:], from)
3✔
4524
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4525

3✔
4526
        if edges.Get(edgeKey[:]) != nil {
3✔
4527
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4528
                        " when there is already a policy present", channelID)
×
4529
        }
×
4530

4531
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4532
}
4533

4534
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4535
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
3✔
4536

3✔
4537
        var edgeKey [33 + 8]byte
3✔
4538
        copy(edgeKey[:], nodePub)
3✔
4539
        copy(edgeKey[33:], chanID)
3✔
4540

3✔
4541
        edgeBytes := edges.Get(edgeKey[:])
3✔
4542
        if edgeBytes == nil {
3✔
4543
                return nil, ErrEdgeNotFound
×
4544
        }
×
4545

4546
        // No need to deserialize unknown policy.
4547
        if bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4548
                return nil, nil
3✔
4549
        }
3✔
4550

4551
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4552

3✔
4553
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4554
        switch {
3✔
4555
        // If the db policy was missing an expected optional field, we return
4556
        // nil as if the policy was unknown.
UNCOV
4557
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
UNCOV
4558
                return nil, nil
×
4559

4560
        // If the policy contains invalid TLV bytes, we return nil as if
4561
        // the policy was unknown.
4562
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4563
                return nil, nil
×
4564

4565
        case err != nil:
×
4566
                return nil, err
×
4567
        }
4568

4569
        return ep, nil
3✔
4570
}
4571

4572
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4573
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4574
        error) {
3✔
4575

3✔
4576
        edgeInfo := edgeIndex.Get(chanID)
3✔
4577
        if edgeInfo == nil {
3✔
4578
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4579
                        chanID)
×
4580
        }
×
4581

4582
        // The first node is contained within the first half of the edge
4583
        // information. We only propagate the error here and below if it's
4584
        // something other than edge non-existence.
4585
        node1Pub := edgeInfo[:33]
3✔
4586
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4587
        if err != nil {
3✔
4588
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4589
                        node1Pub)
×
4590
        }
×
4591

4592
        // Similarly, the second node is contained within the latter
4593
        // half of the edge information.
4594
        node2Pub := edgeInfo[33:66]
3✔
4595
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4596
        if err != nil {
3✔
4597
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4598
                        node2Pub)
×
4599
        }
×
4600

4601
        return edge1, edge2, nil
3✔
4602
}
4603

4604
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4605
        to []byte) error {
3✔
4606

3✔
4607
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4608
        if err != nil {
3✔
4609
                return err
×
4610
        }
×
4611

4612
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4613
                return err
×
4614
        }
×
4615

4616
        var scratch [8]byte
3✔
4617
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4618
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4619
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4620
                return err
×
4621
        }
×
4622

4623
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
3✔
4624
                return err
×
4625
        }
×
4626
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
3✔
4627
                return err
×
4628
        }
×
4629
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
3✔
4630
                return err
×
4631
        }
×
4632
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
3✔
4633
                return err
×
4634
        }
×
4635
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
3✔
4636
        if err != nil {
3✔
4637
                return err
×
4638
        }
×
4639
        err = binary.Write(
3✔
4640
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
3✔
4641
        )
3✔
4642
        if err != nil {
3✔
4643
                return err
×
4644
        }
×
4645

4646
        if _, err := w.Write(to); err != nil {
3✔
4647
                return err
×
4648
        }
×
4649

4650
        // If the max_htlc field is present, we write it. To be compatible with
4651
        // older versions that wasn't aware of this field, we write it as part
4652
        // of the opaque data.
4653
        // TODO(halseth): clean up when moving to TLV.
4654
        var opaqueBuf bytes.Buffer
3✔
4655
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4656
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4657
                if err != nil {
3✔
4658
                        return err
×
4659
                }
×
4660
        }
4661

4662
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
4663
        err = edge.ExtraOpaqueData.ValidateTLV()
3✔
4664
        if err != nil {
3✔
UNCOV
4665
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
UNCOV
4666
        }
×
4667

4668
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4669
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4670
        }
×
4671
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4672
                return err
×
4673
        }
×
4674

4675
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4676
                return err
×
4677
        }
×
4678

4679
        return nil
3✔
4680
}
4681

4682
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
3✔
4683
        // Deserialize the policy. Note that in case an optional field is not
3✔
4684
        // found or if the edge has invalid TLV data, then both an error and a
3✔
4685
        // populated policy object are returned so that the caller can decide
3✔
4686
        // if it still wants to use the edge or not.
3✔
4687
        edge, err := deserializeChanEdgePolicyRaw(r)
3✔
4688
        if err != nil &&
3✔
4689
                !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4690
                !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4691

×
4692
                return nil, err
×
4693
        }
×
4694

4695
        return edge, err
3✔
4696
}
4697

4698
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4699
        error) {
3✔
4700

3✔
4701
        edge := &models.ChannelEdgePolicy{}
3✔
4702

3✔
4703
        var err error
3✔
4704
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4705
        if err != nil {
3✔
4706
                return nil, err
×
4707
        }
×
4708

4709
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4710
                return nil, err
×
4711
        }
×
4712

4713
        var scratch [8]byte
3✔
4714
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4715
                return nil, err
×
4716
        }
×
4717
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4718
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4719

3✔
4720
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4721
                return nil, err
×
4722
        }
×
4723
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4724
                return nil, err
×
4725
        }
×
4726
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4727
                return nil, err
×
4728
        }
×
4729

4730
        var n uint64
3✔
4731
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4732
                return nil, err
×
4733
        }
×
4734
        edge.MinHTLC = lnwire.MilliSatoshi(n)
3✔
4735

3✔
4736
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4737
                return nil, err
×
4738
        }
×
4739
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
4740

3✔
4741
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4742
                return nil, err
×
4743
        }
×
4744
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4745

3✔
4746
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4747
                return nil, err
×
4748
        }
×
4749

4750
        // We'll try and see if there are any opaque bytes left, if not, then
4751
        // we'll ignore the EOF error and return the edge as is.
4752
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4753
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4754
        )
3✔
4755
        switch {
3✔
4756
        case errors.Is(err, io.ErrUnexpectedEOF):
×
UNCOV
4757
        case errors.Is(err, io.EOF):
×
4758
        case err != nil:
×
4759
                return nil, err
×
4760
        }
4761

4762
        // See if optional fields are present.
4763
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4764
                // The max_htlc field should be at the beginning of the opaque
3✔
4765
                // bytes.
3✔
4766
                opq := edge.ExtraOpaqueData
3✔
4767

3✔
4768
                // If the max_htlc field is not present, it might be old data
3✔
4769
                // stored before this field was validated. We'll return the
3✔
4770
                // edge along with an error.
3✔
4771
                if len(opq) < 8 {
3✔
UNCOV
4772
                        return edge, ErrEdgePolicyOptionalFieldNotFound
×
UNCOV
4773
                }
×
4774

4775
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4776
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4777

3✔
4778
                // Exclude the parsed field from the rest of the opaque data.
3✔
4779
                edge.ExtraOpaqueData = opq[8:]
3✔
4780
        }
4781

4782
        // Attempt to extract the inbound fee from the opaque data. If we fail
4783
        // to parse the TLV here, we return an error we also return the edge
4784
        // so that the caller can still use it. This is for backwards
4785
        // compatibility in case we have already persisted some policies that
4786
        // have invalid TLV data.
4787
        var inboundFee lnwire.Fee
3✔
4788
        typeMap, err := edge.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
4789
        if err != nil {
3✔
4790
                return edge, fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
4791
        }
×
4792

4793
        val, ok := typeMap[lnwire.FeeRecordType]
3✔
4794
        if ok && val == nil {
6✔
4795
                edge.InboundFee = fn.Some(inboundFee)
3✔
4796
        }
3✔
4797

4798
        return edge, nil
3✔
4799
}
4800

4801
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4802
// KVStore and a kvdb.RTx.
4803
type chanGraphNodeTx struct {
4804
        tx   kvdb.RTx
4805
        db   *KVStore
4806
        node *models.LightningNode
4807
}
4808

4809
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4810
// interface.
4811
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4812

4813
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4814
        node *models.LightningNode) *chanGraphNodeTx {
3✔
4815

3✔
4816
        return &chanGraphNodeTx{
3✔
4817
                tx:   tx,
3✔
4818
                db:   db,
3✔
4819
                node: node,
3✔
4820
        }
3✔
4821
}
3✔
4822

4823
// Node returns the raw information of the node.
4824
//
4825
// NOTE: This is a part of the NodeRTx interface.
4826
func (c *chanGraphNodeTx) Node() *models.LightningNode {
3✔
4827
        return c.node
3✔
4828
}
3✔
4829

4830
// FetchNode fetches the node with the given pub key under the same transaction
4831
// used to fetch the current node. The returned node is also a NodeRTx and any
4832
// operations on that NodeRTx will also be done under the same transaction.
4833
//
4834
// NOTE: This is a part of the NodeRTx interface.
UNCOV
4835
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
×
UNCOV
4836
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
×
UNCOV
4837
        if err != nil {
×
4838
                return nil, err
×
4839
        }
×
4840

UNCOV
4841
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4842
}
4843

4844
// ForEachChannel can be used to iterate over the node's channels under
4845
// the same transaction used to fetch the node.
4846
//
4847
// NOTE: This is a part of the NodeRTx interface.
4848
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
UNCOV
4849
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
×
UNCOV
4850

×
UNCOV
4851
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
×
UNCOV
4852
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
×
UNCOV
4853
                        policy2 *models.ChannelEdgePolicy) error {
×
UNCOV
4854

×
UNCOV
4855
                        return f(info, policy1, policy2)
×
UNCOV
4856
                },
×
4857
        )
4858
}
4859

4860
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4861
// purposes.
4862
//
4863
// NOTE: this helper currently creates a ChannelGraph that is only ever backed
4864
// by the `KVStore` of the `V1Store` interface.
UNCOV
4865
func MakeTestGraph(t testing.TB, opts ...ChanGraphOption) *ChannelGraph {
×
UNCOV
4866
        t.Helper()
×
UNCOV
4867

×
UNCOV
4868
        // Next, create KVStore for the first time.
×
UNCOV
4869
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
×
UNCOV
4870
        t.Cleanup(backendCleanup)
×
UNCOV
4871
        require.NoError(t, err)
×
UNCOV
4872
        t.Cleanup(func() {
×
UNCOV
4873
                require.NoError(t, backend.Close())
×
UNCOV
4874
        })
×
4875

UNCOV
4876
        graphStore, err := NewKVStore(backend)
×
UNCOV
4877
        require.NoError(t, err)
×
UNCOV
4878

×
UNCOV
4879
        graph, err := NewChannelGraph(graphStore, opts...)
×
UNCOV
4880
        require.NoError(t, err)
×
UNCOV
4881
        require.NoError(t, graph.Start())
×
UNCOV
4882
        t.Cleanup(func() {
×
UNCOV
4883
                require.NoError(t, graph.Stop())
×
UNCOV
4884
        })
×
4885

UNCOV
4886
        return graph
×
4887
}
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