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

lightningnetwork / lnd / 16140017036

08 Jul 2025 09:55AM UTC coverage: 57.817% (+0.01%) from 57.803%
16140017036

Pull #10043

github

web-flow
Merge 465abec84 into b815109b8
Pull Request #10043: multi: add context.Context param to more graphdb.V1Store methods

25 of 38 new or added lines in 9 files covered. (65.79%)

33 existing lines in 7 files now uncovered.

98514 of 170388 relevant lines covered (57.82%)

1.79 hits per line

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

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

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/sha256"
7
        "encoding/binary"
8
        "errors"
9
        "fmt"
10
        "io"
11
        "math"
12
        "net"
13
        "sort"
14
        "sync"
15
        "time"
16

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

302
                channelMap[key] = edge
3✔
303

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

310
        return channelMap, nil
3✔
311
}
312

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

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

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

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

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

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

369
        return nil
3✔
370
}
371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

612
                return cb(directedChannel)
3✔
613
        }
614

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

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

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

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

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

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

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

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

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

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

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

×
681
                channels := make(map[uint64]*DirectedChannel)
×
682

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

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

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

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

×
718
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
719
                                        directedChannel.OtherNode =
×
720
                                                e.NodeKey1Bytes
×
721
                                }
×
722

723
                                channels[e.ChannelID] = directedChannel
×
724

×
725
                                return nil
×
726
                        })
727
                if err != nil {
×
728
                        return err
×
729
                }
×
730

731
                return cb(node.PubKeyBytes, channels)
×
732
        })
733
}
734

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

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

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

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

×
768
                                        return nil
×
769
                                }
×
770

771
                                chanEdgeFound[chanID] = struct{}{}
×
772

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

784
        return disabledChanIDs, nil
×
785
}
786

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

3✔
796
        return forEachNode(c.db, func(tx kvdb.RTx,
3✔
797
                node *models.LightningNode) error {
6✔
798

3✔
799
                return cb(newChanGraphNodeTx(tx, c, node))
3✔
800
        })
3✔
801
}
802

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

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

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

829
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
830
                        node, err := deserializeLightningNode(nodeReader)
3✔
831
                        if err != nil {
3✔
832
                                return err
×
833
                        }
×
834

835
                        // Execute the callback, the transaction will abort if
836
                        // this returns an error.
837
                        return cb(tx, &node)
3✔
838
                })
839
        }
840

841
        return kvdb.View(db, traversal, func() {})
6✔
842
}
843

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

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

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

867
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
868
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
869
                                nodeReader,
3✔
870
                        )
3✔
871
                        if err != nil {
3✔
872
                                return err
×
873
                        }
×
874

875
                        // Execute the callback, the transaction will abort if
876
                        // this returns an error.
877
                        return cb(node, features)
3✔
878
                })
879
        }
880

881
        return kvdb.View(c.db, traversal, func() {})
6✔
882
}
883

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

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

904
                node, err := sourceNodeWithTx(nodes)
3✔
905
                if err != nil {
6✔
906
                        return err
3✔
907
                }
3✔
908
                source = node
3✔
909

3✔
910
                return nil
3✔
911
        }, func() {
3✔
912
                source = nil
3✔
913
        })
3✔
914
        if err != nil {
6✔
915
                return nil, err
3✔
916
        }
3✔
917

918
        return source, nil
3✔
919
}
920

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

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

938
        return &node, nil
3✔
939
}
940

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

3✔
947
        nodePubBytes := node.PubKeyBytes[:]
3✔
948

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

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

963
                // Finally, we commit the information of the lightning node
964
                // itself.
965
                return addLightningNode(tx, node)
3✔
966
        }, func() {})
3✔
967
}
968

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

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

987
        return c.nodeScheduler.Execute(ctx, r)
3✔
988
}
989

990
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
991
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
992
        if err != nil {
3✔
993
                return err
×
994
        }
×
995

996
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
997
        if err != nil {
3✔
998
                return err
×
999
        }
×
1000

1001
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
1002
                nodeUpdateIndexBucket,
3✔
1003
        )
3✔
1004
        if err != nil {
3✔
1005
                return err
×
1006
        }
×
1007

1008
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
1009
}
1010

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

3✔
1016
        var alias string
3✔
1017

3✔
1018
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1019
                nodes := tx.ReadBucket(nodeBucket)
3✔
1020
                if nodes == nil {
3✔
1021
                        return ErrGraphNodesNotFound
×
1022
                }
×
1023

1024
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
3✔
1025
                if aliases == nil {
3✔
1026
                        return ErrGraphNodesNotFound
×
1027
                }
×
1028

1029
                nodePub := pub.SerializeCompressed()
3✔
1030
                a := aliases.Get(nodePub)
3✔
1031
                if a == nil {
3✔
1032
                        return ErrNodeAliasNotFound
×
1033
                }
×
1034

1035
                // TODO(roasbeef): should actually be using the utf-8
1036
                // package...
1037
                alias = string(a)
3✔
1038

3✔
1039
                return nil
3✔
1040
        }, func() {
3✔
1041
                alias = ""
3✔
1042
        })
3✔
1043
        if err != nil {
3✔
1044
                return "", err
×
1045
        }
×
1046

1047
        return alias, nil
3✔
1048
}
1049

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

×
1055
        // TODO(roasbeef): ensure dangling edges are removed...
×
1056
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
1057
                nodes := tx.ReadWriteBucket(nodeBucket)
×
1058
                if nodes == nil {
×
1059
                        return ErrGraphNodeNotFound
×
1060
                }
×
1061

1062
                return c.deleteLightningNode(nodes, nodePub[:])
×
1063
        }, func() {})
×
1064
}
1065

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

3✔
1071
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
3✔
1072
        if aliases == nil {
3✔
1073
                return ErrGraphNodesNotFound
×
1074
        }
×
1075

1076
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
1077
                return err
×
1078
        }
×
1079

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

1088
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
1089
                return err
×
1090
        }
×
1091

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

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

3✔
1107
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
1108
}
1109

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

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

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

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

1151
        return c.chanScheduler.Execute(ctx, r)
3✔
1152
}
1153

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

3✔
1159
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1160
        var chanKey [8]byte
3✔
1161
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1162

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

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

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

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

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

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

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

1249
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1250
}
1251

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

3✔
1261
        var (
3✔
1262
                upd1Time time.Time
3✔
1263
                upd2Time time.Time
3✔
1264
                exists   bool
3✔
1265
                isZombie bool
3✔
1266
        )
3✔
1267

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

3✔
1277
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1278
        }
3✔
1279
        c.cacheMu.RUnlock()
3✔
1280

3✔
1281
        c.cacheMu.Lock()
3✔
1282
        defer c.cacheMu.Unlock()
3✔
1283

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

2✔
1292
                return upd1Time, upd2Time, exists, isZombie, nil
2✔
1293
        }
2✔
1294

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

1305
                var channelID [8]byte
3✔
1306
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1307

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

1319
                        return nil
3✔
1320
                }
1321

1322
                exists = true
3✔
1323
                isZombie = false
3✔
1324

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

1333
                e1, e2, err := fetchChanEdgePolicies(
3✔
1334
                        edgeIndex, edges, channelID[:],
3✔
1335
                )
3✔
1336
                if err != nil {
3✔
1337
                        return err
×
1338
                }
×
1339

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

1349
                return nil
3✔
1350
        }, func() {}); err != nil {
3✔
1351
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1352
        }
×
1353

