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

lightningnetwork / lnd / 15566926733

10 Jun 2025 06:05PM UTC coverage: 58.331% (-10.2%) from 68.487%
15566926733

push

github

web-flow
Merge pull request #9897 from ellemouton/inboundFeeTLV

multi: explicitly define InboundFees in ChannelUpdate and ChannelEdgePolicy

79 of 131 new or added lines in 11 files covered. (60.31%)

28366 existing lines in 455 files now uncovered.

97695 of 167484 relevant lines covered (58.33%)

1.81 hits per line

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

68.19
/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
// getChannelMap loads all channel edge policies from the database and stores
245
// them in a map.
246
func (c *KVStore) getChannelMap(edges kvdb.RBucket) (
247
        map[channelMapKey]*models.ChannelEdgePolicy, error) {
3✔
248

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

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

3✔
260
                        return nil
3✔
261
                }
3✔
262

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

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

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

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

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

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

295
                case err != nil:
×
296
                        return err
×
297
                }
298

299
                channelMap[key] = edge
3✔
300

3✔
301
                return nil
3✔
302
        })
303
        if err != nil {
3✔
304
                return nil, err
×
305
        }
×
306

307
        return channelMap, nil
3✔
308
}
309

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

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

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

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

357
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
3✔
358
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
3✔
359

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

366
        return nil
3✔
367
}
368

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

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

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

388
        case errors.Is(err, ErrGraphNodeNotFound):
3✔
389
                return false, nil, nil
3✔
390
        }
391

392
        return true, node.Addresses, nil
3✔
393
}
394

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

3✔
407
        return c.db.View(func(tx kvdb.RTx) error {
6✔
408
                edges := tx.ReadBucket(edgeBucket)
3✔
409
                if edges == nil {
3✔
410
                        return ErrGraphNoEdgesFound
×
411
                }
×
412

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

420
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
421
                if edgeIndex == nil {
3✔
422
                        return ErrGraphNoEdgesFound
×
423
                }
×
424

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

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

440
                                policy1 := channelMap[channelMapKey{
3✔
441
                                        nodeKey: info.NodeKey1Bytes,
3✔
442
                                        chanID:  chanID,
3✔
443
                                }]
3✔
444

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

3✔
450
                                return cb(&info, policy1, policy2)
3✔
451
                        },
452
                )
453
        }, func() {})
3✔
454
}
455

456
// forEachNodeDirectedChannel iterates through all channels of a given node,
457
// executing the passed callback on the directed edge representing the channel
458
// and its incoming policy. If the callback returns an error, then the iteration
459
// is halted with the error propagated back up to the caller. An optional read
460
// transaction may be provided. If none is provided, a new one will be created.
461
//
462
// Unknown policies are passed into the callback as nil values.
463
func (c *KVStore) forEachNodeDirectedChannel(tx kvdb.RTx,
464
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
3✔
465

3✔
466
        // Fallback that uses the database.
3✔
467
        toNodeCallback := func() route.Vertex {
6✔
468
                return node
3✔
469
        }
3✔
470
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
471
        if err != nil {
3✔
472
                return err
×
473
        }
×
474

475
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
3✔
476
                p2 *models.ChannelEdgePolicy) error {
6✔
477

3✔
478
                var cachedInPolicy *models.CachedEdgePolicy
3✔
479
                if p2 != nil {
6✔
480
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
481
                        cachedInPolicy.ToNodePubKey = toNodeCallback
3✔
482
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
3✔
483
                }
3✔
484

485
                directedChannel := &DirectedChannel{
3✔
486
                        ChannelID:    e.ChannelID,
3✔
487
                        IsNode1:      node == e.NodeKey1Bytes,
3✔
488
                        OtherNode:    e.NodeKey2Bytes,
3✔
489
                        Capacity:     e.Capacity,
3✔
490
                        OutPolicySet: p1 != nil,
3✔
491
                        InPolicy:     cachedInPolicy,
3✔
492
                }
3✔
493

3✔
494
                if p1 != nil {
6✔
495
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
NEW
496
                                directedChannel.InboundFee = fee
×
NEW
497
                        })
×
498
                }
499

500
                if node == e.NodeKey2Bytes {
6✔
501
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
502
                }
3✔
503

504
                return cb(directedChannel)
3✔
505
        }
506

507
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
508
}
509

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

3✔
516
        // Fallback that uses the database.
3✔
517
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
518
        switch {
3✔
519
        // If the node exists and has features, return them directly.
520
        case err == nil:
3✔
521
                return targetNode.Features, nil
3✔
522

523
        // If we couldn't find a node announcement, populate a blank feature
524
        // vector.
UNCOV
525
        case errors.Is(err, ErrGraphNodeNotFound):
×
UNCOV
526
                return lnwire.EmptyFeatureVector(), nil
×
527

528
        // Otherwise, bubble the error up.
529
        default:
×
530
                return nil, err
×
531
        }
532
}
533

534
// ForEachNodeDirectedChannel iterates through all channels of a given node,
535
// executing the passed callback on the directed edge representing the channel
536
// and its incoming policy. If the callback returns an error, then the iteration
537
// is halted with the error propagated back up to the caller.
538
//
539
// Unknown policies are passed into the callback as nil values.
540
//
541
// NOTE: this is part of the graphdb.NodeTraverser interface.
542
func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
543
        cb func(channel *DirectedChannel) error) error {
3✔
544

3✔
545
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
3✔
546
}
3✔
547

548
// FetchNodeFeatures returns the features of the given node. If no features are
549
// known for the node, an empty feature vector is returned.
550
//
551
// NOTE: this is part of the graphdb.NodeTraverser interface.
552
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
553
        *lnwire.FeatureVector, error) {
3✔
554

3✔
555
        return c.fetchNodeFeatures(nil, nodePub)
3✔
556
}
3✔
557

558
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
559
// data to the call-back.
560
//
561
// NOTE: The callback contents MUST not be modified.
562
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
UNCOV
563
        chans map[uint64]*DirectedChannel) error) error {
×
UNCOV
564

×
UNCOV
565
        // Otherwise call back to a version that uses the database directly.
×
UNCOV
566
        // We'll iterate over each node, then the set of channels for each
×
UNCOV
567
        // node, and construct a similar callback functiopn signature as the
×
UNCOV
568
        // main funcotin expects.
×
UNCOV
569
        return c.forEachNode(func(tx kvdb.RTx,
×
UNCOV
570
                node *models.LightningNode) error {
×
UNCOV
571

×
UNCOV
572
                channels := make(map[uint64]*DirectedChannel)
×
UNCOV
573

×
UNCOV
574
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
×
UNCOV
575
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
UNCOV
576
                                p1 *models.ChannelEdgePolicy,
×
UNCOV
577
                                p2 *models.ChannelEdgePolicy) error {
×
UNCOV
578

×
UNCOV
579
                                toNodeCallback := func() route.Vertex {
×
580
                                        return node.PubKeyBytes
×
581
                                }
×
UNCOV
582
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
UNCOV
583
                                        tx, node.PubKeyBytes,
×
UNCOV
584
                                )
×
UNCOV
585
                                if err != nil {
×
586
                                        return err
×
587
                                }
×
588

UNCOV
589
                                var cachedInPolicy *models.CachedEdgePolicy
×
UNCOV
590
                                if p2 != nil {
×
UNCOV
591
                                        cachedInPolicy =
×
UNCOV
592
                                                models.NewCachedPolicy(p2)
×
UNCOV
593
                                        cachedInPolicy.ToNodePubKey =
×
UNCOV
594
                                                toNodeCallback
×
UNCOV
595
                                        cachedInPolicy.ToNodeFeatures =
×
UNCOV
596
                                                toNodeFeatures
×
UNCOV
597
                                }
×
598

UNCOV
599
                                directedChannel := &DirectedChannel{
×
UNCOV
600
                                        ChannelID: e.ChannelID,
×
UNCOV
601
                                        IsNode1: node.PubKeyBytes ==
×
UNCOV
602
                                                e.NodeKey1Bytes,
×
UNCOV
603
                                        OtherNode:    e.NodeKey2Bytes,
×
UNCOV
604
                                        Capacity:     e.Capacity,
×
UNCOV
605
                                        OutPolicySet: p1 != nil,
×
UNCOV
606
                                        InPolicy:     cachedInPolicy,
×
UNCOV
607
                                }
×
UNCOV
608

×
UNCOV
609
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
UNCOV
610
                                        directedChannel.OtherNode =
×
UNCOV
611
                                                e.NodeKey1Bytes
×
UNCOV
612
                                }
×
613

UNCOV
614
                                channels[e.ChannelID] = directedChannel
×
UNCOV
615

×
UNCOV
616
                                return nil
×
617
                        })
UNCOV
618
                if err != nil {
×
619
                        return err
×
620
                }
×
621

UNCOV
622
                return cb(node.PubKeyBytes, channels)
×
623
        })
624
}
625

626
// DisabledChannelIDs returns the channel ids of disabled channels.
627
// A channel is disabled when two of the associated ChanelEdgePolicies
628
// have their disabled bit on.
UNCOV
629
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
×
UNCOV
630
        var disabledChanIDs []uint64
×
UNCOV
631
        var chanEdgeFound map[uint64]struct{}
×
UNCOV
632

×
UNCOV
633
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
634
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
635
                if edges == nil {
×
636
                        return ErrGraphNoEdgesFound
×
637
                }
×
638

UNCOV
639
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
UNCOV
640
                        disabledEdgePolicyBucket,
×
UNCOV
641
                )
×
UNCOV
642
                if disabledEdgePolicyIndex == nil {
×
UNCOV
643
                        return nil
×
UNCOV
644
                }
×
645

646
                // We iterate over all disabled policies and we add each channel
647
                // that has more than one disabled policy to disabledChanIDs
648
                // array.
UNCOV
649
                return disabledEdgePolicyIndex.ForEach(
×
UNCOV
650
                        func(k, v []byte) error {
×
UNCOV
651
                                chanID := byteOrder.Uint64(k[:8])
×
UNCOV
652
                                _, edgeFound := chanEdgeFound[chanID]
×
UNCOV
653
                                if edgeFound {
×
UNCOV
654
                                        delete(chanEdgeFound, chanID)
×
UNCOV
655
                                        disabledChanIDs = append(
×
UNCOV
656
                                                disabledChanIDs, chanID,
×
UNCOV
657
                                        )
×
UNCOV
658

×
UNCOV
659
                                        return nil
×
UNCOV
660
                                }
×
661

UNCOV
662
                                chanEdgeFound[chanID] = struct{}{}
×
UNCOV
663

×
UNCOV
664
                                return nil
×
665
                        },
666
                )
UNCOV
667
        }, func() {
×
UNCOV
668
                disabledChanIDs = nil
×
UNCOV
669
                chanEdgeFound = make(map[uint64]struct{})
×
UNCOV
670
        })
×
UNCOV
671
        if err != nil {
×
672
                return nil, err
×
673
        }
×
674

UNCOV
675
        return disabledChanIDs, nil
×
676
}
677

678
// ForEachNode iterates through all the stored vertices/nodes in the graph,
679
// executing the passed callback with each node encountered. If the callback
680
// returns an error, then the transaction is aborted and the iteration stops
681
// early. Any operations performed on the NodeTx passed to the call-back are
682
// executed under the same read transaction and so, methods on the NodeTx object
683
// _MUST_ only be called from within the call-back.
684
func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error {
3✔
685
        return c.forEachNode(func(tx kvdb.RTx,
3✔
686
                node *models.LightningNode) error {
6✔
687

3✔
688
                return cb(newChanGraphNodeTx(tx, c, node))
3✔
689
        })
3✔
690
}
691

692
// forEachNode iterates through all the stored vertices/nodes in the graph,
693
// executing the passed callback with each node encountered. If the callback
694
// returns an error, then the transaction is aborted and the iteration stops
695
// early.
696
//
697
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
698
// traversal when graph gets mega.
699
func (c *KVStore) forEachNode(
700
        cb func(kvdb.RTx, *models.LightningNode) error) error {
3✔
701

3✔
702
        traversal := func(tx kvdb.RTx) error {
6✔
703
                // First grab the nodes bucket which stores the mapping from
3✔
704
                // pubKey to node information.
3✔
705
                nodes := tx.ReadBucket(nodeBucket)
3✔
706
                if nodes == nil {
3✔
707
                        return ErrGraphNotFound
×
708
                }
×
709

710
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
711
                        // If this is the source key, then we skip this
3✔
712
                        // iteration as the value for this key is a pubKey
3✔
713
                        // rather than raw node information.
3✔
714
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
715
                                return nil
3✔
716
                        }
3✔
717

718
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
719
                        node, err := deserializeLightningNode(nodeReader)
3✔
720
                        if err != nil {
3✔
721
                                return err
×
722
                        }
×
723

724
                        // Execute the callback, the transaction will abort if
725
                        // this returns an error.
726
                        return cb(tx, &node)
3✔
727
                })
728
        }
729

730
        return kvdb.View(c.db, traversal, func() {})
6✔
731
}
732

733
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
734
// graph, executing the passed callback with each node encountered. If the
735
// callback returns an error, then the transaction is aborted and the iteration
736
// stops early.
737
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
738
        *lnwire.FeatureVector) error) error {
3✔
739

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

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

756
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
757
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
758
                                nodeReader,
3✔
759
                        )
3✔
760
                        if err != nil {
3✔
761
                                return err
×
762
                        }
×
763

764
                        // Execute the callback, the transaction will abort if
765
                        // this returns an error.
766
                        return cb(node, features)
3✔
767
                })
768
        }
769

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

773
// SourceNode returns the source node of the graph. The source node is treated
774
// as the center node within a star-graph. This method may be used to kick off
775
// a path finding algorithm in order to explore the reachability of another
776
// node based off the source node.
777
func (c *KVStore) SourceNode() (*models.LightningNode, error) {
3✔
778
        var source *models.LightningNode
3✔
779
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
780
                // First grab the nodes bucket which stores the mapping from
3✔
781
                // pubKey to node information.
3✔
782
                nodes := tx.ReadBucket(nodeBucket)
3✔
783
                if nodes == nil {
3✔
784
                        return ErrGraphNotFound
×
785
                }
×
786

787
                node, err := c.sourceNode(nodes)
3✔
788
                if err != nil {
3✔
UNCOV
789
                        return err
×
UNCOV
790
                }
×
791
                source = node
3✔
792

3✔
793
                return nil
3✔
794
        }, func() {
3✔
795
                source = nil
3✔
796
        })
3✔
797
        if err != nil {
3✔
UNCOV
798
                return nil, err
×
UNCOV
799
        }
×
800

801
        return source, nil
3✔
802
}
803

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

3✔
811
        selfPub := nodes.Get(sourceKey)
3✔
812
        if selfPub == nil {
3✔
UNCOV
813
                return nil, ErrSourceNodeNotSet
×
UNCOV
814
        }
×
815

816
        // With the pubKey of the source node retrieved, we're able to
817
        // fetch the full node information.
818
        node, err := fetchLightningNode(nodes, selfPub)
3✔
819
        if err != nil {
3✔
820
                return nil, err
×
821
        }
×
822

823
        return &node, nil
3✔
824
}
825

826
// SetSourceNode sets the source node within the graph database. The source
827
// node is to be used as the center of a star-graph within path finding
828
// algorithms.
829
func (c *KVStore) SetSourceNode(node *models.LightningNode) error {
3✔
830
        nodePubBytes := node.PubKeyBytes[:]
3✔
831

3✔
832
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
833
                // First grab the nodes bucket which stores the mapping from
3✔
834
                // pubKey to node information.
3✔
835
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
836
                if err != nil {
3✔
837
                        return err
×
838
                }
×
839

840
                // Next we create the mapping from source to the targeted
841
                // public key.
842
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
3✔
843
                        return err
×
844
                }
×
845

846
                // Finally, we commit the information of the lightning node
847
                // itself.
848
                return addLightningNode(tx, node)
3✔
849
        }, func() {})
3✔
850
}
851

852
// AddLightningNode adds a vertex/node to the graph database. If the node is not
853
// in the database from before, this will add a new, unconnected one to the
854
// graph. If it is present from before, this will update that node's
855
// information. Note that this method is expected to only be called to update an
856
// already present node from a node announcement, or to insert a node found in a
857
// channel update.
858
//
859
// TODO(roasbeef): also need sig of announcement.
860
func (c *KVStore) AddLightningNode(node *models.LightningNode,
861
        opts ...batch.SchedulerOption) error {
3✔
862

3✔
863
        ctx := context.TODO()
3✔
864

3✔
865
        r := &batch.Request[kvdb.RwTx]{
3✔
866
                Opts: batch.NewSchedulerOptions(opts...),
3✔
867
                Do: func(tx kvdb.RwTx) error {
6✔
868
                        return addLightningNode(tx, node)
3✔
869
                },
3✔
870
        }
871

872
        return c.nodeScheduler.Execute(ctx, r)
3✔
873
}
874

875
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
876
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
877
        if err != nil {
3✔
878
                return err
×
879
        }
×
880

881
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
882
        if err != nil {
3✔
883
                return err
×
884
        }
×
885

886
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
887
                nodeUpdateIndexBucket,
3✔
888
        )
3✔
889
        if err != nil {
3✔
890
                return err
×
891
        }
×
892

893
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
894
}
895

