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

lightningnetwork / lnd / 15778248138

20 Jun 2025 11:47AM UTC coverage: 68.143% (+0.007%) from 68.136%
15778248138

push

github

web-flow
Merge pull request #9969 from ellemouton/fixLnwireTestDataRace

lnwire: fix test data race

134483 of 197355 relevant lines covered (68.14%)

22133.8 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

572✔
265
                        return nil
572✔
266
                }
572✔
267

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

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

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

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

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

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

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

304
                channelMap[key] = edge
993✔
305

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

312
        return channelMap, nil
144✔
313
}
314

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

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

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

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

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

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

371
        return nil
172✔
372
}
373

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

399✔
529
                                if policy1 != nil {
798✔
530
                                        cachedPolicy1 = models.NewCachedPolicy(
399✔
531
                                                policy1,
399✔
532
                                        )
399✔
533
                                }
399✔
534

535
                                if policy2 != nil {
798✔
536
                                        cachedPolicy2 = models.NewCachedPolicy(
399✔
537
                                                policy2,
399✔
538
                                        )
399✔
539
                                }
399✔
540

541
                                return cb(
399✔
542
                                        models.NewCachedEdge(&info),
399✔
543
                                        cachedPolicy1, cachedPolicy2,
399✔
544
                                )
399✔
545
                        },
546
                )
547
        }, func() {})
140✔
548
}
549

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

265✔
560
        // Fallback that uses the database.
265✔
561
        toNodeCallback := func() route.Vertex {
400✔
562
                return node
135✔
563
        }
135✔
564
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
265✔
565
        if err != nil {
265✔
566
                return err
×
567
        }
×
568

569
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
265✔
570
                p2 *models.ChannelEdgePolicy) error {
954✔
571

689✔
572
                var cachedInPolicy *models.CachedEdgePolicy
689✔
573
                if p2 != nil {
1,375✔
574
                        cachedInPolicy = models.NewCachedPolicy(p2)
686✔
575
                        cachedInPolicy.ToNodePubKey = toNodeCallback
686✔
576
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
686✔
577
                }
686✔
578

579
                directedChannel := &DirectedChannel{
689✔
580
                        ChannelID:    e.ChannelID,
689✔
581
                        IsNode1:      node == e.NodeKey1Bytes,
689✔
582
                        OtherNode:    e.NodeKey2Bytes,
689✔
583
                        Capacity:     e.Capacity,
689✔
584
                        OutPolicySet: p1 != nil,
689✔
585
                        InPolicy:     cachedInPolicy,
689✔
586
                }
689✔
587

689✔
588
                if p1 != nil {
1,377✔
589
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
1,024✔
590
                                directedChannel.InboundFee = fee
336✔
591
                        })
336✔
592
                }
593

594
                if node == e.NodeKey2Bytes {
1,035✔
595
                        directedChannel.OtherNode = e.NodeKey1Bytes
346✔
596
                }
346✔
597

598
                return cb(directedChannel)
689✔
599
        }
600

601
        return nodeTraversal(tx, node[:], c.db, dbCallback)
265✔
602
}
603

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

710✔
610
        // Fallback that uses the database.
710✔
611
        targetNode, err := c.FetchLightningNodeTx(tx, node)
710✔
612
        switch {
710✔
613
        // If the node exists and has features, return them directly.
614
        case err == nil:
699✔
615
                return targetNode.Features, nil
699✔
616

617
        // If we couldn't find a node announcement, populate a blank feature
618
        // vector.
619
        case errors.Is(err, ErrGraphNodeNotFound):
11✔
620
                return lnwire.EmptyFeatureVector(), nil
11✔
621

622
        // Otherwise, bubble the error up.
623
        default:
×
624
                return nil, err
×
625
        }
626
}
627

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

26✔
639
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
26✔
640
}
26✔
641

642
// FetchNodeFeatures returns the features of the given node. If no features are
643
// known for the node, an empty feature vector is returned.
644
//
645
// NOTE: this is part of the graphdb.NodeTraverser interface.
646
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
647
        *lnwire.FeatureVector, error) {
4✔
648

4✔
649
        return c.fetchNodeFeatures(nil, nodePub)
4✔
650
}
4✔
651

652
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
653
// data to the call-back.
654
//
655
// NOTE: The callback contents MUST not be modified.
656
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
657
        chans map[uint64]*DirectedChannel) error) error {
1✔
658

1✔
659
        // Otherwise call back to a version that uses the database directly.
1✔
660
        // We'll iterate over each node, then the set of channels for each
1✔
661
        // node, and construct a similar callback functiopn signature as the
1✔
662
        // main funcotin expects.
1✔
663
        return c.forEachNode(func(tx kvdb.RTx,
1✔
664
                node *models.LightningNode) error {
21✔
665

20✔
666
                channels := make(map[uint64]*DirectedChannel)
20✔
667

20✔
668
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
20✔
669
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
670
                                p1 *models.ChannelEdgePolicy,
20✔
671
                                p2 *models.ChannelEdgePolicy) error {
210✔
672

190✔
673
                                toNodeCallback := func() route.Vertex {
190✔
674
                                        return node.PubKeyBytes
×
675
                                }
×
676
                                toNodeFeatures, err := c.fetchNodeFeatures(
190✔
677
                                        tx, node.PubKeyBytes,
190✔
678
                                )
190✔
679
                                if err != nil {
190✔
680
                                        return err
×
681
                                }
×
682

683
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
684
                                if p2 != nil {
380✔
685
                                        cachedInPolicy =
190✔
686
                                                models.NewCachedPolicy(p2)
190✔
687
                                        cachedInPolicy.ToNodePubKey =
190✔
688
                                                toNodeCallback
190✔
689
                                        cachedInPolicy.ToNodeFeatures =
190✔
690
                                                toNodeFeatures
190✔
691
                                }
190✔
692

693
                                directedChannel := &DirectedChannel{
190✔
694
                                        ChannelID: e.ChannelID,
190✔
695
                                        IsNode1: node.PubKeyBytes ==
190✔
696
                                                e.NodeKey1Bytes,
190✔
697
                                        OtherNode:    e.NodeKey2Bytes,
190✔
698
                                        Capacity:     e.Capacity,
190✔
699
                                        OutPolicySet: p1 != nil,
190✔
700
                                        InPolicy:     cachedInPolicy,
190✔
701
                                }
190✔
702

190✔
703
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
704
                                        directedChannel.OtherNode =
95✔
705
                                                e.NodeKey1Bytes
95✔
706
                                }
95✔
707

708
                                channels[e.ChannelID] = directedChannel
190✔
709

190✔
710
                                return nil
190✔
711
                        })
712
                if err != nil {
20✔
713
                        return err
×
714
                }
×
715

716
                return cb(node.PubKeyBytes, channels)
20✔
717
        })
718
}
719

720
// DisabledChannelIDs returns the channel ids of disabled channels.
721
// A channel is disabled when two of the associated ChanelEdgePolicies
722
// have their disabled bit on.
723
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
6✔
724
        var disabledChanIDs []uint64
6✔
725
        var chanEdgeFound map[uint64]struct{}
6✔
726

6✔
727
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
728
                edges := tx.ReadBucket(edgeBucket)
6✔
729
                if edges == nil {
6✔
730
                        return ErrGraphNoEdgesFound
×
731
                }
×
732

733
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
734
                        disabledEdgePolicyBucket,
6✔
735
                )