1354
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1355
                upd1Time: upd1Time.Unix(),
3✔
1356
                upd2Time: upd2Time.Unix(),
3✔
1357
                flags:    packRejectFlags(exists, isZombie),
3✔
1358
        })
3✔
1359

3✔
1360
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1361
}
1362

1363
// AddEdgeProof sets the proof of an existing edge in the graph database.
1364
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1365
        proof *models.ChannelAuthProof) error {
3✔
1366

3✔
1367
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1368
        var chanKey [8]byte
3✔
1369
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1370

3✔
1371
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1372
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1373
                if edges == nil {
3✔
1374
                        return ErrEdgeNotFound
×
1375
                }
×
1376

1377
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1378
                if edgeIndex == nil {
3✔
1379
                        return ErrEdgeNotFound
×
1380
                }
×
1381

1382
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1383
                if err != nil {
3✔
1384
                        return err
×
1385
                }
×
1386

1387
                edge.AuthProof = proof
3✔
1388

3✔
1389
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1390
        }, func() {})
3✔
1391
}
1392

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

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

3✔
1414
        c.cacheMu.Lock()
3✔
1415
        defer c.cacheMu.Unlock()
3✔
1416

3✔
1417
        var (
3✔
1418
                chansClosed []*models.ChannelEdgeInfo
3✔
1419
                prunedNodes []route.Vertex
3✔
1420
        )
3✔
1421

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

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

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

3✔
1458
                        var opBytes bytes.Buffer
3✔
1459
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1460
                        if err != nil {
3✔
1461
                                return err
×
1462
                        }
×
1463

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

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

1483
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1484
                }
1485

1486
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1487
                if err != nil {
3✔
1488
                        return err
×
1489
                }
×
1490

1491
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1492
                        pruneLogBucket,
3✔
1493
                )
3✔
1494
                if err != nil {
3✔
1495
                        return err
×
1496
                }
×
1497

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

3✔
1504
                var newTip [pruneTipBytes]byte
3✔
1505
                copy(newTip[:], blockHash[:])
3✔
1506

3✔
1507
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1508
                if err != nil {
3✔
1509
                        return err
×
1510
                }
×
1511

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

3✔
1517
                return err
3✔
1518
        }, func() {
3✔
1519
                chansClosed = nil
3✔
1520
                prunedNodes = nil
3✔
1521
        })
3✔
1522
        if err != nil {
3✔
1523
                return nil, nil, err
×
1524
        }
×
1525

1526
        for _, channel := range chansClosed {
6✔
1527
                c.rejectCache.remove(channel.ChannelID)
3✔
1528
                c.chanCache.remove(channel.ChannelID)
3✔
1529
        }
3✔
1530

1531
        return chansClosed, prunedNodes, nil
3✔
1532
}
1533

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

1554
                var err error
3✔
1555
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1556
                if err != nil {
3✔
1557
                        return err
×
1558
                }
×
1559

1560
                return nil
3✔
1561
        }, func() {
3✔
1562
                prunedNodes = nil
3✔
1563
        })
3✔
1564

1565
        return prunedNodes, err
3✔
1566
}
1567

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

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

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

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

1595
                var nodePub [33]byte
3✔
1596
                copy(nodePub[:], pubKey)
3✔
1597
                nodeRefCounts[nodePub] = 0
3✔
1598

3✔
1599
                return nil
3✔
1600
        })
1601
        if err != nil {
3✔
1602
                return nil, err
×
1603
        }
×
1604

1605
        // To ensure we never delete the source node, we'll start off by
1606
        // bumping its ref count to 1.
1607
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1608

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

3✔
1620
                // With the nodes extracted, we'll increase the ref count of
3✔
1621
                // each of the nodes.
3✔
1622
                nodeRefCounts[node1]++
3✔
1623
                nodeRefCounts[node2]++
3✔
1624

3✔
1625
                return nil
3✔
1626
        })
3✔
1627
        if err != nil {
3✔
1628
                return nil, err
×
1629
        }
×
1630

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

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

×
1649
                                log.Warnf("Unable to prune node %x from the "+
×
1650
                                        "graph: %v", nodePubKey, err)
×
1651
                                continue
×
1652
                        }
1653

1654
                        return nil, err
×
1655
                }
1656

1657
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1658
                        nodePubKey[:])
3✔
1659

3✔
1660
                pruned = append(pruned, nodePubKey)
3✔
1661
        }
1662

1663
        if len(pruned) > 0 {
6✔
1664
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1665
                        len(pruned))
3✔
1666
        }
3✔
1667

1668
        return pruned, err
3✔
1669
}
1670

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

2✔
1681
        // Every channel having a ShortChannelID starting at 'height'
2✔
1682
        // will no longer be confirmed.
2✔
1683
        startShortChanID := lnwire.ShortChannelID{
2✔
1684
                BlockHeight: height,
2✔
1685
        }
2✔
1686

2✔
1687
        // Delete everything after this height from the db up until the
2✔
1688
        // SCID alias range.
2✔
1689
        endShortChanID := aliasmgr.StartingAlias
2✔
1690

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

2✔
1697
        c.cacheMu.Lock()
2✔
1698
        defer c.cacheMu.Unlock()
2✔
1699

2✔
1700
        // Keep track of the channels that are removed from the graph.
2✔
1701
        var removedChans []*models.ChannelEdgeInfo
2✔
1702

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

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

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

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

1747
                        removedChans = append(removedChans, edgeInfo)
2✔
1748
                }
1749

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

1757
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1758
                        pruneLogBucket,
2✔
1759
                )
2✔
1760
                if err != nil {
2✔
1761
                        return err
×
1762
                }
×
1763

1764
                var pruneKeyStart [4]byte
2✔
1765
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1766

2✔
1767
                var pruneKeyEnd [4]byte
2✔
1768
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1769

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

1780
                for _, k := range pruneKeys {
4✔
1781
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1782
                                return err
×
1783
                        }
×
1784
                }
1785

1786
                return nil
2✔
1787
        }, func() {
2✔
1788
                removedChans = nil
2✔
1789
        }); err != nil {
2✔
1790
                return nil, err
×
1791
        }
×
1792

1793
        for _, channel := range removedChans {
4✔
1794
                c.rejectCache.remove(channel.ChannelID)
2✔
1795
                c.chanCache.remove(channel.ChannelID)
2✔
1796
        }
2✔
1797

1798
        return removedChans, nil
2✔
1799
}
1800

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

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

1821
                pruneCursor := pruneBucket.ReadCursor()
3✔
1822

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

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

3✔
1835
                return nil
3✔
1836
        }, func() {})
3✔
1837
        if err != nil {
6✔
1838
                return nil, 0, err
3✔
1839
        }
3✔
1840

1841
        return &tipHash, tipHeight, nil
3✔
1842
}
1843

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

3✔
1855
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1856
        // channels
3✔
1857
        // TODO(roasbeef): don't delete both edges?
3✔
1858

3✔
1859
        c.cacheMu.Lock()
3✔
1860
        defer c.cacheMu.Unlock()
3✔
1861

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

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

1896
                        infos = append(infos, edgeInfo)
3✔
1897
                }
1898

1899
                return nil
3✔
1900
        }, func() {
3✔
1901
                infos = nil
3✔
1902
        })
3✔
1903
        if err != nil {
3✔
1904
                return nil, err
×
1905
        }
×
1906

1907
        for _, chanID := range chanIDs {
6✔
1908
                c.rejectCache.remove(chanID)
3✔
1909
                c.chanCache.remove(chanID)
3✔
1910
        }