896
// LookupAlias attempts to return the alias as advertised by the target node.
897
// TODO(roasbeef): currently assumes that aliases are unique...
898
func (c *KVStore) LookupAlias(pub *btcec.PublicKey) (string, error) {
3✔
899
        var alias string
3✔
900

3✔
901
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
902
                nodes := tx.ReadBucket(nodeBucket)
3✔
903
                if nodes == nil {
3✔
904
                        return ErrGraphNodesNotFound
×
905
                }
×
906

907
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
3✔
908
                if aliases == nil {
3✔
909
                        return ErrGraphNodesNotFound
×
910
                }
×
911

912
                nodePub := pub.SerializeCompressed()
3✔
913
                a := aliases.Get(nodePub)
3✔
914
                if a == nil {
3✔
UNCOV
915
                        return ErrNodeAliasNotFound
×
UNCOV
916
                }
×
917

918
                // TODO(roasbeef): should actually be using the utf-8
919
                // package...
920
                alias = string(a)
3✔
921

3✔
922
                return nil
3✔
923
        }, func() {
3✔
924
                alias = ""
3✔
925
        })
3✔
926
        if err != nil {
3✔
UNCOV
927
                return "", err
×
UNCOV
928
        }
×
929

930
        return alias, nil
3✔
931
}
932

933
// DeleteLightningNode starts a new database transaction to remove a vertex/node
934
// from the database according to the node's public key.
UNCOV
935
func (c *KVStore) DeleteLightningNode(nodePub route.Vertex) error {
×
UNCOV
936
        // TODO(roasbeef): ensure dangling edges are removed...
×
UNCOV
937
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
938
                nodes := tx.ReadWriteBucket(nodeBucket)
×
UNCOV
939
                if nodes == nil {
×
940
                        return ErrGraphNodeNotFound
×
941
                }
×
942

UNCOV
943
                return c.deleteLightningNode(nodes, nodePub[:])
×
UNCOV
944
        }, func() {})
×
945
}
946

947
// deleteLightningNode uses an existing database transaction to remove a
948
// vertex/node from the database according to the node's public key.
949
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
950
        compressedPubKey []byte) error {
3✔
951

3✔
952
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
3✔
953
        if aliases == nil {
3✔
954
                return ErrGraphNodesNotFound
×
955
        }
×
956

957
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
958
                return err
×
959
        }
×
960

961
        // Before we delete the node, we'll fetch its current state so we can
962
        // determine when its last update was to clear out the node update
963
        // index.
964
        node, err := fetchLightningNode(nodes, compressedPubKey)
3✔
965
        if err != nil {
3✔
UNCOV
966
                return err
×
UNCOV
967
        }
×
968

969
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
970
                return err
×
971
        }
×
972

973
        // Finally, we'll delete the index entry for the node within the
974
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
975
        // need to track its last update.
976
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
977
        if nodeUpdateIndex == nil {
3✔
978
                return ErrGraphNodesNotFound
×
979
        }
×
980

981
        // In order to delete the entry, we'll need to reconstruct the key for
982
        // its last update.
983
        updateUnix := uint64(node.LastUpdate.Unix())
3✔
984
        var indexKey [8 + 33]byte
3✔
985
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
986
        copy(indexKey[8:], compressedPubKey)
3✔
987

3✔
988
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
989
}
990

991
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
992
// undirected edge from the two target nodes are created. The information stored
993
// denotes the static attributes of the channel, such as the channelID, the keys
994
// involved in creation of the channel, and the set of features that the channel
995
// supports. The chanPoint and chanID are used to uniquely identify the edge
996
// globally within the database.
997
func (c *KVStore) AddChannelEdge(edge *models.ChannelEdgeInfo,
998
        opts ...batch.SchedulerOption) error {
3✔
999

3✔
1000
        ctx := context.TODO()
3✔
1001

3✔
1002
        var alreadyExists bool
3✔
1003
        r := &batch.Request[kvdb.RwTx]{
3✔
1004
                Opts: batch.NewSchedulerOptions(opts...),
3✔
1005
                Reset: func() {
6✔
1006
                        alreadyExists = false
3✔
1007
                },
3✔
1008
                Do: func(tx kvdb.RwTx) error {
3✔
1009
                        err := c.addChannelEdge(tx, edge)
3✔
1010

3✔
1011
                        // Silence ErrEdgeAlreadyExist so that the batch can
3✔
1012
                        // succeed, but propagate the error via local state.
3✔
1013
                        if errors.Is(err, ErrEdgeAlreadyExist) {
3✔
UNCOV
1014
                                alreadyExists = true
×
UNCOV
1015
                                return nil
×
UNCOV
1016
                        }
×
1017

1018
                        return err
3✔
1019
                },
1020
                OnCommit: func(err error) error {
3✔
1021
                        switch {
3✔
1022
                        case err != nil:
×
1023
                                return err
×
UNCOV
1024
                        case alreadyExists:
×
UNCOV
1025
                                return ErrEdgeAlreadyExist
×
1026
                        default:
3✔
1027
                                c.rejectCache.remove(edge.ChannelID)
3✔
1028
                                c.chanCache.remove(edge.ChannelID)
3✔
1029
                                return nil
3✔
1030
                        }
1031
                },
1032
        }
1033

1034
        return c.chanScheduler.Execute(ctx, r)
3✔
1035
}
1036

1037
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1038
// utilize an existing db transaction.
1039
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1040
        edge *models.ChannelEdgeInfo) error {
3✔
1041

3✔
1042
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1043
        var chanKey [8]byte
3✔
1044
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1045

3✔
1046
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1047
        if err != nil {
3✔
1048
                return err
×
1049
        }
×
1050
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1051
        if err != nil {
3✔
1052
                return err
×
1053
        }
×
1054
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1055
        if err != nil {
3✔
1056
                return err
×
1057
        }
×
1058
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1059
        if err != nil {
3✔
1060
                return err
×
1061
        }
×
1062

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

1069
        // Before we insert the channel into the database, we'll ensure that
1070
        // both nodes already exist in the channel graph. If either node
1071
        // doesn't, then we'll insert a "shell" node that just includes its
1072
        // public key, so subsequent validation and queries can work properly.
1073
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
3✔
1074
        switch {
3✔
1075
        case errors.Is(node1Err, ErrGraphNodeNotFound):
3✔
1076
                node1Shell := models.LightningNode{
3✔
1077
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1078
                        HaveNodeAnnouncement: false,
3✔
1079
                }
3✔
1080
                err := addLightningNode(tx, &node1Shell)
3✔
1081
                if err != nil {
3✔
1082
                        return fmt.Errorf("unable to create shell node "+
×
1083
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1084
                }
×
1085
        case node1Err != nil:
×
1086
                return node1Err
×
1087
        }
1088

1089
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
1090
        switch {
3✔
1091
        case errors.Is(node2Err, ErrGraphNodeNotFound):
3✔
1092
                node2Shell := models.LightningNode{
3✔
1093
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1094
                        HaveNodeAnnouncement: false,
3✔
1095
                }
3✔
1096
                err := addLightningNode(tx, &node2Shell)
3✔
1097
                if err != nil {
3✔
1098
                        return fmt.Errorf("unable to create shell node "+
×
1099
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1100
                }
×
1101
        case node2Err != nil:
×
1102
                return node2Err
×
1103
        }
1104

1105
        // If the edge hasn't been created yet, then we'll first add it to the
1106
        // edge index in order to associate the edge between two nodes and also
1107
        // store the static components of the channel.
1108
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1109
                return err
×
1110
        }
×
1111

1112
        // Mark edge policies for both sides as unknown. This is to enable
1113
        // efficient incoming channel lookup for a node.
1114
        keys := []*[33]byte{
3✔
1115
                &edge.NodeKey1Bytes,
3✔
1116
                &edge.NodeKey2Bytes,
3✔
1117
        }
3✔
1118
        for _, key := range keys {
6✔
1119
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1120
                if err != nil {
3✔
1121
                        return err
×
1122
                }
×
1123
        }
1124

1125
        // Finally we add it to the channel index which maps channel points
1126
        // (outpoints) to the shorter channel ID's.
1127
        var b bytes.Buffer
3✔
1128
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1129
                return err
×
1130
        }
×
1131

1132
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1133
}
1134

1135
// HasChannelEdge returns true if the database knows of a channel edge with the
1136
// passed channel ID, and false otherwise. If an edge with that ID is found
1137
// within the graph, then two time stamps representing the last time the edge
1138
// was updated for both directed edges are returned along with the boolean. If
1139
// it is not found, then the zombie index is checked and its result is returned
1140
// as the second boolean.
1141
func (c *KVStore) HasChannelEdge(
1142
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1143

3✔
1144
        var (
3✔
1145
                upd1Time time.Time
3✔
1146
                upd2Time time.Time
3✔
1147
                exists   bool
3✔
1148
                isZombie bool
3✔
1149
        )
3✔
1150

3✔
1151
        // We'll query the cache with the shared lock held to allow multiple
3✔
1152
        // readers to access values in the cache concurrently if they exist.
3✔
1153
        c.cacheMu.RLock()
3✔
1154
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1155
                c.cacheMu.RUnlock()
3✔
1156
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1157
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1158
                exists, isZombie = entry.flags.unpack()
3✔
1159

3✔
1160
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1161
        }
3✔
1162
        c.cacheMu.RUnlock()
3✔
1163

3✔
1164
        c.cacheMu.Lock()
3✔
1165
        defer c.cacheMu.Unlock()
3✔
1166

3✔
1167
        // The item was not found with the shared lock, so we'll acquire the
3✔
1168
        // exclusive lock and check the cache again in case another method added
3✔
1169
        // the entry to the cache while no lock was held.
3✔
1170
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1171
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1172
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1173
                exists, isZombie = entry.flags.unpack()
3✔
1174

3✔
1175
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1176
        }
3✔
1177

1178
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1179
                edges := tx.ReadBucket(edgeBucket)
3✔
1180
                if edges == nil {
3✔
1181
                        return ErrGraphNoEdgesFound
×
1182
                }
×
1183
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1184
                if edgeIndex == nil {
3✔
1185
                        return ErrGraphNoEdgesFound
×
1186
                }
×
1187

1188
                var channelID [8]byte
3✔
1189
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1190

3✔
1191
                // If the edge doesn't exist, then we'll also check our zombie
3✔
1192
                // index.
3✔
1193
                if edgeIndex.Get(channelID[:]) == nil {
6✔
1194
                        exists = false
3✔
1195
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1196
                        if zombieIndex != nil {
6✔
1197
                                isZombie, _, _ = isZombieEdge(
3✔
1198
                                        zombieIndex, chanID,
3✔
1199
                                )
3✔
1200
                        }
3✔
1201

1202
                        return nil
3✔
1203
                }
1204

1205
                exists = true
3✔
1206
                isZombie = false
3✔
1207

3✔
1208
                // If the channel has been found in the graph, then retrieve
3✔
1209
                // the edges itself so we can return the last updated
3✔
1210
                // timestamps.
3✔
1211
                nodes := tx.ReadBucket(nodeBucket)
3✔
1212
                if nodes == nil {
3✔
1213
                        return ErrGraphNodeNotFound
×
1214
                }
×
1215

1216
                e1, e2, err := fetchChanEdgePolicies(
3✔
1217
                        edgeIndex, edges, channelID[:],
3✔
1218
                )
3✔
1219
                if err != nil {
3✔
1220
                        return err
×
1221
                }
×
1222

1223
                // As we may have only one of the edges populated, only set the
1224
                // update time if the edge was found in the database.
1225
                if e1 != nil {
6✔
1226
                        upd1Time = e1.LastUpdate
3✔
1227
                }
3✔
1228
                if e2 != nil {
6✔
1229
                        upd2Time = e2.LastUpdate
3✔
1230
                }
3✔
1231

1232
                return nil
3✔
1233
        }, func() {}); err != nil {
3✔
1234
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1235
        }
×
1236

1237
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1238
                upd1Time: upd1Time.Unix(),
3✔
1239
                upd2Time: upd2Time.Unix(),
3✔
1240
                flags:    packRejectFlags(exists, isZombie),
3✔
1241
        })
3✔
1242

3✔
1243
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1244
}
1245

1246
// AddEdgeProof sets the proof of an existing edge in the graph database.
1247
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1248
        proof *models.ChannelAuthProof) error {
3✔
1249

3✔
1250
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1251
        var chanKey [8]byte
3✔
1252
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1253

3✔
1254
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1255
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1256
                if edges == nil {
3✔
1257
                        return ErrEdgeNotFound
×
1258
                }
×
1259

1260
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1261
                if edgeIndex == nil {
3✔
1262
                        return ErrEdgeNotFound
×
1263
                }
×
1264

1265
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1266
                if err != nil {
3✔
1267
                        return err
×
1268
                }
×
1269

1270
                edge.AuthProof = proof
3✔
1271

3✔
1272
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1273
        }, func() {})
3✔
1274
}
1275

1276
const (
1277
        // pruneTipBytes is the total size of the value which stores a prune
1278
        // entry of the graph in the prune log. The "prune tip" is the last
1279
        // entry in the prune log, and indicates if the channel graph is in
1280
        // sync with the current UTXO state. The structure of the value
1281
        // is: blockHash, taking 32 bytes total.
1282
        pruneTipBytes = 32
1283
)
1284

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

3✔
1297
        c.cacheMu.Lock()
3✔
1298
        defer c.cacheMu.Unlock()
3✔
1299

3✔
1300
        var (
3✔
1301
                chansClosed []*models.ChannelEdgeInfo
3✔
1302
                prunedNodes []route.Vertex
3✔
1303
        )
3✔
1304

3✔
1305
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1306
                // First grab the edges bucket which houses the information
3✔
1307
                // we'd like to delete
3✔
1308
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1309
                if err != nil {
3✔
1310
                        return err
×
1311
                }
×
1312

1313
                // Next grab the two edge indexes which will also need to be
1314
                // updated.
1315
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1316
                if err != nil {
3✔
1317
                        return err
×
1318
                }
×
1319
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1320
                        channelPointBucket,
3✔
1321
                )
3✔
1322
                if err != nil {
3✔
1323
                        return err
×
1324
                }
×
1325
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1326
                if nodes == nil {
3✔
1327
                        return ErrSourceNodeNotSet
×
1328
                }
×
1329
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1330
                if err != nil {
3✔
1331
                        return err
×
1332
                }
×
1333

1334
                // For each of the outpoints that have been spent within the
1335
                // block, we attempt to delete them from the graph as if that
1336
                // outpoint was a channel, then it has now been closed.
1337
                for _, chanPoint := range spentOutputs {
6✔
1338
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1339
                        // if NOT if filter
3✔
1340

3✔
1341
                        var opBytes bytes.Buffer
3✔
1342
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1343
                        if err != nil {
3✔
1344
                                return err
×
1345
                        }
×
1346

1347
                        // First attempt to see if the channel exists within
1348
                        // the database, if not, then we can exit early.
1349
                        chanID := chanIndex.Get(opBytes.Bytes())
3✔
1350
                        if chanID == nil {
3✔
UNCOV
1351
                                continue
×
1352
                        }
1353

1354
                        // Attempt to delete the channel, an ErrEdgeNotFound
1355
                        // will be returned if that outpoint isn't known to be
1356
                        // a channel. If no error is returned, then a channel
1357
                        // was successfully pruned.
1358
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1359
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1360
                                chanID, false, false,
3✔
1361
                        )
3✔
1362
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1363
                                return err
×
1364
                        }
×
1365

1366
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1367
                }
1368

1369
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1370
                if err != nil {
3✔
1371
                        return err
×
1372
                }
×
1373

1374
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1375
                        pruneLogBucket,
3✔
1376
                )
3✔
1377
                if err != nil {
3✔
1378
                        return err
×
1379
                }
×
1380

1381
                // With the graph pruned, add a new entry to the prune log,
1382
                // which can be used to check if the graph is fully synced with
1383
                // the current UTXO state.
1384
                var blockHeightBytes [4]byte
3✔
1385
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
3✔
1386

3✔
1387
                var newTip [pruneTipBytes]byte
3✔
1388
                copy(newTip[:], blockHash[:])
3✔
1389

3✔
1390
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1391
                if err != nil {
3✔
1392
                        return err
×
1393
                }
×
1394

1395
                // Now that the graph has been pruned, we'll also attempt to
1396
                // prune any nodes that have had a channel closed within the
1397
                // latest block.
1398
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1399

3✔
1400
                return err
3✔
1401
        }, func() {
3✔
1402
                chansClosed = nil
3✔
1403
                prunedNodes = nil
3✔
1404
        })
3✔
1405
        if err != nil {
3✔
1406
                return nil, nil, err
×
1407
        }
×
1408

1409
        for _, channel := range chansClosed {
6✔
1410
                c.rejectCache.remove(channel.ChannelID)
3✔
1411
                c.chanCache.remove(channel.ChannelID)
3✔
1412
        }
3✔
1413

1414
        return chansClosed, prunedNodes, nil
3✔
1415
}
1416

1417
// PruneGraphNodes is a garbage collection method which attempts to prune out
1418
// any nodes from the channel graph that are currently unconnected. This ensure
1419
// that we only maintain a graph of reachable nodes. In the event that a pruned
1420
// node gains more channels, it will be re-added back to the graph.
1421
func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error) {
3✔
1422
        var prunedNodes []route.Vertex
3✔
1423
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1424
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1425
                if nodes == nil {
3✔
1426
                        return ErrGraphNodesNotFound
×
1427
                }
×
1428
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1429
                if edges == nil {
3✔
1430
                        return ErrGraphNotFound
×
1431
                }
×
1432
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1433
                if edgeIndex == nil {
3✔
1434
                        return ErrGraphNoEdgesFound
×
1435
                }
×
1436

1437
                var err error
3✔
1438
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1439
                if err != nil {
3✔
1440
                        return err
×
1441
                }
×
1442

1443
                return nil
3✔
1444
        }, func() {
3✔
1445
                prunedNodes = nil
3✔
1446
        })
3✔
1447

1448
        return prunedNodes, err
3✔
1449
}
1450

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

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

3✔
1459
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1460
        // even if it no longer has any open channels.
3✔
1461
        sourceNode, err := c.sourceNode(nodes)
3✔
1462
        if err != nil {
3✔
1463
                return nil, err
×
1464
        }