6✔
736
                if disabledEdgePolicyIndex == nil {
7✔
737
                        return nil
1✔
738
                }
1✔
739

740
                // We iterate over all disabled policies and we add each channel
741
                // that has more than one disabled policy to disabledChanIDs
742
                // array.
743
                return disabledEdgePolicyIndex.ForEach(
5✔
744
                        func(k, v []byte) error {
16✔
745
                                chanID := byteOrder.Uint64(k[:8])
11✔
746
                                _, edgeFound := chanEdgeFound[chanID]
11✔
747
                                if edgeFound {
15✔
748
                                        delete(chanEdgeFound, chanID)
4✔
749
                                        disabledChanIDs = append(
4✔
750
                                                disabledChanIDs, chanID,
4✔
751
                                        )
4✔
752

4✔
753
                                        return nil
4✔
754
                                }
4✔
755

756
                                chanEdgeFound[chanID] = struct{}{}
7✔
757

7✔
758
                                return nil
7✔
759
                        },
760
                )
761
        }, func() {
6✔
762
                disabledChanIDs = nil
6✔
763
                chanEdgeFound = make(map[uint64]struct{})
6✔
764
        })
6✔
765
        if err != nil {
6✔
766
                return nil, err
×
767
        }
×
768

769
        return disabledChanIDs, nil
6✔
770
}
771

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

1,161✔
782
                return cb(newChanGraphNodeTx(tx, c, node))
1,161✔
783
        })
1,161✔
784
}
785

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

132✔
796
        traversal := func(tx kvdb.RTx) error {
264✔
797
                // First grab the nodes bucket which stores the mapping from
132✔
798
                // pubKey to node information.
132✔
799
                nodes := tx.ReadBucket(nodeBucket)
132✔
800
                if nodes == nil {
132✔
801
                        return ErrGraphNotFound
×
802
                }
×
803

804
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,574✔
805
                        // If this is the source key, then we skip this
1,442✔
806
                        // iteration as the value for this key is a pubKey
1,442✔
807
                        // rather than raw node information.
1,442✔
808
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,706✔
809
                                return nil
264✔
810
                        }
264✔
811

812
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
813
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
814
                        if err != nil {
1,181✔
815
                                return err
×
816
                        }
×
817

818
                        // Execute the callback, the transaction will abort if
819
                        // this returns an error.
820
                        return cb(tx, &node)
1,181✔
821
                })
822
        }
823

824
        return kvdb.View(c.db, traversal, func() {})
264✔
825
}
826

827
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
828
// graph, executing the passed callback with each node encountered. If the
829
// callback returns an error, then the transaction is aborted and the iteration
830
// stops early.
831
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
832
        *lnwire.FeatureVector) error) error {
141✔
833

141✔
834
        traversal := func(tx kvdb.RTx) error {
282✔
835
                // First grab the nodes bucket which stores the mapping from
141✔
836
                // pubKey to node information.
141✔
837
                nodes := tx.ReadBucket(nodeBucket)
141✔
838
                if nodes == nil {
141✔
839
                        return ErrGraphNotFound
×
840
                }
×
841

842
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
540✔
843
                        // If this is the source key, then we skip this
399✔
844
                        // iteration as the value for this key is a pubKey
399✔
845
                        // rather than raw node information.
399✔
846
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
678✔
847
                                return nil
279✔
848
                        }
279✔
849

850
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
851
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
123✔
852
                                nodeReader,
123✔
853
                        )
123✔
854
                        if err != nil {
123✔
855
                                return err
×
856
                        }
×
857

858
                        // Execute the callback, the transaction will abort if
859
                        // this returns an error.
860
                        return cb(node, features)
123✔
861
                })
862
        }
863

864
        return kvdb.View(c.db, traversal, func() {})
282✔
865
}
866

867
// SourceNode returns the source node of the graph. The source node is treated
868
// as the center node within a star-graph. This method may be used to kick off
869
// a path finding algorithm in order to explore the reachability of another
870
// node based off the source node.
871
func (c *KVStore) SourceNode(_ context.Context) (*models.LightningNode,
872
        error) {
240✔
873

240✔
874
        var source *models.LightningNode
240✔
875
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
480✔
876
                // First grab the nodes bucket which stores the mapping from
240✔
877
                // pubKey to node information.
240✔
878
                nodes := tx.ReadBucket(nodeBucket)
240✔
879
                if nodes == nil {
240✔
880
                        return ErrGraphNotFound
×
881
                }
×
882

883
                node, err := c.sourceNode(nodes)
240✔
884
                if err != nil {
241✔
885
                        return err
1✔
886
                }
1✔
887
                source = node
239✔
888

239✔
889
                return nil
239✔
890
        }, func() {
240✔
891
                source = nil
240✔
892
        })
240✔
893
        if err != nil {
241✔
894
                return nil, err
1✔
895
        }
1✔
896

897
        return source, nil
239✔
898
}
899

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

491✔
907
        selfPub := nodes.Get(sourceKey)
491✔
908
        if selfPub == nil {
492✔
909
                return nil, ErrSourceNodeNotSet
1✔
910
        }
1✔
911

912
        // With the pubKey of the source node retrieved, we're able to
913
        // fetch the full node information.
914
        node, err := fetchLightningNode(nodes, selfPub)
490✔
915
        if err != nil {
490✔
916
                return nil, err
×
917
        }
×
918

919
        return &node, nil
490✔
920
}
921

922
// SetSourceNode sets the source node within the graph database. The source
923
// node is to be used as the center of a star-graph within path finding
924
// algorithms.
925
func (c *KVStore) SetSourceNode(_ context.Context,
926
        node *models.LightningNode) error {
117✔
927

117✔
928
        nodePubBytes := node.PubKeyBytes[:]
117✔
929

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

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

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

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

806✔
961
        r := &batch.Request[kvdb.RwTx]{
806✔
962
                Opts: batch.NewSchedulerOptions(opts...),
806✔
963
                Do: func(tx kvdb.RwTx) error {
1,612✔
964
                        return addLightningNode(tx, node)
806✔
965
                },
806✔
966
        }
967

968
        return c.nodeScheduler.Execute(ctx, r)
806✔
969
}
970

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

977
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
1,003✔
978
        if err != nil {
1,003✔
979
                return err
×
980
        }
×
981

982
        updateIndex, err := nodes.CreateBucketIfNotExists(
1,003✔
983
                nodeUpdateIndexBucket,
1,003✔
984
        )
1,003✔
985
        if err != nil {
1,003✔
986
                return err
×
987
        }
×
988

989
        return putLightningNode(nodes, aliases, updateIndex, node)
1,003✔
990
}
991

992
// LookupAlias attempts to return the alias as advertised by the target node.
993
// TODO(roasbeef): currently assumes that aliases are unique...
994
func (c *KVStore) LookupAlias(_ context.Context,
995
        pub *btcec.PublicKey) (string, error) {
5✔
996

5✔
997
        var alias string
5✔
998

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

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

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

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

4✔
1020
                return nil
4✔
1021
        }, func() {
5✔
1022
                alias = ""
5✔
1023
        })
5✔
1024
        if err != nil {
6✔
1025
                return "", err
1✔
1026
        }
1✔
1027

1028
        return alias, nil
4✔
1029
}
1030

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

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

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

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

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

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

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

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

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

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

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

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

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

1,725✔
1109
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,725✔
1110
                        // succeed, but propagate the error via local state.