3✔
1911

1912
        return infos, nil
3✔
1913
}
1914

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

1930
        return chanID, nil
3✔
1931
}
1932

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

1940
        edges := tx.ReadBucket(edgeBucket)
3✔
1941
        if edges == nil {
3✔
1942
                return 0, ErrGraphNoEdgesFound
×
1943
        }
×
1944
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1945
        if chanIndex == nil {
3✔
1946
                return 0, ErrGraphNoEdgesFound
×
1947
        }
×
1948

1949
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1950
        if chanIDBytes == nil {
6✔
1951
                return 0, ErrEdgeNotFound
3✔
1952
        }
3✔
1953

1954
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1955

3✔
1956
        return chanID, nil
3✔
1957
}
1958

1959
// TODO(roasbeef): allow updates to use Batch?
1960

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

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

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

3✔
1981
                lastChanID, _ := cidCursor.Last()
3✔
1982

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

1989
                // Otherwise, we'll de serialize the channel ID and return it
1990
                // to the caller.
1991
                cid = byteOrder.Uint64(lastChanID)
3✔
1992

3✔
1993
                return nil
3✔
1994
        }, func() {
3✔
1995
                cid = 0
3✔
1996
        })
3✔
1997
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
3✔
1998
                return 0, err
×
1999
        }
×
2000

2001
        return cid, nil
3✔
2002
}
2003

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

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

2015
        // Policy2 points to the "second" edge policy of the channel containing
2016
        // the dynamic information required to properly route through the edge.
2017
        Policy2 *models.ChannelEdgePolicy
2018

2019
        // Node1 is "node 1" in the channel. This is the node that would have
2020
        // produced Policy1 if it exists.
2021
        Node1 *models.LightningNode
2022

2023
        // Node2 is "node 2" in the channel. This is the node that would have
2024
        // produced Policy2 if it exists.
2025
        Node2 *models.LightningNode
2026
}
2027

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

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

3✔
2040
        c.cacheMu.Lock()
3✔
2041
        defer c.cacheMu.Unlock()
3✔
2042

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

2058
                nodes := tx.ReadBucket(nodeBucket)
3✔
2059
                if nodes == nil {
3✔
2060
                        return ErrGraphNodesNotFound
×
2061
                }
×
2062

2063
                // We'll now obtain a cursor to perform a range query within
2064
                // the index to find all channels within the horizon.
2065
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
2066

3✔
2067
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
2068
                byteOrder.PutUint64(
3✔
2069
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2070
                )
3✔
2071
                byteOrder.PutUint64(
3✔
2072
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2073
                )
3✔
2074

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

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

2094
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
2095
                                hits++
3✔
2096
                                edgesSeen[chanIDInt] = struct{}{}
3✔
2097
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
2098

3✔
2099
                                continue
3✔
2100
                        }
2101

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

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

2122
                        node1, err := fetchLightningNode(
3✔
2123
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2124
                        )
3✔
2125
                        if err != nil {
3✔
2126
                                return err
×
2127
                        }
×
2128

2129
                        node2, err := fetchLightningNode(
3✔
2130
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2131
                        )
3✔
2132
                        if err != nil {
3✔
2133
                                return err
×
2134
                        }
×
2135

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

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

2162
        case err != nil:
×
2163
                return nil, err
×
2164
        }
2165

2166
        // Insert any edges loaded from disk into the cache.
2167
        for chanid, channel := range edgesToCache {
6✔
2168
                c.chanCache.insert(chanid, channel)
3✔
2169
        }
3✔
2170

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

2180
        return edgesInHorizon, nil
3✔
2181
}
2182

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

3✔
2190
        var nodesInHorizon []models.LightningNode
3✔
2191

3✔
2192
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2193
                nodes := tx.ReadBucket(nodeBucket)
3✔
2194
                if nodes == nil {
3✔
2195
                        return ErrGraphNodesNotFound
×
2196
                }
×
2197

2198
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2199
                if nodeUpdateIndex == nil {
3✔
2200
                        return ErrGraphNodesNotFound
×
2201
                }
×
2202

2203
                // We'll now obtain a cursor to perform a range query within
2204
                // the index to find all node announcements within the horizon.
2205
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2206

3✔
2207
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2208
                byteOrder.PutUint64(
3✔
2209
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2210
                )
3✔
2211
                byteOrder.PutUint64(
3✔
2212
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2213
                )
3✔
2214

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

2228
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2229
                }
2230

2231
                return nil
3✔
2232
        }, func() {
3✔
2233
                nodesInHorizon = nil
3✔
2234
        })
3✔
2235
        switch {
3✔
2236
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2237
                fallthrough
×
2238
        case errors.Is(err, ErrGraphNodesNotFound):
×
2239
                break
×
2240

2241
        case err != nil:
×
2242
                return nil, err
×
2243
        }
2244

2245
        return nodesInHorizon, nil
3✔
2246
}
2247

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

3✔
2257
        var (
3✔
2258
                newChanIDs   []uint64
3✔
2259
                knownZombies []ChannelUpdateInfo
3✔
2260
        )
3✔
2261

3✔
2262
        c.cacheMu.Lock()
3✔
2263
        defer c.cacheMu.Unlock()
3✔
2264

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

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

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

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

2292
                        // If the edge is a known zombie, skip it.
2293
                        if zombieIndex != nil {
6✔
2294
                                isZombie, _, _ := isZombieEdge(
3✔
2295
                                        zombieIndex, scid,
3✔
2296
                                )
3✔
2297

3✔
2298
                                if isZombie {
3✔
2299
                                        knownZombies = append(
×
2300
                                                knownZombies, info,
×
2301
                                        )
×
2302

×
2303
                                        continue
×
2304
                                }
2305
                        }
2306

2307
                        newChanIDs = append(newChanIDs, scid)
3✔
2308
                }
2309

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

2324
                return ogChanIDs, nil, nil
×
2325

2326
        case err != nil:
×
2327
                return nil, nil, err
×
2328
        }
2329

2330
        return newChanIDs, knownZombies, nil
3✔
2331
}
2332

2333
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2334
// latest received channel updates for the channel.
2335
type ChannelUpdateInfo struct {
2336
        // ShortChannelID is the SCID identifier of the channel.
2337
        ShortChannelID lnwire.ShortChannelID
2338

2339
        // Node1UpdateTimestamp is the timestamp of the latest received update
2340
        // from the node 1 channel peer. This will be set to zero time if no
2341
        // update has yet been received from this node.
2342
        Node1UpdateTimestamp time.Time
2343

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

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

3✔
2356
        chanInfo := ChannelUpdateInfo{
3✔
2357
                ShortChannelID:       scid,
3✔
2358
                Node1UpdateTimestamp: node1Timestamp,
3✔
2359
                Node2UpdateTimestamp: node2Timestamp,
3✔
2360
        }
3✔
2361

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

2366
        if node2Timestamp.IsZero() {
6✔
2367
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2368
        }
3✔
2369

2370
        return chanInfo
3✔
2371
}
2372