×
1465

1466
        // We'll use this map to keep count the number of references to a node
1467
        // in the graph. A node should only be removed once it has no more
1468
        // references in the graph.
1469
        nodeRefCounts := make(map[[33]byte]int)
3✔
1470
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1471
                // If this is the source key, then we skip this
3✔
1472
                // iteration as the value for this key is a pubKey
3✔
1473
                // rather than raw node information.
3✔
1474
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1475
                        return nil
3✔
1476
                }
3✔
1477

1478
                var nodePub [33]byte
3✔
1479
                copy(nodePub[:], pubKey)
3✔
1480
                nodeRefCounts[nodePub] = 0
3✔
1481

3✔
1482
                return nil
3✔
1483
        })
1484
        if err != nil {
3✔
1485
                return nil, err
×
1486
        }
×
1487

1488
        // To ensure we never delete the source node, we'll start off by
1489
        // bumping its ref count to 1.
1490
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1491

3✔
1492
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1493
        // edge info. We'll use this scan to populate our reference count map
3✔
1494
        // above.
3✔
1495
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
6✔
1496
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1497
                // the nodes that this edge attaches. We'll extract them, and
3✔
1498
                // add them to the ref count map.
3✔
1499
                var node1, node2 [33]byte
3✔
1500
                copy(node1[:], edgeInfoBytes[:33])
3✔
1501
                copy(node2[:], edgeInfoBytes[33:])
3✔
1502

3✔
1503
                // With the nodes extracted, we'll increase the ref count of
3✔
1504
                // each of the nodes.
3✔
1505
                nodeRefCounts[node1]++
3✔
1506
                nodeRefCounts[node2]++
3✔
1507

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

1514
        // Finally, we'll make a second pass over the set of nodes, and delete
1515
        // any nodes that have a ref count of zero.
1516
        var pruned []route.Vertex
3✔
1517
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1518
                // If the ref count of the node isn't zero, then we can safely
3✔
1519
                // skip it as it still has edges to or from it within the
3✔
1520
                // graph.
3✔
1521
                if refCount != 0 {
6✔
1522
                        continue
3✔
1523
                }
1524

1525
                // If we reach this point, then there are no longer any edges
1526
                // that connect this node, so we can delete it.
1527
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1528
                if err != nil {
3✔
1529
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1530
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1531

×
1532
                                log.Warnf("Unable to prune node %x from the "+
×
1533
                                        "graph: %v", nodePubKey, err)
×
1534
                                continue
×
1535
                        }
1536

1537
                        return nil, err
×
1538
                }
1539

1540
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1541
                        nodePubKey[:])
3✔
1542

3✔
1543
                pruned = append(pruned, nodePubKey)
3✔
1544
        }
1545

1546
        if len(pruned) > 0 {
6✔
1547
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1548
                        len(pruned))
3✔
1549
        }
3✔
1550

1551
        return pruned, err
3✔
1552
}
1553

1554
// DisconnectBlockAtHeight is used to indicate that the block specified
1555
// by the passed height has been disconnected from the main chain. This
1556
// will "rewind" the graph back to the height below, deleting channels
1557
// that are no longer confirmed from the graph. The prune log will be
1558
// set to the last prune height valid for the remaining chain.
1559
// Channels that were removed from the graph resulting from the
1560
// disconnected block are returned.
1561
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1562
        []*models.ChannelEdgeInfo, error) {
2✔
1563

2✔
1564
        // Every channel having a ShortChannelID starting at 'height'
2✔
1565
        // will no longer be confirmed.
2✔
1566
        startShortChanID := lnwire.ShortChannelID{
2✔
1567
                BlockHeight: height,
2✔
1568
        }
2✔
1569

2✔
1570
        // Delete everything after this height from the db up until the
2✔
1571
        // SCID alias range.
2✔
1572
        endShortChanID := aliasmgr.StartingAlias
2✔
1573

2✔
1574
        // The block height will be the 3 first bytes of the channel IDs.
2✔
1575
        var chanIDStart [8]byte
2✔
1576
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
2✔
1577
        var chanIDEnd [8]byte
2✔
1578
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
2✔
1579

2✔
1580
        c.cacheMu.Lock()
2✔
1581
        defer c.cacheMu.Unlock()
2✔
1582

2✔
1583
        // Keep track of the channels that are removed from the graph.
2✔
1584
        var removedChans []*models.ChannelEdgeInfo
2✔
1585

2✔
1586
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
4✔
1587
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
2✔
1588
                if err != nil {
2✔
1589
                        return err
×
1590
                }
×
1591
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
2✔
1592
                if err != nil {
2✔
1593
                        return err
×
1594
                }
×
1595
                chanIndex, err := edges.CreateBucketIfNotExists(
2✔
1596
                        channelPointBucket,
2✔
1597
                )
2✔
1598
                if err != nil {
2✔
1599
                        return err
×
1600
                }
×
1601
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
2✔
1602
                if err != nil {
2✔
1603
                        return err
×
1604
                }
×
1605

1606
                // Scan from chanIDStart to chanIDEnd, deleting every
1607
                // found edge.
1608
                // NOTE: we must delete the edges after the cursor loop, since
1609
                // modifying the bucket while traversing is not safe.
1610
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1611
                // so that the StartingAlias itself isn't deleted.
1612
                var keys [][]byte
2✔
1613
                cursor := edgeIndex.ReadWriteCursor()
2✔
1614

2✔
1615
                //nolint:ll
2✔
1616
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
2✔
1617
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
4✔
1618
                        keys = append(keys, k)
2✔
1619
                }
2✔
1620

1621
                for _, k := range keys {
4✔
1622
                        edgeInfo, err := c.delChannelEdgeUnsafe(
2✔
1623
                                edges, edgeIndex, chanIndex, zombieIndex,
2✔
1624
                                k, false, false,
2✔
1625
                        )
2✔
1626
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
2✔
1627
                                return err
×
1628
                        }
×
1629

1630
                        removedChans = append(removedChans, edgeInfo)
2✔
1631
                }
1632

1633
                // Delete all the entries in the prune log having a height
1634
                // greater or equal to the block disconnected.
1635
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
2✔
1636
                if err != nil {
2✔
1637
                        return err
×
1638
                }
×
1639

1640
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1641
                        pruneLogBucket,
2✔
1642
                )
2✔
1643
                if err != nil {
2✔
1644
                        return err
×
1645
                }
×
1646

1647
                var pruneKeyStart [4]byte
2✔
1648
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1649

2✔
1650
                var pruneKeyEnd [4]byte
2✔
1651
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1652

2✔
1653
                // To avoid modifying the bucket while traversing, we delete
2✔
1654
                // the keys in a second loop.
2✔
1655
                var pruneKeys [][]byte
2✔
1656
                pruneCursor := pruneBucket.ReadWriteCursor()
2✔
1657
                //nolint:ll
2✔
1658
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
2✔
1659
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
4✔
1660
                        pruneKeys = append(pruneKeys, k)
2✔
1661
                }
2✔
1662

1663
                for _, k := range pruneKeys {
4✔
1664
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1665
                                return err
×
1666
                        }
×
1667
                }
1668

1669
                return nil
2✔
1670
        }, func() {
2✔
1671
                removedChans = nil
2✔
1672
        }); err != nil {
2✔
1673
                return nil, err
×
1674
        }
×
1675

1676
        for _, channel := range removedChans {
4✔
1677
                c.rejectCache.remove(channel.ChannelID)
2✔
1678
                c.chanCache.remove(channel.ChannelID)
2✔
1679
        }
2✔
1680

1681
        return removedChans, nil
2✔
1682
}
1683

1684
// PruneTip returns the block height and hash of the latest block that has been
1685
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1686
// to tell if the graph is currently in sync with the current best known UTXO
1687
// state.
1688
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
3✔
1689
        var (
3✔
1690
                tipHash   chainhash.Hash
3✔
1691
                tipHeight uint32
3✔
1692
        )
3✔
1693

3✔
1694
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1695
                graphMeta := tx.ReadBucket(graphMetaBucket)
3✔
1696
                if graphMeta == nil {
3✔
1697
                        return ErrGraphNotFound
×
1698
                }
×
1699
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
3✔
1700
                if pruneBucket == nil {
3✔
1701
                        return ErrGraphNeverPruned
×
1702
                }
×
1703

1704
                pruneCursor := pruneBucket.ReadCursor()
3✔
1705

3✔
1706
                // The prune key with the largest block height will be our
3✔
1707
                // prune tip.
3✔
1708
                k, v := pruneCursor.Last()
3✔
1709
                if k == nil {
6✔
1710
                        return ErrGraphNeverPruned
3✔
1711
                }
3✔
1712

1713
                // Once we have the prune tip, the value will be the block hash,
1714
                // and the key the block height.
1715
                copy(tipHash[:], v)
3✔
1716
                tipHeight = byteOrder.Uint32(k)
3✔
1717

3✔
1718
                return nil
3✔
1719
        }, func() {})
3✔
1720
        if err != nil {
6✔
1721
                return nil, 0, err
3✔
1722
        }
3✔
1723

1724
        return &tipHash, tipHeight, nil
3✔
1725
}
1726

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

3✔
1738
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1739
        // channels
3✔
1740
        // TODO(roasbeef): don't delete both edges?
3✔
1741

3✔
1742
        c.cacheMu.Lock()
3✔
1743
        defer c.cacheMu.Unlock()
3✔
1744

3✔
1745
        var infos []*models.ChannelEdgeInfo
3✔
1746
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1747
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1748
                if edges == nil {
3✔
1749
                        return ErrEdgeNotFound
×
1750
                }
×
1751
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1752
                if edgeIndex == nil {
3✔
1753
                        return ErrEdgeNotFound
×
1754
                }
×
1755
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
3✔
1756
                if chanIndex == nil {
3✔
1757
                        return ErrEdgeNotFound
×
1758
                }
×
1759
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1760
                if nodes == nil {
3✔
1761
                        return ErrGraphNodeNotFound
×
1762
                }
×
1763
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1764
                if err != nil {
3✔
1765
                        return err
×
1766
                }
×
1767

1768
                var rawChanID [8]byte
3✔
1769
                for _, chanID := range chanIDs {
6✔
1770
                        byteOrder.PutUint64(rawChanID[:], chanID)
3✔
1771
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1772
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1773
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1774
                        )
3✔
1775
                        if err != nil {
3✔
UNCOV
1776
                                return err
×
UNCOV
1777
                        }
×
1778

1779
                        infos = append(infos, edgeInfo)
3✔
1780
                }
1781

1782
                return nil
3✔
1783
        }, func() {
3✔
1784
                infos = nil
3✔
1785
        })
3✔
1786
        if err != nil {
3✔
UNCOV
1787
                return nil, err
×
UNCOV
1788
        }
×
1789

1790
        for _, chanID := range chanIDs {
6✔
1791
                c.rejectCache.remove(chanID)
3✔
1792
                c.chanCache.remove(chanID)
3✔
1793
        }
3✔
1794

1795
        return infos, nil
3✔
1796
}
1797

1798
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1799
// passed channel point (outpoint). If the passed channel doesn't exist within
1800
// the database, then ErrEdgeNotFound is returned.
1801
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1802
        var chanID uint64
3✔
1803
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1804
                var err error
3✔
1805
                chanID, err = getChanID(tx, chanPoint)
3✔
1806
                return err
3✔
1807
        }, func() {
6✔
1808
                chanID = 0
3✔
1809
        }); err != nil {
6✔
1810
                return 0, err
3✔
1811
        }
3✔
1812

1813
        return chanID, nil
3✔
1814
}
1815

1816
// getChanID returns the assigned channel ID for a given channel point.
1817
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1818
        var b bytes.Buffer
3✔
1819
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1820
                return 0, err
×
1821
        }
×
1822

1823
        edges := tx.ReadBucket(edgeBucket)
3✔
1824
        if edges == nil {
3✔
1825
                return 0, ErrGraphNoEdgesFound
×
1826
        }
×
1827
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1828
        if chanIndex == nil {
3✔
1829
                return 0, ErrGraphNoEdgesFound
×
1830
        }
×
1831

1832
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1833
        if chanIDBytes == nil {
6✔
1834
                return 0, ErrEdgeNotFound
3✔
1835
        }
3✔
1836

1837
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1838

3✔
1839
        return chanID, nil
3✔
1840
}
1841

1842
// TODO(roasbeef): allow updates to use Batch?
1843

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

3✔
1850
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1851
                edges := tx.ReadBucket(edgeBucket)
3✔
1852
                if edges == nil {
3✔
1853
                        return ErrGraphNoEdgesFound
×
1854
                }
×
1855
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1856
                if edgeIndex == nil {
3✔
1857
                        return ErrGraphNoEdgesFound
×
1858
                }
×
1859

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

3✔
1864
                lastChanID, _ := cidCursor.Last()
3✔
1865

3✔
1866
                // If there's no key, then this means that we don't actually
3✔
1867
                // know of any channels, so we'll return a predicable error.
3✔
1868
                if lastChanID == nil {
6✔
1869
                        return ErrGraphNoEdgesFound
3✔
1870
                }
3✔
1871

1872
                // Otherwise, we'll de serialize the channel ID and return it
1873
                // to the caller.
1874
                cid = byteOrder.Uint64(lastChanID)
3✔
1875

3✔
1876
                return nil
3✔
1877
        }, func() {
3✔
1878
                cid = 0
3✔
1879
        })
3✔
1880
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
3✔
1881
                return 0, err
×
1882
        }
×
1883

1884
        return cid, nil
3✔
1885
}
1886

1887
// ChannelEdge represents the complete set of information for a channel edge in
1888
// the known channel graph. This struct couples the core information of the
1889
// edge as well as each of the known advertised edge policies.
1890
type ChannelEdge struct {
1891
        // Info contains all the static information describing the channel.
1892
        Info *models.ChannelEdgeInfo
1893

1894
        // Policy1 points to the "first" edge policy of the channel containing
1895
        // the dynamic information required to properly route through the edge.
1896
        Policy1 *models.ChannelEdgePolicy
1897

1898
        // Policy2 points to the "second" edge policy of the channel containing
1899
        // the dynamic information required to properly route through the edge.
1900
        Policy2 *models.ChannelEdgePolicy
1901

1902
        // Node1 is "node 1" in the channel. This is the node that would have
1903
        // produced Policy1 if it exists.
1904
        Node1 *models.LightningNode
1905

1906
        // Node2 is "node 2" in the channel. This is the node that would have
1907
        // produced Policy2 if it exists.
1908
        Node2 *models.LightningNode
1909
}
1910

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

3✔
1916
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
1917
        // additional map to keep track of the edges already seen to prevent
3✔
1918
        // re-adding it.
3✔
1919
        var edgesSeen map[uint64]struct{}
3✔
1920
        var edgesToCache map[uint64]ChannelEdge
3✔
1921
        var edgesInHorizon []ChannelEdge
3✔
1922

3✔
1923
        c.cacheMu.Lock()
3✔
1924
        defer c.cacheMu.Unlock()
3✔
1925

3✔
1926
        var hits int
3✔
1927
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1928
                edges := tx.ReadBucket(edgeBucket)
3✔
1929
                if edges == nil {
3✔
1930
                        return ErrGraphNoEdgesFound
×
1931
                }
×
1932
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1933
                if edgeIndex == nil {
3✔
1934
                        return ErrGraphNoEdgesFound
×
1935
                }
×
1936
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
3✔
1937
                if edgeUpdateIndex == nil {
3✔
1938
                        return ErrGraphNoEdgesFound
×
1939
                }
×
1940

1941
                nodes := tx.ReadBucket(nodeBucket)
3✔
1942
                if nodes == nil {
3✔
1943
                        return ErrGraphNodesNotFound
×
1944
                }
×
1945

1946
                // We'll now obtain a cursor to perform a range query within
1947
                // the index to find all channels within the horizon.
1948
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
1949

3✔
1950
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
1951
                byteOrder.PutUint64(
3✔
1952
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
1953
                )
3✔
1954
                byteOrder.PutUint64(
3✔
1955
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
1956
                )
3✔
1957

3✔
1958
                // With our start and end times constructed, we'll step through
3✔
1959
                // the index collecting the info and policy of each update of
3✔
1960
                // each channel that has a last update within the time range.
3✔
1961
                //
3✔
1962
                //nolint:ll
3✔
1963
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
1964
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
1965
                        // We have a new eligible entry, so we'll slice of the
3✔
1966
                        // chan ID so we can query it in the DB.
3✔
1967
                        chanID := indexKey[8:]
3✔
1968

3✔
1969
                        // If we've already retrieved the info and policies for
3✔
1970
                        // this edge, then we can skip it as we don't need to do
3✔
1971
                        // so again.
3✔
1972
                        chanIDInt := byteOrder.Uint64(chanID)
3✔
1973
                        if _, ok := edgesSeen[chanIDInt]; ok {
3✔
UNCOV
1974
                                continue
×
1975
                        }
1976

1977
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
1978
                                hits++
3✔
1979
                                edgesSeen[chanIDInt] = struct{}{}
3✔
1980
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
1981

3✔
1982
                                continue
3✔
1983
                        }
1984

1985
                        // First, we'll fetch the static edge information.
1986
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
1987
                        if err != nil {
3✔
1988
                                chanID := byteOrder.Uint64(chanID)
×
1989
                                return fmt.Errorf("unable to fetch info for "+
×
1990
                                        "edge with chan_id=%v: %v", chanID, err)
×
1991
                        }
×
1992

1993
                        // With the static information obtained, we'll now
1994
                        // fetch the dynamic policy info.
1995
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
1996
                                edgeIndex, edges, chanID,
3✔
1997
                        )
3✔
1998
                        if err != nil {
3✔
1999
                                chanID := byteOrder.Uint64(chanID)
×
2000
                                return fmt.Errorf("unable to fetch policies "+
×
2001
                                        "for edge with chan_id=%v: %v", chanID,
×
2002
                                        err)
×
2003
                        }