1,725✔
1111
                        if errors.Is(err, ErrEdgeAlreadyExist) {
1,962✔
1112
                                alreadyExists = true
237✔
1113
                                return nil
237✔
1114
                        }
237✔
1115

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

1132
        return c.chanScheduler.Execute(ctx, r)
1,725✔
1133
}
1134

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

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

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

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

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

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

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

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

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

1230
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,488✔
1231
}
1232

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

217✔
1242
        var (
217✔
1243
                upd1Time time.Time
217✔
1244
                upd2Time time.Time
217✔
1245
                exists   bool
217✔
1246
                isZombie bool
217✔
1247
        )
217✔
1248

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

75✔
1258
                return upd1Time, upd2Time, exists, isZombie, nil
75✔
1259
        }
75✔
1260
        c.cacheMu.RUnlock()
145✔
1261

145✔
1262
        c.cacheMu.Lock()
145✔
1263
        defer c.cacheMu.Unlock()
145✔
1264

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

5✔
1273
                return upd1Time, upd2Time, exists, isZombie, nil
5✔
1274
        }
5✔
1275

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

1286
                var channelID [8]byte
143✔
1287
                byteOrder.PutUint64(channelID[:], chanID)
143✔
1288

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

1300
                        return nil
90✔
1301
                }
1302

1303
                exists = true
56✔
1304
                isZombie = false
56✔
1305

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

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

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

1330
                return nil
56✔
1331
        }, func() {}); err != nil {
143✔
1332
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1333
        }
×
1334

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

143✔
1341
        return upd1Time, upd2Time, exists, isZombie, nil
143✔
1342
}
1343

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

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

5✔
1352
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
10✔
1353
                edges := tx.ReadWriteBucket(edgeBucket)
5✔
1354
                if edges == nil {
5✔
1355
                        return ErrEdgeNotFound
×
1356
                }
×
1357

1358
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1359
                if edgeIndex == nil {
5✔
1360
                        return ErrEdgeNotFound
×
1361
                }
×
1362

1363
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
5✔
1364
                if err != nil {
5✔
1365
                        return err
×
1366
                }
×
1367

1368
                edge.AuthProof = proof
5✔
1369

5✔
1370
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
5✔
1371
        }, func() {})
5✔
1372
}
1373

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

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

230✔
1395
        c.cacheMu.Lock()
230✔
1396
        defer c.cacheMu.Unlock()
230✔
1397

230✔
1398
        var (
230✔
1399
                chansClosed []*models.ChannelEdgeInfo
230✔
1400
                prunedNodes []route.Vertex
230✔
1401
        )
230✔
1402

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

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

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

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

1445
                        // First attempt to see if the channel exists within
1446
                        // the database, if not, then we can exit early.
1447
                        chanID := chanIndex.Get(opBytes.Bytes())
116✔
1448
                        if chanID == nil {
212✔
1449
                                continue
96✔
1450
                        }
1451

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

1464
                        chansClosed = append(chansClosed, edgeInfo)
20✔
1465
                }
1466

1467
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
230✔
1468
                if err != nil {
230✔
1469
                        return err
×
1470
                }
×
1471

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

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

230✔
1485
                var newTip [pruneTipBytes]byte
230✔
1486
                copy(newTip[:], blockHash[:])
230✔
1487

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

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

230✔
1498
                return err
230✔
1499
        }, func() {
230✔
1500
                chansClosed = nil
230✔
1501
                prunedNodes = nil
230✔
1502
        })
230✔
1503
        if err != nil {
230✔
1504
                return nil, nil, err
×
1505
        }
×
1506

1507
        for _, channel := range chansClosed {
250✔
1508
                c.rejectCache.remove(channel.ChannelID)
20✔
1509
                c.chanCache.remove(channel.ChannelID)
20✔
1510
        }
20✔
1511

1512
        return chansClosed, prunedNodes, nil
230✔
1513
}
1514

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

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

1541
                return nil
26✔
1542
        }, func() {
26✔
1543
                prunedNodes = nil
26✔
1544
        })
26✔
1545

1546
        return prunedNodes, err
26✔
1547
}
1548

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

253✔
1555
        log.Trace("Pruning nodes from graph with no open channels")
253✔
1556

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

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

1576
                var nodePub [33]byte
492✔
1577
                copy(nodePub[:], pubKey)
492✔
1578
                nodeRefCounts[nodePub] = 0
492✔
1579

492✔
1580
                return nil
492✔
1581
        })
1582
        if err != nil {
253✔
1583
                return nil, err
×
1584
        }
×
1585

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

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

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

197✔
1606
                return nil
197✔
1607
        })
197✔
1608
        if err != nil {
253✔
1609
                return nil, err
×
1610
        }
×
1611

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

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

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

1635
                        return nil, err
×
1636
                }
1637

1638
                log.Infof("Pruned unconnected node %x from channel graph",
68✔
1639
                        nodePubKey[:])
68✔
1640

68✔
1641
                pruned = append(pruned, nodePubKey)
68✔
1642
        }
1643

1644
        if len(pruned) > 0 {
305✔
1645
                log.Infof("Pruned %v unconnected nodes from the channel graph",
52✔
1646
                        len(pruned))
52✔
1647
        }
52✔
1648

1649
        return pruned, err
253✔
1650
}
1651

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

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

158✔
1668
        // Delete everything after this height from the db up until the
158✔
1669
        // SCID alias range.
158✔
1670
        endShortChanID := aliasmgr.StartingAlias
158✔
1671

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

158✔
1678
        c.cacheMu.Lock()
158✔
1679
        defer c.cacheMu.Unlock()
158✔
1680

158✔
1681
        // Keep track of the channels that are removed from the graph.
158✔
1682
        var removedChans []*models.ChannelEdgeInfo
158✔
1683

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

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

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

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

1728
                        removedChans = append(removedChans, edgeInfo)
97✔
1729
                }
1730

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

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

1745
                var pruneKeyStart [4]byte
158✔
1746
                byteOrder.PutUint32(pruneKeyStart[:], height)
158✔
1747

158✔
1748
                var pruneKeyEnd [4]byte
158✔
1749
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
158✔
1750

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

1761
                for _, k := range pruneKeys {
252✔
1762
                        if err := pruneBucket.Delete(k); err != nil {
94✔
1763
                                return err
×
1764
                        }
×
1765
                }
1766

1767
                return nil
158✔
1768
        }, func() {
158✔
1769
                removedChans = nil
158✔
1770
        }); err != nil {
158✔
1771
                return nil, err
×
1772
        }
×
1773

1774
        for _, channel := range removedChans {
255✔
1775
                c.rejectCache.remove(channel.ChannelID)
97✔
1776
                c.chanCache.remove(channel.ChannelID)
97✔
1777
        }
97✔
1778

1779
        return removedChans, nil
158✔
1780
}
1781

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

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

1802
                pruneCursor := pruneBucket.ReadCursor()
56✔
1803

56✔
1804
                // The prune key with the largest block height will be our
56✔
1805
                // prune tip.
56✔
1806
                k, v := pruneCursor.Last()
56✔
1807
                if k == nil {
77✔
1808
                        return ErrGraphNeverPruned
21✔
1809
                }
21✔
1810

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

38✔
1816
                return nil
38✔
1817
        }, func() {})
56✔
1818
        if err != nil {
77✔
1819
                return nil, 0, err
21✔
1820
        }
21✔
1821

1822
        return &tipHash, tipHeight, nil