2373
// BlockChannelRange represents a range of channels for a given block height.
2374
type BlockChannelRange struct {
2375
        // Height is the height of the block all of the channels below were
2376
        // included in.
2377
        Height uint32
2378

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

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

3✔
2396
        startChanID := &lnwire.ShortChannelID{
3✔
2397
                BlockHeight: startHeight,
3✔
2398
        }
3✔
2399

3✔
2400
        endChanID := lnwire.ShortChannelID{
3✔
2401
                BlockHeight: endHeight,
3✔
2402
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2403
                TxPosition:  math.MaxUint16,
3✔
2404
        }
3✔
2405

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

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

2424
                cursor := edgeIndex.ReadCursor()
3✔
2425

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

2439
                        if edgeInfo.AuthProof == nil {
6✔
2440
                                continue
3✔
2441
                        }
2442

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

3✔
2448
                        chanInfo := NewChannelUpdateInfo(
3✔
2449
                                cid, time.Time{}, time.Time{},
3✔
2450
                        )
3✔
2451

3✔
2452
                        if !withTimestamps {
3✔
2453
                                channelsPerBlock[cid.BlockHeight] = append(
×
2454
                                        channelsPerBlock[cid.BlockHeight],
×
2455
                                        chanInfo,
×
2456
                                )
×
2457

×
2458
                                continue
×
2459
                        }
2460

2461
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2462

3✔
2463
                        rawPolicy := edges.Get(node1Key)
3✔
2464
                        if len(rawPolicy) != 0 {
6✔
2465
                                r := bytes.NewReader(rawPolicy)
3✔
2466

3✔
2467
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2468
                                if err != nil && !errors.Is(
3✔
2469
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2470
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2471

×
2472
                                        return err
×
2473
                                }
×
2474

2475
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2476
                        }
2477

2478
                        rawPolicy = edges.Get(node2Key)
3✔
2479
                        if len(rawPolicy) != 0 {
6✔
2480
                                r := bytes.NewReader(rawPolicy)
3✔
2481

3✔
2482
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2483
                                if err != nil && !errors.Is(
3✔
2484
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2485
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2486

×
2487
                                        return err
×
2488
                                }
×
2489

2490
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2491
                        }
2492

2493
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2494
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2495
                        )
3✔
2496
                }
2497

2498
                return nil
3✔
2499
        }, func() {
3✔
2500
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2501
        })
3✔
2502

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

2509
        case err != nil:
×
2510
                return nil, err
×
2511
        }
2512

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

2522
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2523
        for _, block := range blocks {
6✔
2524
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2525
                        Height:   block,
3✔
2526
                        Channels: channelsPerBlock[block],
3✔
2527
                })
3✔
2528
        }
3✔
2529

2530
        return channelRanges, nil
3✔
2531
}
2532

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

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

3✔
2554
        var (
3✔
2555
                chanEdges []ChannelEdge
3✔
2556
                cidBytes  [8]byte
3✔
2557
        )
3✔
2558

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

2573
                for _, cid := range chanIDs {
6✔
2574
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2575

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

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

2598
                        node1, err := fetchLightningNode(
3✔
2599
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2600
                        )
3✔
2601
                        if err != nil {
3✔
2602
                                return err
×
2603
                        }
×
2604

2605
                        node2, err := fetchLightningNode(
3✔
2606
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2607
                        )
3✔
2608
                        if err != nil {
3✔
2609
                                return err
×
2610
                        }
×
2611

2612
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2613
                                Info:    &edgeInfo,
3✔
2614
                                Policy1: edge1,
3✔
2615
                                Policy2: edge2,
3✔
2616
                                Node1:   &node1,
3✔
2617
                                Node2:   &node2,
3✔
2618
                        })
3✔
2619
                }
2620

2621
                return nil
3✔
2622
        }
2623

2624
        if tx == nil {
6✔
2625
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2626
                        chanEdges = nil
3✔
2627
                })
3✔
2628
                if err != nil {
3✔
2629
                        return nil, err
×
2630
                }
×
2631

2632
                return chanEdges, nil
3✔
2633
        }
2634

2635
        err := fetchChanInfos(tx)
×
2636
        if err != nil {
×
2637
                return nil, err
×
2638
        }
×
2639

2640
        return chanEdges, nil
×
2641
}
2642

2643
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2644
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2645

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

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

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

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

2682
        return nil
3✔
2683
}
2684

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

3✔
2696
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2697
        if err != nil {
3✔
2698
                return nil, err
×
2699
        }
×
2700

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

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

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

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

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

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

2767
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2768
        if strictZombie {
3✔
2769
                var e1UpdateTime, e2UpdateTime *time.Time
×
2770
                if edge1 != nil {
×
2771
                        e1UpdateTime = &edge1.LastUpdate
×
2772
                }
×
2773
                if edge2 != nil {
×
2774
                        e2UpdateTime = &edge2.LastUpdate
×
2775
                }
×
2776

2777
                nodeKey1, nodeKey2 = makeZombiePubkeys(
×
2778
                        &edgeInfo, e1UpdateTime, e2UpdateTime,
×
2779
                )
×
2780
        }
2781

2782
        return &edgeInfo, markEdgeZombie(
3✔
2783
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2784
        )
3✔
2785
}
2786

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

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

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

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

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

3✔
2838
        var (
3✔
2839
                isUpdate1    bool
3✔
2840
                edgeNotFound bool
3✔
2841
                from, to     route.Vertex
3✔
2842
        )
3✔
2843

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

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

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

2879
        err := c.chanScheduler.Execute(ctx, r)
3✔
2880

3✔
2881
        return from, to, err
3✔
2882
}
2883

2884
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2885
        isUpdate1 bool) {
3✔
2886

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

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

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

3✔
2921
        var noVertex route.Vertex
3✔
2922

3✔
2923
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2924
        if edges == nil {
3✔
2925
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2926
        }
×
2927
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2928
        if edgeIndex == nil {
3✔
2929
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2930
        }
×
2931

2932
        // Create the channelID key be converting the channel ID
2933
        // integer into a byte slice.
2934
        var chanID [8]byte
3✔
2935
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2936

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

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

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

2965
        var (
3✔
2966
                fromNodePubKey route.Vertex
3✔
2967
                toNodePubKey   route.Vertex
3✔
2968
        )
3✔
2969
        copy(fromNodePubKey[:], fromNode)
3✔
2970
        copy(toNodePubKey[:], toNode)
3✔
2971

3✔
2972
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
3✔
2973
}
2974

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

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

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

3✔
2998
                        nodeIsPublic = true
3✔
2999
                        return errDone
3✔
3000
                }
3✔
3001

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

3009
                // Otherwise, we'll continue our search.
3010
                return nil
3✔
3011
        })
3012
        if err != nil && !errors.Is(err, errDone) {
3✔
3013
                return false, err
×
3014
        }
×
3015

3016
        return nodeIsPublic, nil
3✔
3017
}
3018

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

3✔
3026
        return c.fetchLightningNode(tx, nodePub)
3✔
3027
}
3✔
3028

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

3✔
3035
        return c.fetchLightningNode(nil, nodePub)
3✔
3036
}
3✔
3037

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

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

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

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

3069
                node = &n
3✔
3070

3✔
3071
                return nil
3✔
3072
        }
3073

3074
        if tx == nil {
6✔
3075
                err := kvdb.View(
3✔
3076
                        c.db, fetch, func() {
6✔
3077
                                node = nil
3✔
3078
                        },
3✔
3079
                )
3080
                if err != nil {
6✔
3081
                        return nil, err
3✔
3082
                }
3✔
3083

3084
                return node, nil
3✔
3085
        }
3086

3087
        err := fetch(tx)
×
3088
        if err != nil {
×
3089
                return nil, err
×
3090
        }
×
3091

3092
        return node, nil
×
3093
}
3094

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