×
2004

2005
                        node1, err := fetchLightningNode(
3✔
2006
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2007
                        )
3✔
2008
                        if err != nil {
3✔
2009
                                return err
×
2010
                        }
×
2011

2012
                        node2, err := fetchLightningNode(
3✔
2013
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2014
                        )
3✔
2015
                        if err != nil {
3✔
2016
                                return err
×
2017
                        }
×
2018

2019
                        // Finally, we'll collate this edge with the rest of
2020
                        // edges to be returned.
2021
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2022
                        channel := ChannelEdge{
3✔
2023
                                Info:    &edgeInfo,
3✔
2024
                                Policy1: edge1,
3✔
2025
                                Policy2: edge2,
3✔
2026
                                Node1:   &node1,
3✔
2027
                                Node2:   &node2,
3✔
2028
                        }
3✔
2029
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2030
                        edgesToCache[chanIDInt] = channel
3✔
2031
                }
2032

2033
                return nil
3✔
2034
        }, func() {
3✔
2035
                edgesSeen = make(map[uint64]struct{})
3✔
2036
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2037
                edgesInHorizon = nil
3✔
2038
        })
3✔
2039
        switch {
3✔
2040
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2041
                fallthrough
×
2042
        case errors.Is(err, ErrGraphNodesNotFound):
×
2043
                break
×
2044

2045
        case err != nil:
×
2046
                return nil, err
×
2047
        }
2048

2049
        // Insert any edges loaded from disk into the cache.
2050
        for chanid, channel := range edgesToCache {
6✔
2051
                c.chanCache.insert(chanid, channel)
3✔
2052
        }
3✔
2053

2054
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
3✔
2055
                float64(hits)/float64(len(edgesInHorizon)), hits,
3✔
2056
                len(edgesInHorizon))
3✔
2057

3✔
2058
        return edgesInHorizon, nil
3✔
2059
}
2060

2061
// NodeUpdatesInHorizon returns all the known lightning node which have an
2062
// update timestamp within the passed range. This method can be used by two
2063
// nodes to quickly determine if they have the same set of up to date node
2064
// announcements.
2065
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2066
        endTime time.Time) ([]models.LightningNode, error) {
3✔
2067

3✔
2068
        var nodesInHorizon []models.LightningNode
3✔
2069

3✔
2070
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2071
                nodes := tx.ReadBucket(nodeBucket)
3✔
2072
                if nodes == nil {
3✔
2073
                        return ErrGraphNodesNotFound
×
2074
                }
×
2075

2076
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2077
                if nodeUpdateIndex == nil {
3✔
2078
                        return ErrGraphNodesNotFound
×
2079
                }
×
2080

2081
                // We'll now obtain a cursor to perform a range query within
2082
                // the index to find all node announcements within the horizon.
2083
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2084

3✔
2085
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2086
                byteOrder.PutUint64(
3✔
2087
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2088
                )
3✔
2089
                byteOrder.PutUint64(
3✔
2090
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2091
                )
3✔
2092

3✔
2093
                // With our start and end times constructed, we'll step through
3✔
2094
                // the index collecting info for each node within the time
3✔
2095
                // range.
3✔
2096
                //
3✔
2097
                //nolint:ll
3✔
2098
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2099
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2100
                        nodePub := indexKey[8:]
3✔
2101
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2102
                        if err != nil {
3✔
2103
                                return err
×
2104
                        }
×
2105

2106
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2107
                }
2108

2109
                return nil
3✔
2110
        }, func() {
3✔
2111
                nodesInHorizon = nil
3✔
2112
        })
3✔
2113
        switch {
3✔
2114
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2115
                fallthrough
×
2116
        case errors.Is(err, ErrGraphNodesNotFound):
×
2117
                break
×
2118

2119
        case err != nil:
×
2120
                return nil, err
×
2121
        }
2122

2123
        return nodesInHorizon, nil
3✔
2124
}
2125

2126
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2127
// ID's that we don't know and are not known zombies of the passed set. In other
2128
// words, we perform a set difference of our set of chan ID's and the ones
2129
// passed in. This method can be used by callers to determine the set of
2130
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2131
// known zombies is also returned.
2132
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2133
        []ChannelUpdateInfo, error) {
3✔
2134

3✔
2135
        var (
3✔
2136
                newChanIDs   []uint64
3✔
2137
                knownZombies []ChannelUpdateInfo
3✔
2138
        )
3✔
2139

3✔
2140
        c.cacheMu.Lock()
3✔
2141
        defer c.cacheMu.Unlock()
3✔
2142

3✔
2143
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2144
                edges := tx.ReadBucket(edgeBucket)
3✔
2145
                if edges == nil {
3✔
2146
                        return ErrGraphNoEdgesFound
×
2147
                }
×
2148
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2149
                if edgeIndex == nil {
3✔
2150
                        return ErrGraphNoEdgesFound
×
2151
                }
×
2152

2153
                // Fetch the zombie index, it may not exist if no edges have
2154
                // ever been marked as zombies. If the index has been
2155
                // initialized, we will use it later to skip known zombie edges.
2156
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2157

3✔
2158
                // We'll run through the set of chanIDs and collate only the
3✔
2159
                // set of channel that are unable to be found within our db.
3✔
2160
                var cidBytes [8]byte
3✔
2161
                for _, info := range chansInfo {
6✔
2162
                        scid := info.ShortChannelID.ToUint64()
3✔
2163
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2164

3✔
2165
                        // If the edge is already known, skip it.
3✔
2166
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
6✔
2167
                                continue
3✔
2168
                        }
2169

2170
                        // If the edge is a known zombie, skip it.
2171
                        if zombieIndex != nil {
6✔
2172
                                isZombie, _, _ := isZombieEdge(
3✔
2173
                                        zombieIndex, scid,
3✔
2174
                                )
3✔
2175

3✔
2176
                                if isZombie {
3✔
UNCOV
2177
                                        knownZombies = append(
×
UNCOV
2178
                                                knownZombies, info,
×
UNCOV
2179
                                        )
×
UNCOV
2180

×
UNCOV
2181
                                        continue
×
2182
                                }
2183
                        }
2184

2185
                        newChanIDs = append(newChanIDs, scid)
3✔
2186
                }
2187

2188
                return nil
3✔
2189
        }, func() {
3✔
2190
                newChanIDs = nil
3✔
2191
                knownZombies = nil
3✔
2192
        })
3✔
2193
        switch {
3✔
2194
        // If we don't know of any edges yet, then we'll return the entire set
2195
        // of chan IDs specified.
2196
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2197
                ogChanIDs := make([]uint64, len(chansInfo))
×
2198
                for i, info := range chansInfo {
×
2199
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2200
                }
×
2201

2202
                return ogChanIDs, nil, nil
×
2203

2204
        case err != nil:
×
2205
                return nil, nil, err
×
2206
        }
2207

2208
        return newChanIDs, knownZombies, nil
3✔
2209
}
2210

2211
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2212
// latest received channel updates for the channel.
2213
type ChannelUpdateInfo struct {
2214
        // ShortChannelID is the SCID identifier of the channel.
2215
        ShortChannelID lnwire.ShortChannelID
2216

2217
        // Node1UpdateTimestamp is the timestamp of the latest received update
2218
        // from the node 1 channel peer. This will be set to zero time if no
2219
        // update has yet been received from this node.
2220
        Node1UpdateTimestamp time.Time
2221

2222
        // Node2UpdateTimestamp is the timestamp of the latest received update
2223
        // from the node 2 channel peer. This will be set to zero time if no
2224
        // update has yet been received from this node.
2225
        Node2UpdateTimestamp time.Time
2226
}
2227

2228
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2229
// timestamps with zero seconds unix timestamp which equals
2230
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2231
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2232
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2233

3✔
2234
        chanInfo := ChannelUpdateInfo{
3✔
2235
                ShortChannelID:       scid,
3✔
2236
                Node1UpdateTimestamp: node1Timestamp,
3✔
2237
                Node2UpdateTimestamp: node2Timestamp,
3✔
2238
        }
3✔
2239

3✔
2240
        if node1Timestamp.IsZero() {
6✔
2241
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2242
        }
3✔
2243

2244
        if node2Timestamp.IsZero() {
6✔
2245
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2246
        }
3✔
2247

2248
        return chanInfo
3✔
2249
}
2250

2251
// BlockChannelRange represents a range of channels for a given block height.
2252
type BlockChannelRange struct {
2253
        // Height is the height of the block all of the channels below were
2254
        // included in.
2255
        Height uint32
2256

2257
        // Channels is the list of channels identified by their short ID
2258
        // representation known to us that were included in the block height
2259
        // above. The list may include channel update timestamp information if
2260
        // requested.
2261
        Channels []ChannelUpdateInfo
2262
}
2263

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

3✔
2274
        startChanID := &lnwire.ShortChannelID{
3✔
2275
                BlockHeight: startHeight,
3✔
2276
        }
3✔
2277

3✔
2278
        endChanID := lnwire.ShortChannelID{
3✔
2279
                BlockHeight: endHeight,
3✔
2280
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2281
                TxPosition:  math.MaxUint16,
3✔
2282
        }
3✔
2283

3✔
2284
        // As we need to perform a range scan, we'll convert the starting and
3✔
2285
        // ending height to their corresponding values when encoded using short
3✔
2286
        // channel ID's.
3✔
2287
        var chanIDStart, chanIDEnd [8]byte
3✔
2288
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
3✔
2289
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
3✔
2290

3✔
2291
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
3✔
2292
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2293
                edges := tx.ReadBucket(edgeBucket)
3✔
2294
                if edges == nil {
3✔
2295
                        return ErrGraphNoEdgesFound
×
2296
                }
×
2297
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2298
                if edgeIndex == nil {
3✔
2299
                        return ErrGraphNoEdgesFound
×
2300
                }
×
2301

2302
                cursor := edgeIndex.ReadCursor()
3✔
2303

3✔
2304
                // We'll now iterate through the database, and find each
3✔
2305
                // channel ID that resides within the specified range.
3✔
2306
                //
3✔
2307
                //nolint:ll
3✔
2308
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
2309
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
6✔
2310
                        // Don't send alias SCIDs during gossip sync.
3✔
2311
                        edgeReader := bytes.NewReader(v)
3✔
2312
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
3✔
2313
                        if err != nil {
3✔
2314
                                return err
×
2315
                        }
×
2316

2317
                        if edgeInfo.AuthProof == nil {
6✔
2318
                                continue
3✔
2319
                        }
2320

2321
                        // This channel ID rests within the target range, so
2322
                        // we'll add it to our returned set.
2323
                        rawCid := byteOrder.Uint64(k)
3✔
2324
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2325

3✔
2326
                        chanInfo := NewChannelUpdateInfo(
3✔
2327
                                cid, time.Time{}, time.Time{},
3✔
2328
                        )
3✔
2329

3✔
2330
                        if !withTimestamps {
3✔
UNCOV
2331
                                channelsPerBlock[cid.BlockHeight] = append(
×
UNCOV
2332
                                        channelsPerBlock[cid.BlockHeight],
×
UNCOV
2333
                                        chanInfo,
×
UNCOV
2334
                                )
×
UNCOV
2335

×
UNCOV
2336
                                continue
×
2337
                        }
2338

2339
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2340

3✔
2341
                        rawPolicy := edges.Get(node1Key)
3✔
2342
                        if len(rawPolicy) != 0 {
6✔
2343
                                r := bytes.NewReader(rawPolicy)
3✔
2344

3✔
2345
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2346
                                if err != nil && !errors.Is(
3✔
2347
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2348
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2349

×
2350
                                        return err
×
2351
                                }
×
2352

2353
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2354
                        }
2355

2356
                        rawPolicy = edges.Get(node2Key)
3✔
2357
                        if len(rawPolicy) != 0 {
6✔
2358
                                r := bytes.NewReader(rawPolicy)
3✔
2359

3✔
2360
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2361
                                if err != nil && !errors.Is(
3✔
2362
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2363
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2364

×
2365
                                        return err
×
2366
                                }
×
2367

2368
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2369
                        }
2370

2371
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2372
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2373
                        )
3✔
2374
                }
2375

2376
                return nil
3✔
2377
        }, func() {
3✔
2378
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2379
        })
3✔
2380

2381
        switch {
3✔
2382
        // If we don't know of any channels yet, then there's nothing to
2383
        // filter, so we'll return an empty slice.
2384
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
3✔
2385
                return nil, nil
3✔
2386

2387
        case err != nil:
×
2388
                return nil, err
×
2389
        }
2390

2391
        // Return the channel ranges in ascending block height order.
2392
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2393
        for block := range channelsPerBlock {
6✔
2394
                blocks = append(blocks, block)
3✔
2395
        }
3✔
2396
        sort.Slice(blocks, func(i, j int) bool {
6✔
2397
                return blocks[i] < blocks[j]
3✔
2398
        })
3✔
2399

2400
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2401
        for _, block := range blocks {
6✔
2402
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2403
                        Height:   block,
3✔
2404
                        Channels: channelsPerBlock[block],
3✔
2405
                })
3✔
2406
        }
3✔
2407

2408
        return channelRanges, nil
3✔
2409
}
2410

2411
// FetchChanInfos returns the set of channel edges that correspond to the passed
2412
// channel ID's. If an edge is the query is unknown to the database, it will
2413
// skipped and the result will contain only those edges that exist at the time
2414
// of the query. This can be used to respond to peer queries that are seeking to
2415
// fill in gaps in their view of the channel graph.
2416
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
2417
        return c.fetchChanInfos(nil, chanIDs)
3✔
2418
}
3✔
2419

2420
// fetchChanInfos returns the set of channel edges that correspond to the passed
2421
// channel ID's. If an edge is the query is unknown to the database, it will
2422
// skipped and the result will contain only those edges that exist at the time
2423
// of the query. This can be used to respond to peer queries that are seeking to
2424
// fill in gaps in their view of the channel graph.
2425
//
2426
// NOTE: An optional transaction may be provided. If none is provided, then a
2427
// new one will be created.
2428
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2429
        []ChannelEdge, error) {
3✔
2430
        // TODO(roasbeef): sort cids?
3✔
2431

3✔
2432
        var (
3✔
2433
                chanEdges []ChannelEdge
3✔
2434
                cidBytes  [8]byte
3✔
2435
        )
3✔
2436

3✔
2437
        fetchChanInfos := func(tx kvdb.RTx) error {
6✔
2438
                edges := tx.ReadBucket(edgeBucket)
3✔
2439
                if edges == nil {
3✔
2440
                        return ErrGraphNoEdgesFound
×
2441
                }
×
2442
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2443
                if edgeIndex == nil {
3✔
2444
                        return ErrGraphNoEdgesFound
×
2445
                }
×
2446
                nodes := tx.ReadBucket(nodeBucket)
3✔
2447
                if nodes == nil {
3✔
2448
                        return ErrGraphNotFound
×
2449
                }
×
2450

2451
                for _, cid := range chanIDs {
6✔
2452
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2453

3✔
2454
                        // First, we'll fetch the static edge information. If
3✔
2455
                        // the edge is unknown, we will skip the edge and
3✔
2456
                        // continue gathering all known edges.
3✔
2457
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2458
                                edgeIndex, cidBytes[:],
3✔
2459
                        )
3✔
2460
                        switch {
3✔
UNCOV
2461
                        case errors.Is(err, ErrEdgeNotFound):
×
UNCOV
2462
                                continue
×
2463
                        case err != nil:
×
2464
                                return err
×
2465
                        }
2466

2467
                        // With the static information obtained, we'll now
2468
                        // fetch the dynamic policy info.
2469
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2470
                                edgeIndex, edges, cidBytes[:],
3✔
2471
                        )
3✔
2472
                        if err != nil {
3✔
2473
                                return err
×
2474
                        }
×
2475

2476
                        node1, err := fetchLightningNode(
3✔
2477
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2478
                        )
3✔
2479
                        if err != nil {
3✔
2480
                                return err
×
2481
                        }
×
2482

2483
                        node2, err := fetchLightningNode(
3✔
2484
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2485
                        )
3✔
2486
                        if err != nil {
3✔
2487
                                return err
×
2488
                        }
×
2489

2490
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2491
                                Info:    &edgeInfo,
3✔
2492
                                Policy1: edge1,
3✔
2493
                                Policy2: edge2,
3✔
2494
                                Node1:   &node1,
3✔
2495
                                Node2:   &node2,
3✔
2496
                        })
3✔
2497
                }
2498

2499
                return nil
3✔
2500
        }
2501

2502
        if tx == nil {
6✔
2503
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2504
                        chanEdges = nil
3✔
2505
                })
3✔
2506
                if err != nil {
3✔
2507
                        return nil, err
×
2508
                }
×
2509

2510
                return chanEdges, nil
3✔
2511
        }
2512

2513
        err := fetchChanInfos(tx)
×
2514
        if err != nil {
×
2515
                return nil, err
×
2516
        }
×
2517

2518
        return chanEdges, nil
×
2519
}
2520

2521
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2522
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2523

3✔
2524
        // First, we'll fetch the edge update index bucket which currently
3✔
2525
        // stores an entry for the channel we're about to delete.
3✔
2526
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2527
        if updateIndex == nil {
3✔
2528
                // No edges in bucket, return early.
×
2529
                return nil
×
2530
        }
×
2531

2532
        // Now that we have the bucket, we'll attempt to construct a template
2533
        // for the index key: updateTime || chanid.
2534
        var indexKey [8 + 8]byte
3✔
2535
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2536

3✔
2537
        // With the template constructed, we'll attempt to delete an entry that
3✔
2538
        // would have been created by both edges: we'll alternate the update
3✔
2539
        // times, as one may had overridden the other.