38✔
1823
}
1824

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

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

152✔
1840
        c.cacheMu.Lock()
152✔
1841
        defer c.cacheMu.Unlock()
152✔
1842

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

1866
                var rawChanID [8]byte
152✔
1867
                for _, chanID := range chanIDs {
245✔
1868
                        byteOrder.PutUint64(rawChanID[:], chanID)
93✔
1869
                        edgeInfo, err := c.delChannelEdgeUnsafe(
93✔
1870
                                edges, edgeIndex, chanIndex, zombieIndex,
93✔
1871
                                rawChanID[:], markZombie, strictZombiePruning,
93✔
1872
                        )
93✔
1873
                        if err != nil {
158✔
1874
                                return err
65✔
1875
                        }
65✔
1876

1877
                        infos = append(infos, edgeInfo)
28✔
1878
                }
1879

1880
                return nil
87✔
1881
        }, func() {
152✔
1882
                infos = nil
152✔
1883
        })
152✔
1884
        if err != nil {
217✔
1885
                return nil, err
65✔
1886
        }
65✔
1887

1888
        for _, chanID := range chanIDs {
115✔
1889
                c.rejectCache.remove(chanID)
28✔
1890
                c.chanCache.remove(chanID)
28✔
1891
        }
28✔
1892

1893
        return infos, nil
87✔
1894
}
1895

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

1911
        return chanID, nil
4✔
1912
}
1913

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

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

1930
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1931
        if chanIDBytes == nil {
7✔
1932
                return 0, ErrEdgeNotFound
3✔
1933
        }
3✔
1934

1935
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1936

4✔
1937
        return chanID, nil
4✔
1938
}
1939

1940
// TODO(roasbeef): allow updates to use Batch?
1941

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

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

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

6✔
1962
                lastChanID, _ := cidCursor.Last()
6✔
1963

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

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

5✔
1974
                return nil
5✔
1975
        }, func() {
6✔
1976
                cid = 0
6✔
1977
        })
6✔
1978
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
6✔
1979
                return 0, err
×
1980
        }
×
1981

1982
        return cid, nil
6✔
1983
}
1984

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

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

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

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

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

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

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

143✔
2021
        c.cacheMu.Lock()
143✔
2022
        defer c.cacheMu.Unlock()
143✔
2023

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

2039
                nodes := tx.ReadBucket(nodeBucket)
143✔
2040
                if nodes == nil {
143✔
2041
                        return ErrGraphNodesNotFound
×
2042
                }
×
2043

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

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

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

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

2075
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
42✔
2076
                                hits++
12✔
2077
                                edgesSeen[chanIDInt] = struct{}{}
12✔
2078
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
2079

12✔
2080
                                continue
12✔
2081
                        }
2082

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

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

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

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

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

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

2143
        case err != nil:
×
2144
                return nil, err
×
2145
        }
2146

2147
        // Insert any edges loaded from disk into the cache.
2148
        for chanid, channel := range edgesToCache {
164✔
2149
                c.chanCache.insert(chanid, channel)
21✔
2150
        }
21✔
2151

2152
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
143✔
2153
                float64(hits)/float64(len(edgesInHorizon)), hits,
143✔
2154
                len(edgesInHorizon))
143✔
2155

143✔
2156
        return edgesInHorizon, nil
143✔
2157
}
2158

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

11✔
2166
        var nodesInHorizon []models.LightningNode
11✔
2167

11✔
2168
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2169
                nodes := tx.ReadBucket(nodeBucket)
11✔
2170
                if nodes == nil {
11✔
2171
                        return ErrGraphNodesNotFound
×
2172
                }
×
2173

2174
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2175
                if nodeUpdateIndex == nil {
11✔
2176
                        return ErrGraphNodesNotFound
×
2177
                }
×
2178

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

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

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

2204
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2205
                }
2206

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

2217
        case err != nil:
×
2218
                return nil, err
×
2219
        }
2220

2221
        return nodesInHorizon, nil
11✔
2222
}
2223

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

126✔
2233
        var (
126✔
2234
                newChanIDs   []uint64
126✔
2235
                knownZombies []ChannelUpdateInfo
126✔
2236
        )
126✔
2237

126✔
2238
        c.cacheMu.Lock()
126✔
2239
        defer c.cacheMu.Unlock()
126✔
2240

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

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

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

96✔
2263
                        // If the edge is already known, skip it.
96✔
2264
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
118✔
2265
                                continue
22✔
2266
                        }
2267

2268
                        // If the edge is a known zombie, skip it.
2269
                        if zombieIndex != nil {
154✔
2270
                                isZombie, _, _ := isZombieEdge(
77✔
2271
                                        zombieIndex, scid,
77✔
2272
                                )
77✔
2273

77✔
2274
                                if isZombie {
118✔
2275
                                        knownZombies = append(
41✔
2276
                                                knownZombies, info,
41✔
2277
                                        )
41✔
2278

41✔
2279
                                        continue
41✔
2280
                                }
2281
                        }
2282

2283
                        newChanIDs = append(newChanIDs, scid)
36✔
2284
                }
2285

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

2300
                return ogChanIDs, nil, nil
×
2301

2302
        case err != nil:
×
2303
                return nil, nil, err
×
2304
        }
2305

2306
        return newChanIDs, knownZombies, nil
126✔
2307
}
2308

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

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

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

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

199✔
2332
        chanInfo := ChannelUpdateInfo{
199✔
2333
                ShortChannelID:       scid,
199✔
2334
                Node1UpdateTimestamp: node1Timestamp,
199✔
2335
                Node2UpdateTimestamp: node2Timestamp,
199✔
2336
        }
199✔
2337

199✔
2338
        if node1Timestamp.IsZero() {
388✔
2339
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
189✔
2340
        }
189✔
2341

2342
        if node2Timestamp.IsZero() {
388✔
2343
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
189✔
2344
        }
189✔
2345

2346
        return chanInfo
199✔
2347
}
2348

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

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

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

14✔
2372
        startChanID := &lnwire.ShortChannelID{
14✔
2373
                BlockHeight: startHeight,
14✔
2374
        }
14✔
2375

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

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

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

2400
                cursor := edgeIndex.ReadCursor()
14✔
2401

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

2415
                        if edgeInfo.AuthProof == nil {
50✔
2416
                                continue
3✔
2417
                        }
2418

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

47✔
2424
                        chanInfo := NewChannelUpdateInfo(
47✔
2425
                                cid, time.Time{}, time.Time{},
47✔
2426
                        )
47✔
2427

47✔
2428
                        if !withTimestamps {
69✔
2429
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2430
                                        channelsPerBlock[cid.BlockHeight],
22✔
2431
                                        chanInfo,
22✔
2432
                                )
22✔
2433

22✔
2434
                                continue
22✔
2435
                        }
2436

2437
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2438

25✔
2439
                        rawPolicy := edges.Get(node1Key)
25✔
2440
                        if len(rawPolicy) != 0 {
34✔
2441
                                r := bytes.NewReader(rawPolicy)
9✔
2442

9✔
2443
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2444
                                if err != nil && !errors.Is(
9✔
2445
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2446
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
9✔
2447

×
2448
                                        return err
×
2449
                                }
×
2450

2451
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2452
                        }
2453

2454
                        rawPolicy = edges.Get(node2Key)