3✔
3103
        var (
3✔
3104
                updateTime time.Time
3✔
3105
                exists     bool
3✔
3106
        )
3✔
3107

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

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

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

3133
                exists = true
3✔
3134
                updateTime = node.LastUpdate
3✔
3135

3✔
3136
                return nil
3✔
3137
        }, func() {
3✔
3138
                updateTime = time.Time{}
3✔
3139
                exists = false
3✔
3140
        })
3✔
3141
        if err != nil {
3✔
3142
                return time.Time{}, exists, err
×
3143
        }
×
3144

3145
        return updateTime, exists, nil
3✔
3146
}
3147

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

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

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

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

3191
                        outgoingPolicy, err := fetchChanEdgePolicy(
3✔
3192
                                edges, chanID, nodePub,
3✔
3193
                        )
3✔
3194
                        if err != nil {
3✔
3195
                                return err
×
3196
                        }
×
3197

3198
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3199
                        if err != nil {
3✔
3200
                                return err
×
3201
                        }
×
3202

3203
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3204
                                edges, chanID, otherNode[:],
3✔
3205
                        )
3✔
3206
                        if err != nil {
3✔
3207
                                return err
×
3208
                        }
×
3209

3210
                        // Finally, we execute the callback.
3211
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3212
                        if err != nil {
6✔
3213
                                return err
3✔
3214
                        }
3✔
3215
                }
3216

3217
                return nil
3✔
3218
        }
3219

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

3226
        // Otherwise, we re-use the existing transaction to execute the graph
3227
        // traversal.
3228
        return traversal(tx)
3✔
3229
}
3230

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

3✔
3243
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
3✔
3244
                info *models.ChannelEdgeInfo, policy,
3✔
3245
                policy2 *models.ChannelEdgePolicy) error {
6✔
3246

3✔
3247
                return cb(info, policy, policy2)
3✔
3248
        })
3✔
3249
}
3250

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

3✔
3259
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3260
                nodes := tx.ReadBucket(nodeBucket)
3✔
3261
                if nodes == nil {
3✔
3262
                        return ErrGraphNotFound
×
3263
                }
×
3264

3265
                node, err := sourceNodeWithTx(nodes)
3✔
3266
                if err != nil {
3✔
3267
                        return err
×
3268
                }
×
3269

3270
                return nodeTraversal(
3✔
3271
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
3✔
3272
                                info *models.ChannelEdgeInfo,
3✔
3273
                                policy, _ *models.ChannelEdgePolicy) error {
6✔
3274

3✔
3275
                                peer, err := c.fetchOtherNode(
3✔
3276
                                        tx, info, node.PubKeyBytes[:],
3✔
3277
                                )
3✔
3278
                                if err != nil {
3✔
3279
                                        return err
×
3280
                                }
×
3281

3282
                                return cb(
3✔
3283
                                        info.ChannelPoint, policy != nil, peer,
3✔
3284
                                )
3✔
3285
                        },
3286
                )
3287
        }, func() {})
3✔
3288
}
3289

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

3✔
3308
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3309
}
3✔
3310

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

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

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

3339
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3340
                if err != nil {
3✔
3341
                        return err
×
3342
                }
×
3343

3344
                targetNode = &node
3✔
3345

3✔
3346
                return nil
3✔
3347
        }
3348

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

3360
        return targetNode, err
3✔
3361
}
3362

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

3✔
3372
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3373
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3374

3✔
3375
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3376
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3377

3✔
3378
        return node1Key[:], node2Key[:]
3✔
3379
}
3✔
3380

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

3✔
3390
        var (
3✔
3391
                edgeInfo *models.ChannelEdgeInfo
3✔
3392
                policy1  *models.ChannelEdgePolicy
3✔
3393
                policy2  *models.ChannelEdgePolicy
3✔
3394
        )
3✔
3395

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

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

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

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

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

3447
                policy1 = e1
3✔
3448
                policy2 = e2
3✔
3449

3✔
3450
                return nil
3✔
3451
        }, func() {
3✔
3452
                edgeInfo = nil
3✔
3453
                policy1 = nil
3✔
3454
                policy2 = nil
3✔
3455
        })
3✔
3456
        if err != nil {
6✔
3457
                return nil, nil, nil, err
3✔
3458
        }
3✔
3459

3460
        return edgeInfo, policy1, policy2, nil
3✔
3461
}
3462

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

3✔
3476
        var (
3✔
3477
                edgeInfo  *models.ChannelEdgeInfo
3✔
3478
                policy1   *models.ChannelEdgePolicy
3✔
3479
                policy2   *models.ChannelEdgePolicy
3✔
3480
                channelID [8]byte
3✔
3481
        )
3✔
3482

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

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

3503
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3504

3✔
3505
                // Now, attempt to fetch edge.
3✔
3506
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3507

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

3519
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3520
                                zombieIndex, chanID,
3✔
3521
                        )
3✔
3522
                        if !isZombie {
6✔
3523
                                return ErrEdgeNotFound
3✔
3524
                        }
3✔
3525

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

3✔
3535
                        return ErrZombieEdge
3✔
3536
                }
3537

3538
                // Otherwise, we'll just return the error if any.
3539
                if err != nil {
3✔
3540
                        return err
×
3541
                }
×
3542

3543
                edgeInfo = &edge
3✔
3544

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

3554
                policy1 = e1
3✔
3555
                policy2 = e2
3✔
3556

3✔
3557
                return nil
3✔
3558
        }, func() {
3✔
3559
                edgeInfo = nil
3✔
3560
                policy1 = nil
3✔
3561
                policy2 = nil
3✔
3562
        })
3✔
3563
        if errors.Is(err, ErrZombieEdge) {
6✔
3564
                return edgeInfo, nil, nil, err
3✔
3565
        }
3✔
3566
        if err != nil {
6✔
3567
                return nil, nil, nil, err
3✔
3568
        }
3✔
3569

3570
        return edgeInfo, policy1, policy2, nil
3✔
3571
}
3572

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

3592
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3593

3✔
3594
                return err
3✔
3595
        }, func() {
3✔
3596
                nodeIsPublic = false
3✔
3597
        })
3✔
3598
        if err != nil {
3✔
3599
                return false, err
×
3600
        }
×
3601

3602
        return nodeIsPublic, nil
3✔
3603
}
3604

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

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

3✔
3622
        return bldr.Script()
3✔
3623
}
3624

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

3633
        // OutPoint is the outpoint of the target channel.
3634
        OutPoint wire.OutPoint
3635
}
3636

3637
// String returns a human readable version of the target EdgePoint. We return
3638
// the outpoint directly as it is enough to uniquely identify the edge point.
3639
func (e *EdgePoint) String() string {
×
3640
        return e.OutPoint.String()
×
3641
}
×
3642

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

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

3✔
3675
                                var chanPoint wire.OutPoint
3✔
3676
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3677
                                if err != nil {
3✔
3678
                                        return err
×
3679
                                }
×
3680

3681
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3682
                                        edgeIndex, chanID,
3✔
3683
                                )
3✔
3684
                                if err != nil {
3✔
3685
                                        return err
×
3686
                                }
×
3687

3688
                                pkScript, err := genMultiSigP2WSH(
3✔
3689
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3690
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3691
                                )
3✔
3692
                                if err != nil {
3✔
3693
                                        return err
×
3694
                                }
×
3695

3696
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3697
                                        FundingPkScript: pkScript,
3✔
3698
                                        OutPoint:        chanPoint,