3✔
2540
        if edge1 != nil {
6✔
2541
                byteOrder.PutUint64(
3✔
2542
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
3✔
2543
                )
3✔
2544
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2545
                        return err
×
2546
                }
×
2547
        }
2548

2549
        // We'll also attempt to delete the entry that may have been created by
2550
        // the second edge.
2551
        if edge2 != nil {
6✔
2552
                byteOrder.PutUint64(
3✔
2553
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2554
                )
3✔
2555
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2556
                        return err
×
2557
                }
×
2558
        }
2559

2560
        return nil
3✔
2561
}
2562

2563
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2564
// cache. It then goes on to delete any policy info and edge info for this
2565
// channel from the DB and finally, if isZombie is true, it will add an entry
2566
// for this channel in the zombie index.
2567
//
2568
// NOTE: this method MUST only be called if the cacheMu has already been
2569
// acquired.
2570
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2571
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2572
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
3✔
2573

3✔
2574
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2575
        if err != nil {
3✔
UNCOV
2576
                return nil, err
×
UNCOV
2577
        }
×
2578

2579
        // We'll also remove the entry in the edge update index bucket before
2580
        // we delete the edges themselves so we can access their last update
2581
        // times.
2582
        cid := byteOrder.Uint64(chanID)
3✔
2583
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2584
        if err != nil {
3✔
2585
                return nil, err
×
2586
        }
×
2587
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2588
        if err != nil {
3✔
2589
                return nil, err
×
2590
        }
×
2591

2592
        // The edge key is of the format pubKey || chanID. First we construct
2593
        // the latter half, populating the channel ID.
2594
        var edgeKey [33 + 8]byte
3✔
2595
        copy(edgeKey[33:], chanID)
3✔
2596

3✔
2597
        // With the latter half constructed, copy over the first public key to
3✔
2598
        // delete the edge in this direction, then the second to delete the
3✔
2599
        // edge in the opposite direction.
3✔
2600
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2601
        if edges.Get(edgeKey[:]) != nil {
6✔
2602
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2603
                        return nil, err
×
2604
                }
×
2605
        }
2606
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2607
        if edges.Get(edgeKey[:]) != nil {
6✔
2608
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2609
                        return nil, err
×
2610
                }
×
2611
        }
2612

2613
        // As part of deleting the edge we also remove all disabled entries
2614
        // from the edgePolicyDisabledIndex bucket. We do that for both
2615
        // directions.
2616
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
3✔
2617
        if err != nil {
3✔
2618
                return nil, err
×
2619
        }
×
2620
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2621
        if err != nil {
3✔
2622
                return nil, err
×
2623
        }
×
2624

2625
        // With the edge data deleted, we can purge the information from the two
2626
        // edge indexes.
2627
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2628
                return nil, err
×
2629
        }
×
2630
        var b bytes.Buffer
3✔
2631
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2632
                return nil, err
×
2633
        }
×
2634
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
2635
                return nil, err
×
2636
        }
×
2637

2638
        // Finally, we'll mark the edge as a zombie within our index if it's
2639
        // being removed due to the channel becoming a zombie. We do this to
2640
        // ensure we don't store unnecessary data for spent channels.
2641
        if !isZombie {
6✔
2642
                return &edgeInfo, nil
3✔
2643
        }
3✔
2644

2645
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2646
        if strictZombie {
3✔
UNCOV
2647
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
×
UNCOV
2648
        }
×
2649

2650
        return &edgeInfo, markEdgeZombie(
3✔
2651
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2652
        )
3✔
2653
}
2654

2655
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2656
// particular pair of channel policies. The return values are one of:
2657
//  1. (pubkey1, pubkey2)
2658
//  2. (pubkey1, blank)
2659
//  3. (blank, pubkey2)
2660
//
2661
// A blank pubkey means that corresponding node will be unable to resurrect a
2662
// channel on its own. For example, node1 may continue to publish recent
2663
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2664
// we don't want another fresh update from node1 to resurrect, as the edge can
2665
// only become live once node2 finally sends something recent.
2666
//
2667
// In the case where we have neither update, we allow either party to resurrect
2668
// the channel. If the channel were to be marked zombie again, it would be
2669
// marked with the correct lagging channel since we received an update from only
2670
// one side.
2671
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
UNCOV
2672
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
×
UNCOV
2673

×
UNCOV
2674
        switch {
×
2675
        // If we don't have either edge policy, we'll return both pubkeys so
2676
        // that the channel can be resurrected by either party.
UNCOV
2677
        case e1 == nil && e2 == nil:
×
UNCOV
2678
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2679

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

2687
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2688
        // return a blank pubkey for edge1. In this case, only an update from
2689
        // edge2 can resurect the channel.
UNCOV
2690
        default:
×
UNCOV
2691
                return [33]byte{}, info.NodeKey2Bytes
×
2692
        }
2693
}
2694

2695
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2696
// within the database for the referenced channel. The `flags` attribute within
2697
// the ChannelEdgePolicy determines which of the directed edges are being
2698
// updated. If the flag is 1, then the first node's information is being
2699
// updated, otherwise it's the second node's information. The node ordering is
2700
// determined by the lexicographical ordering of the identity public keys of the
2701
// nodes on either side of the channel.
2702
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2703
        opts ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
3✔
2704

3✔
2705
        var (
3✔
2706
                ctx          = context.TODO()
3✔
2707
                isUpdate1    bool
3✔
2708
                edgeNotFound bool
3✔
2709
                from, to     route.Vertex
3✔
2710
        )
3✔
2711

3✔
2712
        r := &batch.Request[kvdb.RwTx]{
3✔
2713
                Opts: batch.NewSchedulerOptions(opts...),
3✔
2714
                Reset: func() {
6✔
2715
                        isUpdate1 = false
3✔
2716
                        edgeNotFound = false
3✔
2717
                },
3✔
2718
                Do: func(tx kvdb.RwTx) error {
3✔
2719
                        var err error
3✔
2720
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
3✔
2721
                        if err != nil {
3✔
UNCOV
2722
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
×
UNCOV
2723
                        }
×
2724

2725
                        // Silence ErrEdgeNotFound so that the batch can
2726
                        // succeed, but propagate the error via local state.
2727
                        if errors.Is(err, ErrEdgeNotFound) {
3✔
UNCOV
2728
                                edgeNotFound = true
×
UNCOV
2729
                                return nil
×
UNCOV
2730
                        }
×
2731

2732
                        return err
3✔
2733
                },
2734
                OnCommit: func(err error) error {
3✔
2735
                        switch {
3✔
2736
                        case err != nil:
×
2737
                                return err
×
UNCOV
2738
                        case edgeNotFound:
×
UNCOV
2739
                                return ErrEdgeNotFound
×
2740
                        default:
3✔
2741
                                c.updateEdgeCache(edge, isUpdate1)
3✔
2742
                                return nil
3✔
2743
                        }
2744
                },
2745
        }
2746

2747
        err := c.chanScheduler.Execute(ctx, r)
3✔
2748

3✔
2749
        return from, to, err
3✔
2750
}
2751

2752
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2753
        isUpdate1 bool) {
3✔
2754

3✔
2755
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2756
        // the entry with the updated timestamp for the direction that was just
3✔
2757
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2758
        // during the next query for this edge.
3✔
2759
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2760
                if isUpdate1 {
6✔
2761
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2762
                } else {
6✔
2763
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2764
                }
3✔
2765
                c.rejectCache.insert(e.ChannelID, entry)
3✔
2766
        }
2767

2768
        // If an entry for this channel is found in channel cache, we'll modify
2769
        // the entry with the updated policy for the direction that was just
2770
        // written. If the edge doesn't exist, we'll defer loading the info and
2771
        // policies and lazily read from disk during the next query.
2772
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
6✔
2773
                if isUpdate1 {
6✔
2774
                        channel.Policy1 = e
3✔
2775
                } else {
6✔
2776
                        channel.Policy2 = e
3✔
2777
                }
3✔
2778
                c.chanCache.insert(e.ChannelID, channel)
3✔
2779
        }
2780
}
2781

2782
// updateEdgePolicy attempts to update an edge's policy within the relevant
2783
// buckets using an existing database transaction. The returned boolean will be
2784
// true if the updated policy belongs to node1, and false if the policy belonged
2785
// to node2.
2786
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2787
        route.Vertex, route.Vertex, bool, error) {
3✔
2788

3✔
2789
        var noVertex route.Vertex
3✔
2790

3✔
2791
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2792
        if edges == nil {
3✔
2793
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2794
        }
×
2795
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2796
        if edgeIndex == nil {
3✔
2797
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2798
        }
×
2799

2800
        // Create the channelID key be converting the channel ID
2801
        // integer into a byte slice.
2802
        var chanID [8]byte
3✔
2803
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2804

3✔
2805
        // With the channel ID, we then fetch the value storing the two
3✔
2806
        // nodes which connect this channel edge.
3✔
2807
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2808
        if nodeInfo == nil {
3✔
UNCOV
2809
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2810
        }
×
2811

2812
        // Depending on the flags value passed above, either the first
2813
        // or second edge policy is being updated.
2814
        var fromNode, toNode []byte
3✔
2815
        var isUpdate1 bool
3✔
2816
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2817
                fromNode = nodeInfo[:33]
3✔
2818
                toNode = nodeInfo[33:66]
3✔
2819
                isUpdate1 = true
3✔
2820
        } else {
6✔
2821
                fromNode = nodeInfo[33:66]
3✔
2822
                toNode = nodeInfo[:33]
3✔
2823
                isUpdate1 = false
3✔
2824
        }
3✔
2825

2826
        // Finally, with the direction of the edge being updated
2827
        // identified, we update the on-disk edge representation.
2828
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
3✔
2829
        if err != nil {
3✔
2830
                return noVertex, noVertex, false, err
×
2831
        }
×
2832

2833
        var (
3✔
2834
                fromNodePubKey route.Vertex
3✔
2835
                toNodePubKey   route.Vertex
3✔
2836
        )
3✔
2837
        copy(fromNodePubKey[:], fromNode)
3✔
2838
        copy(toNodePubKey[:], toNode)
3✔
2839

3✔
2840
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
3✔
2841
}
2842

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

3✔
2849
        // In order to determine whether this node is publicly advertised within
3✔
2850
        // the graph, we'll need to look at all of its edges and check whether
3✔
2851
        // they extend to any other node than the source node. errDone will be
3✔
2852
        // used to terminate the check early.
3✔
2853
        nodeIsPublic := false
3✔
2854
        errDone := errors.New("done")
3✔
2855
        err := c.forEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
3✔
2856
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
3✔
2857
                _ *models.ChannelEdgePolicy) error {
6✔
2858

3✔
2859
                // If this edge doesn't extend to the source node, we'll
3✔
2860
                // terminate our search as we can now conclude that the node is
3✔
2861
                // publicly advertised within the graph due to the local node
3✔
2862
                // knowing of the current edge.
3✔
2863
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
3✔
2864
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
6✔
2865

3✔
2866
                        nodeIsPublic = true
3✔
2867
                        return errDone
3✔
2868
                }
3✔
2869

2870
                // Since the edge _does_ extend to the source node, we'll also
2871
                // need to ensure that this is a public edge.
2872
                if info.AuthProof != nil {
6✔
2873
                        nodeIsPublic = true
3✔
2874
                        return errDone
3✔
2875
                }
3✔
2876

2877
                // Otherwise, we'll continue our search.
2878
                return nil
3✔
2879
        })
2880
        if err != nil && !errors.Is(err, errDone) {
3✔
2881
                return false, err
×
2882
        }
×
2883

2884
        return nodeIsPublic, nil
3✔
2885
}
2886

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

3✔
2894
        return c.fetchLightningNode(tx, nodePub)
3✔
2895
}
3✔
2896

2897
// FetchLightningNode attempts to look up a target node by its identity public
2898
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2899
// returned.
2900
func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
2901
        *models.LightningNode, error) {
3✔
2902

3✔
2903
        return c.fetchLightningNode(nil, nodePub)
3✔
2904
}
3✔
2905

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

3✔
2913
        var node *models.LightningNode
3✔
2914
        fetch := func(tx kvdb.RTx) error {
6✔
2915
                // First grab the nodes bucket which stores the mapping from
3✔
2916
                // pubKey to node information.
3✔
2917
                nodes := tx.ReadBucket(nodeBucket)
3✔
2918
                if nodes == nil {
3✔
2919
                        return ErrGraphNotFound
×
2920
                }
×
2921

2922
                // If a key for this serialized public key isn't found, then
2923
                // the target node doesn't exist within the database.
2924
                nodeBytes := nodes.Get(nodePub[:])
3✔
2925
                if nodeBytes == nil {
6✔
2926
                        return ErrGraphNodeNotFound
3✔
2927
                }
3✔
2928

2929
                // If the node is found, then we can de deserialize the node
2930
                // information to return to the user.
2931
                nodeReader := bytes.NewReader(nodeBytes)
3✔
2932
                n, err := deserializeLightningNode(nodeReader)
3✔
2933
                if err != nil {
3✔
2934
                        return err
×
2935
                }
×
2936

2937
                node = &n
3✔
2938

3✔
2939
                return nil
3✔
2940
        }
2941

2942
        if tx == nil {
6✔
2943
                err := kvdb.View(
3✔
2944
                        c.db, fetch, func() {
6✔
2945
                                node = nil
3✔
2946
                        },
3✔
2947
                )
2948
                if err != nil {
6✔
2949
                        return nil, err
3✔
2950
                }
3✔
2951

2952
                return node, nil
3✔
2953
        }
2954

UNCOV
2955
        err := fetch(tx)
×
UNCOV
2956
        if err != nil {
×
UNCOV
2957
                return nil, err
×
UNCOV
2958
        }
×
2959

UNCOV
2960
        return node, nil
×
2961
}
2962

2963
// HasLightningNode determines if the graph has a vertex identified by the
2964
// target node identity public key. If the node exists in the database, a
2965
// timestamp of when the data for the node was lasted updated is returned along
2966
// with a true boolean. Otherwise, an empty time.Time is returned with a false
2967
// boolean.
2968
func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
2969
        error) {
3✔
2970

3✔
2971
        var (
3✔
2972
                updateTime time.Time
3✔
2973
                exists     bool
3✔
2974
        )
3✔
2975

3✔
2976
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2977
                // First grab the nodes bucket which stores the mapping from
3✔
2978
                // pubKey to node information.
3✔
2979
                nodes := tx.ReadBucket(nodeBucket)
3✔
2980
                if nodes == nil {
3✔
2981
                        return ErrGraphNotFound
×
2982
                }
×
2983

2984
                // If a key for this serialized public key isn't found, we can
2985
                // exit early.
2986
                nodeBytes := nodes.Get(nodePub[:])
3✔
2987
                if nodeBytes == nil {
6✔
2988
                        exists = false
3✔
2989
                        return nil
3✔
2990
                }
3✔
2991

2992
                // Otherwise we continue on to obtain the time stamp
2993
                // representing the last time the data for this node was
2994
                // updated.
2995
                nodeReader := bytes.NewReader(nodeBytes)
3✔
2996
                node, err := deserializeLightningNode(nodeReader)
3✔
2997
                if err != nil {
3✔
2998
                        return err
×
2999
                }
×
3000

3001
                exists = true
3✔
3002
                updateTime = node.LastUpdate
3✔
3003

3✔
3004
                return nil
3✔
3005
        }, func() {
3✔
3006
                updateTime = time.Time{}
3✔
3007
                exists = false
3✔
3008
        })
3✔
3009
        if err != nil {
3✔
3010
                return time.Time{}, exists, err
×
3011
        }
×
3012

3013
        return updateTime, exists, nil
3✔
3014
}
3015

3016
// nodeTraversal is used to traverse all channels of a node given by its
3017
// public key and passes channel information into the specified callback.
3018
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3019
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3020
                *models.ChannelEdgePolicy) error) error {
3✔
3021

3✔
3022
        traversal := func(tx kvdb.RTx) error {
6✔
3023
                edges := tx.ReadBucket(edgeBucket)
3✔
3024
                if edges == nil {
3✔
3025
                        return ErrGraphNotFound
×
3026
                }
×
3027
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3028
                if edgeIndex == nil {
3✔
3029
                        return ErrGraphNoEdgesFound
×
3030
                }
×
3031

3032
                // In order to reach all the edges for this node, we take
3033
                // advantage of the construction of the key-space within the
3034
                // edge bucket. The keys are stored in the form: pubKey ||
3035
                // chanID. Therefore, starting from a chanID of zero, we can
3036
                // scan forward in the bucket, grabbing all the edges for the
3037
                // node. Once the prefix no longer matches, then we know we're
3038
                // done.
3039
                var nodeStart [33 + 8]byte
3✔
3040
                copy(nodeStart[:], nodePub)
3✔
3041
                copy(nodeStart[33:], chanStart[:])
3✔
3042

3✔
3043
                // Starting from the key pubKey || 0, we seek forward in the
3✔
3044
                // bucket until the retrieved key no longer has the public key
3✔
3045
                // as its prefix. This indicates that we've stepped over into
3✔
3046
                // another node's edges, so we can terminate our scan.
3✔
3047
                edgeCursor := edges.ReadCursor()
3✔
3048
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
6✔
3049
                        // If the prefix still matches, the channel id is
3✔
3050
                        // returned in nodeEdge. Channel id is used to lookup
3✔
3051
                        // the node at the other end of the channel and both
3✔
3052
                        // edge policies.
3✔
3053
                        chanID := nodeEdge[33:]
3✔
3054
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3055
                        if err != nil {
3✔
3056
                                return err
×
3057
                        }
×
3058

3059
                        outgoingPolicy, err := fetchChanEdgePolicy(
3✔
3060
                                edges, chanID, nodePub,
3✔
3061
                        )
3✔
3062
                        if err != nil {
3✔
3063
                                return err
×
3064
                        }
×
3065

3066
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3067
                        if err != nil {
3✔
3068
                                return err
×
3069
                        }
×
3070

3071
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3072
                                edges, chanID, otherNode[:],
3✔
3073
                        )
3✔
3074
                        if err != nil {
3✔
3075
                                return err
×
3076
                        }
×
3077

3078
                        // Finally, we execute the callback.
3079
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3080
                        if err != nil {
6✔
3081
                                return err
3✔
3082
                        }
3✔
3083
                }