25✔
2455
                        if len(rawPolicy) != 0 {
39✔
2456
                                r := bytes.NewReader(rawPolicy)
14✔
2457

14✔
2458
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2459
                                if err != nil && !errors.Is(
14✔
2460
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2461
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
14✔
2462

×
2463
                                        return err
×
2464
                                }
×
2465

2466
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2467
                        }
2468

2469
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2470
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2471
                        )
25✔
2472
                }
2473

2474
                return nil
14✔
2475
        }, func() {
14✔
2476
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2477
        })
14✔
2478

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

2485
        case err != nil:
×
2486
                return nil, err
×
2487
        }
2488

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

2498
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2499
        for _, block := range blocks {
36✔
2500
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2501
                        Height:   block,
25✔
2502
                        Channels: channelsPerBlock[block],
25✔
2503
                })
25✔
2504
        }
25✔
2505

2506
        return channelRanges, nil
11✔
2507
}
2508

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

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

7✔
2530
        var (
7✔
2531
                chanEdges []ChannelEdge
7✔
2532
                cidBytes  [8]byte
7✔
2533
        )
7✔
2534

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

2549
                for _, cid := range chanIDs {
21✔
2550
                        byteOrder.PutUint64(cidBytes[:], cid)
14✔
2551

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

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

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

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

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

2597
                return nil
7✔
2598
        }
2599

2600
        if tx == nil {
14✔
2601
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2602
                        chanEdges = nil
7✔
2603
                })
7✔
2604
                if err != nil {
7✔
2605
                        return nil, err
×
2606
                }
×
2607

2608
                return chanEdges, nil
7✔
2609
        }
2610

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

2616
        return chanEdges, nil
×
2617
}
2618

2619
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2620
        edge1, edge2 *models.ChannelEdgePolicy) error {
140✔
2621

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

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

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

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

2658
        return nil
140✔
2659
}
2660

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

205✔
2672
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
205✔
2673
        if err != nil {
270✔
2674
                return nil, err
65✔
2675
        }
65✔
2676

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

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

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

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

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

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

2743
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
25✔
2744
        if strictZombie {
28✔
2745
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2746
        }
3✔
2747

2748
        return &edgeInfo, markEdgeZombie(
25✔
2749
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
25✔
2750
        )
25✔
2751
}
2752

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

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

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

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

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

2,668✔
2804
        var (
2,668✔
2805
                isUpdate1    bool
2,668✔
2806
                edgeNotFound bool
2,668✔
2807
                from, to     route.Vertex
2,668✔
2808
        )
2,668✔
2809

2,668✔
2810
        r := &batch.Request[kvdb.RwTx]{
2,668✔
2811
                Opts: batch.NewSchedulerOptions(opts...),
2,668✔
2812
                Reset: func() {
5,337✔
2813
                        isUpdate1 = false
2,669✔
2814
                        edgeNotFound = false
2,669✔
2815
                },
2,669✔
2816
                Do: func(tx kvdb.RwTx) error {
2,669✔
2817
                        var err error
2,669✔
2818
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
2,669✔
2819
                        if err != nil {
2,674✔
2820
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
5✔
2821
                        }
5✔
2822

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

2830
                        return err
2,666✔
2831
                },
2832
                OnCommit: func(err error) error {
2,668✔
2833
                        switch {
2,668✔
2834
                        case err != nil:
1✔
2835
                                return err
1✔
2836
                        case edgeNotFound:
3✔
2837
                                return ErrEdgeNotFound
3✔
2838
                        default:
2,664✔
2839
                                c.updateEdgeCache(edge, isUpdate1)
2,664✔
2840
                                return nil
2,664✔
2841
                        }
2842
                },
2843
        }
2844

2845
        err := c.chanScheduler.Execute(ctx, r)
2,668✔
2846

2,668✔
2847
        return from, to, err
2,668✔
2848
}
2849

2850
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2851
        isUpdate1 bool) {
2,664✔
2852

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

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

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

2,669✔
2887
        var noVertex route.Vertex
2,669✔
2888

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

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

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

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

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

2931
        var (
2,664✔
2932
                fromNodePubKey route.Vertex
2,664✔
2933
                toNodePubKey   route.Vertex
2,664✔
2934
        )
2,664✔
2935
        copy(fromNodePubKey[:], fromNode)
2,664✔
2936
        copy(toNodePubKey[:], toNode)
2,664✔
2937

2,664✔
2938
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
2,664✔
2939
}
2940

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

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

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

6✔
2964
                        nodeIsPublic = true
6✔
2965
                        return errDone
6✔
2966
                }
6✔
2967

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

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

2982
        return nodeIsPublic, nil
16✔
2983
}
2984

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

3,654✔
2992
        return c.fetchLightningNode(tx, nodePub)
3,654✔
2993
}
3,654✔
2994

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

162✔
3001
        return c.fetchLightningNode(nil, nodePub)
162✔
3002
}
162✔
3003

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

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

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

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

3035
                node = &n
3,798✔
3036

3,798✔
3037
                return nil
3,798✔
3038
        }
3039

3040
        if tx == nil {
3,999✔
3041
                err := kvdb.View(
186✔
3042
                        c.db, fetch, func() {
372✔
3043
                                node = nil
186✔
3044
                        },
186✔
3045
                )
3046
                if err != nil {
193✔
3047
                        return nil, err
7✔
3048
                }
7✔
3049

3050
                return node, nil
182✔
3051
        }
3052

3053
        err := fetch(tx)
3,627✔
3054
        if err != nil {
3,638✔
3055
                return nil, err
11✔
3056
        }
11✔
3057

3058
        return node, nil
3,616✔
3059
}
3060

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

20✔
3069
        var (
20✔
3070
                updateTime time.Time
20✔
3071
                exists     bool
20✔
3072
        )
20✔
3073

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

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

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

3099
                exists = true
17✔
3100
                updateTime = node.LastUpdate
17✔
3101

17✔
3102
                return nil
17✔
3103
        }, func() {
20✔
3104
                updateTime = time.Time{}
20✔
3105
                exists = false
20✔
3106
        })
20✔
3107
        if err != nil {
20✔
3108
                return time.Time{}, exists, err
×
3109
        }
×
3110

3111
        return updateTime, exists, nil
20✔
3112
}
3113

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

1,270✔
3120
        traversal := func(tx kvdb.RTx) error {
2,540✔
3121
                edges := tx.ReadBucket(edgeBucket)
1,270✔
3122
                if edges == nil {
1,270✔
3123
                        return ErrGraphNotFound
×
3124
                }
×
3125
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,270✔
3126
                if edgeIndex == nil {
1,270✔
3127
                        return ErrGraphNoEdgesFound
×
3128
                }
×
3129

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

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

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

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

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

3176
                        // Finally, we execute the callback.
3177
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,845✔
3178
                        if err != nil {
3,857✔
3179
                                return err
12✔
3180
                        }
12✔
3181
                }
3182

3183
                return nil
1,261✔
3184
        }
3185

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

3192
        // Otherwise, we re-use the existing transaction to execute the graph
3193
        // traversal.
3194
        return traversal(tx)
1,241✔
3195
}
3196

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

9✔
3209
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
9✔
3210
                info *models.ChannelEdgeInfo, policy,
9✔
3211
                policy2 *models.ChannelEdgePolicy) error {
22✔
3212

13✔
3213
                return cb(info, policy, policy2)
13✔
3214
        })
13✔
3215
}
3216

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

4✔
3224
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3225
                nodes := tx.ReadBucket(nodeBucket)