3✔
3699
                                })
3✔
3700

3✔
3701
                                return nil
3✔
3702
                        },
3703
                )
3704
        }, func() {
3✔
3705
                edgePoints = nil
3✔
3706
        }); err != nil {
3✔
3707
                return nil, err
×
3708
        }
×
3709

3710
        return edgePoints, nil
3✔
3711
}
3712

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

×
3719
        c.cacheMu.Lock()
×
3720
        defer c.cacheMu.Unlock()
×
3721

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

3733
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3734
        })
3735
        if err != nil {
×
3736
                return err
×
3737
        }
×
3738

3739
        c.rejectCache.remove(chanID)
×
3740
        c.chanCache.remove(chanID)
×
3741

×
3742
        return nil
×
3743
}
3744

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

3✔
3751
        var k [8]byte
3✔
3752
        byteOrder.PutUint64(k[:], chanID)
3✔
3753

3✔
3754
        var v [66]byte
3✔
3755
        copy(v[:33], pubKey1[:])
3✔
3756
        copy(v[33:], pubKey2[:])
3✔
3757

3✔
3758
        return zombieIndex.Put(k[:], v[:])
3✔
3759
}
3✔
3760

3761
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3762
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
3763
        c.cacheMu.Lock()
×
3764
        defer c.cacheMu.Unlock()
×
3765

×
3766
        return c.markEdgeLiveUnsafe(nil, chanID)
×
3767
}
×
3768

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

3786
                var k [8]byte
×
3787
                byteOrder.PutUint64(k[:], chanID)
×
3788

×
3789
                if len(zombieIndex.Get(k[:])) == 0 {
×
3790
                        return ErrZombieEdgeNotFound
×
3791
                }
×
3792

3793
                return zombieIndex.Delete(k[:])
×
3794
        }
3795

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

3808
        c.rejectCache.remove(chanID)
×
3809
        c.chanCache.remove(chanID)
×
3810

×
3811
        return nil
×
3812
}
3813

3814
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3815
// zombie, then the two node public keys corresponding to this edge are also
3816
// returned.
3817
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte,
3818
        error) {
×
3819

×
3820
        var (
×
3821
                isZombie         bool
×
3822
                pubKey1, pubKey2 [33]byte
×
3823
        )
×
3824

×
3825
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
3826
                edges := tx.ReadBucket(edgeBucket)
×
3827
                if edges == nil {
×
3828
                        return ErrGraphNoEdgesFound
×
3829
                }
×
3830
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
3831
                if zombieIndex == nil {
×
3832
                        return nil
×
3833
                }
×
3834

3835
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
3836

×
3837
                return nil
×
3838
        }, func() {
×
3839
                isZombie = false
×
3840
                pubKey1 = [33]byte{}
×
3841
                pubKey2 = [33]byte{}
×
3842
        })
×
3843
        if err != nil {
×
3844
                return false, [33]byte{}, [33]byte{}, fmt.Errorf("%w: %w "+
×
3845
                        "(chanID=%d)", ErrCantCheckIfZombieEdgeStr, err, chanID)
×
3846
        }
×
3847

3848
        return isZombie, pubKey1, pubKey2, nil
×
3849
}
3850

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

3✔
3857
        var k [8]byte
3✔
3858
        byteOrder.PutUint64(k[:], chanID)
3✔
3859

3✔
3860
        v := zombieIndex.Get(k[:])
3✔
3861
        if v == nil {
6✔
3862
                return false, [33]byte{}, [33]byte{}
3✔
3863
        }
3✔
3864

3865
        var pubKey1, pubKey2 [33]byte
3✔
3866
        copy(pubKey1[:], v[:33])
3✔
3867
        copy(pubKey2[:], v[33:])
3✔
3868

3✔
3869
        return true, pubKey1, pubKey2
3✔
3870
}
3871

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

3885
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
3886
                        numZombies++
×
3887
                        return nil
×
3888
                })
×
3889
        }, func() {
×
3890
                numZombies = 0
×
3891
        })
×
3892
        if err != nil {
×
3893
                return 0, err
×
3894
        }
×
3895

3896
        return numZombies, nil
×
3897
}
3898

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

3909
                var k [8]byte
×
3910
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
3911

×
3912
                return closedScids.Put(k[:], []byte{})
×
3913
        }, func() {})
×
3914
}
3915

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

3927
                var k [8]byte
3✔
3928
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3929

3✔
3930
                if closedScids.Get(k[:]) != nil {
3✔
3931
                        isClosed = true
×
3932
                        return nil
×
3933
                }
×
3934

3935
                return nil
3✔
3936
        }, func() {
3✔
3937
                isClosed = false
3✔
3938
        })
3✔
3939
        if err != nil {
3✔
3940
                return false, err
×
3941
        }
×
3942

3943
        return isClosed, nil
3✔
3944
}
3945

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

3957
// nodeTraverserSession implements the NodeTraverser interface but with a
3958
// backing read only transaction for a consistent view of the graph.
3959
type nodeTraverserSession struct {
3960
        tx kvdb.RTx
3961
        db *KVStore
3962
}
3963

3964
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3965
// node.
3966
//
3967
// NOTE: Part of the NodeTraverser interface.
3968
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3969
        cb func(channel *DirectedChannel) error) error {
×
3970

×
3971
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
×
3972
}
×
3973

3974
// FetchNodeFeatures returns the features of the given node. If the node is
3975
// unknown, assume no additional features are supported.
3976
//
3977
// NOTE: Part of the NodeTraverser interface.
3978
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
3979
        *lnwire.FeatureVector, error) {
×
3980

×
3981
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
3982
}
×
3983

3984
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3985
        node *models.LightningNode) error {
3✔
3986

3✔
3987
        var (
3✔
3988
                scratch [16]byte
3✔
3989
                b       bytes.Buffer
3✔
3990
        )
3✔
3991

3✔
3992
        pub, err := node.PubKey()
3✔
3993
        if err != nil {
3✔
3994
                return err
×
3995
        }
×
3996
        nodePub := pub.SerializeCompressed()
3✔
3997

3✔
3998
        // If the node has the update time set, write it, else write 0.
3✔
3999
        updateUnix := uint64(0)
3✔
4000
        if node.LastUpdate.Unix() > 0 {
6✔
4001
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
4002
        }
3✔
4003

4004
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
4005
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
4006
                return err
×
4007
        }
×
4008

4009
        if _, err := b.Write(nodePub); err != nil {
3✔
4010
                return err
×
4011
        }
×
4012

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

4022
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
4023
        }
4024

4025
        // Write HaveNodeAnnouncement=1.
4026
        byteOrder.PutUint16(scratch[:2], 1)
3✔
4027
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4028
                return err
×
4029
        }
×
4030

4031
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
4032
                return err
×
4033
        }
×
4034
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
4035
                return err
×
4036
        }
×
4037
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
4038
                return err
×
4039
        }
×
4040

4041
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
4042
                return err
×
4043
        }
×
4044

4045
        if err := node.Features.Encode(&b); err != nil {
3✔
4046
                return err
×
4047
        }
×
4048

4049
        numAddresses := uint16(len(node.Addresses))
3✔
4050
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
4051
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4052
                return err
×
4053
        }
×
4054

4055
        for _, address := range node.Addresses {
6✔
4056
                if err := SerializeAddr(&b, address); err != nil {
3✔
4057
                        return err
×
4058
                }
×
4059
        }
4060