3084

3085
                return nil
3✔
3086
        }
3087

3088
        // If no transaction was provided, then we'll create a new transaction
3089
        // to execute the transaction within.
3090
        if tx == nil {
6✔
3091
                return kvdb.View(db, traversal, func() {})
6✔
3092
        }
3093

3094
        // Otherwise, we re-use the existing transaction to execute the graph
3095
        // traversal.
3096
        return traversal(tx)
3✔
3097
}
3098

3099
// ForEachNodeChannel iterates through all channels of the given node,
3100
// executing the passed callback with an edge info structure and the policies
3101
// of each end of the channel. The first edge policy is the outgoing edge *to*
3102
// the connecting node, while the second is the incoming edge *from* the
3103
// connecting node. If the callback returns an error, then the iteration is
3104
// halted with the error propagated back up to the caller.
3105
//
3106
// Unknown policies are passed into the callback as nil values.
3107
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3108
        cb func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3109
                *models.ChannelEdgePolicy) error) error {
3✔
3110

3✔
3111
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
3✔
3112
                info *models.ChannelEdgeInfo, policy,
3✔
3113
                policy2 *models.ChannelEdgePolicy) error {
6✔
3114

3✔
3115
                return cb(info, policy, policy2)
3✔
3116
        })
3✔
3117
}
3118

3119
// ForEachSourceNodeChannel iterates through all channels of the source node,
3120
// executing the passed callback on each. The callback is provided with the
3121
// channel's outpoint, whether we have a policy for the channel and the channel
3122
// peer's node information.
3123
func (c *KVStore) ForEachSourceNodeChannel(cb func(chanPoint wire.OutPoint,
3124
        havePolicy bool, otherNode *models.LightningNode) error) error {
3✔
3125

3✔
3126
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3127
                nodes := tx.ReadBucket(nodeBucket)
3✔
3128
                if nodes == nil {
3✔
3129
                        return ErrGraphNotFound
×
3130
                }
×
3131

3132
                node, err := c.sourceNode(nodes)
3✔
3133
                if err != nil {
3✔
3134
                        return err
×
3135
                }
×
3136

3137
                return nodeTraversal(
3✔
3138
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
3✔
3139
                                info *models.ChannelEdgeInfo,
3✔
3140
                                policy, _ *models.ChannelEdgePolicy) error {
6✔
3141

3✔
3142
                                peer, err := c.fetchOtherNode(
3✔
3143
                                        tx, info, node.PubKeyBytes[:],
3✔
3144
                                )
3✔
3145
                                if err != nil {
3✔
3146
                                        return err
×
3147
                                }
×
3148

3149
                                return cb(
3✔
3150
                                        info.ChannelPoint, policy != nil, peer,
3✔
3151
                                )
3✔
3152
                        },
3153
                )
3154
        }, func() {})
3✔
3155
}
3156

3157
// forEachNodeChannelTx iterates through all channels of the given node,
3158
// executing the passed callback with an edge info structure and the policies
3159
// of each end of the channel. The first edge policy is the outgoing edge *to*
3160
// the connecting node, while the second is the incoming edge *from* the
3161
// connecting node. If the callback returns an error, then the iteration is
3162
// halted with the error propagated back up to the caller.
3163
//
3164
// Unknown policies are passed into the callback as nil values.
3165
//
3166
// If the caller wishes to re-use an existing boltdb transaction, then it
3167
// should be passed as the first argument.  Otherwise, the first argument should
3168
// be nil and a fresh transaction will be created to execute the graph
3169
// traversal.
3170
func (c *KVStore) forEachNodeChannelTx(tx kvdb.RTx,
3171
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3172
                *models.ChannelEdgePolicy,
3173
                *models.ChannelEdgePolicy) error) error {
3✔
3174

3✔
3175
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3176
}
3✔
3177

3178
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3179
// the target node in the channel. This is useful when one knows the pubkey of
3180
// one of the nodes, and wishes to obtain the full LightningNode for the other
3181
// end of the channel.
3182
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3183
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3184
        *models.LightningNode, error) {
3✔
3185

3✔
3186
        // Ensure that the node passed in is actually a member of the channel.
3✔
3187
        var targetNodeBytes [33]byte
3✔
3188
        switch {
3✔
3189
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3190
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3191
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3192
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3193
        default:
×
3194
                return nil, fmt.Errorf("node not participating in this channel")
×
3195
        }
3196

3197
        var targetNode *models.LightningNode
3✔
3198
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3199
                // First grab the nodes bucket which stores the mapping from
3✔
3200
                // pubKey to node information.
3✔
3201
                nodes := tx.ReadBucket(nodeBucket)
3✔
3202
                if nodes == nil {
3✔
3203
                        return ErrGraphNotFound
×
3204
                }
×
3205

3206
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3207
                if err != nil {
3✔
3208
                        return err
×
3209
                }
×
3210

3211
                targetNode = &node
3✔
3212

3✔
3213
                return nil
3✔
3214
        }
3215

3216
        // If the transaction is nil, then we'll need to create a new one,
3217
        // otherwise we can use the existing db transaction.
3218
        var err error
3✔
3219
        if tx == nil {
3✔
3220
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3221
                        targetNode = nil
×
3222
                })
×
3223
        } else {
3✔
3224
                err = fetchNodeFunc(tx)
3✔
3225
        }
3✔
3226

3227
        return targetNode, err
3✔
3228
}
3229

3230
// computeEdgePolicyKeys is a helper function that can be used to compute the
3231
// keys used to index the channel edge policy info for the two nodes of the
3232
// edge. The keys for node 1 and node 2 are returned respectively.
3233
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3✔
3234
        var (
3✔
3235
                node1Key [33 + 8]byte
3✔
3236
                node2Key [33 + 8]byte
3✔
3237
        )
3✔
3238

3✔
3239
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3240
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3241

3✔
3242
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3243
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3244

3✔
3245
        return node1Key[:], node2Key[:]
3✔
3246
}
3✔
3247

3248
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3249
// the channel identified by the funding outpoint. If the channel can't be
3250
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3251
// information for the channel itself is returned as well as two structs that
3252
// contain the routing policies for the channel in either direction.
3253
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3254
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3255
        *models.ChannelEdgePolicy, error) {
3✔
3256

3✔
3257
        var (
3✔
3258
                edgeInfo *models.ChannelEdgeInfo
3✔
3259
                policy1  *models.ChannelEdgePolicy
3✔
3260
                policy2  *models.ChannelEdgePolicy
3✔
3261
        )
3✔
3262

3✔
3263
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3264
                // First, grab the node bucket. This will be used to populate
3✔
3265
                // the Node pointers in each edge read from disk.
3✔
3266
                nodes := tx.ReadBucket(nodeBucket)
3✔
3267
                if nodes == nil {
3✔
3268
                        return ErrGraphNotFound
×
3269
                }
×
3270

3271
                // Next, grab the edge bucket which stores the edges, and also
3272
                // the index itself so we can group the directed edges together
3273
                // logically.
3274
                edges := tx.ReadBucket(edgeBucket)
3✔
3275
                if edges == nil {
3✔
3276
                        return ErrGraphNoEdgesFound
×
3277
                }
×
3278
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3279
                if edgeIndex == nil {
3✔
3280
                        return ErrGraphNoEdgesFound
×
3281
                }
×
3282

3283
                // If the channel's outpoint doesn't exist within the outpoint
3284
                // index, then the edge does not exist.
3285
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3286
                if chanIndex == nil {
3✔
3287
                        return ErrGraphNoEdgesFound
×
3288
                }
×
3289
                var b bytes.Buffer
3✔
3290
                if err := WriteOutpoint(&b, op); err != nil {
3✔
3291
                        return err
×
3292
                }
×
3293
                chanID := chanIndex.Get(b.Bytes())
3✔
3294
                if chanID == nil {
6✔
3295
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3296
                }
3✔
3297

3298
                // If the channel is found to exists, then we'll first retrieve
3299
                // the general information for the channel.
3300
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3301
                if err != nil {
3✔
3302
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3303
                }
×
3304
                edgeInfo = &edge
3✔
3305

3✔
3306
                // Once we have the information about the channels' parameters,
3✔
3307
                // we'll fetch the routing policies for each for the directed
3✔
3308
                // edges.
3✔
3309
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3310
                if err != nil {
3✔
3311
                        return fmt.Errorf("failed to find policy: %w", err)
×
3312
                }
×
3313

3314
                policy1 = e1
3✔
3315
                policy2 = e2
3✔
3316

3✔
3317
                return nil
3✔
3318
        }, func() {
3✔
3319
                edgeInfo = nil
3✔
3320
                policy1 = nil
3✔
3321
                policy2 = nil
3✔
3322
        })
3✔
3323
        if err != nil {
6✔
3324
                return nil, nil, nil, err
3✔
3325
        }
3✔
3326

3327
        return edgeInfo, policy1, policy2, nil
3✔
3328
}
3329

3330
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3331
// channel identified by the channel ID. If the channel can't be found, then
3332
// ErrEdgeNotFound is returned. A struct which houses the general information
3333
// for the channel itself is returned as well as two structs that contain the
3334
// routing policies for the channel in either direction.
3335
//
3336
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3337
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3338
// the ChannelEdgeInfo will only include the public keys of each node.
3339
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3340
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3341
        *models.ChannelEdgePolicy, error) {
3✔
3342

3✔
3343
        var (
3✔
3344
                edgeInfo  *models.ChannelEdgeInfo
3✔
3345
                policy1   *models.ChannelEdgePolicy
3✔
3346
                policy2   *models.ChannelEdgePolicy
3✔
3347
                channelID [8]byte
3✔
3348
        )
3✔
3349

3✔
3350
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3351
                // First, grab the node bucket. This will be used to populate
3✔
3352
                // the Node pointers in each edge read from disk.
3✔
3353
                nodes := tx.ReadBucket(nodeBucket)
3✔
3354
                if nodes == nil {
3✔
3355
                        return ErrGraphNotFound
×
3356
                }
×
3357

3358
                // Next, grab the edge bucket which stores the edges, and also
3359
                // the index itself so we can group the directed edges together
3360
                // logically.
3361
                edges := tx.ReadBucket(edgeBucket)
3✔
3362
                if edges == nil {
3✔
3363
                        return ErrGraphNoEdgesFound
×
3364
                }
×
3365
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3366
                if edgeIndex == nil {
3✔
3367
                        return ErrGraphNoEdgesFound
×
3368
                }
×
3369

3370
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3371

3✔
3372
                // Now, attempt to fetch edge.
3✔
3373
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3374

3✔
3375
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3376
                // see if we've previously marked it as so.
3✔
3377
                if errors.Is(err, ErrEdgeNotFound) {
6✔
3378
                        // If the zombie index doesn't exist, or the edge is not
3✔
3379
                        // marked as a zombie within it, then we'll return the
3✔
3380
                        // original ErrEdgeNotFound error.
3✔
3381
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3382
                        if zombieIndex == nil {
3✔
3383
                                return ErrEdgeNotFound
×
3384
                        }
×
3385

3386
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3387
                                zombieIndex, chanID,
3✔
3388
                        )
3✔
3389
                        if !isZombie {
6✔
3390
                                return ErrEdgeNotFound
3✔
3391
                        }
3✔
3392

3393
                        // Otherwise, the edge is marked as a zombie, so we'll
3394
                        // populate the edge info with the public keys of each
3395
                        // party as this is the only information we have about
3396
                        // it and return an error signaling so.
3397
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3398
                                NodeKey1Bytes: pubKey1,
3✔
3399
                                NodeKey2Bytes: pubKey2,
3✔
3400
                        }
3✔
3401

3✔
3402
                        return ErrZombieEdge
3✔
3403
                }
3404

3405
                // Otherwise, we'll just return the error if any.
3406
                if err != nil {
3✔
3407
                        return err
×
3408
                }
×
3409

3410
                edgeInfo = &edge
3✔
3411

3✔
3412
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3413
                // edge.
3✔
3414
                e1, e2, err := fetchChanEdgePolicies(
3✔
3415
                        edgeIndex, edges, channelID[:],
3✔
3416
                )
3✔
3417
                if err != nil {
3✔
3418
                        return err
×
3419
                }
×
3420

3421
                policy1 = e1
3✔
3422
                policy2 = e2
3✔
3423

3✔
3424
                return nil
3✔
3425
        }, func() {
3✔
3426
                edgeInfo = nil
3✔
3427
                policy1 = nil
3✔
3428
                policy2 = nil
3✔
3429
        })
3✔
3430
        if errors.Is(err, ErrZombieEdge) {
6✔
3431
                return edgeInfo, nil, nil, err
3✔
3432
        }
3✔
3433
        if err != nil {
6✔
3434
                return nil, nil, nil, err
3✔
3435
        }
3✔
3436

3437
        return edgeInfo, policy1, policy2, nil
3✔
3438
}
3439

3440
// IsPublicNode is a helper method that determines whether the node with the
3441
// given public key is seen as a public node in the graph from the graph's
3442
// source node's point of view.
3443
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3444
        var nodeIsPublic bool
3✔
3445
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3446
                nodes := tx.ReadBucket(nodeBucket)
3✔
3447
                if nodes == nil {
3✔
3448
                        return ErrGraphNodesNotFound
×
3449
                }
×
3450
                ourPubKey := nodes.Get(sourceKey)
3✔
3451
                if ourPubKey == nil {
3✔
3452
                        return ErrSourceNodeNotSet
×
3453
                }
×
3454
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3455
                if err != nil {
3✔
3456
                        return err
×
3457
                }
×
3458

3459
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3460

3✔
3461
                return err
3✔
3462
        }, func() {
3✔
3463
                nodeIsPublic = false
3✔
3464
        })
3✔
3465
        if err != nil {
3✔
3466
                return false, err
×
3467
        }
×
3468

3469
        return nodeIsPublic, nil
3✔
3470
}
3471

3472
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3473
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3474
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3475
        if err != nil {
3✔
3476
                return nil, err
×
3477
        }
×
3478

3479
        // With the witness script generated, we'll now turn it into a p2wsh
3480
        // script:
3481
        //  * OP_0 <sha256(script)>
3482
        bldr := txscript.NewScriptBuilder(
3✔
3483
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3484
        )
3✔
3485
        bldr.AddOp(txscript.OP_0)
3✔
3486
        scriptHash := sha256.Sum256(witnessScript)
3✔
3487
        bldr.AddData(scriptHash[:])
3✔
3488

3✔
3489
        return bldr.Script()
3✔
3490
}
3491

3492
// EdgePoint couples the outpoint of a channel with the funding script that it
3493
// creates. The FilteredChainView will use this to watch for spends of this
3494
// edge point on chain. We require both of these values as depending on the
3495
// concrete implementation, either the pkScript, or the out point will be used.
3496
type EdgePoint struct {
3497
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3498
        FundingPkScript []byte
3499

3500
        // OutPoint is the outpoint of the target channel.
3501
        OutPoint wire.OutPoint
3502
}
3503

3504
// String returns a human readable version of the target EdgePoint. We return
3505
// the outpoint directly as it is enough to uniquely identify the edge point.
3506
func (e *EdgePoint) String() string {
×
3507
        return e.OutPoint.String()
×
3508
}
×
3509

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

3533
                // Once we have the proper bucket, we'll range over each key
3534
                // (which is the channel point for the channel) and decode it,
3535
                // accumulating each entry.
3536
                return chanIndex.ForEach(
3✔
3537
                        func(chanPointBytes, chanID []byte) error {
6✔
3538
                                chanPointReader := bytes.NewReader(
3✔
3539
                                        chanPointBytes,
3✔
3540
                                )
3✔
3541

3✔
3542
                                var chanPoint wire.OutPoint
3✔
3543
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3544
                                if err != nil {
3✔
3545
                                        return err
×
3546
                                }
×
3547

3548
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3549
                                        edgeIndex, chanID,
3✔
3550
                                )
3✔
3551
                                if err != nil {
3✔
3552
                                        return err
×
3553
                                }
×
3554

3555
                                pkScript, err := genMultiSigP2WSH(
3✔
3556
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3557
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3558
                                )
3✔
3559
                                if err != nil {
3✔
3560
                                        return err
×
3561
                                }
×
3562

3563
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3564
                                        FundingPkScript: pkScript,
3✔
3565
                                        OutPoint:        chanPoint,
3✔
3566
                                })
3✔
3567

3✔
3568
                                return nil
3✔
3569
                        },
3570
                )
3571
        }, func() {
3✔
3572
                edgePoints = nil
3✔
3573
        }); err != nil {
3✔
3574
                return nil, err
×
3575
        }
×
3576

3577
        return edgePoints, nil
3✔
3578
}
3579

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

×
UNCOV
3586
        c.cacheMu.Lock()
×
UNCOV
3587
        defer c.cacheMu.Unlock()
×
UNCOV
3588

×
UNCOV
3589
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3590
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3591
                if edges == nil {
×
3592
                        return ErrGraphNoEdgesFound
×
3593
                }
×
UNCOV
3594
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
UNCOV
3595
                if err != nil {
×
3596
                        return fmt.Errorf("unable to create zombie "+
×
3597
                                "bucket: %w", err)
×
3598
                }
×
3599

UNCOV
3600
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3601
        })
UNCOV
3602
        if err != nil {
×
3603
                return err
×
3604
        }
×
3605