4✔
3226
                if nodes == nil {
4✔
3227
                        return ErrGraphNotFound
×
3228
                }
×
3229

3230
                node, err := c.sourceNode(nodes)
4✔
3231
                if err != nil {
4✔
3232
                        return err
×
3233
                }
×
3234

3235
                return nodeTraversal(
4✔
3236
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
4✔
3237
                                info *models.ChannelEdgeInfo,
4✔
3238
                                policy, _ *models.ChannelEdgePolicy) error {
9✔
3239

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

3247
                                return cb(
5✔
3248
                                        info.ChannelPoint, policy != nil, peer,
5✔
3249
                                )
5✔
3250
                        },
3251
                )
3252
        }, func() {})
4✔
3253
}
3254

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

1,001✔
3273
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3274
}
1,001✔
3275

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

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

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

3304
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
5✔
3305
                if err != nil {
5✔
3306
                        return err
×
3307
                }
×
3308

3309
                targetNode = &node
5✔
3310

5✔
3311
                return nil
5✔
3312
        }
3313

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

3325
        return targetNode, err
5✔
3326
}
3327

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

25✔
3337
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3338
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3339

25✔
3340
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3341
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3342

25✔
3343
        return node1Key[:], node2Key[:]
25✔
3344
}
25✔
3345

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

14✔
3355
        var (
14✔
3356
                edgeInfo *models.ChannelEdgeInfo
14✔
3357
                policy1  *models.ChannelEdgePolicy
14✔
3358
                policy2  *models.ChannelEdgePolicy
14✔
3359
        )
14✔
3360

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

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

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

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

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

3412
                policy1 = e1
4✔
3413
                policy2 = e2
4✔
3414

4✔
3415
                return nil
4✔
3416
        }, func() {
14✔
3417
                edgeInfo = nil
14✔
3418
                policy1 = nil
14✔
3419
                policy2 = nil
14✔
3420
        })
14✔
3421
        if err != nil {
27✔
3422
                return nil, nil, nil, err
13✔
3423
        }
13✔
3424

3425
        return edgeInfo, policy1, policy2, nil
4✔
3426
}
3427

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

2,686✔
3441
        var (
2,686✔
3442
                edgeInfo  *models.ChannelEdgeInfo
2,686✔
3443
                policy1   *models.ChannelEdgePolicy
2,686✔
3444
                policy2   *models.ChannelEdgePolicy
2,686✔
3445
                channelID [8]byte
2,686✔
3446
        )
2,686✔
3447

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

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

3468
                byteOrder.PutUint64(channelID[:], chanID)
2,686✔
3469

2,686✔
3470
                // Now, attempt to fetch edge.
2,686✔
3471
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
2,686✔
3472

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

3484
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3485
                                zombieIndex, chanID,
4✔
3486
                        )
4✔
3487
                        if !isZombie {
7✔
3488
                                return ErrEdgeNotFound
3✔
3489
                        }
3✔
3490

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

4✔
3500
                        return ErrZombieEdge
4✔
3501
                }
3502

3503
                // Otherwise, we'll just return the error if any.
3504
                if err != nil {
2,685✔
3505
                        return err
×
3506
                }
×
3507

3508
                edgeInfo = &edge
2,685✔
3509

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

3519
                policy1 = e1
2,685✔
3520
                policy2 = e2
2,685✔
3521

2,685✔
3522
                return nil
2,685✔
3523
        }, func() {
2,686✔
3524
                edgeInfo = nil
2,686✔
3525
                policy1 = nil
2,686✔
3526
                policy2 = nil
2,686✔
3527
        })
2,686✔
3528
        if errors.Is(err, ErrZombieEdge) {
2,690✔
3529
                return edgeInfo, nil, nil, err
4✔
3530
        }
4✔
3531
        if err != nil {
2,688✔
3532
                return nil, nil, nil, err
3✔
3533
        }
3✔
3534

3535
        return edgeInfo, policy1, policy2, nil
2,685✔
3536
}
3537

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

3557
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3558

16✔
3559
                return err
16✔
3560
        }, func() {
16✔
3561
                nodeIsPublic = false
16✔
3562
        })
16✔
3563
        if err != nil {
16✔
3564
                return false, err
×
3565
        }
×
3566

3567
        return nodeIsPublic, nil
16✔
3568
}
3569

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

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

49✔
3587
        return bldr.Script()
49✔
3588
}
3589

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

3598
        // OutPoint is the outpoint of the target channel.
3599
        OutPoint wire.OutPoint
3600
}
3601

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

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

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

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

3646
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3647
                                        edgeIndex, chanID,
45✔
3648
                                )
45✔
3649
                                if err != nil {
45✔
3650
                                        return err
×
3651
                                }
×
3652

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

3661
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3662
                                        FundingPkScript: pkScript,
45✔
3663
                                        OutPoint:        chanPoint,
45✔
3664
                                })
45✔
3665

45✔
3666
                                return nil
45✔
3667
                        },
3668
                )
3669
        }, func() {
25✔
3670
                edgePoints = nil
25✔
3671
        }); err != nil {
25✔
3672
                return nil, err
×
3673
        }
×
3674

3675
        return edgePoints, nil
25✔
3676
}
3677

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

134✔
3684
        c.cacheMu.Lock()
134✔
3685
        defer c.cacheMu.Unlock()
134✔
3686

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

3698
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
134✔
3699
        })
3700
        if err != nil {
134✔
3701
                return err
×
3702
        }
×
3703

3704
        c.rejectCache.remove(chanID)
134✔
3705
        c.chanCache.remove(chanID)
134✔
3706

134✔
3707
        return nil
134✔
3708
}
3709

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

159✔
3716
        var k [8]byte
159✔
3717
        byteOrder.PutUint64(k[:], chanID)
159✔
3718

159✔
3719
        var v [66]byte
159✔
3720
        copy(v[:33], pubKey1[:])
159✔
3721
        copy(v[33:], pubKey2[:])
159✔
3722

159✔
3723
        return zombieIndex.Put(k[:], v[:])
159✔
3724
}
159✔
3725

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

20✔
3731
        return c.markEdgeLiveUnsafe(nil, chanID)
20✔
3732
}
20✔
3733

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

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

20✔
3754
                if len(zombieIndex.Get(k[:])) == 0 {
21✔
3755
                        return ErrZombieEdgeNotFound
1✔
3756
                }
1✔
3757

3758
                return zombieIndex.Delete(k[:])
19✔
3759
        }
3760

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

3773
        c.rejectCache.remove(chanID)
19✔
3774
        c.chanCache.remove(chanID)
19✔
3775

19✔
3776
        return nil
19✔
3777
}
3778

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

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

3798
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
14✔
3799

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

3810
        return isZombie, pubKey1, pubKey2
14✔
3811
}
3812

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

179✔
3819
        var k [8]byte
179✔
3820
        byteOrder.PutUint64(k[:], chanID)
179✔
3821

179✔
3822
        v := zombieIndex.Get(k[:])
179✔
3823
        if v == nil {
273✔
3824
                return false, [33]byte{}, [33]byte{}
94✔
3825
        }
94✔
3826

3827
        var pubKey1, pubKey2 [33]byte
88✔
3828
        copy(pubKey1[:], v[:33])
88✔
3829
        copy(pubKey2[:], v[33:])
88✔
3830

88✔
3831
        return true, pubKey1, pubKey2
88✔
3832
}
3833

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