4061
        sigLen := len(node.AuthSigBytes)
3✔
4062
        if sigLen > 80 {
3✔
4063
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4064
                        sigLen)
×
4065
        }
×
4066

4067
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
4068
        if err != nil {
3✔
4069
                return err
×
4070
        }
×
4071

4072
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4073
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4074
        }
×
4075
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
4076
        if err != nil {
3✔
4077
                return err
×
4078
        }
×
4079

4080
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
4081
                return err
×
4082
        }
×
4083

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

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

3✔
4097
                var oldIndexKey [8 + 33]byte
3✔
4098
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
4099
                copy(oldIndexKey[8:], nodePub)
3✔
4100

3✔
4101
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4102
                        return err
×
4103
                }
×
4104
        }
4105

4106
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4107
                return err
×
4108
        }
×
4109

4110
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
4111
}
4112

4113
func fetchLightningNode(nodeBucket kvdb.RBucket,
4114
        nodePub []byte) (models.LightningNode, error) {
3✔
4115

3✔
4116
        nodeBytes := nodeBucket.Get(nodePub)
3✔
4117
        if nodeBytes == nil {
6✔
4118
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
4119
        }
3✔
4120

4121
        nodeReader := bytes.NewReader(nodeBytes)
3✔
4122

3✔
4123
        return deserializeLightningNode(nodeReader)
3✔
4124
}
4125

4126
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4127
        *lnwire.FeatureVector, error) {
3✔
4128

3✔
4129
        var (
3✔
4130
                pubKey      route.Vertex
3✔
4131
                features    = lnwire.EmptyFeatureVector()
3✔
4132
                nodeScratch [8]byte
3✔
4133
        )
3✔
4134

3✔
4135
        // Skip ahead:
3✔
4136
        // - LastUpdate (8 bytes)
3✔
4137
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
4138
                return pubKey, nil, err
×
4139
        }
×
4140

4141
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
4142
                return pubKey, nil, err
×
4143
        }
×
4144

4145
        // Read the node announcement flag.
4146
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
4147
                return pubKey, nil, err
×
4148
        }
×
4149
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4150

3✔
4151
        // The rest of the data is optional, and will only be there if we got a
3✔
4152
        // node announcement for this node.
3✔
4153
        if hasNodeAnn == 0 {
6✔
4154
                return pubKey, features, nil
3✔
4155
        }
3✔
4156

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

4170
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4171
                return pubKey, nil, err
×
4172
        }
×
4173

4174
        if err := features.Decode(r); err != nil {
3✔
4175
                return pubKey, nil, err
×
4176
        }
×
4177

4178
        return pubKey, features, nil
3✔
4179
}
4180

4181
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4182
        var (
3✔
4183
                node    models.LightningNode
3✔
4184
                scratch [8]byte
3✔
4185
                err     error
3✔
4186
        )
3✔
4187

3✔
4188
        // Always populate a feature vector, even if we don't have a node
3✔
4189
        // announcement and short circuit below.
3✔
4190
        node.Features = lnwire.EmptyFeatureVector()
3✔
4191

3✔
4192
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4193
                return models.LightningNode{}, err
×
4194
        }
×
4195

4196
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4197
        node.LastUpdate = time.Unix(unix, 0)
3✔
4198

3✔
4199
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4200
                return models.LightningNode{}, err
×
4201
        }
×
4202

4203
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4204
                return models.LightningNode{}, err
×
4205
        }
×
4206

4207
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4208
        if hasNodeAnn == 1 {
6✔
4209
                node.HaveNodeAnnouncement = true
3✔
4210
        } else {
6✔
4211
                node.HaveNodeAnnouncement = false
3✔
4212
        }
3✔
4213

4214
        // The rest of the data is optional, and will only be there if we got a
4215
        // node announcement for this node.
4216
        if !node.HaveNodeAnnouncement {
6✔
4217
                return node, nil
3✔
4218
        }
3✔
4219

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

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

4237
        err = node.Features.Decode(r)
3✔
4238
        if err != nil {
3✔
4239
                return models.LightningNode{}, err
×
4240
        }
×
4241

4242
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4243
                return models.LightningNode{}, err
×
4244
        }
×
4245
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4246

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

3✔
4257
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4258
        if err != nil {
3✔
4259
                return models.LightningNode{}, err
×
4260
        }
×
4261

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

4274
        if len(extraBytes) > 0 {
3✔
4275
                node.ExtraOpaqueData = extraBytes
×
4276
        }
×
4277

4278
        return node, nil
3✔
4279
}
4280

4281
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4282
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4283

3✔
4284
        var b bytes.Buffer
3✔
4285

3✔
4286
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4287
                return err
×
4288
        }
×
4289
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4290
                return err
×
4291
        }
×
4292
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4293
                return err
×
4294
        }
×
4295
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4296
                return err
×
4297
        }
×
4298

4299
        var featureBuf bytes.Buffer
3✔
4300
        if err := edgeInfo.Features.Encode(&featureBuf); err != nil {
3✔
4301
                return fmt.Errorf("unable to encode features: %w", err)
×
4302
        }
×
4303

4304
        if err := wire.WriteVarBytes(&b, 0, featureBuf.Bytes()); err != nil {
3✔
4305
                return err
×
4306
        }
×
4307

4308
        authProof := edgeInfo.AuthProof
3✔
4309
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4310
        if authProof != nil {
6✔
4311
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4312
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4313
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4314
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4315
        }
3✔
4316

4317
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4318
                return err
×
4319
        }
×
4320
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4321
                return err
×
4322
        }
×
4323
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4324
                return err
×
4325
        }
×
4326
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4327
                return err
×
4328
        }
×
4329

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

4344
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4345
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4346
        }
×
4347
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4348
        if err != nil {
3✔
4349
                return err
×
4350
        }
×
4351

4352
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4353
}
4354

4355
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4356
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4357

3✔
4358
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4359
        if edgeInfoBytes == nil {
6✔
4360
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4361
        }
3✔
4362

4363
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4364

3✔
4365
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4366
}
4367

4368
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4369
        var (
3✔
4370
                err      error
3✔
4371
                edgeInfo models.ChannelEdgeInfo
3✔
4372
        )
3✔
4373

3✔
4374
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4375
                return models.ChannelEdgeInfo{}, err
×
4376
        }
×
4377
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4378
                return models.ChannelEdgeInfo{}, err
×
4379
        }
×
4380
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4381
                return models.ChannelEdgeInfo{}, err
×
4382
        }
×
4383
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4384
                return models.ChannelEdgeInfo{}, err
×
4385
        }
×
4386

4387
        featureBytes, err := wire.ReadVarBytes(r, 0, 900, "features")
3✔
4388
        if err != nil {
3✔
4389
                return models.ChannelEdgeInfo{}, err
×
4390
        }
×
4391

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

3✔
4400
        proof := &models.ChannelAuthProof{}
3✔
4401

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

4419
        if !proof.IsEmpty() {
6✔
4420
                edgeInfo.AuthProof = proof
3✔
4421
        }
3✔
4422

4423
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4424
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4425
                return models.ChannelEdgeInfo{}, err
×
4426
        }
×
4427
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4428
                return models.ChannelEdgeInfo{}, err
×
4429
        }
×
4430
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4431
                return models.ChannelEdgeInfo{}, err
×
4432
        }
×
4433

4434
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4435
                return models.ChannelEdgeInfo{}, err
×
4436
        }
×
4437

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

4450
        return edgeInfo, nil