UNCOV
3606
        c.rejectCache.remove(chanID)
×
UNCOV
3607
        c.chanCache.remove(chanID)
×
UNCOV
3608

×
UNCOV
3609
        return nil
×
3610
}
3611

3612
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3613
// keys should represent the node public keys of the two parties involved in the
3614
// edge.
3615
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3616
        pubKey2 [33]byte) error {
3✔
3617

3✔
3618
        var k [8]byte
3✔
3619
        byteOrder.PutUint64(k[:], chanID)
3✔
3620

3✔
3621
        var v [66]byte
3✔
3622
        copy(v[:33], pubKey1[:])
3✔
3623
        copy(v[33:], pubKey2[:])
3✔
3624

3✔
3625
        return zombieIndex.Put(k[:], v[:])
3✔
3626
}
3✔
3627

3628
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
UNCOV
3629
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
UNCOV
3630
        c.cacheMu.Lock()
×
UNCOV
3631
        defer c.cacheMu.Unlock()
×
UNCOV
3632

×
UNCOV
3633
        return c.markEdgeLiveUnsafe(nil, chanID)
×
UNCOV
3634
}
×
3635

3636
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3637
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3638
// case a new transaction will be created.
3639
//
3640
// NOTE: this method MUST only be called if the cacheMu has already been
3641
// acquired.
UNCOV
3642
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
UNCOV
3643
        dbFn := func(tx kvdb.RwTx) error {
×
UNCOV
3644
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3645
                if edges == nil {
×
3646
                        return ErrGraphNoEdgesFound
×
3647
                }
×
UNCOV
3648
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
×
UNCOV
3649
                if zombieIndex == nil {
×
3650
                        return nil
×
3651
                }
×
3652

UNCOV
3653
                var k [8]byte
×
UNCOV
3654
                byteOrder.PutUint64(k[:], chanID)
×
UNCOV
3655

×
UNCOV
3656
                if len(zombieIndex.Get(k[:])) == 0 {
×
UNCOV
3657
                        return ErrZombieEdgeNotFound
×
UNCOV
3658
                }
×
3659

UNCOV
3660
                return zombieIndex.Delete(k[:])
×
3661
        }
3662

3663
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3664
        // the existing transaction
UNCOV
3665
        var err error
×
UNCOV
3666
        if tx == nil {
×
UNCOV
3667
                err = kvdb.Update(c.db, dbFn, func() {})
×
3668
        } else {
×
3669
                err = dbFn(tx)
×
3670
        }
×
UNCOV
3671
        if err != nil {
×
UNCOV
3672
                return err
×
UNCOV
3673
        }
×
3674

UNCOV
3675
        c.rejectCache.remove(chanID)
×
UNCOV
3676
        c.chanCache.remove(chanID)
×
UNCOV
3677

×
UNCOV
3678
        return nil
×
3679
}
3680

3681
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3682
// zombie, then the two node public keys corresponding to this edge are also
3683
// returned.
UNCOV
3684
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
×
UNCOV
3685
        var (
×
UNCOV
3686
                isZombie         bool
×
UNCOV
3687
                pubKey1, pubKey2 [33]byte
×
UNCOV
3688
        )
×
UNCOV
3689

×
UNCOV
3690
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3691
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3692
                if edges == nil {
×
3693
                        return ErrGraphNoEdgesFound
×
3694
                }
×
UNCOV
3695
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3696
                if zombieIndex == nil {
×
3697
                        return nil
×
3698
                }
×
3699

UNCOV
3700
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
UNCOV
3701

×
UNCOV
3702
                return nil
×
UNCOV
3703
        }, func() {
×
UNCOV
3704
                isZombie = false
×
UNCOV
3705
                pubKey1 = [33]byte{}
×
UNCOV
3706
                pubKey2 = [33]byte{}
×
UNCOV
3707
        })
×
UNCOV
3708
        if err != nil {
×
3709
                return false, [33]byte{}, [33]byte{}
×
3710
        }
×
3711

UNCOV
3712
        return isZombie, pubKey1, pubKey2
×
3713
}
3714

3715
// isZombieEdge returns whether an entry exists for the given channel in the
3716
// zombie index. If an entry exists, then the two node public keys corresponding
3717
// to this edge are also returned.
3718
func isZombieEdge(zombieIndex kvdb.RBucket,
3719
        chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3720

3✔
3721
        var k [8]byte
3✔
3722
        byteOrder.PutUint64(k[:], chanID)
3✔
3723

3✔
3724
        v := zombieIndex.Get(k[:])
3✔
3725
        if v == nil {
6✔
3726
                return false, [33]byte{}, [33]byte{}
3✔
3727
        }
3✔
3728

3729
        var pubKey1, pubKey2 [33]byte
3✔
3730
        copy(pubKey1[:], v[:33])
3✔
3731
        copy(pubKey2[:], v[33:])
3✔
3732

3✔
3733
        return true, pubKey1, pubKey2
3✔
3734
}
3735

3736
// NumZombies returns the current number of zombie channels in the graph.
UNCOV
3737
func (c *KVStore) NumZombies() (uint64, error) {
×
UNCOV
3738
        var numZombies uint64
×
UNCOV
3739
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3740
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3741
                if edges == nil {
×
3742
                        return nil
×
3743
                }
×
UNCOV
3744
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3745
                if zombieIndex == nil {
×
3746
                        return nil
×
3747
                }
×
3748

UNCOV
3749
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
UNCOV
3750
                        numZombies++
×
UNCOV
3751
                        return nil
×
UNCOV
3752
                })
×
UNCOV
3753
        }, func() {
×
UNCOV
3754
                numZombies = 0
×
UNCOV
3755
        })
×
UNCOV
3756
        if err != nil {
×
3757
                return 0, err
×
3758
        }
×
3759

UNCOV
3760
        return numZombies, nil
×
3761
}
3762

3763
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3764
// that we can ignore channel announcements that we know to be closed without
3765
// having to validate them and fetch a block.
UNCOV
3766
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
×
UNCOV
3767
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3768
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
UNCOV
3769
                if err != nil {
×
3770
                        return err
×
3771
                }
×
3772

UNCOV
3773
                var k [8]byte
×
UNCOV
3774
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
UNCOV
3775

×
UNCOV
3776
                return closedScids.Put(k[:], []byte{})
×
UNCOV
3777
        }, func() {})
×
3778
}
3779

3780
// IsClosedScid checks whether a channel identified by the passed in scid is
3781
// closed. This helps avoid having to perform expensive validation checks.
3782
// TODO: Add an LRU cache to cut down on disc reads.
3783
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3784
        var isClosed bool
3✔
3785
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3786
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3787
                if closedScids == nil {
3✔
3788
                        return ErrClosedScidsNotFound
×
3789
                }
×
3790

3791
                var k [8]byte
3✔
3792
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3793

3✔
3794
                if closedScids.Get(k[:]) != nil {
3✔
UNCOV
3795
                        isClosed = true
×
UNCOV
3796
                        return nil
×
UNCOV
3797
                }
×
3798

3799
                return nil
3✔
3800
        }, func() {
3✔
3801
                isClosed = false
3✔
3802
        })
3✔
3803
        if err != nil {
3✔
3804
                return false, err
×
3805
        }
×
3806

3807
        return isClosed, nil
3✔
3808
}
3809

3810
// GraphSession will provide the call-back with access to a NodeTraverser
3811
// instance which can be used to perform queries against the channel graph.
UNCOV
3812
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
×
UNCOV
3813
        return c.db.View(func(tx walletdb.ReadTx) error {
×
UNCOV
3814
                return cb(&nodeTraverserSession{
×
UNCOV
3815
                        db: c,
×
UNCOV
3816
                        tx: tx,
×
UNCOV
3817
                })
×
UNCOV
3818
        }, func() {})
×
3819
}
3820

3821
// nodeTraverserSession implements the NodeTraverser interface but with a
3822
// backing read only transaction for a consistent view of the graph.
3823
type nodeTraverserSession struct {
3824
        tx kvdb.RTx
3825
        db *KVStore
3826
}
3827

3828
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3829
// node.
3830
//
3831
// NOTE: Part of the NodeTraverser interface.
3832
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
UNCOV
3833
        cb func(channel *DirectedChannel) error) error {
×
UNCOV
3834

×
UNCOV
3835
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
×
UNCOV
3836
}
×
3837

3838
// FetchNodeFeatures returns the features of the given node. If the node is
3839
// unknown, assume no additional features are supported.
3840
//
3841
// NOTE: Part of the NodeTraverser interface.
3842
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
UNCOV
3843
        *lnwire.FeatureVector, error) {
×
UNCOV
3844

×
UNCOV
3845
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
UNCOV
3846
}
×
3847

3848
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3849
        node *models.LightningNode) error {
3✔
3850

3✔
3851
        var (
3✔
3852
                scratch [16]byte
3✔
3853
                b       bytes.Buffer
3✔
3854
        )
3✔
3855

3✔
3856
        pub, err := node.PubKey()
3✔
3857
        if err != nil {
3✔
3858
                return err
×
3859
        }
×
3860
        nodePub := pub.SerializeCompressed()
3✔
3861

3✔
3862
        // If the node has the update time set, write it, else write 0.
3✔
3863
        updateUnix := uint64(0)
3✔
3864
        if node.LastUpdate.Unix() > 0 {
6✔
3865
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
3866
        }
3✔
3867

3868
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
3869
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
3870
                return err
×
3871
        }
×
3872

3873
        if _, err := b.Write(nodePub); err != nil {
3✔
3874
                return err
×
3875
        }
×
3876

3877
        // If we got a node announcement for this node, we will have the rest
3878
        // of the data available. If not we don't have more data to write.
3879
        if !node.HaveNodeAnnouncement {
6✔
3880
                // Write HaveNodeAnnouncement=0.
3✔
3881
                byteOrder.PutUint16(scratch[:2], 0)
3✔
3882
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
3883
                        return err
×
3884
                }
×
3885

3886
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
3887
        }
3888

3889
        // Write HaveNodeAnnouncement=1.
3890
        byteOrder.PutUint16(scratch[:2], 1)
3✔
3891
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
3892
                return err
×
3893
        }
×
3894

3895
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
3896
                return err
×
3897
        }
×
3898
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
3899
                return err
×
3900
        }
×
3901
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
3902
                return err
×
3903
        }
×
3904

3905
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
3906
                return err
×
3907
        }
×
3908

3909
        if err := node.Features.Encode(&b); err != nil {
3✔
3910
                return err
×
3911
        }
×
3912

3913
        numAddresses := uint16(len(node.Addresses))
3✔
3914
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
3915
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
3916
                return err
×
3917
        }
×
3918

3919
        for _, address := range node.Addresses {
6✔
3920
                if err := SerializeAddr(&b, address); err != nil {
3✔
3921
                        return err
×
3922
                }
×
3923
        }
3924

3925
        sigLen := len(node.AuthSigBytes)
3✔
3926
        if sigLen > 80 {
3✔
3927
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
3928
                        sigLen)
×
3929
        }
×
3930

3931
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
3932
        if err != nil {
3✔
3933
                return err
×
3934
        }
×
3935

3936
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
3937
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
3938
        }
×
3939
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
3940
        if err != nil {
3✔
3941
                return err
×
3942
        }
×
3943

3944
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
3945
                return err
×
3946
        }
×
3947

3948
        // With the alias bucket updated, we'll now update the index that
3949
        // tracks the time series of node updates.
3950
        var indexKey [8 + 33]byte
3✔
3951
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
3952
        copy(indexKey[8:], nodePub)
3✔
3953

3✔
3954
        // If there was already an old index entry for this node, then we'll
3✔
3955
        // delete the old one before we write the new entry.
3✔
3956
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
6✔
3957
                // Extract out the old update time to we can reconstruct the
3✔
3958
                // prior index key to delete it from the index.
3✔
3959
                oldUpdateTime := nodeBytes[:8]
3✔
3960

3✔
3961
                var oldIndexKey [8 + 33]byte
3✔
3962
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
3963
                copy(oldIndexKey[8:], nodePub)
3✔
3964

3✔
3965
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
3966
                        return err
×
3967
                }
×
3968
        }
3969

3970
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
3971
                return err
×
3972
        }
×
3973

3974
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
3975
}
3976

3977
func fetchLightningNode(nodeBucket kvdb.RBucket,
3978
        nodePub []byte) (models.LightningNode, error) {
3✔
3979

3✔
3980
        nodeBytes := nodeBucket.Get(nodePub)
3✔
3981
        if nodeBytes == nil {
6✔
3982
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
3983
        }
3✔
3984

3985
        nodeReader := bytes.NewReader(nodeBytes)
3✔
3986

3✔
3987
        return deserializeLightningNode(nodeReader)
3✔
3988
}
3989

3990
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
3991
        *lnwire.FeatureVector, error) {
3✔
3992

3✔
3993
        var (
3✔
3994
                pubKey      route.Vertex
3✔
3995
                features    = lnwire.EmptyFeatureVector()
3✔
3996
                nodeScratch [8]byte
3✔
3997
        )
3✔
3998

3✔
3999
        // Skip ahead:
3✔
4000
        // - LastUpdate (8 bytes)
3✔
4001
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
4002
                return pubKey, nil, err
×
4003
        }
×
4004

4005
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
4006
                return pubKey, nil, err
×
4007
        }
×
4008

4009
        // Read the node announcement flag.
4010
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
4011
                return pubKey, nil, err
×
4012
        }
×
4013
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4014

3✔
4015
        // The rest of the data is optional, and will only be there if we got a
3✔
4016
        // node announcement for this node.
3✔
4017
        if hasNodeAnn == 0 {
6✔
4018
                return pubKey, features, nil
3✔
4019
        }
3✔
4020

4021
        // We did get a node announcement for this node, so we'll have the rest
4022
        // of the data available.
4023
        var rgb uint8
3✔
4024
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4025
                return pubKey, nil, err
×
4026
        }
×
4027
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4028
                return pubKey, nil, err
×
4029
        }
×
4030
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4031
                return pubKey, nil, err
×
4032
        }
×
4033

4034
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4035
                return pubKey, nil, err
×
4036
        }
×
4037

4038
        if err := features.Decode(r); err != nil {
3✔
4039
                return pubKey, nil, err
×
4040
        }
×
4041

4042
        return pubKey, features, nil
3✔
4043
}
4044

4045
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4046
        var (
3✔
4047
                node    models.LightningNode
3✔
4048
                scratch [8]byte
3✔
4049
                err     error
3✔
4050
        )
3✔
4051

3✔
4052
        // Always populate a feature vector, even if we don't have a node
3✔
4053
        // announcement and short circuit below.
3✔
4054
        node.Features = lnwire.EmptyFeatureVector()
3✔
4055

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

4060
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4061
        node.LastUpdate = time.Unix(unix, 0)
3✔
4062

3✔
4063
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4064
                return models.LightningNode{}, err
×
4065
        }
×
4066

4067
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4068
                return models.LightningNode{}, err
×
4069
        }
×
4070

4071
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4072
        if hasNodeAnn == 1 {
6✔
4073
                node.HaveNodeAnnouncement = true
3✔
4074
        } else {
6✔
4075
                node.HaveNodeAnnouncement = false
3✔
4076
        }
3✔
4077

4078
        // The rest of the data is optional, and will only be there if we got a
4079
        // node announcement for this node.
4080
        if !node.HaveNodeAnnouncement {
6✔
4081
                return node, nil
3✔
4082
        }
3✔
4083

4084
        // We did get a node announcement for this node, so we'll have the rest
4085
        // of the data available.
4086
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
3✔
4087
                return models.LightningNode{}, err
×
4088
        }
×
4089
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
3✔
4090
                return models.LightningNode{}, err
×
4091
        }
×
4092
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4093
                return models.LightningNode{}, err
×
4094
        }
×
4095

4096
        node.Alias, err = wire.ReadVarString(r, 0)
3✔
4097
        if err != nil {
3✔
4098
                return models.LightningNode{}, err
×
4099
        }
×
4100

4101
        err = node.Features.Decode(r)
3✔
4102
        if err != nil {
3✔
4103
                return models.LightningNode{}, err
×
4104
        }
×
4105

4106
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4107
                return models.LightningNode{}, err
×
4108
        }
×
4109
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4110

3✔
4111
        var addresses []net.Addr
3✔
4112
        for i := 0; i < numAddresses; i++ {
6✔
4113
                address, err := DeserializeAddr(r)
3✔
4114
                if err != nil {
3✔
4115
                        return models.LightningNode{}, err
×
4116
                }
×
4117
                addresses = append(addresses, address)
3✔
4118
        }
4119
        node.Addresses = addresses
3✔
4120

3✔
4121
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4122
        if err != nil {
3✔
4123
                return models.LightningNode{}, err
×
4124
        }
×
4125

4126
        // We'll try and see if there are any opaque bytes left, if not, then
4127
        // we'll ignore the EOF error and return the node as is.
4128
        extraBytes, err := wire.ReadVarBytes(
3✔
4129
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4130
        )
3✔
4131
        switch {
3✔
4132
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4133
        case errors.Is(err, io.EOF):
×
4134
        case err != nil:
×
4135
                return models.LightningNode{}, err
×
4136
        }
4137

4138
        if len(extraBytes) > 0 {
3✔
UNCOV
4139
                node.ExtraOpaqueData = extraBytes
×
UNCOV
4140
        }
×
4141

4142
        return node, nil
3✔
4143
}
4144

4145
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4146
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4147

3✔
4148
        var b bytes.Buffer
3✔
4149

3✔
4150
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4151
                return err
×
4152
        }
×
4153
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4154
                return err
×
4155
        }
×
4156
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4157
                return err
×
4158
        }
×
4159
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4160
                return err
×
4161
        }
×
4162

4163
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
3✔
4164
                return err
×
4165
        }
×
4166

4167
        authProof := edgeInfo.AuthProof