3847
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3848
                        numZombies++
2✔
3849
                        return nil
2✔
3850
                })
2✔
3851
        }, func() {
4✔
3852
                numZombies = 0
4✔
3853
        })
4✔
3854
        if err != nil {
4✔
3855
                return 0, err
×
3856
        }
×
3857

3858
        return numZombies, nil
4✔
3859
}
3860

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

3871
                var k [8]byte
1✔
3872
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3873

1✔
3874
                return closedScids.Put(k[:], []byte{})
1✔
3875
        }, func() {})
1✔
3876
}
3877

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

3889
                var k [8]byte
5✔
3890
                byteOrder.PutUint64(k[:], scid.ToUint64())
5✔
3891

5✔
3892
                if closedScids.Get(k[:]) != nil {
6✔
3893
                        isClosed = true
1✔
3894
                        return nil
1✔
3895
                }
1✔
3896

3897
                return nil
4✔
3898
        }, func() {
5✔
3899
                isClosed = false
5✔
3900
        })
5✔
3901
        if err != nil {
5✔
3902
                return false, err
×
3903
        }
×
3904

3905
        return isClosed, nil
5✔
3906
}
3907

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

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

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

239✔
3933
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
239✔
3934
}
239✔
3935

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

254✔
3943
        return c.db.fetchNodeFeatures(c.tx, nodePub)
254✔
3944
}
254✔
3945

3946
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3947
        node *models.LightningNode) error {
1,003✔
3948

1,003✔
3949
        var (
1,003✔
3950
                scratch [16]byte
1,003✔
3951
                b       bytes.Buffer
1,003✔
3952
        )
1,003✔
3953

1,003✔
3954
        pub, err := node.PubKey()
1,003✔
3955
        if err != nil {
1,003✔
3956
                return err
×
3957
        }
×
3958
        nodePub := pub.SerializeCompressed()
1,003✔
3959

1,003✔
3960
        // If the node has the update time set, write it, else write 0.
1,003✔
3961
        updateUnix := uint64(0)
1,003✔
3962
        if node.LastUpdate.Unix() > 0 {
1,869✔
3963
                updateUnix = uint64(node.LastUpdate.Unix())
866✔
3964
        }
866✔
3965

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

3971
        if _, err := b.Write(nodePub); err != nil {
1,003✔
3972
                return err
×
3973
        }
×
3974

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

3984
                return nodeBucket.Put(nodePub, b.Bytes())
87✔
3985
        }
3986

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

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

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

4007
        if err := node.Features.Encode(&b); err != nil {
919✔
4008
                return err
×
4009
        }
×
4010

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

4017
        for _, address := range node.Addresses {
2,075✔
4018
                if err := SerializeAddr(&b, address); err != nil {
1,156✔
4019
                        return err
×
4020
                }
×
4021
        }
4022

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

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

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

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

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

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

110✔
4059
                var oldIndexKey [8 + 33]byte
110✔
4060
                copy(oldIndexKey[:8], oldUpdateTime)
110✔
4061
                copy(oldIndexKey[8:], nodePub)
110✔
4062

110✔
4063
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
110✔
4064
                        return err
×
4065
                }
×
4066
        }
4067

4068
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
919✔
4069
                return err
×
4070
        }
×
4071

4072
        return nodeBucket.Put(nodePub, b.Bytes())
919✔
4073
}
4074

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

3,625✔
4078
        nodeBytes := nodeBucket.Get(nodePub)
3,625✔
4079
        if nodeBytes == nil {
3,712✔
4080
                return models.LightningNode{}, ErrGraphNodeNotFound
87✔
4081
        }
87✔
4082

4083
        nodeReader := bytes.NewReader(nodeBytes)
3,541✔
4084

3,541✔
4085
        return deserializeLightningNode(nodeReader)
3,541✔
4086
}
4087

4088
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4089
        *lnwire.FeatureVector, error) {
123✔
4090

123✔
4091
        var (
123✔
4092
                pubKey      route.Vertex
123✔
4093
                features    = lnwire.EmptyFeatureVector()
123✔
4094
                nodeScratch [8]byte
123✔
4095
        )
123✔
4096

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

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

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

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

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

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

4136
        if err := features.Decode(r); err != nil {
123✔
4137
                return pubKey, nil, err
×
4138
        }
×
4139

4140
        return pubKey, features, nil
123✔
4141
}
4142

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

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

8,528✔
4154
        if _, err := r.Read(scratch[:]); err != nil {
8,528✔
4155
                return models.LightningNode{}, err
×
4156
        }
×
4157

4158
        unix := int64(byteOrder.Uint64(scratch[:]))
8,528✔
4159
        node.LastUpdate = time.Unix(unix, 0)
8,528✔
4160

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

4165
        if _, err := r.Read(scratch[:2]); err != nil {
8,528✔
4166
                return models.LightningNode{}, err
×
4167
        }
×
4168

4169
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,528✔
4170
        if hasNodeAnn == 1 {
16,911✔
4171
                node.HaveNodeAnnouncement = true
8,383✔
4172
        } else {
8,531✔
4173
                node.HaveNodeAnnouncement = false
148✔
4174
        }
148✔
4175

4176
        // The rest of the data is optional, and will only be there if we got a
4177
        // node announcement for this node.
4178
        if !node.HaveNodeAnnouncement {
8,676✔
4179
                return node, nil
148✔
4180
        }
148✔
4181

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

4194
        node.Alias, err = wire.ReadVarString(r, 0)
8,383✔
4195
        if err != nil {
8,383✔
4196
                return models.LightningNode{}, err
×
4197
        }
×
4198

4199
        err = node.Features.Decode(r)
8,383✔
4200
        if err != nil {
8,383✔
4201
                return models.LightningNode{}, err
×
4202
        }
×
4203

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

8,383✔
4209
        var addresses []net.Addr
8,383✔
4210
        for i := 0; i < numAddresses; i++ {
19,019✔
4211
                address, err := DeserializeAddr(r)
10,636✔
4212
                if err != nil {
10,636✔
4213
                        return models.LightningNode{}, err
×
4214
                }
×
4215
                addresses = append(addresses, address)
10,636✔
4216
        }
4217
        node.Addresses = addresses
8,383✔
4218

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

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

4236
        if len(extraBytes) > 0 {
8,393✔
4237
                node.ExtraOpaqueData = extraBytes
10✔
4238
        }
10✔
4239

4240
        return node, nil
8,383✔
4241
}
4242

4243
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4244
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,490✔
4245

1,490✔
4246
        var b bytes.Buffer
1,490✔
4247

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

4261
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,490✔
4262
                return err
×
4263
        }
×
4264

4265
        authProof := edgeInfo.AuthProof
1,490✔
4266
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,490✔
4267
        if authProof != nil {
2,896✔
4268
                nodeSig1 = authProof.NodeSig1Bytes
1,406✔
4269
                nodeSig2 = authProof.NodeSig2Bytes
1,406✔
4270
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,406✔
4271
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,406✔
4272
        }
1,406✔
4273

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

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

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

4309
        return edgeIndex.Put(chanID[:], b.Bytes())
1,490✔
4310
}
4311

4312
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4313
        chanID []byte) (models.ChannelEdgeInfo, error) {
6,804✔
4314

6,804✔
4315
        edgeInfoBytes := edgeIndex.Get(chanID)
6,804✔
4316
        if edgeInfoBytes == nil {
6,876✔
4317
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
72✔
4318
        }
72✔
4319

4320
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
6,735✔
4321

6,735✔
4322
        return deserializeChanEdgeInfo(edgeInfoReader)
6,735✔
4323
}
4324