3✔
4451
}
4452

4453
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4454
        from, to []byte) error {
3✔
4455

3✔
4456
        var edgeKey [33 + 8]byte
3✔
4457
        copy(edgeKey[:], from)
3✔
4458
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4459

3✔
4460
        var b bytes.Buffer
3✔
4461
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
4462
                return err
×
4463
        }
×
4464

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

3✔
4472
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4473
        if err != nil {
3✔
4474
                return err
×
4475
        }
×
4476

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

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

×
4504
                        return err
×
4505
                }
×
4506

4507
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4508

3✔
4509
                var oldIndexKey [8 + 8]byte
3✔
4510
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4511
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4512

3✔
4513
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4514
                        return err
×
4515
                }
×
4516
        }
4517

4518
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4519
                return err
×
4520
        }
×
4521

4522
        err = updateEdgePolicyDisabledIndex(
3✔
4523
                edges, edge.ChannelID,
3✔
4524
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4525
                edge.IsDisabled(),
3✔
4526
        )
3✔
4527
        if err != nil {
3✔
4528
                return err
×
4529
        }
×
4530

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

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

3✔
4546
        var disabledEdgeKey [8 + 1]byte
3✔
4547
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4548
        if direction {
6✔
4549
                disabledEdgeKey[8] = 1
3✔
4550
        }
3✔
4551

4552
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4553
                disabledEdgePolicyBucket,
3✔
4554
        )
3✔
4555
        if err != nil {
3✔
4556
                return err
×
4557
        }
×
4558

4559
        if disabled {
6✔
4560
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4561
        }
3✔
4562

4563
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4564
}
4565

4566
// putChanEdgePolicyUnknown marks the edge policy as unknown
4567
// in the edges bucket.
4568
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4569
        from []byte) error {
3✔
4570

3✔
4571
        var edgeKey [33 + 8]byte
3✔
4572
        copy(edgeKey[:], from)
3✔
4573
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4574

3✔
4575
        if edges.Get(edgeKey[:]) != nil {
3✔
4576
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4577
                        " when there is already a policy present", channelID)
×
4578
        }
×
4579

4580
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4581
}
4582

4583
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4584
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
3✔
4585

3✔
4586
        var edgeKey [33 + 8]byte
3✔
4587
        copy(edgeKey[:], nodePub)
3✔
4588
        copy(edgeKey[33:], chanID)
3✔
4589

3✔
4590
        edgeBytes := edges.Get(edgeKey[:])
3✔
4591
        if edgeBytes == nil {
3✔
4592
                return nil, ErrEdgeNotFound
×
4593
        }
×
4594

4595
        // No need to deserialize unknown policy.
4596
        if bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4597
                return nil, nil
3✔
4598
        }
3✔
4599

4600
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4601

3✔
4602
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4603
        switch {
3✔
4604
        // If the db policy was missing an expected optional field, we return
4605
        // nil as if the policy was unknown.
4606
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
4607
                return nil, nil
×
4608

4609
        // If the policy contains invalid TLV bytes, we return nil as if
4610
        // the policy was unknown.
4611
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4612
                return nil, nil
×
4613

4614
        case err != nil:
×
4615
                return nil, err
×
4616
        }
4617

4618
        return ep, nil
3✔
4619
}
4620

4621
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4622
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4623
        error) {
3✔
4624

3✔
4625
        edgeInfo := edgeIndex.Get(chanID)
3✔
4626
        if edgeInfo == nil {
3✔
4627
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4628
                        chanID)
×
4629
        }
×
4630

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

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

4650
        return edge1, edge2, nil
3✔
4651
}
4652

4653
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4654
        to []byte) error {
3✔
4655

3✔
4656
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4657
        if err != nil {
3✔
4658
                return err
×
4659
        }
×
4660

4661
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4662
                return err
×
4663
        }
×
4664

4665
        var scratch [8]byte
3✔
4666
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4667
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4668
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4669
                return err
×
4670
        }
×
4671

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

4695
        if _, err := w.Write(to); err != nil {
3✔
4696
                return err
×
4697
        }
×
4698

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

4711
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
4712
        err = edge.ExtraOpaqueData.ValidateTLV()
3✔
4713
        if err != nil {
3✔
4714
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
4715
        }
×
4716

4717
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4718
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4719
        }
×
4720
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4721
                return err
×
4722
        }
×
4723

4724
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4725
                return err
×
4726
        }
×
4727

4728
        return nil
3✔
4729
}
4730

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

×
4741
                return nil, err
×
4742
        }
×
4743

4744
        return edge, err
3✔
4745
}
4746

4747
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4748
        error) {
3✔
4749

3✔
4750
        edge := &models.ChannelEdgePolicy{}
3✔
4751

3✔
4752
        var err error
3✔
4753
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4754
        if err != nil {
3✔
4755
                return nil, err
×
4756
        }
×
4757

4758
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4759
                return nil, err
×
4760
        }
×
4761

4762
        var scratch [8]byte
3✔
4763
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4764
                return nil, err
×
4765
        }
×
4766
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4767
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4768

3✔
4769
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4770
                return nil, err
×
4771
        }
×
4772
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4773
                return nil, err
×
4774
        }
×
4775
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4776
                return nil, err
×
4777
        }
×
4778

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

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

3✔
4790
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4791
                return nil, err
×
4792
        }
×
4793
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4794

3✔
4795
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4796
                return nil, err
×
4797
        }
×
4798

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

4811
        // See if optional fields are present.
4812
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4813
                // The max_htlc field should be at the beginning of the opaque
3✔
4814
                // bytes.
3✔
4815
                opq := edge.ExtraOpaqueData
3✔
4816

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

4824
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4825
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4826

3✔
4827
                // Exclude the parsed field from the rest of the opaque data.
3✔
4828
                edge.ExtraOpaqueData = opq[8:]
3✔
4829
        }
4830

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

4842
        val, ok := typeMap[lnwire.FeeRecordType]
3✔
4843
        if ok && val == nil {
6✔
4844
                edge.InboundFee = fn.Some(inboundFee)
3✔
4845
        }
3✔
4846

4847
        return edge, nil
3✔
4848
}
4849

4850
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4851
// KVStore and a kvdb.RTx.
4852
type chanGraphNodeTx struct {
4853
        tx   kvdb.RTx
4854
        db   *KVStore
4855
        node *models.LightningNode
4856
}
4857

4858
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4859
// interface.
4860
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4861

4862
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4863
        node *models.LightningNode) *chanGraphNodeTx {
3✔
4864

3✔
4865
        return &chanGraphNodeTx{
3✔
4866
                tx:   tx,
3✔
4867
                db:   db,
3✔
4868
                node: node,
3✔
4869
        }
3✔
4870
}
3✔
4871

4872
// Node returns the raw information of the node.
4873
//
4874
// NOTE: This is a part of the NodeRTx interface.
4875
func (c *chanGraphNodeTx) Node() *models.LightningNode {
3✔
4876
        return c.node
3✔
4877
}
3✔
4878

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

4890
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4891
}
4892

4893
// ForEachChannel can be used to iterate over the node's channels under
4894
// the same transaction used to fetch the node.
4895
//
4896
// NOTE: This is a part of the NodeRTx interface.
4897
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4898
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
×
4899

×
4900
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
×
4901
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
×
4902
                        policy2 *models.ChannelEdgePolicy) error {
×
4903

×
4904
                        return f(info, policy1, policy2)
×
4905
                },
×
4906
        )
4907
}
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