3✔
4168
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4169
        if authProof != nil {
6✔
4170
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4171
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4172
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4173
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4174
        }
3✔
4175

4176
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4177
                return err
×
4178
        }
×
4179
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4180
                return err
×
4181
        }
×
4182
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4183
                return err
×
4184
        }
×
4185
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4186
                return err
×
4187
        }
×
4188

4189
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4190
                return err
×
4191
        }
×
4192
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
3✔
4193
        if err != nil {
3✔
4194
                return err
×
4195
        }
×
4196
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4197
                return err
×
4198
        }
×
4199
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4200
                return err
×
4201
        }
×
4202

4203
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4204
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4205
        }
×
4206
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4207
        if err != nil {
3✔
4208
                return err
×
4209
        }
×
4210

4211
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4212
}
4213

4214
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4215
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4216

3✔
4217
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4218
        if edgeInfoBytes == nil {
6✔
4219
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4220
        }
3✔
4221

4222
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4223

3✔
4224
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4225
}
4226

4227
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4228
        var (
3✔
4229
                err      error
3✔
4230
                edgeInfo models.ChannelEdgeInfo
3✔
4231
        )
3✔
4232

3✔
4233
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4234
                return models.ChannelEdgeInfo{}, err
×
4235
        }
×
4236
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4237
                return models.ChannelEdgeInfo{}, err
×
4238
        }
×
4239
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4240
                return models.ChannelEdgeInfo{}, err
×
4241
        }
×
4242
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4243
                return models.ChannelEdgeInfo{}, err
×
4244
        }
×
4245

4246
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
3✔
4247
        if err != nil {
3✔
4248
                return models.ChannelEdgeInfo{}, err
×
4249
        }
×
4250

4251
        proof := &models.ChannelAuthProof{}
3✔
4252

3✔
4253
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4254
        if err != nil {
3✔
4255
                return models.ChannelEdgeInfo{}, err
×
4256
        }
×
4257
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4258
        if err != nil {
3✔
4259
                return models.ChannelEdgeInfo{}, err
×
4260
        }
×
4261
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4262
        if err != nil {
3✔
4263
                return models.ChannelEdgeInfo{}, err
×
4264
        }
×
4265
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4266
        if err != nil {
3✔
4267
                return models.ChannelEdgeInfo{}, err
×
4268
        }
×
4269

4270
        if !proof.IsEmpty() {
6✔
4271
                edgeInfo.AuthProof = proof
3✔
4272
        }
3✔
4273

4274
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4275
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4276
                return models.ChannelEdgeInfo{}, err
×
4277
        }
×
4278
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4279
                return models.ChannelEdgeInfo{}, err
×
4280
        }
×
4281
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4282
                return models.ChannelEdgeInfo{}, err
×
4283
        }
×
4284

4285
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4286
                return models.ChannelEdgeInfo{}, err
×
4287
        }
×
4288

4289
        // We'll try and see if there are any opaque bytes left, if not, then
4290
        // we'll ignore the EOF error and return the edge as is.
4291
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4292
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4293
        )
3✔
4294
        switch {
3✔
4295
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4296
        case errors.Is(err, io.EOF):
×
4297
        case err != nil:
×
4298
                return models.ChannelEdgeInfo{}, err
×
4299
        }
4300

4301
        return edgeInfo, nil
3✔
4302
}
4303

4304
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4305
        from, to []byte) error {
3✔
4306

3✔
4307
        var edgeKey [33 + 8]byte
3✔
4308
        copy(edgeKey[:], from)
3✔
4309
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4310

3✔
4311
        var b bytes.Buffer
3✔
4312
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
4313
                return err
×
4314
        }
×
4315

4316
        // Before we write out the new edge, we'll create a new entry in the
4317
        // update index in order to keep it fresh.
4318
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4319
        var indexKey [8 + 8]byte
3✔
4320
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4321
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4322

3✔
4323
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4324
        if err != nil {
3✔
4325
                return err
×
4326
        }
×
4327

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

3✔
4335
                // In order to delete the old entry, we'll need to obtain the
3✔
4336
                // *prior* update time in order to delete it. To do this, we'll
3✔
4337
                // need to deserialize the existing policy within the database
3✔
4338
                // (now outdated by the new one), and delete its corresponding
3✔
4339
                // entry within the update index. We'll ignore any
3✔
4340
                // ErrEdgePolicyOptionalFieldNotFound or ErrParsingExtraTLVBytes
3✔
4341
                // errors, as we only need the channel ID and update time to
3✔
4342
                // delete the entry.
3✔
4343
                //
3✔
4344
                // TODO(halseth): get rid of these invalid policies in a
3✔
4345
                // migration.
3✔
4346
                // TODO(elle): complete the above TODO in migration from kvdb
3✔
4347
                // to SQL.
3✔
4348
                oldEdgePolicy, err := deserializeChanEdgePolicy(
3✔
4349
                        bytes.NewReader(edgeBytes),
3✔
4350
                )
3✔
4351
                if err != nil &&
3✔
4352
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4353
                        !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4354

×
4355
                        return err
×
4356
                }
×
4357

4358
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4359

3✔
4360
                var oldIndexKey [8 + 8]byte
3✔
4361
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4362
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4363

3✔
4364
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4365
                        return err
×
4366
                }
×
4367
        }
4368

4369
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4370
                return err
×
4371
        }
×
4372

4373
        err = updateEdgePolicyDisabledIndex(
3✔
4374
                edges, edge.ChannelID,
3✔
4375
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4376
                edge.IsDisabled(),
3✔
4377
        )
3✔
4378
        if err != nil {
3✔
4379
                return err
×
4380
        }
×
4381

4382
        return edges.Put(edgeKey[:], b.Bytes())
3✔
4383
}
4384

4385
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4386
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4387
// one.
4388
// The direction represents the direction of the edge and disabled is used for
4389
// deciding whether to remove or add an entry to the bucket.
4390
// In general a channel is disabled if two entries for the same chanID exist
4391
// in this bucket.
4392
// Maintaining the bucket this way allows a fast retrieval of disabled
4393
// channels, for example when prune is needed.
4394
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4395
        direction bool, disabled bool) error {
3✔
4396

3✔
4397
        var disabledEdgeKey [8 + 1]byte
3✔
4398
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4399
        if direction {
6✔
4400
                disabledEdgeKey[8] = 1
3✔
4401
        }
3✔
4402

4403
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4404
                disabledEdgePolicyBucket,
3✔
4405
        )
3✔
4406
        if err != nil {
3✔
4407
                return err
×
4408
        }
×
4409

4410
        if disabled {
6✔
4411
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4412
        }
3✔
4413

4414
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4415
}
4416

4417
// putChanEdgePolicyUnknown marks the edge policy as unknown
4418
// in the edges bucket.
4419
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4420
        from []byte) error {
3✔
4421

3✔
4422
        var edgeKey [33 + 8]byte
3✔
4423
        copy(edgeKey[:], from)
3✔
4424
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4425

3✔
4426
        if edges.Get(edgeKey[:]) != nil {
3✔
4427
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4428
                        " when there is already a policy present", channelID)
×
4429
        }
×
4430

4431
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4432
}
4433

4434
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4435
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
3✔
4436

3✔
4437
        var edgeKey [33 + 8]byte
3✔
4438
        copy(edgeKey[:], nodePub)
3✔
4439
        copy(edgeKey[33:], chanID)
3✔
4440

3✔
4441
        edgeBytes := edges.Get(edgeKey[:])
3✔
4442
        if edgeBytes == nil {
3✔
4443
                return nil, ErrEdgeNotFound
×
4444
        }
×
4445

4446
        // No need to deserialize unknown policy.
4447
        if bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4448
                return nil, nil
3✔
4449
        }
3✔
4450

4451
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4452

3✔
4453
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4454
        switch {
3✔
4455
        // If the db policy was missing an expected optional field, we return
4456
        // nil as if the policy was unknown.
UNCOV
4457
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
UNCOV
4458
                return nil, nil
×
4459

4460
        // If the policy contains invalid TLV bytes, we return nil as if
4461
        // the policy was unknown.
NEW
4462
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
NEW
4463
                return nil, nil
×
4464

4465
        case err != nil:
×
4466
                return nil, err
×
4467
        }
4468

4469
        return ep, nil
3✔
4470
}
4471

4472
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4473
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4474
        error) {
3✔
4475

3✔
4476
        edgeInfo := edgeIndex.Get(chanID)
3✔
4477
        if edgeInfo == nil {
3✔
4478
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4479
                        chanID)
×
4480
        }
×
4481

4482
        // The first node is contained within the first half of the edge
4483
        // information. We only propagate the error here and below if it's
4484
        // something other than edge non-existence.
4485
        node1Pub := edgeInfo[:33]
3✔
4486
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4487
        if err != nil {
3✔
4488
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4489
                        node1Pub)
×
4490
        }
×
4491

4492
        // Similarly, the second node is contained within the latter
4493
        // half of the edge information.
4494
        node2Pub := edgeInfo[33:66]
3✔
4495
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4496
        if err != nil {
3✔
4497
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4498
                        node2Pub)
×
4499
        }
×
4500

4501
        return edge1, edge2, nil
3✔
4502
}
4503

4504
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4505
        to []byte) error {
3✔
4506

3✔
4507
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4508
        if err != nil {
3✔
4509
                return err
×
4510
        }
×
4511

4512
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4513
                return err
×
4514
        }
×
4515

4516
        var scratch [8]byte
3✔
4517
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4518
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4519
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4520
                return err
×
4521
        }
×
4522

4523
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
3✔
4524
                return err
×
4525
        }
×
4526
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
3✔
4527
                return err
×
4528
        }
×
4529
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
3✔
4530
                return err
×
4531
        }
×
4532
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
3✔
4533
                return err
×
4534
        }
×
4535
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
3✔
4536
        if err != nil {
3✔
4537
                return err
×
4538
        }
×
4539
        err = binary.Write(
3✔
4540
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
3✔
4541
        )
3✔
4542
        if err != nil {
3✔
4543
                return err
×
4544
        }
×
4545

4546
        if _, err := w.Write(to); err != nil {
3✔
4547
                return err
×
4548
        }
×
4549

4550
        // If the max_htlc field is present, we write it. To be compatible with
4551
        // older versions that wasn't aware of this field, we write it as part
4552
        // of the opaque data.
4553
        // TODO(halseth): clean up when moving to TLV.
4554
        var opaqueBuf bytes.Buffer
3✔
4555
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4556
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4557
                if err != nil {
3✔
4558
                        return err
×
4559
                }
×
4560
        }
4561

4562
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
4563
        err = edge.ExtraOpaqueData.ValidateTLV()
3✔
4564
        if err != nil {
3✔
NEW
4565
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
NEW
4566
        }
×
4567

4568
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4569
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4570
        }
×
4571
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4572
                return err
×
4573
        }
×
4574

4575
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4576
                return err
×
4577
        }
×
4578

4579
        return nil
3✔
4580
}
4581

4582
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
3✔
4583
        // Deserialize the policy. Note that in case an optional field is not
3✔
4584
        // found or if the edge has invalid TLV data, then both an error and a
3✔
4585
        // populated policy object are returned so that the caller can decide
3✔
4586
        // if it still wants to use the edge or not.
3✔
4587
        edge, err := deserializeChanEdgePolicyRaw(r)
3✔
4588
        if err != nil &&
3✔
4589
                !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4590
                !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4591

×
NEW
4592
                return nil, err
×
4593
        }
×
4594

4595
        return edge, err
3✔
4596
}
4597

4598
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4599
        error) {
3✔
4600

3✔
4601
        edge := &models.ChannelEdgePolicy{}
3✔
4602

3✔
4603
        var err error
3✔
4604
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4605
        if err != nil {
3✔
4606
                return nil, err
×
4607
        }
×
4608

4609
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4610
                return nil, err
×
4611
        }
×
4612

4613
        var scratch [8]byte
3✔
4614
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4615
                return nil, err
×
4616
        }
×
4617
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4618
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4619

3✔
4620
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4621
                return nil, err
×
4622
        }
×
4623
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4624
                return nil, err
×
4625
        }
×
4626
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4627
                return nil, err
×
4628
        }
×
4629

4630
        var n uint64
3✔
4631
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4632
                return nil, err
×
4633
        }
×
4634
        edge.MinHTLC = lnwire.MilliSatoshi(n)
3✔
4635

3✔
4636
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4637
                return nil, err
×
4638
        }
×
4639
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
4640

3✔
4641
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4642
                return nil, err
×
4643
        }
×
4644
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4645

3✔
4646
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4647
                return nil, err
×
4648
        }
×
4649

4650
        // We'll try and see if there are any opaque bytes left, if not, then
4651
        // we'll ignore the EOF error and return the edge as is.
4652
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4653
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4654
        )
3✔
4655
        switch {
3✔
4656
        case errors.Is(err, io.ErrUnexpectedEOF):
×
UNCOV
4657
        case errors.Is(err, io.EOF):
×
4658
        case err != nil:
×
4659
                return nil, err
×
4660
        }
4661

4662
        // See if optional fields are present.
4663
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4664
                // The max_htlc field should be at the beginning of the opaque
3✔
4665
                // bytes.
3✔
4666
                opq := edge.ExtraOpaqueData
3✔
4667

3✔
4668
                // If the max_htlc field is not present, it might be old data
3✔
4669
                // stored before this field was validated. We'll return the
3✔
4670
                // edge along with an error.
3✔
4671
                if len(opq) < 8 {
3✔
UNCOV
4672
                        return edge, ErrEdgePolicyOptionalFieldNotFound
×
UNCOV
4673
                }
×
4674

4675
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4676
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4677

3✔
4678
                // Exclude the parsed field from the rest of the opaque data.
3✔
4679
                edge.ExtraOpaqueData = opq[8:]
3✔
4680
        }
4681

4682
        // Attempt to extract the inbound fee from the opaque data. If we fail
4683
        // to parse the TLV here, we return an error we also return the edge
4684
        // so that the caller can still use it. This is for backwards
4685
        // compatibility in case we have already persisted some policies that
4686
        // have invalid TLV data.
4687
        var inboundFee lnwire.Fee
3✔
4688
        typeMap, err := edge.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
4689
        if err != nil {
3✔
NEW
4690
                return edge, fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
NEW
4691
        }
×
4692

4693
        val, ok := typeMap[lnwire.FeeRecordType]
3✔
4694
        if ok && val == nil {
6✔
4695
                edge.InboundFee = fn.Some(inboundFee)
3✔
4696
        }
3✔
4697

4698
        return edge, nil
3✔
4699
}
4700

4701
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4702
// KVStore and a kvdb.RTx.
4703
type chanGraphNodeTx struct {
4704
        tx   kvdb.RTx
4705
        db   *KVStore
4706
        node *models.LightningNode
4707
}
4708

4709
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4710
// interface.
4711
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4712

4713
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4714
        node *models.LightningNode) *chanGraphNodeTx {
3✔
4715

3✔
4716
        return &chanGraphNodeTx{
3✔
4717
                tx:   tx,
3✔
4718
                db:   db,
3✔
4719
                node: node,
3✔
4720
        }
3✔
4721
}
3✔
4722

4723
// Node returns the raw information of the node.
4724
//
4725
// NOTE: This is a part of the NodeRTx interface.
4726
func (c *chanGraphNodeTx) Node() *models.LightningNode {
3✔
4727
        return c.node
3✔
4728
}
3✔
4729

4730
// FetchNode fetches the node with the given pub key under the same transaction
4731
// used to fetch the current node. The returned node is also a NodeRTx and any
4732
// operations on that NodeRTx will also be done under the same transaction.
4733
//
4734
// NOTE: This is a part of the NodeRTx interface.
UNCOV
4735
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
×
UNCOV
4736
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
×
UNCOV
4737
        if err != nil {
×
4738
                return nil, err
×
4739
        }
×
4740

UNCOV
4741
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4742
}
4743

4744
// ForEachChannel can be used to iterate over the node's channels under
4745
// the same transaction used to fetch the node.
4746
//
4747
// NOTE: This is a part of the NodeRTx interface.
4748
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
UNCOV
4749
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
×
UNCOV
4750

×
UNCOV
4751
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
×
UNCOV
4752
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
×
UNCOV
4753
                        policy2 *models.ChannelEdgePolicy) error {
×
UNCOV
4754

×
UNCOV
4755
                        return f(info, policy1, policy2)
×
UNCOV
4756
                },
×
4757
        )
4758
}
4759

4760
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4761
// purposes.
4762
//
4763
// NOTE: this helper currently creates a ChannelGraph that is only ever backed
4764
// by the `KVStore` of the `V1Store` interface.
UNCOV
4765
func MakeTestGraph(t testing.TB, opts ...ChanGraphOption) *ChannelGraph {
×
UNCOV
4766
        t.Helper()
×
UNCOV
4767

×
UNCOV
4768
        // Next, create KVStore for the first time.
×
UNCOV
4769
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
×
UNCOV
4770
        t.Cleanup(backendCleanup)
×
UNCOV
4771
        require.NoError(t, err)
×
UNCOV
4772
        t.Cleanup(func() {
×
UNCOV
4773
                require.NoError(t, backend.Close())
×
UNCOV
4774
        })
×
4775

UNCOV
4776
        graphStore, err := NewKVStore(backend)
×
UNCOV
4777
        require.NoError(t, err)
×
UNCOV
4778

×
UNCOV
4779
        graph, err := NewChannelGraph(graphStore, opts...)
×
UNCOV
4780
        require.NoError(t, err)
×
UNCOV
4781
        require.NoError(t, graph.Start())
×
UNCOV
4782
        t.Cleanup(func() {
×
UNCOV
4783
                require.NoError(t, graph.Stop())
×
UNCOV
4784
        })
×
4785

UNCOV
4786
        return graph
×
4787
}
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