4325
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
7,274✔
4326
        var (
7,274✔
4327
                err      error
7,274✔
4328
                edgeInfo models.ChannelEdgeInfo
7,274✔
4329
        )
7,274✔
4330

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

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

4349
        proof := &models.ChannelAuthProof{}
7,274✔
4350

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

4368
        if !proof.IsEmpty() {
11,445✔
4369
                edgeInfo.AuthProof = proof
4,171✔
4370
        }
4,171✔
4371

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

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

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

4399
        return edgeInfo, nil
7,274✔
4400
}
4401

4402
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4403
        from, to []byte) error {
2,666✔
4404

2,666✔
4405
        var edgeKey [33 + 8]byte
2,666✔
4406
        copy(edgeKey[:], from)
2,666✔
4407
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,666✔
4408

2,666✔
4409
        var b bytes.Buffer
2,666✔
4410
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,668✔
4411
                return err
2✔
4412
        }
2✔
4413

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

2,664✔
4421
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,664✔
4422
        if err != nil {
2,664✔
4423
                return err
×
4424
        }
×
4425

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

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

×
4453
                        return err
×
4454
                }
×
4455

4456
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
26✔
4457

26✔
4458
                var oldIndexKey [8 + 8]byte
26✔
4459
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
26✔
4460
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
26✔
4461

26✔
4462
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
26✔
4463
                        return err
×
4464
                }
×
4465
        }
4466

4467
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,664✔
4468
                return err
×
4469
        }
×
4470

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

4480
        return edges.Put(edgeKey[:], b.Bytes())
2,664✔
4481
}
4482

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

2,938✔
4495
        var disabledEdgeKey [8 + 1]byte
2,938✔
4496
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,938✔
4497
        if direction {
4,406✔
4498
                disabledEdgeKey[8] = 1
1,468✔
4499
        }
1,468✔
4500

4501
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,938✔
4502
                disabledEdgePolicyBucket,
2,938✔
4503
        )
2,938✔
4504
        if err != nil {
2,938✔
4505
                return err
×
4506
        }
×
4507

4508
        if disabled {
2,967✔
4509
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4510
        }
29✔
4511

4512
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,912✔
4513
}
4514

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

2,973✔
4520
        var edgeKey [33 + 8]byte
2,973✔
4521
        copy(edgeKey[:], from)
2,973✔
4522
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,973✔
4523

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

4529
        return edges.Put(edgeKey[:], unknownPolicy)
2,973✔
4530
}
4531

4532
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4533
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
13,485✔
4534

13,485✔
4535
        var edgeKey [33 + 8]byte
13,485✔
4536
        copy(edgeKey[:], nodePub)
13,485✔
4537
        copy(edgeKey[33:], chanID)
13,485✔
4538

13,485✔
4539
        edgeBytes := edges.Get(edgeKey[:])
13,485✔
4540
        if edgeBytes == nil {
13,485✔
4541
                return nil, ErrEdgeNotFound
×
4542
        }
×
4543

4544
        // No need to deserialize unknown policy.
4545
        if bytes.Equal(edgeBytes, unknownPolicy) {
15,056✔
4546
                return nil, nil
1,571✔
4547
        }
1,571✔
4548

4549
        edgeReader := bytes.NewReader(edgeBytes)
11,917✔
4550

11,917✔
4551
        ep, err := deserializeChanEdgePolicy(edgeReader)
11,917✔
4552
        switch {
11,917✔
4553
        // If the db policy was missing an expected optional field, we return
4554
        // nil as if the policy was unknown.
4555
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
2✔
4556
                return nil, nil
2✔
4557

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

4563
        case err != nil:
×
4564
                return nil, err
×
4565
        }
4566

4567
        return ep, nil
11,915✔
4568
}
4569

4570
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4571
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4572
        error) {
2,902✔
4573

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

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

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

4599
        return edge1, edge2, nil
2,902✔
4600
}
4601

4602
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4603
        to []byte) error {
2,668✔
4604

2,668✔
4605
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,668✔
4606
        if err != nil {
2,668✔
4607
                return err
×
4608
        }
×
4609

4610
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,668✔
4611
                return err
×
4612
        }
×
4613

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

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

4644
        if _, err := w.Write(to); err != nil {
2,668✔
4645
                return err
×
4646
        }
×
4647

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

4660
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
4661
        err = edge.ExtraOpaqueData.ValidateTLV()
2,668✔
4662
        if err != nil {
2,670✔
4663
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
2✔
4664
        }
2✔
4665

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

4673
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,666✔
4674
                return err
×
4675
        }
×
4676

4677
        return nil
2,666✔
4678
}
4679

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

×
4690
                return nil, err
×
4691
        }
×
4692

4693
        return edge, err
11,941✔
4694
}
4695

4696
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4697
        error) {
12,948✔
4698

12,948✔
4699
        edge := &models.ChannelEdgePolicy{}
12,948✔
4700

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

4707
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
12,948✔
4708
                return nil, err
×
4709
        }
×
4710

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

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

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

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

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

12,948✔
4744
        if _, err := r.Read(edge.ToNode[:]); err != nil {
12,948✔
4745
                return nil, err
×
4746
        }
×
4747

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

4760
        // See if optional fields are present.
4761
        if edge.MessageFlags.HasMaxHtlc() {
24,943✔
4762
                // The max_htlc field should be at the beginning of the opaque
11,995✔
4763
                // bytes.
11,995✔
4764
                opq := edge.ExtraOpaqueData
11,995✔
4765

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

4773
                maxHtlc := byteOrder.Uint64(opq[:8])
11,991✔
4774
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
11,991✔
4775

11,991✔
4776
                // Exclude the parsed field from the rest of the opaque data.
11,991✔
4777
                edge.ExtraOpaqueData = opq[8:]
11,991✔
4778
        }
4779

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

4791
        val, ok := typeMap[lnwire.FeeRecordType]
12,944✔
4792
        if ok && val == nil {
14,658✔
4793
                edge.InboundFee = fn.Some(inboundFee)
1,714✔
4794
        }
1,714✔
4795

4796
        return edge, nil
12,944✔
4797
}
4798

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

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

4811
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4812
        node *models.LightningNode) *chanGraphNodeTx {
4,105✔
4813

4,105✔
4814
        return &chanGraphNodeTx{
4,105✔
4815
                tx:   tx,
4,105✔
4816
                db:   db,
4,105✔
4817
                node: node,
4,105✔
4818
        }
4,105✔
4819
}
4,105✔
4820

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

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

4839
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4840
}
4841

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

965✔
4849
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4850
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4851
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4852

2,944✔
4853
                        return f(info, policy1, policy2)
2,944✔
4854
                },
2,944✔
4855
        )
4856
}
4857

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

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

4874
        graphStore, err := NewKVStore(backend)
153✔
4875
        require.NoError(t, err)
153✔
4876

153✔
4877
        graph, err := NewChannelGraph(graphStore, opts...)
153✔
4878
        require.NoError(t, err)
153✔
4879
        require.NoError(t, graph.Start())
153✔
4880
        t.Cleanup(func() {
306✔
4881
                require.NoError(t, graph.Stop())
153✔
4882
        })
153✔
4883

4884
        return graph
153✔
4885
}
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