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

lightningnetwork / lnd / 17027244024

17 Aug 2025 11:32PM UTC coverage: 57.287% (-9.5%) from 66.765%
17027244024

Pull #10167

github

web-flow
Merge fcb4f4303 into fb1adfc21
Pull Request #10167: multi: bump Go to 1.24.6

3 of 18 new or added lines in 6 files covered. (16.67%)

28537 existing lines in 457 files now uncovered.

99094 of 172978 relevant lines covered (57.29%)

1.78 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

302
                channelMap[key] = edge
3✔
303

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

310
        return channelMap, nil
3✔
311
}
312

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

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

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

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

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

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

369
        return nil
3✔
370
}
371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
470
                                return cb(&info, policy1, policy2)
3✔
471
                        },
472
                )
473
        }, reset)
474
}
475

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

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

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

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

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

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

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

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

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

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

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

557
                                return cb(
3✔
558
                                        models.NewCachedEdge(&info),
3✔
559
                                        cachedPolicy1, cachedPolicy2,
3✔
560
                                )
3✔
561
                        },
562
                )
563
        }, reset)
564
}
565

566
// forEachNodeDirectedChannel iterates through all channels of a given node,
567
// executing the passed callback on the directed edge representing the channel
568
// and its incoming policy. If the callback returns an error, then the iteration
569
// is halted with the error propagated back up to the caller. An optional read
570
// transaction may be provided. If none is provided, a new one will be created.
571
//
572
// Unknown policies are passed into the callback as nil values.
573
//
574
// NOTE: the reset param is only meaningful if the tx param is nil. If it is
575
// not nil, the caller is expected to have passed in a reset to the parent
576
// function's View/Update call which will then apply to the whole transaction.
577
func (c *KVStore) forEachNodeDirectedChannel(tx kvdb.RTx,
578
        node route.Vertex, cb func(channel *DirectedChannel) error,
579
        reset func()) error {
3✔
580

3✔
581
        // Fallback that uses the database.
3✔
582
        toNodeCallback := func() route.Vertex {
6✔
583
                return node
3✔
584
        }
3✔
585
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
586
        if err != nil {
3✔
587
                return err
×
588
        }
×
589

590
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
3✔
591
                p2 *models.ChannelEdgePolicy) error {
6✔
592

3✔
593
                var cachedInPolicy *models.CachedEdgePolicy
3✔
594
                if p2 != nil {
6✔
595
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
596
                        cachedInPolicy.ToNodePubKey = toNodeCallback
3✔
597
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
3✔
598
                }
3✔
599

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

3✔
609
                if p1 != nil {
6✔
610
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
UNCOV
611
                                directedChannel.InboundFee = fee
×
UNCOV
612
                        })
×
613
                }
614

615
                if node == e.NodeKey2Bytes {
6✔
616
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
617
                }
3✔
618

619
                return cb(directedChannel)
3✔
620
        }
621

622
        return nodeTraversal(tx, node[:], c.db, dbCallback, reset)
3✔
623
}
624

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

3✔
631
        // Fallback that uses the database.
3✔
632
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
633
        switch {
3✔
634
        // If the node exists and has features, return them directly.
635
        case err == nil:
3✔
636
                return targetNode.Features, nil
3✔
637

638
        // If we couldn't find a node announcement, populate a blank feature
639
        // vector.
UNCOV
640
        case errors.Is(err, ErrGraphNodeNotFound):
×
UNCOV
641
                return lnwire.EmptyFeatureVector(), nil
×
642

643
        // Otherwise, bubble the error up.
644
        default:
×
645
                return nil, err
×
646
        }
647
}
648

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

3✔
660
        return c.forEachNodeDirectedChannel(nil, nodePub, cb, reset)
3✔
661
}
3✔
662

663
// FetchNodeFeatures returns the features of the given node. If no features are
664
// known for the node, an empty feature vector is returned.
665
//
666
// NOTE: this is part of the graphdb.NodeTraverser interface.
667
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
668
        *lnwire.FeatureVector, error) {
3✔
669

3✔
670
        return c.fetchNodeFeatures(nil, nodePub)
3✔
671
}
3✔
672

673
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
674
// data to the call-back.
675
//
676
// NOTE: The callback contents MUST not be modified.
677
func (c *KVStore) ForEachNodeCached(ctx context.Context, withAddrs bool,
678
        cb func(ctx context.Context, node route.Vertex, addrs []net.Addr,
UNCOV
679
                chans map[uint64]*DirectedChannel) error, reset func()) error {
×
UNCOV
680

×
UNCOV
681
        // Otherwise call back to a version that uses the database directly.
×
UNCOV
682
        // We'll iterate over each node, then the set of channels for each
×
UNCOV
683
        // node, and construct a similar callback functiopn signature as the
×
UNCOV
684
        // main funcotin expects.
×
UNCOV
685
        return forEachNode(c.db, func(tx kvdb.RTx,
×
UNCOV
686
                node *models.LightningNode) error {
×
UNCOV
687

×
UNCOV
688
                channels := make(map[uint64]*DirectedChannel)
×
UNCOV
689

×
UNCOV
690
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
×
UNCOV
691
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
UNCOV
692
                                p1 *models.ChannelEdgePolicy,
×
UNCOV
693
                                p2 *models.ChannelEdgePolicy) error {
×
UNCOV
694

×
UNCOV
695
                                toNodeCallback := func() route.Vertex {
×
696
                                        return node.PubKeyBytes
×
697
                                }
×
UNCOV
698
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
UNCOV
699
                                        tx, node.PubKeyBytes,
×
UNCOV
700
                                )
×
UNCOV
701
                                if err != nil {
×
702
                                        return err
×
703
                                }
×
704

UNCOV
705
                                var cachedInPolicy *models.CachedEdgePolicy
×
UNCOV
706
                                if p2 != nil {
×
UNCOV
707
                                        cachedInPolicy =
×
UNCOV
708
                                                models.NewCachedPolicy(p2)
×
UNCOV
709
                                        cachedInPolicy.ToNodePubKey =
×
UNCOV
710
                                                toNodeCallback
×
UNCOV
711
                                        cachedInPolicy.ToNodeFeatures =
×
UNCOV
712
                                                toNodeFeatures
×
UNCOV
713
                                }
×
714

UNCOV
715
                                directedChannel := &DirectedChannel{
×
UNCOV
716
                                        ChannelID: e.ChannelID,
×
UNCOV
717
                                        IsNode1: node.PubKeyBytes ==
×
UNCOV
718
                                                e.NodeKey1Bytes,
×
UNCOV
719
                                        OtherNode:    e.NodeKey2Bytes,
×
UNCOV
720
                                        Capacity:     e.Capacity,
×
UNCOV
721
                                        OutPolicySet: p1 != nil,
×
UNCOV
722
                                        InPolicy:     cachedInPolicy,
×
UNCOV
723
                                }
×
UNCOV
724

×
UNCOV
725
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
UNCOV
726
                                        directedChannel.OtherNode =
×
UNCOV
727
                                                e.NodeKey1Bytes
×
UNCOV
728
                                }
×
729

UNCOV
730
                                channels[e.ChannelID] = directedChannel
×
UNCOV
731

×
UNCOV
732
                                return nil
×
733
                        }, reset,
734
                )
UNCOV
735
                if err != nil {
×
736
                        return err
×
737
                }
×
738

UNCOV
739
                var addrs []net.Addr
×
UNCOV
740
                if withAddrs {
×
UNCOV
741
                        addrs = node.Addresses
×
UNCOV
742
                }
×
743

UNCOV
744
                return cb(ctx, node.PubKeyBytes, addrs, channels)
×
745
        }, reset)
746
}
747

748
// DisabledChannelIDs returns the channel ids of disabled channels.
749
// A channel is disabled when two of the associated ChanelEdgePolicies
750
// have their disabled bit on.
UNCOV
751
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
×
UNCOV
752
        var disabledChanIDs []uint64
×
UNCOV
753
        var chanEdgeFound map[uint64]struct{}
×
UNCOV
754

×
UNCOV
755
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
756
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
757
                if edges == nil {
×
758
                        return ErrGraphNoEdgesFound
×
759
                }
×
760

UNCOV
761
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
UNCOV
762
                        disabledEdgePolicyBucket,
×
UNCOV
763
                )
×
UNCOV
764
                if disabledEdgePolicyIndex == nil {
×
UNCOV
765
                        return nil
×
UNCOV
766
                }
×
767

768
                // We iterate over all disabled policies and we add each channel
769
                // that has more than one disabled policy to disabledChanIDs
770
                // array.
UNCOV
771
                return disabledEdgePolicyIndex.ForEach(
×
UNCOV
772
                        func(k, v []byte) error {
×
UNCOV
773
                                chanID := byteOrder.Uint64(k[:8])
×
UNCOV
774
                                _, edgeFound := chanEdgeFound[chanID]
×
UNCOV
775
                                if edgeFound {
×
UNCOV
776
                                        delete(chanEdgeFound, chanID)
×
UNCOV
777
                                        disabledChanIDs = append(
×
UNCOV
778
                                                disabledChanIDs, chanID,
×
UNCOV
779
                                        )
×
UNCOV
780

×
UNCOV
781
                                        return nil
×
UNCOV
782
                                }
×
783

UNCOV
784
                                chanEdgeFound[chanID] = struct{}{}
×
UNCOV
785

×
UNCOV
786
                                return nil
×
787
                        },
788
                )
UNCOV
789
        }, func() {
×
UNCOV
790
                disabledChanIDs = nil
×
UNCOV
791
                chanEdgeFound = make(map[uint64]struct{})
×
UNCOV
792
        })
×
UNCOV
793
        if err != nil {
×
794
                return nil, err
×
795
        }
×
796

UNCOV
797
        return disabledChanIDs, nil
×
798
}
799

800
// ForEachNode iterates through all the stored vertices/nodes in the graph,
801
// executing the passed callback with each node encountered. If the callback
802
// returns an error, then the transaction is aborted and the iteration stops
803
// early.
804
//
805
// NOTE: this is part of the V1Store interface.
806
func (c *KVStore) ForEachNode(_ context.Context,
807
        cb func(*models.LightningNode) error, reset func()) error {
3✔
808

3✔
809
        return forEachNode(c.db, func(tx kvdb.RTx,
3✔
810
                node *models.LightningNode) error {
6✔
811

3✔
812
                return cb(node)
3✔
813
        }, reset)
3✔
814
}
815

816
// forEachNode iterates through all the stored vertices/nodes in the graph,
817
// executing the passed callback with each node encountered. If the callback
818
// returns an error, then the transaction is aborted and the iteration stops
819
// early.
820
//
821
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
822
// traversal when graph gets mega.
823
func forEachNode(db kvdb.Backend,
824
        cb func(kvdb.RTx, *models.LightningNode) error, reset func()) error {
3✔
825

3✔
826
        traversal := func(tx kvdb.RTx) error {
6✔
827
                // First grab the nodes bucket which stores the mapping from
3✔
828
                // pubKey to node information.
3✔
829
                nodes := tx.ReadBucket(nodeBucket)
3✔
830
                if nodes == nil {
3✔
831
                        return ErrGraphNotFound
×
832
                }
×
833

834
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
835
                        // If this is the source key, then we skip this
3✔
836
                        // iteration as the value for this key is a pubKey
3✔
837
                        // rather than raw node information.
3✔
838
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
839
                                return nil
3✔
840
                        }
3✔
841

842
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
843
                        node, err := deserializeLightningNode(nodeReader)
3✔
844
                        if err != nil {
3✔
845
                                return err
×
846
                        }
×
847

848
                        // Execute the callback, the transaction will abort if
849
                        // this returns an error.
850
                        return cb(tx, &node)
3✔
851
                })
852
        }
853

854
        return kvdb.View(db, traversal, reset)
3✔
855
}
856

857
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
858
// graph, executing the passed callback with each node encountered. If the
859
// callback returns an error, then the transaction is aborted and the iteration
860
// stops early.
861
func (c *KVStore) ForEachNodeCacheable(_ context.Context,
862
        cb func(route.Vertex, *lnwire.FeatureVector) error,
863
        reset func()) error {
3✔
864

3✔
865
        traversal := func(tx kvdb.RTx) error {
6✔
866
                // First grab the nodes bucket which stores the mapping from
3✔
867
                // pubKey to node information.
3✔
868
                nodes := tx.ReadBucket(nodeBucket)
3✔
869
                if nodes == nil {
3✔
870
                        return ErrGraphNotFound
×
871
                }
×
872

873
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
874
                        // If this is the source key, then we skip this
3✔
875
                        // iteration as the value for this key is a pubKey
3✔
876
                        // rather than raw node information.
3✔
877
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
878
                                return nil
3✔
879
                        }
3✔
880

881
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
882
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
883
                                nodeReader,
3✔
884
                        )
3✔
885
                        if err != nil {
3✔
886
                                return err
×
887
                        }
×
888

889
                        // Execute the callback, the transaction will abort if
890
                        // this returns an error.
891
                        return cb(node, features)
3✔
892
                })
893
        }
894

895
        return kvdb.View(c.db, traversal, reset)
3✔
896
}
897

898
// SourceNode returns the source node of the graph. The source node is treated
899
// as the center node within a star-graph. This method may be used to kick off
900
// a path finding algorithm in order to explore the reachability of another
901
// node based off the source node.
902
func (c *KVStore) SourceNode(_ context.Context) (*models.LightningNode, error) {
3✔
903
        return sourceNode(c.db)
3✔
904
}
3✔
905

906
// sourceNode fetches the source node of the graph. The source node is treated
907
// as the center node within a star-graph.
908
func sourceNode(db kvdb.Backend) (*models.LightningNode, error) {
3✔
909
        var source *models.LightningNode
3✔
910
        err := kvdb.View(db, func(tx kvdb.RTx) error {
6✔
911
                // First grab the nodes bucket which stores the mapping from
3✔
912
                // pubKey to node information.
3✔
913
                nodes := tx.ReadBucket(nodeBucket)
3✔
914
                if nodes == nil {
3✔
915
                        return ErrGraphNotFound
×
916
                }
×
917

918
                node, err := sourceNodeWithTx(nodes)
3✔
919
                if err != nil {
6✔
920
                        return err
3✔
921
                }
3✔
922
                source = node
3✔
923

3✔
924
                return nil
3✔
925
        }, func() {
3✔
926
                source = nil
3✔
927
        })
3✔
928
        if err != nil {
6✔
929
                return nil, err
3✔
930
        }
3✔
931

932
        return source, nil
3✔
933
}
934

935
// sourceNodeWithTx uses an existing database transaction and returns the source
936
// node of the graph. The source node is treated as the center node within a
937
// star-graph. This method may be used to kick off a path finding algorithm in
938
// order to explore the reachability of another node based off the source node.
939
func sourceNodeWithTx(nodes kvdb.RBucket) (*models.LightningNode, error) {
3✔
940
        selfPub := nodes.Get(sourceKey)
3✔
941
        if selfPub == nil {
6✔
942
                return nil, ErrSourceNodeNotSet
3✔
943
        }
3✔
944

945
        // With the pubKey of the source node retrieved, we're able to
946
        // fetch the full node information.
947
        node, err := fetchLightningNode(nodes, selfPub)
3✔
948
        if err != nil {
3✔
949
                return nil, err
×
950
        }
×
951

952
        return &node, nil
3✔
953
}
954

955
// SetSourceNode sets the source node within the graph database. The source
956
// node is to be used as the center of a star-graph within path finding
957
// algorithms.
958
func (c *KVStore) SetSourceNode(_ context.Context,
959
        node *models.LightningNode) error {
3✔
960

3✔
961
        nodePubBytes := node.PubKeyBytes[:]
3✔
962

3✔
963
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
964
                // First grab the nodes bucket which stores the mapping from
3✔
965
                // pubKey to node information.
3✔
966
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
967
                if err != nil {
3✔
968
                        return err
×
969
                }
×
970

971
                // Next we create the mapping from source to the targeted
972
                // public key.
973
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
3✔
974
                        return err
×
975
                }
×
976

977
                // Finally, we commit the information of the lightning node
978
                // itself.
979
                return addLightningNode(tx, node)
3✔
980
        }, func() {})
3✔
981
}
982

983
// AddLightningNode adds a vertex/node to the graph database. If the node is not
984
// in the database from before, this will add a new, unconnected one to the
985
// graph. If it is present from before, this will update that node's
986
// information. Note that this method is expected to only be called to update an
987
// already present node from a node announcement, or to insert a node found in a
988
// channel update.
989
//
990
// TODO(roasbeef): also need sig of announcement.
991
func (c *KVStore) AddLightningNode(ctx context.Context,
992
        node *models.LightningNode, opts ...batch.SchedulerOption) error {
3✔
993

3✔
994
        r := &batch.Request[kvdb.RwTx]{
3✔
995
                Opts: batch.NewSchedulerOptions(opts...),
3✔
996
                Do: func(tx kvdb.RwTx) error {
6✔
997
                        return addLightningNode(tx, node)
3✔
998
                },
3✔
999
        }
1000

1001
        return c.nodeScheduler.Execute(ctx, r)
3✔
1002
}
1003

1004
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
1005
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1006
        if err != nil {
3✔
1007
                return err
×
1008
        }
×
1009

1010
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
1011
        if err != nil {
3✔
1012
                return err
×
1013
        }
×
1014

1015
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
1016
                nodeUpdateIndexBucket,
3✔
1017
        )
3✔
1018
        if err != nil {
3✔
1019
                return err
×
1020
        }
×
1021

1022
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
1023
}
1024

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

3✔
1030
        var alias string
3✔
1031

3✔
1032
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1033
                nodes := tx.ReadBucket(nodeBucket)
3✔
1034
                if nodes == nil {
3✔
1035
                        return ErrGraphNodesNotFound
×
1036
                }
×
1037

1038
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
3✔
1039
                if aliases == nil {
3✔
1040
                        return ErrGraphNodesNotFound
×
1041
                }
×
1042

1043
                nodePub := pub.SerializeCompressed()
3✔
1044
                a := aliases.Get(nodePub)
3✔
1045
                if a == nil {
3✔
UNCOV
1046
                        return ErrNodeAliasNotFound
×
UNCOV
1047
                }
×
1048

1049
                // TODO(roasbeef): should actually be using the utf-8
1050
                // package...
1051
                alias = string(a)
3✔
1052

3✔
1053
                return nil
3✔
1054
        }, func() {
3✔
1055
                alias = ""
3✔
1056
        })
3✔
1057
        if err != nil {
3✔
UNCOV
1058
                return "", err
×
UNCOV
1059
        }
×
1060

1061
        return alias, nil
3✔
1062
}
1063

1064
// DeleteLightningNode starts a new database transaction to remove a vertex/node
1065
// from the database according to the node's public key.
1066
func (c *KVStore) DeleteLightningNode(_ context.Context,
UNCOV
1067
        nodePub route.Vertex) error {
×
UNCOV
1068

×
UNCOV
1069
        // TODO(roasbeef): ensure dangling edges are removed...
×
UNCOV
1070
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
1071
                nodes := tx.ReadWriteBucket(nodeBucket)
×
UNCOV
1072
                if nodes == nil {
×
1073
                        return ErrGraphNodeNotFound
×
1074
                }
×
1075

UNCOV
1076
                return c.deleteLightningNode(nodes, nodePub[:])
×
UNCOV
1077
        }, func() {})
×
1078
}
1079

1080
// deleteLightningNode uses an existing database transaction to remove a
1081
// vertex/node from the database according to the node's public key.
1082
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
1083
        compressedPubKey []byte) error {
3✔
1084

3✔
1085
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
3✔
1086
        if aliases == nil {
3✔
1087
                return ErrGraphNodesNotFound
×
1088
        }
×
1089

1090
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
1091
                return err
×
1092
        }
×
1093

1094
        // Before we delete the node, we'll fetch its current state so we can
1095
        // determine when its last update was to clear out the node update
1096
        // index.
1097
        node, err := fetchLightningNode(nodes, compressedPubKey)
3✔
1098
        if err != nil {
3✔
UNCOV
1099
                return err
×
UNCOV
1100
        }
×
1101

1102
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
1103
                return err
×
1104
        }
×
1105

1106
        // Finally, we'll delete the index entry for the node within the
1107
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1108
        // need to track its last update.
1109
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
1110
        if nodeUpdateIndex == nil {
3✔
1111
                return ErrGraphNodesNotFound
×
1112
        }
×
1113

1114
        // In order to delete the entry, we'll need to reconstruct the key for
1115
        // its last update.
1116
        updateUnix := uint64(node.LastUpdate.Unix())
3✔
1117
        var indexKey [8 + 33]byte
3✔
1118
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
1119
        copy(indexKey[8:], compressedPubKey)
3✔
1120

3✔
1121
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
1122
}
1123

1124
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1125
// undirected edge from the two target nodes are created. The information stored
1126
// denotes the static attributes of the channel, such as the channelID, the keys
1127
// involved in creation of the channel, and the set of features that the channel
1128
// supports. The chanPoint and chanID are used to uniquely identify the edge
1129
// globally within the database.
1130
func (c *KVStore) AddChannelEdge(ctx context.Context,
1131
        edge *models.ChannelEdgeInfo, opts ...batch.SchedulerOption) error {
3✔
1132

3✔
1133
        var alreadyExists bool
3✔
1134
        r := &batch.Request[kvdb.RwTx]{
3✔
1135
                Opts: batch.NewSchedulerOptions(opts...),
3✔
1136
                Reset: func() {
6✔
1137
                        alreadyExists = false
3✔
1138
                },
3✔
1139
                Do: func(tx kvdb.RwTx) error {
3✔
1140
                        err := c.addChannelEdge(tx, edge)
3✔
1141

3✔
1142
                        // Silence ErrEdgeAlreadyExist so that the batch can
3✔
1143
                        // succeed, but propagate the error via local state.
3✔
1144
                        if errors.Is(err, ErrEdgeAlreadyExist) {
3✔
UNCOV
1145
                                alreadyExists = true
×
UNCOV
1146
                                return nil
×
UNCOV
1147
                        }
×
1148

1149
                        return err
3✔
1150
                },
1151
                OnCommit: func(err error) error {
3✔
1152
                        switch {
3✔
1153
                        case err != nil:
×
1154
                                return err
×
UNCOV
1155
                        case alreadyExists:
×
UNCOV
1156
                                return ErrEdgeAlreadyExist
×
1157
                        default:
3✔
1158
                                c.rejectCache.remove(edge.ChannelID)
3✔
1159
                                c.chanCache.remove(edge.ChannelID)
3✔
1160
                                return nil
3✔
1161
                        }
1162
                },
1163
        }
1164

1165
        return c.chanScheduler.Execute(ctx, r)
3✔
1166
}
1167

1168
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1169
// utilize an existing db transaction.
1170
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1171
        edge *models.ChannelEdgeInfo) error {
3✔
1172

3✔
1173
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1174
        var chanKey [8]byte
3✔
1175
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1176

3✔
1177
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1178
        if err != nil {
3✔
1179
                return err
×
1180
        }
×
1181
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1182
        if err != nil {
3✔
1183
                return err
×
1184
        }
×
1185
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1186
        if err != nil {
3✔
1187
                return err
×
1188
        }
×
1189
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1190
        if err != nil {
3✔
1191
                return err
×
1192
        }
×
1193

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

1200
        // Before we insert the channel into the database, we'll ensure that
1201
        // both nodes already exist in the channel graph. If either node
1202
        // doesn't, then we'll insert a "shell" node that just includes its
1203
        // public key, so subsequent validation and queries can work properly.
1204
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
3✔
1205
        switch {
3✔
1206
        case errors.Is(node1Err, ErrGraphNodeNotFound):
3✔
1207
                node1Shell := models.LightningNode{
3✔
1208
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1209
                        HaveNodeAnnouncement: false,
3✔
1210
                }
3✔
1211
                err := addLightningNode(tx, &node1Shell)
3✔
1212
                if err != nil {
3✔
1213
                        return fmt.Errorf("unable to create shell node "+
×
1214
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1215
                }
×
1216
        case node1Err != nil:
×
1217
                return node1Err
×
1218
        }
1219

1220
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
1221
        switch {
3✔
1222
        case errors.Is(node2Err, ErrGraphNodeNotFound):
3✔
1223
                node2Shell := models.LightningNode{
3✔
1224
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1225
                        HaveNodeAnnouncement: false,
3✔
1226
                }
3✔
1227
                err := addLightningNode(tx, &node2Shell)
3✔
1228
                if err != nil {
3✔
1229
                        return fmt.Errorf("unable to create shell node "+
×
1230
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1231
                }
×
1232
        case node2Err != nil:
×
1233
                return node2Err
×
1234
        }
1235

1236
        // If the edge hasn't been created yet, then we'll first add it to the
1237
        // edge index in order to associate the edge between two nodes and also
1238
        // store the static components of the channel.
1239
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1240
                return err
×
1241
        }
×
1242

1243
        // Mark edge policies for both sides as unknown. This is to enable
1244
        // efficient incoming channel lookup for a node.
1245
        keys := []*[33]byte{
3✔
1246
                &edge.NodeKey1Bytes,
3✔
1247
                &edge.NodeKey2Bytes,
3✔
1248
        }
3✔
1249
        for _, key := range keys {
6✔
1250
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1251
                if err != nil {
3✔
1252
                        return err
×
1253
                }
×
1254
        }
1255

1256
        // Finally we add it to the channel index which maps channel points
1257
        // (outpoints) to the shorter channel ID's.
1258
        var b bytes.Buffer
3✔
1259
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1260
                return err
×
1261
        }
×
1262

1263
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1264
}
1265

1266
// HasChannelEdge returns true if the database knows of a channel edge with the
1267
// passed channel ID, and false otherwise. If an edge with that ID is found
1268
// within the graph, then two time stamps representing the last time the edge
1269
// was updated for both directed edges are returned along with the boolean. If
1270
// it is not found, then the zombie index is checked and its result is returned
1271
// as the second boolean.
1272
func (c *KVStore) HasChannelEdge(
1273
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1274

3✔
1275
        var (
3✔
1276
                upd1Time time.Time
3✔
1277
                upd2Time time.Time
3✔
1278
                exists   bool
3✔
1279
                isZombie bool
3✔
1280
        )
3✔
1281

3✔
1282
        // We'll query the cache with the shared lock held to allow multiple
3✔
1283
        // readers to access values in the cache concurrently if they exist.
3✔
1284
        c.cacheMu.RLock()
3✔
1285
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1286
                c.cacheMu.RUnlock()
3✔
1287
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1288
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1289
                exists, isZombie = entry.flags.unpack()
3✔
1290

3✔
1291
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1292
        }
3✔
1293
        c.cacheMu.RUnlock()
3✔
1294

3✔
1295
        c.cacheMu.Lock()
3✔
1296
        defer c.cacheMu.Unlock()
3✔
1297

3✔
1298
        // The item was not found with the shared lock, so we'll acquire the
3✔
1299
        // exclusive lock and check the cache again in case another method added
3✔
1300
        // the entry to the cache while no lock was held.
3✔
1301
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1302
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1303
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1304
                exists, isZombie = entry.flags.unpack()
3✔
1305

3✔
1306
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1307
        }
3✔
1308

1309
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1310
                edges := tx.ReadBucket(edgeBucket)
3✔
1311
                if edges == nil {
3✔
1312
                        return ErrGraphNoEdgesFound
×
1313
                }
×
1314
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1315
                if edgeIndex == nil {
3✔
1316
                        return ErrGraphNoEdgesFound
×
1317
                }
×
1318

1319
                var channelID [8]byte
3✔
1320
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1321

3✔
1322
                // If the edge doesn't exist, then we'll also check our zombie
3✔
1323
                // index.
3✔
1324
                if edgeIndex.Get(channelID[:]) == nil {
6✔
1325
                        exists = false
3✔
1326
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1327
                        if zombieIndex != nil {
6✔
1328
                                isZombie, _, _ = isZombieEdge(
3✔
1329
                                        zombieIndex, chanID,
3✔
1330
                                )
3✔
1331
                        }
3✔
1332

1333
                        return nil
3✔
1334
                }
1335

1336
                exists = true
3✔
1337
                isZombie = false
3✔
1338

3✔
1339
                // If the channel has been found in the graph, then retrieve
3✔
1340
                // the edges itself so we can return the last updated
3✔
1341
                // timestamps.
3✔
1342
                nodes := tx.ReadBucket(nodeBucket)
3✔
1343
                if nodes == nil {
3✔
1344
                        return ErrGraphNodeNotFound
×
1345
                }
×
1346

1347
                e1, e2, err := fetchChanEdgePolicies(
3✔
1348
                        edgeIndex, edges, channelID[:],
3✔
1349
                )
3✔
1350
                if err != nil {
3✔
1351
                        return err
×
1352
                }
×
1353

1354
                // As we may have only one of the edges populated, only set the
1355
                // update time if the edge was found in the database.
1356
                if e1 != nil {
6✔
1357
                        upd1Time = e1.LastUpdate
3✔
1358
                }
3✔
1359
                if e2 != nil {
6✔
1360
                        upd2Time = e2.LastUpdate
3✔
1361
                }
3✔
1362

1363
                return nil
3✔
1364
        }, func() {}); err != nil {
3✔
1365
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1366
        }
×
1367

1368
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1369
                upd1Time: upd1Time.Unix(),
3✔
1370
                upd2Time: upd2Time.Unix(),
3✔
1371
                flags:    packRejectFlags(exists, isZombie),
3✔
1372
        })
3✔
1373

3✔
1374
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1375
}
1376

1377
// AddEdgeProof sets the proof of an existing edge in the graph database.
1378
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1379
        proof *models.ChannelAuthProof) error {
3✔
1380

3✔
1381
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1382
        var chanKey [8]byte
3✔
1383
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
1384

3✔
1385
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1386
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1387
                if edges == nil {
3✔
1388
                        return ErrEdgeNotFound
×
1389
                }
×
1390

1391
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1392
                if edgeIndex == nil {
3✔
1393
                        return ErrEdgeNotFound
×
1394
                }
×
1395

1396
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1397
                if err != nil {
3✔
1398
                        return err
×
1399
                }
×
1400

1401
                edge.AuthProof = proof
3✔
1402

3✔
1403
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
3✔
1404
        }, func() {})
3✔
1405
}
1406

1407
const (
1408
        // pruneTipBytes is the total size of the value which stores a prune
1409
        // entry of the graph in the prune log. The "prune tip" is the last
1410
        // entry in the prune log, and indicates if the channel graph is in
1411
        // sync with the current UTXO state. The structure of the value
1412
        // is: blockHash, taking 32 bytes total.
1413
        pruneTipBytes = 32
1414
)
1415

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

3✔
1428
        c.cacheMu.Lock()
3✔
1429
        defer c.cacheMu.Unlock()
3✔
1430

3✔
1431
        var (
3✔
1432
                chansClosed []*models.ChannelEdgeInfo
3✔
1433
                prunedNodes []route.Vertex
3✔
1434
        )
3✔
1435

3✔
1436
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1437
                // First grab the edges bucket which houses the information
3✔
1438
                // we'd like to delete
3✔
1439
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1440
                if err != nil {
3✔
1441
                        return err
×
1442
                }
×
1443

1444
                // Next grab the two edge indexes which will also need to be
1445
                // updated.
1446
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1447
                if err != nil {
3✔
1448
                        return err
×
1449
                }
×
1450
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1451
                        channelPointBucket,
3✔
1452
                )
3✔
1453
                if err != nil {
3✔
1454
                        return err
×
1455
                }
×
1456
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1457
                if nodes == nil {
3✔
1458
                        return ErrSourceNodeNotSet
×
1459
                }
×
1460
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1461
                if err != nil {
3✔
1462
                        return err
×
1463
                }
×
1464

1465
                // For each of the outpoints that have been spent within the
1466
                // block, we attempt to delete them from the graph as if that
1467
                // outpoint was a channel, then it has now been closed.
1468
                for _, chanPoint := range spentOutputs {
6✔
1469
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1470
                        // if NOT if filter
3✔
1471

3✔
1472
                        var opBytes bytes.Buffer
3✔
1473
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1474
                        if err != nil {
3✔
1475
                                return err
×
1476
                        }
×
1477

1478
                        // First attempt to see if the channel exists within
1479
                        // the database, if not, then we can exit early.
1480
                        chanID := chanIndex.Get(opBytes.Bytes())
3✔
1481
                        if chanID == nil {
3✔
UNCOV
1482
                                continue
×
1483
                        }
1484

1485
                        // Attempt to delete the channel, an ErrEdgeNotFound
1486
                        // will be returned if that outpoint isn't known to be
1487
                        // a channel. If no error is returned, then a channel
1488
                        // was successfully pruned.
1489
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1490
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1491
                                chanID, false, false,
3✔
1492
                        )
3✔
1493
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1494
                                return err
×
1495
                        }
×
1496

1497
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1498
                }
1499

1500
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1501
                if err != nil {
3✔
1502
                        return err
×
1503
                }
×
1504

1505
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1506
                        pruneLogBucket,
3✔
1507
                )
3✔
1508
                if err != nil {
3✔
1509
                        return err
×
1510
                }
×
1511

1512
                // With the graph pruned, add a new entry to the prune log,
1513
                // which can be used to check if the graph is fully synced with
1514
                // the current UTXO state.
1515
                var blockHeightBytes [4]byte
3✔
1516
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
3✔
1517

3✔
1518
                var newTip [pruneTipBytes]byte
3✔
1519
                copy(newTip[:], blockHash[:])
3✔
1520

3✔
1521
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1522
                if err != nil {
3✔
1523
                        return err
×
1524
                }
×
1525

1526
                // Now that the graph has been pruned, we'll also attempt to
1527
                // prune any nodes that have had a channel closed within the
1528
                // latest block.
1529
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1530

3✔
1531
                return err
3✔
1532
        }, func() {
3✔
1533
                chansClosed = nil
3✔
1534
                prunedNodes = nil
3✔
1535
        })
3✔
1536
        if err != nil {
3✔
1537
                return nil, nil, err
×
1538
        }
×
1539

1540
        for _, channel := range chansClosed {
6✔
1541
                c.rejectCache.remove(channel.ChannelID)
3✔
1542
                c.chanCache.remove(channel.ChannelID)
3✔
1543
        }
3✔
1544

1545
        return chansClosed, prunedNodes, nil
3✔
1546
}
1547

1548
// PruneGraphNodes is a garbage collection method which attempts to prune out
1549
// any nodes from the channel graph that are currently unconnected. This ensure
1550
// that we only maintain a graph of reachable nodes. In the event that a pruned
1551
// node gains more channels, it will be re-added back to the graph.
1552
func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error) {
3✔
1553
        var prunedNodes []route.Vertex
3✔
1554
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1555
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1556
                if nodes == nil {
3✔
1557
                        return ErrGraphNodesNotFound
×
1558
                }
×
1559
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1560
                if edges == nil {
3✔
1561
                        return ErrGraphNotFound
×
1562
                }
×
1563
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1564
                if edgeIndex == nil {
3✔
1565
                        return ErrGraphNoEdgesFound
×
1566
                }
×
1567

1568
                var err error
3✔
1569
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
1570
                if err != nil {
3✔
1571
                        return err
×
1572
                }
×
1573

1574
                return nil
3✔
1575
        }, func() {
3✔
1576
                prunedNodes = nil
3✔
1577
        })
3✔
1578

1579
        return prunedNodes, err
3✔
1580
}
1581

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

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

3✔
1590
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1591
        // even if it no longer has any open channels.
3✔
1592
        sourceNode, err := sourceNodeWithTx(nodes)
3✔
1593
        if err != nil {
3✔
1594
                return nil, err
×
1595
        }
×
1596

1597
        // We'll use this map to keep count the number of references to a node
1598
        // in the graph. A node should only be removed once it has no more
1599
        // references in the graph.
1600
        nodeRefCounts := make(map[[33]byte]int)
3✔
1601
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1602
                // If this is the source key, then we skip this
3✔
1603
                // iteration as the value for this key is a pubKey
3✔
1604
                // rather than raw node information.
3✔
1605
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1606
                        return nil
3✔
1607
                }
3✔
1608

1609
                var nodePub [33]byte
3✔
1610
                copy(nodePub[:], pubKey)
3✔
1611
                nodeRefCounts[nodePub] = 0
3✔
1612

3✔
1613
                return nil
3✔
1614
        })
1615
        if err != nil {
3✔
1616
                return nil, err
×
1617
        }
×
1618

1619
        // To ensure we never delete the source node, we'll start off by
1620
        // bumping its ref count to 1.
1621
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1622

3✔
1623
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1624
        // edge info. We'll use this scan to populate our reference count map
3✔
1625
        // above.
3✔
1626
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
6✔
1627
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1628
                // the nodes that this edge attaches. We'll extract them, and
3✔
1629
                // add them to the ref count map.
3✔
1630
                var node1, node2 [33]byte
3✔
1631
                copy(node1[:], edgeInfoBytes[:33])
3✔
1632
                copy(node2[:], edgeInfoBytes[33:])
3✔
1633

3✔
1634
                // With the nodes extracted, we'll increase the ref count of
3✔
1635
                // each of the nodes.
3✔
1636
                nodeRefCounts[node1]++
3✔
1637
                nodeRefCounts[node2]++
3✔
1638

3✔
1639
                return nil
3✔
1640
        })
3✔
1641
        if err != nil {
3✔
1642
                return nil, err
×
1643
        }
×
1644

1645
        // Finally, we'll make a second pass over the set of nodes, and delete
1646
        // any nodes that have a ref count of zero.
1647
        var pruned []route.Vertex
3✔
1648
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1649
                // If the ref count of the node isn't zero, then we can safely
3✔
1650
                // skip it as it still has edges to or from it within the
3✔
1651
                // graph.
3✔
1652
                if refCount != 0 {
6✔
1653
                        continue
3✔
1654
                }
1655

1656
                // If we reach this point, then there are no longer any edges
1657
                // that connect this node, so we can delete it.
1658
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1659
                if err != nil {
3✔
1660
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1661
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1662

×
1663
                                log.Warnf("Unable to prune node %x from the "+
×
1664
                                        "graph: %v", nodePubKey, err)
×
1665
                                continue
×
1666
                        }
1667

1668
                        return nil, err
×
1669
                }
1670

1671
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1672
                        nodePubKey[:])
3✔
1673

3✔
1674
                pruned = append(pruned, nodePubKey)
3✔
1675
        }
1676

1677
        if len(pruned) > 0 {
6✔
1678
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1679
                        len(pruned))
3✔
1680
        }
3✔
1681

1682
        return pruned, err
3✔
1683
}
1684

1685
// DisconnectBlockAtHeight is used to indicate that the block specified
1686
// by the passed height has been disconnected from the main chain. This
1687
// will "rewind" the graph back to the height below, deleting channels
1688
// that are no longer confirmed from the graph. The prune log will be
1689
// set to the last prune height valid for the remaining chain.
1690
// Channels that were removed from the graph resulting from the
1691
// disconnected block are returned.
1692
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
1693
        []*models.ChannelEdgeInfo, error) {
3✔
1694

3✔
1695
        // Every channel having a ShortChannelID starting at 'height'
3✔
1696
        // will no longer be confirmed.
3✔
1697
        startShortChanID := lnwire.ShortChannelID{
3✔
1698
                BlockHeight: height,
3✔
1699
        }
3✔
1700

3✔
1701
        // Delete everything after this height from the db up until the
3✔
1702
        // SCID alias range.
3✔
1703
        endShortChanID := aliasmgr.StartingAlias
3✔
1704

3✔
1705
        // The block height will be the 3 first bytes of the channel IDs.
3✔
1706
        var chanIDStart [8]byte
3✔
1707
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
3✔
1708
        var chanIDEnd [8]byte
3✔
1709
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
3✔
1710

3✔
1711
        c.cacheMu.Lock()
3✔
1712
        defer c.cacheMu.Unlock()
3✔
1713

3✔
1714
        // Keep track of the channels that are removed from the graph.
3✔
1715
        var removedChans []*models.ChannelEdgeInfo
3✔
1716

3✔
1717
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1718
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1719
                if err != nil {
3✔
1720
                        return err
×
1721
                }
×
1722
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1723
                if err != nil {
3✔
1724
                        return err
×
1725
                }
×
1726
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1727
                        channelPointBucket,
3✔
1728
                )
3✔
1729
                if err != nil {
3✔
1730
                        return err
×
1731
                }
×
1732
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1733
                if err != nil {
3✔
1734
                        return err
×
1735
                }
×
1736

1737
                // Scan from chanIDStart to chanIDEnd, deleting every
1738
                // found edge.
1739
                // NOTE: we must delete the edges after the cursor loop, since
1740
                // modifying the bucket while traversing is not safe.
1741
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1742
                // so that the StartingAlias itself isn't deleted.
1743
                var keys [][]byte
3✔
1744
                cursor := edgeIndex.ReadWriteCursor()
3✔
1745

3✔
1746
                //nolint:ll
3✔
1747
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
1748
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
5✔
1749
                        keys = append(keys, k)
2✔
1750
                }
2✔
1751

1752
                for _, k := range keys {
5✔
1753
                        edgeInfo, err := c.delChannelEdgeUnsafe(
2✔
1754
                                edges, edgeIndex, chanIndex, zombieIndex,
2✔
1755
                                k, false, false,
2✔
1756
                        )
2✔
1757
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
2✔
1758
                                return err
×
1759
                        }
×
1760

1761
                        removedChans = append(removedChans, edgeInfo)
2✔
1762
                }
1763

1764
                // Delete all the entries in the prune log having a height
1765
                // greater or equal to the block disconnected.
1766
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1767
                if err != nil {
3✔
1768
                        return err
×
1769
                }
×
1770

1771
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1772
                        pruneLogBucket,
3✔
1773
                )
3✔
1774
                if err != nil {
3✔
1775
                        return err
×
1776
                }
×
1777

1778
                var pruneKeyStart [4]byte
3✔
1779
                byteOrder.PutUint32(pruneKeyStart[:], height)
3✔
1780

3✔
1781
                var pruneKeyEnd [4]byte
3✔
1782
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
3✔
1783

3✔
1784
                // To avoid modifying the bucket while traversing, we delete
3✔
1785
                // the keys in a second loop.
3✔
1786
                var pruneKeys [][]byte
3✔
1787
                pruneCursor := pruneBucket.ReadWriteCursor()
3✔
1788
                //nolint:ll
3✔
1789
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
3✔
1790
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
6✔
1791
                        pruneKeys = append(pruneKeys, k)
3✔
1792
                }
3✔
1793

1794
                for _, k := range pruneKeys {
6✔
1795
                        if err := pruneBucket.Delete(k); err != nil {
3✔
1796
                                return err
×
1797
                        }
×
1798
                }
1799

1800
                return nil
3✔
1801
        }, func() {
3✔
1802
                removedChans = nil
3✔
1803
        }); err != nil {
3✔
1804
                return nil, err
×
1805
        }
×
1806

1807
        for _, channel := range removedChans {
5✔
1808
                c.rejectCache.remove(channel.ChannelID)
2✔
1809
                c.chanCache.remove(channel.ChannelID)
2✔
1810
        }
2✔
1811

1812
        return removedChans, nil
3✔
1813
}
1814

1815
// PruneTip returns the block height and hash of the latest block that has been
1816
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1817
// to tell if the graph is currently in sync with the current best known UTXO
1818
// state.
1819
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
3✔
1820
        var (
3✔
1821
                tipHash   chainhash.Hash
3✔
1822
                tipHeight uint32
3✔
1823
        )
3✔
1824

3✔
1825
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1826
                graphMeta := tx.ReadBucket(graphMetaBucket)
3✔
1827
                if graphMeta == nil {
3✔
1828
                        return ErrGraphNotFound
×
1829
                }
×
1830
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
3✔
1831
                if pruneBucket == nil {
3✔
1832
                        return ErrGraphNeverPruned
×
1833
                }
×
1834

1835
                pruneCursor := pruneBucket.ReadCursor()
3✔
1836

3✔
1837
                // The prune key with the largest block height will be our
3✔
1838
                // prune tip.
3✔
1839
                k, v := pruneCursor.Last()
3✔
1840
                if k == nil {
6✔
1841
                        return ErrGraphNeverPruned
3✔
1842
                }
3✔
1843

1844
                // Once we have the prune tip, the value will be the block hash,
1845
                // and the key the block height.
1846
                copy(tipHash[:], v)
3✔
1847
                tipHeight = byteOrder.Uint32(k)
3✔
1848

3✔
1849
                return nil
3✔
1850
        }, func() {})
3✔
1851
        if err != nil {
6✔
1852
                return nil, 0, err
3✔
1853
        }
3✔
1854

1855
        return &tipHash, tipHeight, nil
3✔
1856
}
1857

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

3✔
1869
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1870
        // channels
3✔
1871
        // TODO(roasbeef): don't delete both edges?
3✔
1872

3✔
1873
        c.cacheMu.Lock()
3✔
1874
        defer c.cacheMu.Unlock()
3✔
1875

3✔
1876
        var infos []*models.ChannelEdgeInfo
3✔
1877
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1878
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1879
                if edges == nil {
3✔
1880
                        return ErrEdgeNotFound
×
1881
                }
×
1882
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1883
                if edgeIndex == nil {
3✔
1884
                        return ErrEdgeNotFound
×
1885
                }
×
1886
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
3✔
1887
                if chanIndex == nil {
3✔
1888
                        return ErrEdgeNotFound
×
1889
                }
×
1890
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1891
                if nodes == nil {
3✔
1892
                        return ErrGraphNodeNotFound
×
1893
                }
×
1894
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1895
                if err != nil {
3✔
1896
                        return err
×
1897
                }
×
1898

1899
                var rawChanID [8]byte
3✔
1900
                for _, chanID := range chanIDs {
6✔
1901
                        byteOrder.PutUint64(rawChanID[:], chanID)
3✔
1902
                        edgeInfo, err := c.delChannelEdgeUnsafe(
3✔
1903
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1904
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1905
                        )
3✔
1906
                        if err != nil {
3✔
UNCOV
1907
                                return err
×
UNCOV
1908
                        }
×
1909

1910
                        infos = append(infos, edgeInfo)
3✔
1911
                }
1912

1913
                return nil
3✔
1914
        }, func() {
3✔
1915
                infos = nil
3✔
1916
        })
3✔
1917
        if err != nil {
3✔
UNCOV
1918
                return nil, err
×
UNCOV
1919
        }
×
1920

1921
        for _, chanID := range chanIDs {
6✔
1922
                c.rejectCache.remove(chanID)
3✔
1923
                c.chanCache.remove(chanID)
3✔
1924
        }
3✔
1925

1926
        return infos, nil
3✔
1927
}
1928

1929
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1930
// passed channel point (outpoint). If the passed channel doesn't exist within
1931
// the database, then ErrEdgeNotFound is returned.
1932
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1933
        var chanID uint64
3✔
1934
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1935
                var err error
3✔
1936
                chanID, err = getChanID(tx, chanPoint)
3✔
1937
                return err
3✔
1938
        }, func() {
6✔
1939
                chanID = 0
3✔
1940
        }); err != nil {
6✔
1941
                return 0, err
3✔
1942
        }
3✔
1943

1944
        return chanID, nil
3✔
1945
}
1946

1947
// getChanID returns the assigned channel ID for a given channel point.
1948
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1949
        var b bytes.Buffer
3✔
1950
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1951
                return 0, err
×
1952
        }
×
1953

1954
        edges := tx.ReadBucket(edgeBucket)
3✔
1955
        if edges == nil {
3✔
1956
                return 0, ErrGraphNoEdgesFound
×
1957
        }
×
1958
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1959
        if chanIndex == nil {
3✔
1960
                return 0, ErrGraphNoEdgesFound
×
1961
        }
×
1962

1963
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1964
        if chanIDBytes == nil {
6✔
1965
                return 0, ErrEdgeNotFound
3✔
1966
        }
3✔
1967

1968
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1969

3✔
1970
        return chanID, nil
3✔
1971
}
1972

1973
// TODO(roasbeef): allow updates to use Batch?
1974

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

3✔
1981
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1982
                edges := tx.ReadBucket(edgeBucket)
3✔
1983
                if edges == nil {
3✔
1984
                        return ErrGraphNoEdgesFound
×
1985
                }
×
1986
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1987
                if edgeIndex == nil {
3✔
1988
                        return ErrGraphNoEdgesFound
×
1989
                }
×
1990

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

3✔
1995
                lastChanID, _ := cidCursor.Last()
3✔
1996

3✔
1997
                // If there's no key, then this means that we don't actually
3✔
1998
                // know of any channels, so we'll return a predicable error.
3✔
1999
                if lastChanID == nil {
6✔
2000
                        return ErrGraphNoEdgesFound
3✔
2001
                }
3✔
2002

2003
                // Otherwise, we'll de serialize the channel ID and return it
2004
                // to the caller.
2005
                cid = byteOrder.Uint64(lastChanID)
3✔
2006

3✔
2007
                return nil
3✔
2008
        }, func() {
3✔
2009
                cid = 0
3✔
2010
        })
3✔
2011
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
3✔
2012
                return 0, err
×
2013
        }
×
2014

2015
        return cid, nil
3✔
2016
}
2017

2018
// ChannelEdge represents the complete set of information for a channel edge in
2019
// the known channel graph. This struct couples the core information of the
2020
// edge as well as each of the known advertised edge policies.
2021
type ChannelEdge struct {
2022
        // Info contains all the static information describing the channel.
2023
        Info *models.ChannelEdgeInfo
2024

2025
        // Policy1 points to the "first" edge policy of the channel containing
2026
        // the dynamic information required to properly route through the edge.
2027
        Policy1 *models.ChannelEdgePolicy
2028

2029
        // Policy2 points to the "second" edge policy of the channel containing
2030
        // the dynamic information required to properly route through the edge.
2031
        Policy2 *models.ChannelEdgePolicy
2032

2033
        // Node1 is "node 1" in the channel. This is the node that would have
2034
        // produced Policy1 if it exists.
2035
        Node1 *models.LightningNode
2036

2037
        // Node2 is "node 2" in the channel. This is the node that would have
2038
        // produced Policy2 if it exists.
2039
        Node2 *models.LightningNode
2040
}
2041

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

3✔
2047
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
2048
        // additional map to keep track of the edges already seen to prevent
3✔
2049
        // re-adding it.
3✔
2050
        var edgesSeen map[uint64]struct{}
3✔
2051
        var edgesToCache map[uint64]ChannelEdge
3✔
2052
        var edgesInHorizon []ChannelEdge
3✔
2053

3✔
2054
        c.cacheMu.Lock()
3✔
2055
        defer c.cacheMu.Unlock()
3✔
2056

3✔
2057
        var hits int
3✔
2058
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2059
                edges := tx.ReadBucket(edgeBucket)
3✔
2060
                if edges == nil {
3✔
2061
                        return ErrGraphNoEdgesFound
×
2062
                }
×
2063
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2064
                if edgeIndex == nil {
3✔
2065
                        return ErrGraphNoEdgesFound
×
2066
                }
×
2067
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
3✔
2068
                if edgeUpdateIndex == nil {
3✔
2069
                        return ErrGraphNoEdgesFound
×
2070
                }
×
2071

2072
                nodes := tx.ReadBucket(nodeBucket)
3✔
2073
                if nodes == nil {
3✔
2074
                        return ErrGraphNodesNotFound
×
2075
                }
×
2076

2077
                // We'll now obtain a cursor to perform a range query within
2078
                // the index to find all channels within the horizon.
2079
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
2080

3✔
2081
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
2082
                byteOrder.PutUint64(
3✔
2083
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2084
                )
3✔
2085
                byteOrder.PutUint64(
3✔
2086
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2087
                )
3✔
2088

3✔
2089
                // With our start and end times constructed, we'll step through
3✔
2090
                // the index collecting the info and policy of each update of
3✔
2091
                // each channel that has a last update within the time range.
3✔
2092
                //
3✔
2093
                //nolint:ll
3✔
2094
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2095
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2096
                        // We have a new eligible entry, so we'll slice of the
3✔
2097
                        // chan ID so we can query it in the DB.
3✔
2098
                        chanID := indexKey[8:]
3✔
2099

3✔
2100
                        // If we've already retrieved the info and policies for
3✔
2101
                        // this edge, then we can skip it as we don't need to do
3✔
2102
                        // so again.
3✔
2103
                        chanIDInt := byteOrder.Uint64(chanID)
3✔
2104
                        if _, ok := edgesSeen[chanIDInt]; ok {
3✔
UNCOV
2105
                                continue
×
2106
                        }
2107

2108
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
2109
                                hits++
3✔
2110
                                edgesSeen[chanIDInt] = struct{}{}
3✔
2111
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
2112

3✔
2113
                                continue
3✔
2114
                        }
2115

2116
                        // First, we'll fetch the static edge information.
2117
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2118
                        if err != nil {
3✔
2119
                                chanID := byteOrder.Uint64(chanID)
×
2120
                                return fmt.Errorf("unable to fetch info for "+
×
2121
                                        "edge with chan_id=%v: %v", chanID, err)
×
2122
                        }
×
2123

2124
                        // With the static information obtained, we'll now
2125
                        // fetch the dynamic policy info.
2126
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2127
                                edgeIndex, edges, chanID,
3✔
2128
                        )
3✔
2129
                        if err != nil {
3✔
2130
                                chanID := byteOrder.Uint64(chanID)
×
2131
                                return fmt.Errorf("unable to fetch policies "+
×
2132
                                        "for edge with chan_id=%v: %v", chanID,
×
2133
                                        err)
×
2134
                        }
×
2135

2136
                        node1, err := fetchLightningNode(
3✔
2137
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2138
                        )
3✔
2139
                        if err != nil {
3✔
2140
                                return err
×
2141
                        }
×
2142

2143
                        node2, err := fetchLightningNode(
3✔
2144
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2145
                        )
3✔
2146
                        if err != nil {
3✔
2147
                                return err
×
2148
                        }
×
2149

2150
                        // Finally, we'll collate this edge with the rest of
2151
                        // edges to be returned.
2152
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2153
                        channel := ChannelEdge{
3✔
2154
                                Info:    &edgeInfo,
3✔
2155
                                Policy1: edge1,
3✔
2156
                                Policy2: edge2,
3✔
2157
                                Node1:   &node1,
3✔
2158
                                Node2:   &node2,
3✔
2159
                        }
3✔
2160
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2161
                        edgesToCache[chanIDInt] = channel
3✔
2162
                }
2163

2164
                return nil
3✔
2165
        }, func() {
3✔
2166
                edgesSeen = make(map[uint64]struct{})
3✔
2167
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2168
                edgesInHorizon = nil
3✔
2169
        })
3✔
2170
        switch {
3✔
2171
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2172
                fallthrough
×
2173
        case errors.Is(err, ErrGraphNodesNotFound):
×
2174
                break
×
2175

2176
        case err != nil:
×
2177
                return nil, err
×
2178
        }
2179

2180
        // Insert any edges loaded from disk into the cache.
2181
        for chanid, channel := range edgesToCache {
6✔
2182
                c.chanCache.insert(chanid, channel)
3✔
2183
        }
3✔
2184

2185
        if len(edgesInHorizon) > 0 {
6✔
2186
                log.Debugf("ChanUpdatesInHorizon hit percentage: %.2f (%d/%d)",
3✔
2187
                        float64(hits)*100/float64(len(edgesInHorizon)), hits,
3✔
2188
                        len(edgesInHorizon))
3✔
2189
        } else {
6✔
2190
                log.Debugf("ChanUpdatesInHorizon returned no edges in "+
3✔
2191
                        "horizon (%s, %s)", startTime, endTime)
3✔
2192
        }
3✔
2193

2194
        return edgesInHorizon, nil
3✔
2195
}
2196

2197
// NodeUpdatesInHorizon returns all the known lightning node which have an
2198
// update timestamp within the passed range. This method can be used by two
2199
// nodes to quickly determine if they have the same set of up to date node
2200
// announcements.
2201
func (c *KVStore) NodeUpdatesInHorizon(startTime,
2202
        endTime time.Time) ([]models.LightningNode, error) {
3✔
2203

3✔
2204
        var nodesInHorizon []models.LightningNode
3✔
2205

3✔
2206
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2207
                nodes := tx.ReadBucket(nodeBucket)
3✔
2208
                if nodes == nil {
3✔
2209
                        return ErrGraphNodesNotFound
×
2210
                }
×
2211

2212
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2213
                if nodeUpdateIndex == nil {
3✔
2214
                        return ErrGraphNodesNotFound
×
2215
                }
×
2216

2217
                // We'll now obtain a cursor to perform a range query within
2218
                // the index to find all node announcements within the horizon.
2219
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2220

3✔
2221
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2222
                byteOrder.PutUint64(
3✔
2223
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2224
                )
3✔
2225
                byteOrder.PutUint64(
3✔
2226
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2227
                )
3✔
2228

3✔
2229
                // With our start and end times constructed, we'll step through
3✔
2230
                // the index collecting info for each node within the time
3✔
2231
                // range.
3✔
2232
                //
3✔
2233
                //nolint:ll
3✔
2234
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2235
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2236
                        nodePub := indexKey[8:]
3✔
2237
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2238
                        if err != nil {
3✔
2239
                                return err
×
2240
                        }
×
2241

2242
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2243
                }
2244

2245
                return nil
3✔
2246
        }, func() {
3✔
2247
                nodesInHorizon = nil
3✔
2248
        })
3✔
2249
        switch {
3✔
2250
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2251
                fallthrough
×
2252
        case errors.Is(err, ErrGraphNodesNotFound):
×
2253
                break
×
2254

2255
        case err != nil:
×
2256
                return nil, err
×
2257
        }
2258

2259
        return nodesInHorizon, nil
3✔
2260
}
2261

2262
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2263
// ID's that we don't know and are not known zombies of the passed set. In other
2264
// words, we perform a set difference of our set of chan ID's and the ones
2265
// passed in. This method can be used by callers to determine the set of
2266
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2267
// known zombies is also returned.
2268
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2269
        []ChannelUpdateInfo, error) {
3✔
2270

3✔
2271
        var (
3✔
2272
                newChanIDs   []uint64
3✔
2273
                knownZombies []ChannelUpdateInfo
3✔
2274
        )
3✔
2275

3✔
2276
        c.cacheMu.Lock()
3✔
2277
        defer c.cacheMu.Unlock()
3✔
2278

3✔
2279
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2280
                edges := tx.ReadBucket(edgeBucket)
3✔
2281
                if edges == nil {
3✔
2282
                        return ErrGraphNoEdgesFound
×
2283
                }
×
2284
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2285
                if edgeIndex == nil {
3✔
2286
                        return ErrGraphNoEdgesFound
×
2287
                }
×
2288

2289
                // Fetch the zombie index, it may not exist if no edges have
2290
                // ever been marked as zombies. If the index has been
2291
                // initialized, we will use it later to skip known zombie edges.
2292
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2293

3✔
2294
                // We'll run through the set of chanIDs and collate only the
3✔
2295
                // set of channel that are unable to be found within our db.
3✔
2296
                var cidBytes [8]byte
3✔
2297
                for _, info := range chansInfo {
6✔
2298
                        scid := info.ShortChannelID.ToUint64()
3✔
2299
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2300

3✔
2301
                        // If the edge is already known, skip it.
3✔
2302
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
6✔
2303
                                continue
3✔
2304
                        }
2305

2306
                        // If the edge is a known zombie, skip it.
2307
                        if zombieIndex != nil {
6✔
2308
                                isZombie, _, _ := isZombieEdge(
3✔
2309
                                        zombieIndex, scid,
3✔
2310
                                )
3✔
2311

3✔
2312
                                if isZombie {
3✔
UNCOV
2313
                                        knownZombies = append(
×
UNCOV
2314
                                                knownZombies, info,
×
UNCOV
2315
                                        )
×
UNCOV
2316

×
UNCOV
2317
                                        continue
×
2318
                                }
2319
                        }
2320

2321
                        newChanIDs = append(newChanIDs, scid)
3✔
2322
                }
2323

2324
                return nil
3✔
2325
        }, func() {
3✔
2326
                newChanIDs = nil
3✔
2327
                knownZombies = nil
3✔
2328
        })
3✔
2329
        switch {
3✔
2330
        // If we don't know of any edges yet, then we'll return the entire set
2331
        // of chan IDs specified.
2332
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2333
                ogChanIDs := make([]uint64, len(chansInfo))
×
2334
                for i, info := range chansInfo {
×
2335
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2336
                }
×
2337

2338
                return ogChanIDs, nil, nil
×
2339

2340
        case err != nil:
×
2341
                return nil, nil, err
×
2342
        }
2343

2344
        return newChanIDs, knownZombies, nil
3✔
2345
}
2346

2347
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2348
// latest received channel updates for the channel.
2349
type ChannelUpdateInfo struct {
2350
        // ShortChannelID is the SCID identifier of the channel.
2351
        ShortChannelID lnwire.ShortChannelID
2352

2353
        // Node1UpdateTimestamp is the timestamp of the latest received update
2354
        // from the node 1 channel peer. This will be set to zero time if no
2355
        // update has yet been received from this node.
2356
        Node1UpdateTimestamp time.Time
2357

2358
        // Node2UpdateTimestamp is the timestamp of the latest received update
2359
        // from the node 2 channel peer. This will be set to zero time if no
2360
        // update has yet been received from this node.
2361
        Node2UpdateTimestamp time.Time
2362
}
2363

2364
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2365
// timestamps with zero seconds unix timestamp which equals
2366
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2367
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2368
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2369

3✔
2370
        chanInfo := ChannelUpdateInfo{
3✔
2371
                ShortChannelID:       scid,
3✔
2372
                Node1UpdateTimestamp: node1Timestamp,
3✔
2373
                Node2UpdateTimestamp: node2Timestamp,
3✔
2374
        }
3✔
2375

3✔
2376
        if node1Timestamp.IsZero() {
6✔
2377
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2378
        }
3✔
2379

2380
        if node2Timestamp.IsZero() {
6✔
2381
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2382
        }
3✔
2383

2384
        return chanInfo
3✔
2385
}
2386

2387
// BlockChannelRange represents a range of channels for a given block height.
2388
type BlockChannelRange struct {
2389
        // Height is the height of the block all of the channels below were
2390
        // included in.
2391
        Height uint32
2392

2393
        // Channels is the list of channels identified by their short ID
2394
        // representation known to us that were included in the block height
2395
        // above. The list may include channel update timestamp information if
2396
        // requested.
2397
        Channels []ChannelUpdateInfo
2398
}
2399

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

3✔
2410
        startChanID := &lnwire.ShortChannelID{
3✔
2411
                BlockHeight: startHeight,
3✔
2412
        }
3✔
2413

3✔
2414
        endChanID := lnwire.ShortChannelID{
3✔
2415
                BlockHeight: endHeight,
3✔
2416
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2417
                TxPosition:  math.MaxUint16,
3✔
2418
        }
3✔
2419

3✔
2420
        // As we need to perform a range scan, we'll convert the starting and
3✔
2421
        // ending height to their corresponding values when encoded using short
3✔
2422
        // channel ID's.
3✔
2423
        var chanIDStart, chanIDEnd [8]byte
3✔
2424
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
3✔
2425
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
3✔
2426

3✔
2427
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
3✔
2428
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2429
                edges := tx.ReadBucket(edgeBucket)
3✔
2430
                if edges == nil {
3✔
2431
                        return ErrGraphNoEdgesFound
×
2432
                }
×
2433
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2434
                if edgeIndex == nil {
3✔
2435
                        return ErrGraphNoEdgesFound
×
2436
                }
×
2437

2438
                cursor := edgeIndex.ReadCursor()
3✔
2439

3✔
2440
                // We'll now iterate through the database, and find each
3✔
2441
                // channel ID that resides within the specified range.
3✔
2442
                //
3✔
2443
                //nolint:ll
3✔
2444
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
2445
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
6✔
2446
                        // Don't send alias SCIDs during gossip sync.
3✔
2447
                        edgeReader := bytes.NewReader(v)
3✔
2448
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
3✔
2449
                        if err != nil {
3✔
2450
                                return err
×
2451
                        }
×
2452

2453
                        if edgeInfo.AuthProof == nil {
6✔
2454
                                continue
3✔
2455
                        }
2456

2457
                        // This channel ID rests within the target range, so
2458
                        // we'll add it to our returned set.
2459
                        rawCid := byteOrder.Uint64(k)
3✔
2460
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2461

3✔
2462
                        chanInfo := NewChannelUpdateInfo(
3✔
2463
                                cid, time.Time{}, time.Time{},
3✔
2464
                        )
3✔
2465

3✔
2466
                        if !withTimestamps {
3✔
UNCOV
2467
                                channelsPerBlock[cid.BlockHeight] = append(
×
UNCOV
2468
                                        channelsPerBlock[cid.BlockHeight],
×
UNCOV
2469
                                        chanInfo,
×
UNCOV
2470
                                )
×
UNCOV
2471

×
UNCOV
2472
                                continue
×
2473
                        }
2474

2475
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2476

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

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

×
2486
                                        return err
×
2487
                                }
×
2488

2489
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2490
                        }
2491

2492
                        rawPolicy = edges.Get(node2Key)
3✔
2493
                        if len(rawPolicy) != 0 {
6✔
2494
                                r := bytes.NewReader(rawPolicy)
3✔
2495

3✔
2496
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2497
                                if err != nil && !errors.Is(
3✔
2498
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2499
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2500

×
2501
                                        return err
×
2502
                                }
×
2503

2504
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2505
                        }
2506

2507
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2508
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2509
                        )
3✔
2510
                }
2511

2512
                return nil
3✔
2513
        }, func() {
3✔
2514
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2515
        })
3✔
2516

2517
        switch {
3✔
2518
        // If we don't know of any channels yet, then there's nothing to
2519
        // filter, so we'll return an empty slice.
2520
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
3✔
2521
                return nil, nil
3✔
2522

2523
        case err != nil:
×
2524
                return nil, err
×
2525
        }
2526

2527
        // Return the channel ranges in ascending block height order.
2528
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2529
        for block := range channelsPerBlock {
6✔
2530
                blocks = append(blocks, block)
3✔
2531
        }
3✔
2532
        sort.Slice(blocks, func(i, j int) bool {
6✔
2533
                return blocks[i] < blocks[j]
3✔
2534
        })
3✔
2535

2536
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2537
        for _, block := range blocks {
6✔
2538
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2539
                        Height:   block,
3✔
2540
                        Channels: channelsPerBlock[block],
3✔
2541
                })
3✔
2542
        }
3✔
2543

2544
        return channelRanges, nil
3✔
2545
}
2546

2547
// FetchChanInfos returns the set of channel edges that correspond to the passed
2548
// channel ID's. If an edge is the query is unknown to the database, it will
2549
// skipped and the result will contain only those edges that exist at the time
2550
// of the query. This can be used to respond to peer queries that are seeking to
2551
// fill in gaps in their view of the channel graph.
2552
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
2553
        return c.fetchChanInfos(nil, chanIDs)
3✔
2554
}
3✔
2555

2556
// fetchChanInfos returns the set of channel edges that correspond to the passed
2557
// channel ID's. If an edge is the query is unknown to the database, it will
2558
// skipped and the result will contain only those edges that exist at the time
2559
// of the query. This can be used to respond to peer queries that are seeking to
2560
// fill in gaps in their view of the channel graph.
2561
//
2562
// NOTE: An optional transaction may be provided. If none is provided, then a
2563
// new one will be created.
2564
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2565
        []ChannelEdge, error) {
3✔
2566
        // TODO(roasbeef): sort cids?
3✔
2567

3✔
2568
        var (
3✔
2569
                chanEdges []ChannelEdge
3✔
2570
                cidBytes  [8]byte
3✔
2571
        )
3✔
2572

3✔
2573
        fetchChanInfos := func(tx kvdb.RTx) error {
6✔
2574
                edges := tx.ReadBucket(edgeBucket)
3✔
2575
                if edges == nil {
3✔
2576
                        return ErrGraphNoEdgesFound
×
2577
                }
×
2578
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2579
                if edgeIndex == nil {
3✔
2580
                        return ErrGraphNoEdgesFound
×
2581
                }
×
2582
                nodes := tx.ReadBucket(nodeBucket)
3✔
2583
                if nodes == nil {
3✔
2584
                        return ErrGraphNotFound
×
2585
                }
×
2586

2587
                for _, cid := range chanIDs {
6✔
2588
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2589

3✔
2590
                        // First, we'll fetch the static edge information. If
3✔
2591
                        // the edge is unknown, we will skip the edge and
3✔
2592
                        // continue gathering all known edges.
3✔
2593
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2594
                                edgeIndex, cidBytes[:],
3✔
2595
                        )
3✔
2596
                        switch {
3✔
UNCOV
2597
                        case errors.Is(err, ErrEdgeNotFound):
×
UNCOV
2598
                                continue
×
2599
                        case err != nil:
×
2600
                                return err
×
2601
                        }
2602

2603
                        // With the static information obtained, we'll now
2604
                        // fetch the dynamic policy info.
2605
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2606
                                edgeIndex, edges, cidBytes[:],
3✔
2607
                        )
3✔
2608
                        if err != nil {
3✔
2609
                                return err
×
2610
                        }
×
2611

2612
                        node1, err := fetchLightningNode(
3✔
2613
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2614
                        )
3✔
2615
                        if err != nil {
3✔
2616
                                return err
×
2617
                        }
×
2618

2619
                        node2, err := fetchLightningNode(
3✔
2620
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2621
                        )
3✔
2622
                        if err != nil {
3✔
2623
                                return err
×
2624
                        }
×
2625

2626
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2627
                                Info:    &edgeInfo,
3✔
2628
                                Policy1: edge1,
3✔
2629
                                Policy2: edge2,
3✔
2630
                                Node1:   &node1,
3✔
2631
                                Node2:   &node2,
3✔
2632
                        })
3✔
2633
                }
2634

2635
                return nil
3✔
2636
        }
2637

2638
        if tx == nil {
6✔
2639
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2640
                        chanEdges = nil
3✔
2641
                })
3✔
2642
                if err != nil {
3✔
2643
                        return nil, err
×
2644
                }
×
2645

2646
                return chanEdges, nil
3✔
2647
        }
2648

2649
        err := fetchChanInfos(tx)
×
2650
        if err != nil {
×
2651
                return nil, err
×
2652
        }
×
2653

2654
        return chanEdges, nil
×
2655
}
2656

2657
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2658
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2659

3✔
2660
        // First, we'll fetch the edge update index bucket which currently
3✔
2661
        // stores an entry for the channel we're about to delete.
3✔
2662
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2663
        if updateIndex == nil {
3✔
2664
                // No edges in bucket, return early.
×
2665
                return nil
×
2666
        }
×
2667

2668
        // Now that we have the bucket, we'll attempt to construct a template
2669
        // for the index key: updateTime || chanid.
2670
        var indexKey [8 + 8]byte
3✔
2671
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2672

3✔
2673
        // With the template constructed, we'll attempt to delete an entry that
3✔
2674
        // would have been created by both edges: we'll alternate the update
3✔
2675
        // times, as one may had overridden the other.
3✔
2676
        if edge1 != nil {
6✔
2677
                byteOrder.PutUint64(
3✔
2678
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
3✔
2679
                )
3✔
2680
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2681
                        return err
×
2682
                }
×
2683
        }
2684

2685
        // We'll also attempt to delete the entry that may have been created by
2686
        // the second edge.
2687
        if edge2 != nil {
6✔
2688
                byteOrder.PutUint64(
3✔
2689
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2690
                )
3✔
2691
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2692
                        return err
×
2693
                }
×
2694
        }
2695

2696
        return nil
3✔
2697
}
2698

2699
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2700
// cache. It then goes on to delete any policy info and edge info for this
2701
// channel from the DB and finally, if isZombie is true, it will add an entry
2702
// for this channel in the zombie index.
2703
//
2704
// NOTE: this method MUST only be called if the cacheMu has already been
2705
// acquired.
2706
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2707
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2708
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
3✔
2709

3✔
2710
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2711
        if err != nil {
3✔
UNCOV
2712
                return nil, err
×
UNCOV
2713
        }
×
2714

2715
        // We'll also remove the entry in the edge update index bucket before
2716
        // we delete the edges themselves so we can access their last update
2717
        // times.
2718
        cid := byteOrder.Uint64(chanID)
3✔
2719
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2720
        if err != nil {
3✔
2721
                return nil, err
×
2722
        }
×
2723
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2724
        if err != nil {
3✔
2725
                return nil, err
×
2726
        }
×
2727

2728
        // The edge key is of the format pubKey || chanID. First we construct
2729
        // the latter half, populating the channel ID.
2730
        var edgeKey [33 + 8]byte
3✔
2731
        copy(edgeKey[33:], chanID)
3✔
2732

3✔
2733
        // With the latter half constructed, copy over the first public key to
3✔
2734
        // delete the edge in this direction, then the second to delete the
3✔
2735
        // edge in the opposite direction.
3✔
2736
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2737
        if edges.Get(edgeKey[:]) != nil {
6✔
2738
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2739
                        return nil, err
×
2740
                }
×
2741
        }
2742
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2743
        if edges.Get(edgeKey[:]) != nil {
6✔
2744
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2745
                        return nil, err
×
2746
                }
×
2747
        }
2748

2749
        // As part of deleting the edge we also remove all disabled entries
2750
        // from the edgePolicyDisabledIndex bucket. We do that for both
2751
        // directions.
2752
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
3✔
2753
        if err != nil {
3✔
2754
                return nil, err
×
2755
        }
×
2756
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2757
        if err != nil {
3✔
2758
                return nil, err
×
2759
        }
×
2760

2761
        // With the edge data deleted, we can purge the information from the two
2762
        // edge indexes.
2763
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2764
                return nil, err
×
2765
        }
×
2766
        var b bytes.Buffer
3✔
2767
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2768
                return nil, err
×
2769
        }
×
2770
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
2771
                return nil, err
×
2772
        }
×
2773

2774
        // Finally, we'll mark the edge as a zombie within our index if it's
2775
        // being removed due to the channel becoming a zombie. We do this to
2776
        // ensure we don't store unnecessary data for spent channels.
2777
        if !isZombie {
6✔
2778
                return &edgeInfo, nil
3✔
2779
        }
3✔
2780

2781
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2782
        if strictZombie {
3✔
UNCOV
2783
                var e1UpdateTime, e2UpdateTime *time.Time
×
UNCOV
2784
                if edge1 != nil {
×
UNCOV
2785
                        e1UpdateTime = &edge1.LastUpdate
×
UNCOV
2786
                }
×
UNCOV
2787
                if edge2 != nil {
×
UNCOV
2788
                        e2UpdateTime = &edge2.LastUpdate
×
UNCOV
2789
                }
×
2790

UNCOV
2791
                nodeKey1, nodeKey2 = makeZombiePubkeys(
×
UNCOV
2792
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
×
UNCOV
2793
                        e1UpdateTime, e2UpdateTime,
×
UNCOV
2794
                )
×
2795
        }
2796

2797
        return &edgeInfo, markEdgeZombie(
3✔
2798
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2799
        )
3✔
2800
}
2801

2802
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2803
// particular pair of channel policies. The return values are one of:
2804
//  1. (pubkey1, pubkey2)
2805
//  2. (pubkey1, blank)
2806
//  3. (blank, pubkey2)
2807
//
2808
// A blank pubkey means that corresponding node will be unable to resurrect a
2809
// channel on its own. For example, node1 may continue to publish recent
2810
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2811
// we don't want another fresh update from node1 to resurrect, as the edge can
2812
// only become live once node2 finally sends something recent.
2813
//
2814
// In the case where we have neither update, we allow either party to resurrect
2815
// the channel. If the channel were to be marked zombie again, it would be
2816
// marked with the correct lagging channel since we received an update from only
2817
// one side.
2818
func makeZombiePubkeys(node1, node2 [33]byte, e1, e2 *time.Time) ([33]byte,
UNCOV
2819
        [33]byte) {
×
UNCOV
2820

×
UNCOV
2821
        switch {
×
2822
        // If we don't have either edge policy, we'll return both pubkeys so
2823
        // that the channel can be resurrected by either party.
2824
        case e1 == nil && e2 == nil:
×
2825
                return node1, node2
×
2826

2827
        // If we're missing edge1, or if both edges are present but edge1 is
2828
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2829
        // means that only an update from edge1 will be able to resurrect the
2830
        // channel.
UNCOV
2831
        case e1 == nil || (e2 != nil && e1.Before(*e2)):
×
UNCOV
2832
                return node1, [33]byte{}
×
2833

2834
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2835
        // return a blank pubkey for edge1. In this case, only an update from
2836
        // edge2 can resurect the channel.
UNCOV
2837
        default:
×
UNCOV
2838
                return [33]byte{}, node1
×
2839
        }
2840
}
2841

2842
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2843
// within the database for the referenced channel. The `flags` attribute within
2844
// the ChannelEdgePolicy determines which of the directed edges are being
2845
// updated. If the flag is 1, then the first node's information is being
2846
// updated, otherwise it's the second node's information. The node ordering is
2847
// determined by the lexicographical ordering of the identity public keys of the
2848
// nodes on either side of the channel.
2849
func (c *KVStore) UpdateEdgePolicy(ctx context.Context,
2850
        edge *models.ChannelEdgePolicy,
2851
        opts ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
3✔
2852

3✔
2853
        var (
3✔
2854
                isUpdate1    bool
3✔
2855
                edgeNotFound bool
3✔
2856
                from, to     route.Vertex
3✔
2857
        )
3✔
2858

3✔
2859
        r := &batch.Request[kvdb.RwTx]{
3✔
2860
                Opts: batch.NewSchedulerOptions(opts...),
3✔
2861
                Reset: func() {
6✔
2862
                        isUpdate1 = false
3✔
2863
                        edgeNotFound = false
3✔
2864
                },
3✔
2865
                Do: func(tx kvdb.RwTx) error {
3✔
2866
                        // Validate that the ExtraOpaqueData is in fact a valid
3✔
2867
                        // TLV stream. This is done here instead of within
3✔
2868
                        // updateEdgePolicy so that updateEdgePolicy can be used
3✔
2869
                        // by unit tests to recreate the case where we already
3✔
2870
                        // have nodes persisted with invalid TLV data.
3✔
2871
                        err := edge.ExtraOpaqueData.ValidateTLV()
3✔
2872
                        if err != nil {
3✔
UNCOV
2873
                                return fmt.Errorf("%w: %w",
×
UNCOV
2874
                                        ErrParsingExtraTLVBytes, err)
×
UNCOV
2875
                        }
×
2876

2877
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
3✔
2878
                        if err != nil {
3✔
UNCOV
2879
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
×
UNCOV
2880
                        }
×
2881

2882
                        // Silence ErrEdgeNotFound so that the batch can
2883
                        // succeed, but propagate the error via local state.
2884
                        if errors.Is(err, ErrEdgeNotFound) {
3✔
UNCOV
2885
                                edgeNotFound = true
×
UNCOV
2886
                                return nil
×
UNCOV
2887
                        }
×
2888

2889
                        return err
3✔
2890
                },
2891
                OnCommit: func(err error) error {
3✔
2892
                        switch {
3✔
UNCOV
2893
                        case err != nil:
×
UNCOV
2894
                                return err
×
UNCOV
2895
                        case edgeNotFound:
×
UNCOV
2896
                                return ErrEdgeNotFound
×
2897
                        default:
3✔
2898
                                c.updateEdgeCache(edge, isUpdate1)
3✔
2899
                                return nil
3✔
2900
                        }
2901
                },
2902
        }
2903

2904
        err := c.chanScheduler.Execute(ctx, r)
3✔
2905

3✔
2906
        return from, to, err
3✔
2907
}
2908

2909
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2910
        isUpdate1 bool) {
3✔
2911

3✔
2912
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2913
        // the entry with the updated timestamp for the direction that was just
3✔
2914
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2915
        // during the next query for this edge.
3✔
2916
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2917
                if isUpdate1 {
6✔
2918
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2919
                } else {
6✔
2920
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2921
                }
3✔
2922
                c.rejectCache.insert(e.ChannelID, entry)
3✔
2923
        }
2924

2925
        // If an entry for this channel is found in channel cache, we'll modify
2926
        // the entry with the updated policy for the direction that was just
2927
        // written. If the edge doesn't exist, we'll defer loading the info and
2928
        // policies and lazily read from disk during the next query.
2929
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
6✔
2930
                if isUpdate1 {
6✔
2931
                        channel.Policy1 = e
3✔
2932
                } else {
6✔
2933
                        channel.Policy2 = e
3✔
2934
                }
3✔
2935
                c.chanCache.insert(e.ChannelID, channel)
3✔
2936
        }
2937
}
2938

2939
// updateEdgePolicy attempts to update an edge's policy within the relevant
2940
// buckets using an existing database transaction. The returned boolean will be
2941
// true if the updated policy belongs to node1, and false if the policy belonged
2942
// to node2.
2943
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2944
        route.Vertex, route.Vertex, bool, error) {
3✔
2945

3✔
2946
        var noVertex route.Vertex
3✔
2947

3✔
2948
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2949
        if edges == nil {
3✔
2950
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2951
        }
×
2952
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2953
        if edgeIndex == nil {
3✔
2954
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2955
        }
×
2956

2957
        // Create the channelID key be converting the channel ID
2958
        // integer into a byte slice.
2959
        var chanID [8]byte
3✔
2960
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2961

3✔
2962
        // With the channel ID, we then fetch the value storing the two
3✔
2963
        // nodes which connect this channel edge.
3✔
2964
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2965
        if nodeInfo == nil {
3✔
UNCOV
2966
                return noVertex, noVertex, false, ErrEdgeNotFound
×
UNCOV
2967
        }
×
2968

2969
        // Depending on the flags value passed above, either the first
2970
        // or second edge policy is being updated.
2971
        var fromNode, toNode []byte
3✔
2972
        var isUpdate1 bool
3✔
2973
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2974
                fromNode = nodeInfo[:33]
3✔
2975
                toNode = nodeInfo[33:66]
3✔
2976
                isUpdate1 = true
3✔
2977
        } else {
6✔
2978
                fromNode = nodeInfo[33:66]
3✔
2979
                toNode = nodeInfo[:33]
3✔
2980
                isUpdate1 = false
3✔
2981
        }
3✔
2982

2983
        // Finally, with the direction of the edge being updated
2984
        // identified, we update the on-disk edge representation.
2985
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
3✔
2986
        if err != nil {
3✔
2987
                return noVertex, noVertex, false, err
×
2988
        }
×
2989

2990
        var (
3✔
2991
                fromNodePubKey route.Vertex
3✔
2992
                toNodePubKey   route.Vertex
3✔
2993
        )
3✔
2994
        copy(fromNodePubKey[:], fromNode)
3✔
2995
        copy(toNodePubKey[:], toNode)
3✔
2996

3✔
2997
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
3✔
2998
}
2999

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

3✔
3006
        // In order to determine whether this node is publicly advertised within
3✔
3007
        // the graph, we'll need to look at all of its edges and check whether
3✔
3008
        // they extend to any other node than the source node. errDone will be
3✔
3009
        // used to terminate the check early.
3✔
3010
        nodeIsPublic := false
3✔
3011
        errDone := errors.New("done")
3✔
3012
        err := c.forEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
3✔
3013
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
3✔
3014
                _ *models.ChannelEdgePolicy) error {
6✔
3015

3✔
3016
                // If this edge doesn't extend to the source node, we'll
3✔
3017
                // terminate our search as we can now conclude that the node is
3✔
3018
                // publicly advertised within the graph due to the local node
3✔
3019
                // knowing of the current edge.
3✔
3020
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
3✔
3021
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
6✔
3022

3✔
3023
                        nodeIsPublic = true
3✔
3024
                        return errDone
3✔
3025
                }
3✔
3026

3027
                // Since the edge _does_ extend to the source node, we'll also
3028
                // need to ensure that this is a public edge.
3029
                if info.AuthProof != nil {
6✔
3030
                        nodeIsPublic = true
3✔
3031
                        return errDone
3✔
3032
                }
3✔
3033

3034
                // Otherwise, we'll continue our search.
3035
                return nil
3✔
3036
        }, func() {
×
3037
                nodeIsPublic = false
×
3038
        })
×
3039
        if err != nil && !errors.Is(err, errDone) {
3✔
3040
                return false, err
×
3041
        }
×
3042

3043
        return nodeIsPublic, nil
3✔
3044
}
3045

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

3✔
3053
        return c.fetchLightningNode(tx, nodePub)
3✔
3054
}
3✔
3055

3056
// FetchLightningNode attempts to look up a target node by its identity public
3057
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3058
// returned.
3059
func (c *KVStore) FetchLightningNode(_ context.Context,
3060
        nodePub route.Vertex) (*models.LightningNode, error) {
3✔
3061

3✔
3062
        return c.fetchLightningNode(nil, nodePub)
3✔
3063
}
3✔
3064

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

3✔
3072
        var node *models.LightningNode
3✔
3073
        fetch := func(tx kvdb.RTx) error {
6✔
3074
                // First grab the nodes bucket which stores the mapping from
3✔
3075
                // pubKey to node information.
3✔
3076
                nodes := tx.ReadBucket(nodeBucket)
3✔
3077
                if nodes == nil {
3✔
3078
                        return ErrGraphNotFound
×
3079
                }
×
3080

3081
                // If a key for this serialized public key isn't found, then
3082
                // the target node doesn't exist within the database.
3083
                nodeBytes := nodes.Get(nodePub[:])
3✔
3084
                if nodeBytes == nil {
6✔
3085
                        return ErrGraphNodeNotFound
3✔
3086
                }
3✔
3087

3088
                // If the node is found, then we can de deserialize the node
3089
                // information to return to the user.
3090
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3091
                n, err := deserializeLightningNode(nodeReader)
3✔
3092
                if err != nil {
3✔
3093
                        return err
×
3094
                }
×
3095

3096
                node = &n
3✔
3097

3✔
3098
                return nil
3✔
3099
        }
3100

3101
        if tx == nil {
6✔
3102
                err := kvdb.View(
3✔
3103
                        c.db, fetch, func() {
6✔
3104
                                node = nil
3✔
3105
                        },
3✔
3106
                )
3107
                if err != nil {
6✔
3108
                        return nil, err
3✔
3109
                }
3✔
3110

3111
                return node, nil
3✔
3112
        }
3113

UNCOV
3114
        err := fetch(tx)
×
UNCOV
3115
        if err != nil {
×
UNCOV
3116
                return nil, err
×
UNCOV
3117
        }
×
3118

UNCOV
3119
        return node, nil
×
3120
}
3121

3122
// HasLightningNode determines if the graph has a vertex identified by the
3123
// target node identity public key. If the node exists in the database, a
3124
// timestamp of when the data for the node was lasted updated is returned along
3125
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3126
// boolean.
3127
func (c *KVStore) HasLightningNode(_ context.Context,
3128
        nodePub [33]byte) (time.Time, bool, error) {
3✔
3129

3✔
3130
        var (
3✔
3131
                updateTime time.Time
3✔
3132
                exists     bool
3✔
3133
        )
3✔
3134

3✔
3135
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3136
                // First grab the nodes bucket which stores the mapping from
3✔
3137
                // pubKey to node information.
3✔
3138
                nodes := tx.ReadBucket(nodeBucket)
3✔
3139
                if nodes == nil {
3✔
3140
                        return ErrGraphNotFound
×
3141
                }
×
3142

3143
                // If a key for this serialized public key isn't found, we can
3144
                // exit early.
3145
                nodeBytes := nodes.Get(nodePub[:])
3✔
3146
                if nodeBytes == nil {
6✔
3147
                        exists = false
3✔
3148
                        return nil
3✔
3149
                }
3✔
3150

3151
                // Otherwise we continue on to obtain the time stamp
3152
                // representing the last time the data for this node was
3153
                // updated.
3154
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3155
                node, err := deserializeLightningNode(nodeReader)
3✔
3156
                if err != nil {
3✔
3157
                        return err
×
3158
                }
×
3159

3160
                exists = true
3✔
3161
                updateTime = node.LastUpdate
3✔
3162

3✔
3163
                return nil
3✔
3164
        }, func() {
3✔
3165
                updateTime = time.Time{}
3✔
3166
                exists = false
3✔
3167
        })
3✔
3168
        if err != nil {
3✔
3169
                return time.Time{}, exists, err
×
3170
        }
×
3171

3172
        return updateTime, exists, nil
3✔
3173
}
3174

3175
// nodeTraversal is used to traverse all channels of a node given by its
3176
// public key and passes channel information into the specified callback.
3177
//
3178
// NOTE: the reset param is only meaningful if the tx param is nil. If it is
3179
// not nil, the caller is expected to have passed in a reset to the parent
3180
// function's View/Update call which will then apply to the whole transaction.
3181
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3182
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3183
                *models.ChannelEdgePolicy) error, reset func()) error {
3✔
3184

3✔
3185
        traversal := func(tx kvdb.RTx) error {
6✔
3186
                edges := tx.ReadBucket(edgeBucket)
3✔
3187
                if edges == nil {
3✔
3188
                        return ErrGraphNotFound
×
3189
                }
×
3190
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3191
                if edgeIndex == nil {
3✔
3192
                        return ErrGraphNoEdgesFound
×
3193
                }
×
3194

3195
                // In order to reach all the edges for this node, we take
3196
                // advantage of the construction of the key-space within the
3197
                // edge bucket. The keys are stored in the form: pubKey ||
3198
                // chanID. Therefore, starting from a chanID of zero, we can
3199
                // scan forward in the bucket, grabbing all the edges for the
3200
                // node. Once the prefix no longer matches, then we know we're
3201
                // done.
3202
                var nodeStart [33 + 8]byte
3✔
3203
                copy(nodeStart[:], nodePub)
3✔
3204
                copy(nodeStart[33:], chanStart[:])
3✔
3205

3✔
3206
                // Starting from the key pubKey || 0, we seek forward in the
3✔
3207
                // bucket until the retrieved key no longer has the public key
3✔
3208
                // as its prefix. This indicates that we've stepped over into
3✔
3209
                // another node's edges, so we can terminate our scan.
3✔
3210
                edgeCursor := edges.ReadCursor()
3✔
3211
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
6✔
3212
                        // If the prefix still matches, the channel id is
3✔
3213
                        // returned in nodeEdge. Channel id is used to lookup
3✔
3214
                        // the node at the other end of the channel and both
3✔
3215
                        // edge policies.
3✔
3216
                        chanID := nodeEdge[33:]
3✔
3217
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3218
                        if err != nil {
3✔
3219
                                return err
×
3220
                        }
×
3221

3222
                        outgoingPolicy, err := fetchChanEdgePolicy(
3✔
3223
                                edges, chanID, nodePub,
3✔
3224
                        )
3✔
3225
                        if err != nil {
3✔
3226
                                return err
×
3227
                        }
×
3228

3229
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3230
                        if err != nil {
3✔
3231
                                return err
×
3232
                        }
×
3233

3234
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3235
                                edges, chanID, otherNode[:],
3✔
3236
                        )
3✔
3237
                        if err != nil {
3✔
3238
                                return err
×
3239
                        }
×
3240

3241
                        // Finally, we execute the callback.
3242
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3243
                        if err != nil {
6✔
3244
                                return err
3✔
3245
                        }
3✔
3246
                }
3247

3248
                return nil
3✔
3249
        }
3250

3251
        // If no transaction was provided, then we'll create a new transaction
3252
        // to execute the transaction within.
3253
        if tx == nil {
6✔
3254
                return kvdb.View(db, traversal, reset)
3✔
3255
        }
3✔
3256

3257
        // Otherwise, we re-use the existing transaction to execute the graph
3258
        // traversal.
3259
        return traversal(tx)
3✔
3260
}
3261

3262
// ForEachNodeChannel iterates through all channels of the given node,
3263
// executing the passed callback with an edge info structure and the policies
3264
// of each end of the channel. The first edge policy is the outgoing edge *to*
3265
// the connecting node, while the second is the incoming edge *from* the
3266
// connecting node. If the callback returns an error, then the iteration is
3267
// halted with the error propagated back up to the caller.
3268
//
3269
// Unknown policies are passed into the callback as nil values.
3270
func (c *KVStore) ForEachNodeChannel(_ context.Context, nodePub route.Vertex,
3271
        cb func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3272
                *models.ChannelEdgePolicy) error, reset func()) error {
3✔
3273

3✔
3274
        return nodeTraversal(
3✔
3275
                nil, nodePub[:], c.db, func(_ kvdb.RTx,
3✔
3276
                        info *models.ChannelEdgeInfo, policy,
3✔
3277
                        policy2 *models.ChannelEdgePolicy) error {
6✔
3278

3✔
3279
                        return cb(info, policy, policy2)
3✔
3280
                }, reset,
3✔
3281
        )
3282
}
3283

3284
// ForEachSourceNodeChannel iterates through all channels of the source node,
3285
// executing the passed callback on each. The callback is provided with the
3286
// channel's outpoint, whether we have a policy for the channel and the channel
3287
// peer's node information.
3288
func (c *KVStore) ForEachSourceNodeChannel(_ context.Context,
3289
        cb func(chanPoint wire.OutPoint, havePolicy bool,
3290
                otherNode *models.LightningNode) error, reset func()) error {
3✔
3291

3✔
3292
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3293
                nodes := tx.ReadBucket(nodeBucket)
3✔
3294
                if nodes == nil {
3✔
3295
                        return ErrGraphNotFound
×
3296
                }
×
3297

3298
                node, err := sourceNodeWithTx(nodes)
3✔
3299
                if err != nil {
3✔
3300
                        return err
×
3301
                }
×
3302

3303
                return nodeTraversal(
3✔
3304
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
3✔
3305
                                info *models.ChannelEdgeInfo,
3✔
3306
                                policy, _ *models.ChannelEdgePolicy) error {
6✔
3307

3✔
3308
                                peer, err := c.fetchOtherNode(
3✔
3309
                                        tx, info, node.PubKeyBytes[:],
3✔
3310
                                )
3✔
3311
                                if err != nil {
3✔
3312
                                        return err
×
3313
                                }
×
3314

3315
                                return cb(
3✔
3316
                                        info.ChannelPoint, policy != nil, peer,
3✔
3317
                                )
3✔
3318
                        }, reset,
3319
                )
3320
        }, reset)
3321
}
3322

3323
// forEachNodeChannelTx iterates through all channels of the given node,
3324
// executing the passed callback with an edge info structure and the policies
3325
// of each end of the channel. The first edge policy is the outgoing edge *to*
3326
// the connecting node, while the second is the incoming edge *from* the
3327
// connecting node. If the callback returns an error, then the iteration is
3328
// halted with the error propagated back up to the caller.
3329
//
3330
// Unknown policies are passed into the callback as nil values.
3331
//
3332
// If the caller wishes to re-use an existing boltdb transaction, then it
3333
// should be passed as the first argument.  Otherwise, the first argument should
3334
// be nil and a fresh transaction will be created to execute the graph
3335
// traversal.
3336
//
3337
// NOTE: the reset function is only meaningful if the tx param is nil.
3338
func (c *KVStore) forEachNodeChannelTx(tx kvdb.RTx,
3339
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3340
                *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error,
3341
        reset func()) error {
3✔
3342

3✔
3343
        return nodeTraversal(tx, nodePub[:], c.db, cb, reset)
3✔
3344
}
3✔
3345

3346
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3347
// the target node in the channel. This is useful when one knows the pubkey of
3348
// one of the nodes, and wishes to obtain the full LightningNode for the other
3349
// end of the channel.
3350
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3351
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3352
        *models.LightningNode, error) {
3✔
3353

3✔
3354
        // Ensure that the node passed in is actually a member of the channel.
3✔
3355
        var targetNodeBytes [33]byte
3✔
3356
        switch {
3✔
3357
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3358
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3359
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3360
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3361
        default:
×
3362
                return nil, fmt.Errorf("node not participating in this channel")
×
3363
        }
3364

3365
        var targetNode *models.LightningNode
3✔
3366
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3367
                // First grab the nodes bucket which stores the mapping from
3✔
3368
                // pubKey to node information.
3✔
3369
                nodes := tx.ReadBucket(nodeBucket)
3✔
3370
                if nodes == nil {
3✔
3371
                        return ErrGraphNotFound
×
3372
                }
×
3373

3374
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3375
                if err != nil {
3✔
3376
                        return err
×
3377
                }
×
3378

3379
                targetNode = &node
3✔
3380

3✔
3381
                return nil
3✔
3382
        }
3383

3384
        // If the transaction is nil, then we'll need to create a new one,
3385
        // otherwise we can use the existing db transaction.
3386
        var err error
3✔
3387
        if tx == nil {
3✔
3388
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3389
                        targetNode = nil
×
3390
                })
×
3391
        } else {
3✔
3392
                err = fetchNodeFunc(tx)
3✔
3393
        }
3✔
3394

3395
        return targetNode, err
3✔
3396
}
3397

3398
// computeEdgePolicyKeys is a helper function that can be used to compute the
3399
// keys used to index the channel edge policy info for the two nodes of the
3400
// edge. The keys for node 1 and node 2 are returned respectively.
3401
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3✔
3402
        var (
3✔
3403
                node1Key [33 + 8]byte
3✔
3404
                node2Key [33 + 8]byte
3✔
3405
        )
3✔
3406

3✔
3407
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3408
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3409

3✔
3410
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3411
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3412

3✔
3413
        return node1Key[:], node2Key[:]
3✔
3414
}
3✔
3415

3416
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3417
// the channel identified by the funding outpoint. If the channel can't be
3418
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3419
// information for the channel itself is returned as well as two structs that
3420
// contain the routing policies for the channel in either direction.
3421
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3422
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3423
        *models.ChannelEdgePolicy, error) {
3✔
3424

3✔
3425
        var (
3✔
3426
                edgeInfo *models.ChannelEdgeInfo
3✔
3427
                policy1  *models.ChannelEdgePolicy
3✔
3428
                policy2  *models.ChannelEdgePolicy
3✔
3429
        )
3✔
3430

3✔
3431
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3432
                // First, grab the node bucket. This will be used to populate
3✔
3433
                // the Node pointers in each edge read from disk.
3✔
3434
                nodes := tx.ReadBucket(nodeBucket)
3✔
3435
                if nodes == nil {
3✔
3436
                        return ErrGraphNotFound
×
3437
                }
×
3438

3439
                // Next, grab the edge bucket which stores the edges, and also
3440
                // the index itself so we can group the directed edges together
3441
                // logically.
3442
                edges := tx.ReadBucket(edgeBucket)
3✔
3443
                if edges == nil {
3✔
3444
                        return ErrGraphNoEdgesFound
×
3445
                }
×
3446
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3447
                if edgeIndex == nil {
3✔
3448
                        return ErrGraphNoEdgesFound
×
3449
                }
×
3450

3451
                // If the channel's outpoint doesn't exist within the outpoint
3452
                // index, then the edge does not exist.
3453
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3454
                if chanIndex == nil {
3✔
3455
                        return ErrGraphNoEdgesFound
×
3456
                }
×
3457
                var b bytes.Buffer
3✔
3458
                if err := WriteOutpoint(&b, op); err != nil {
3✔
3459
                        return err
×
3460
                }
×
3461
                chanID := chanIndex.Get(b.Bytes())
3✔
3462
                if chanID == nil {
6✔
3463
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3464
                }
3✔
3465

3466
                // If the channel is found to exists, then we'll first retrieve
3467
                // the general information for the channel.
3468
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3469
                if err != nil {
3✔
3470
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3471
                }
×
3472
                edgeInfo = &edge
3✔
3473

3✔
3474
                // Once we have the information about the channels' parameters,
3✔
3475
                // we'll fetch the routing policies for each for the directed
3✔
3476
                // edges.
3✔
3477
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3478
                if err != nil {
3✔
3479
                        return fmt.Errorf("failed to find policy: %w", err)
×
3480
                }
×
3481

3482
                policy1 = e1
3✔
3483
                policy2 = e2
3✔
3484

3✔
3485
                return nil
3✔
3486
        }, func() {
3✔
3487
                edgeInfo = nil
3✔
3488
                policy1 = nil
3✔
3489
                policy2 = nil
3✔
3490
        })
3✔
3491
        if err != nil {
6✔
3492
                return nil, nil, nil, err
3✔
3493
        }
3✔
3494

3495
        return edgeInfo, policy1, policy2, nil
3✔
3496
}
3497

3498
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3499
// channel identified by the channel ID. If the channel can't be found, then
3500
// ErrEdgeNotFound is returned. A struct which houses the general information
3501
// for the channel itself is returned as well as two structs that contain the
3502
// routing policies for the channel in either direction.
3503
//
3504
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3505
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3506
// the ChannelEdgeInfo will only include the public keys of each node.
3507
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3508
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3509
        *models.ChannelEdgePolicy, error) {
3✔
3510

3✔
3511
        var (
3✔
3512
                edgeInfo  *models.ChannelEdgeInfo
3✔
3513
                policy1   *models.ChannelEdgePolicy
3✔
3514
                policy2   *models.ChannelEdgePolicy
3✔
3515
                channelID [8]byte
3✔
3516
        )
3✔
3517

3✔
3518
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3519
                // First, grab the node bucket. This will be used to populate
3✔
3520
                // the Node pointers in each edge read from disk.
3✔
3521
                nodes := tx.ReadBucket(nodeBucket)
3✔
3522
                if nodes == nil {
3✔
3523
                        return ErrGraphNotFound
×
3524
                }
×
3525

3526
                // Next, grab the edge bucket which stores the edges, and also
3527
                // the index itself so we can group the directed edges together
3528
                // logically.
3529
                edges := tx.ReadBucket(edgeBucket)
3✔
3530
                if edges == nil {
3✔
3531
                        return ErrGraphNoEdgesFound
×
3532
                }
×
3533
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3534
                if edgeIndex == nil {
3✔
3535
                        return ErrGraphNoEdgesFound
×
3536
                }
×
3537

3538
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3539

3✔
3540
                // Now, attempt to fetch edge.
3✔
3541
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3542

3✔
3543
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3544
                // see if we've previously marked it as so.
3✔
3545
                if errors.Is(err, ErrEdgeNotFound) {
6✔
3546
                        // If the zombie index doesn't exist, or the edge is not
3✔
3547
                        // marked as a zombie within it, then we'll return the
3✔
3548
                        // original ErrEdgeNotFound error.
3✔
3549
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3550
                        if zombieIndex == nil {
3✔
3551
                                return ErrEdgeNotFound
×
3552
                        }
×
3553

3554
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3555
                                zombieIndex, chanID,
3✔
3556
                        )
3✔
3557
                        if !isZombie {
6✔
3558
                                return ErrEdgeNotFound
3✔
3559
                        }
3✔
3560

3561
                        // Otherwise, the edge is marked as a zombie, so we'll
3562
                        // populate the edge info with the public keys of each
3563
                        // party as this is the only information we have about
3564
                        // it and return an error signaling so.
3565
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3566
                                NodeKey1Bytes: pubKey1,
3✔
3567
                                NodeKey2Bytes: pubKey2,
3✔
3568
                        }
3✔
3569

3✔
3570
                        return ErrZombieEdge
3✔
3571
                }
3572

3573
                // Otherwise, we'll just return the error if any.
3574
                if err != nil {
3✔
3575
                        return err
×
3576
                }
×
3577

3578
                edgeInfo = &edge
3✔
3579

3✔
3580
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3581
                // edge.
3✔
3582
                e1, e2, err := fetchChanEdgePolicies(
3✔
3583
                        edgeIndex, edges, channelID[:],
3✔
3584
                )
3✔
3585
                if err != nil {
3✔
3586
                        return err
×
3587
                }
×
3588

3589
                policy1 = e1
3✔
3590
                policy2 = e2
3✔
3591

3✔
3592
                return nil
3✔
3593
        }, func() {
3✔
3594
                edgeInfo = nil
3✔
3595
                policy1 = nil
3✔
3596
                policy2 = nil
3✔
3597
        })
3✔
3598
        if errors.Is(err, ErrZombieEdge) {
6✔
3599
                return edgeInfo, nil, nil, err
3✔
3600
        }
3✔
3601
        if err != nil {
6✔
3602
                return nil, nil, nil, err
3✔
3603
        }
3✔
3604

3605
        return edgeInfo, policy1, policy2, nil
3✔
3606
}
3607

3608
// IsPublicNode is a helper method that determines whether the node with the
3609
// given public key is seen as a public node in the graph from the graph's
3610
// source node's point of view.
3611
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3612
        var nodeIsPublic bool
3✔
3613
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3614
                nodes := tx.ReadBucket(nodeBucket)
3✔
3615
                if nodes == nil {
3✔
3616
                        return ErrGraphNodesNotFound
×
3617
                }
×
3618
                ourPubKey := nodes.Get(sourceKey)
3✔
3619
                if ourPubKey == nil {
3✔
3620
                        return ErrSourceNodeNotSet
×
3621
                }
×
3622
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3623
                if err != nil {
3✔
3624
                        return err
×
3625
                }
×
3626

3627
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3628

3✔
3629
                return err
3✔
3630
        }, func() {
3✔
3631
                nodeIsPublic = false
3✔
3632
        })
3✔
3633
        if err != nil {
3✔
3634
                return false, err
×
3635
        }
×
3636

3637
        return nodeIsPublic, nil
3✔
3638
}
3639

3640
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3641
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3642
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3643
        if err != nil {
3✔
3644
                return nil, err
×
3645
        }
×
3646

3647
        // With the witness script generated, we'll now turn it into a p2wsh
3648
        // script:
3649
        //  * OP_0 <sha256(script)>
3650
        bldr := txscript.NewScriptBuilder(
3✔
3651
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3652
        )
3✔
3653
        bldr.AddOp(txscript.OP_0)
3✔
3654
        scriptHash := sha256.Sum256(witnessScript)
3✔
3655
        bldr.AddData(scriptHash[:])
3✔
3656

3✔
3657
        return bldr.Script()
3✔
3658
}
3659

3660
// EdgePoint couples the outpoint of a channel with the funding script that it
3661
// creates. The FilteredChainView will use this to watch for spends of this
3662
// edge point on chain. We require both of these values as depending on the
3663
// concrete implementation, either the pkScript, or the out point will be used.
3664
type EdgePoint struct {
3665
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3666
        FundingPkScript []byte
3667

3668
        // OutPoint is the outpoint of the target channel.
3669
        OutPoint wire.OutPoint
3670
}
3671

3672
// String returns a human readable version of the target EdgePoint. We return
3673
// the outpoint directly as it is enough to uniquely identify the edge point.
3674
func (e *EdgePoint) String() string {
×
3675
        return e.OutPoint.String()
×
3676
}
×
3677

3678
// ChannelView returns the verifiable edge information for each active channel
3679
// within the known channel graph. The set of UTXO's (along with their scripts)
3680
// returned are the ones that need to be watched on chain to detect channel
3681
// closes on the resident blockchain.
3682
func (c *KVStore) ChannelView() ([]EdgePoint, error) {
3✔
3683
        var edgePoints []EdgePoint
3✔
3684
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3685
                // We're going to iterate over the entire channel index, so
3✔
3686
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3687
                // it's a sub-bucket.
3✔
3688
                edges := tx.ReadBucket(edgeBucket)
3✔
3689
                if edges == nil {
3✔
3690
                        return ErrGraphNoEdgesFound
×
3691
                }
×
3692
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3693
                if chanIndex == nil {
3✔
3694
                        return ErrGraphNoEdgesFound
×
3695
                }
×
3696
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3697
                if edgeIndex == nil {
3✔
3698
                        return ErrGraphNoEdgesFound
×
3699
                }
×
3700

3701
                // Once we have the proper bucket, we'll range over each key
3702
                // (which is the channel point for the channel) and decode it,
3703
                // accumulating each entry.
3704
                return chanIndex.ForEach(
3✔
3705
                        func(chanPointBytes, chanID []byte) error {
6✔
3706
                                chanPointReader := bytes.NewReader(
3✔
3707
                                        chanPointBytes,
3✔
3708
                                )
3✔
3709

3✔
3710
                                var chanPoint wire.OutPoint
3✔
3711
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3712
                                if err != nil {
3✔
3713
                                        return err
×
3714
                                }
×
3715

3716
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3717
                                        edgeIndex, chanID,
3✔
3718
                                )
3✔
3719
                                if err != nil {
3✔
3720
                                        return err
×
3721
                                }
×
3722

3723
                                pkScript, err := genMultiSigP2WSH(
3✔
3724
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3725
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3726
                                )
3✔
3727
                                if err != nil {
3✔
3728
                                        return err
×
3729
                                }
×
3730

3731
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3732
                                        FundingPkScript: pkScript,
3✔
3733
                                        OutPoint:        chanPoint,
3✔
3734
                                })
3✔
3735

3✔
3736
                                return nil
3✔
3737
                        },
3738
                )
3739
        }, func() {
3✔
3740
                edgePoints = nil
3✔
3741
        }); err != nil {
3✔
3742
                return nil, err
×
3743
        }
×
3744

3745
        return edgePoints, nil
3✔
3746
}
3747

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

×
UNCOV
3754
        c.cacheMu.Lock()
×
UNCOV
3755
        defer c.cacheMu.Unlock()
×
UNCOV
3756

×
UNCOV
3757
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3758
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3759
                if edges == nil {
×
3760
                        return ErrGraphNoEdgesFound
×
3761
                }
×
UNCOV
3762
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
UNCOV
3763
                if err != nil {
×
3764
                        return fmt.Errorf("unable to create zombie "+
×
3765
                                "bucket: %w", err)
×
3766
                }
×
3767

UNCOV
3768
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3769
        })
UNCOV
3770
        if err != nil {
×
3771
                return err
×
3772
        }
×
3773

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

×
UNCOV
3777
        return nil
×
3778
}
3779

3780
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3781
// keys should represent the node public keys of the two parties involved in the
3782
// edge.
3783
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3784
        pubKey2 [33]byte) error {
3✔
3785

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

3✔
3789
        var v [66]byte
3✔
3790
        copy(v[:33], pubKey1[:])
3✔
3791
        copy(v[33:], pubKey2[:])
3✔
3792

3✔
3793
        return zombieIndex.Put(k[:], v[:])
3✔
3794
}
3✔
3795

3796
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
UNCOV
3797
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
UNCOV
3798
        c.cacheMu.Lock()
×
UNCOV
3799
        defer c.cacheMu.Unlock()
×
UNCOV
3800

×
UNCOV
3801
        return c.markEdgeLiveUnsafe(nil, chanID)
×
UNCOV
3802
}
×
3803

3804
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3805
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3806
// case a new transaction will be created.
3807
//
3808
// NOTE: this method MUST only be called if the cacheMu has already been
3809
// acquired.
UNCOV
3810
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
UNCOV
3811
        dbFn := func(tx kvdb.RwTx) error {
×
UNCOV
3812
                edges := tx.ReadWriteBucket(edgeBucket)
×
UNCOV
3813
                if edges == nil {
×
3814
                        return ErrGraphNoEdgesFound
×
3815
                }
×
UNCOV
3816
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
×
UNCOV
3817
                if zombieIndex == nil {
×
3818
                        return nil
×
3819
                }
×
3820

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

×
UNCOV
3824
                if len(zombieIndex.Get(k[:])) == 0 {
×
UNCOV
3825
                        return ErrZombieEdgeNotFound
×
UNCOV
3826
                }
×
3827

UNCOV
3828
                return zombieIndex.Delete(k[:])
×
3829
        }
3830

3831
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3832
        // the existing transaction
UNCOV
3833
        var err error
×
UNCOV
3834
        if tx == nil {
×
UNCOV
3835
                err = kvdb.Update(c.db, dbFn, func() {})
×
3836
        } else {
×
3837
                err = dbFn(tx)
×
3838
        }
×
UNCOV
3839
        if err != nil {
×
UNCOV
3840
                return err
×
UNCOV
3841
        }
×
3842

UNCOV
3843
        c.rejectCache.remove(chanID)
×
UNCOV
3844
        c.chanCache.remove(chanID)
×
UNCOV
3845

×
UNCOV
3846
        return nil
×
3847
}
3848

3849
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3850
// zombie, then the two node public keys corresponding to this edge are also
3851
// returned.
3852
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte,
UNCOV
3853
        error) {
×
UNCOV
3854

×
UNCOV
3855
        var (
×
UNCOV
3856
                isZombie         bool
×
UNCOV
3857
                pubKey1, pubKey2 [33]byte
×
UNCOV
3858
        )
×
UNCOV
3859

×
UNCOV
3860
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3861
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3862
                if edges == nil {
×
3863
                        return ErrGraphNoEdgesFound
×
3864
                }
×
UNCOV
3865
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3866
                if zombieIndex == nil {
×
3867
                        return nil
×
3868
                }
×
3869

UNCOV
3870
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
UNCOV
3871

×
UNCOV
3872
                return nil
×
UNCOV
3873
        }, func() {
×
UNCOV
3874
                isZombie = false
×
UNCOV
3875
                pubKey1 = [33]byte{}
×
UNCOV
3876
                pubKey2 = [33]byte{}
×
UNCOV
3877
        })
×
UNCOV
3878
        if err != nil {
×
3879
                return false, [33]byte{}, [33]byte{}, fmt.Errorf("%w: %w "+
×
3880
                        "(chanID=%d)", ErrCantCheckIfZombieEdgeStr, err, chanID)
×
3881
        }
×
3882

UNCOV
3883
        return isZombie, pubKey1, pubKey2, nil
×
3884
}
3885

3886
// isZombieEdge returns whether an entry exists for the given channel in the
3887
// zombie index. If an entry exists, then the two node public keys corresponding
3888
// to this edge are also returned.
3889
func isZombieEdge(zombieIndex kvdb.RBucket,
3890
        chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3891

3✔
3892
        var k [8]byte
3✔
3893
        byteOrder.PutUint64(k[:], chanID)
3✔
3894

3✔
3895
        v := zombieIndex.Get(k[:])
3✔
3896
        if v == nil {
6✔
3897
                return false, [33]byte{}, [33]byte{}
3✔
3898
        }
3✔
3899

3900
        var pubKey1, pubKey2 [33]byte
3✔
3901
        copy(pubKey1[:], v[:33])
3✔
3902
        copy(pubKey2[:], v[33:])
3✔
3903

3✔
3904
        return true, pubKey1, pubKey2
3✔
3905
}
3906

3907
// NumZombies returns the current number of zombie channels in the graph.
UNCOV
3908
func (c *KVStore) NumZombies() (uint64, error) {
×
UNCOV
3909
        var numZombies uint64
×
UNCOV
3910
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3911
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3912
                if edges == nil {
×
3913
                        return nil
×
3914
                }
×
UNCOV
3915
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
UNCOV
3916
                if zombieIndex == nil {
×
3917
                        return nil
×
3918
                }
×
3919

UNCOV
3920
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
UNCOV
3921
                        numZombies++
×
UNCOV
3922
                        return nil
×
UNCOV
3923
                })
×
UNCOV
3924
        }, func() {
×
UNCOV
3925
                numZombies = 0
×
UNCOV
3926
        })
×
UNCOV
3927
        if err != nil {
×
3928
                return 0, err
×
3929
        }
×
3930

UNCOV
3931
        return numZombies, nil
×
3932
}
3933

3934
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3935
// that we can ignore channel announcements that we know to be closed without
3936
// having to validate them and fetch a block.
UNCOV
3937
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
×
UNCOV
3938
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
UNCOV
3939
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
UNCOV
3940
                if err != nil {
×
3941
                        return err
×
3942
                }
×
3943

UNCOV
3944
                var k [8]byte
×
UNCOV
3945
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
UNCOV
3946

×
UNCOV
3947
                return closedScids.Put(k[:], []byte{})
×
UNCOV
3948
        }, func() {})
×
3949
}
3950

3951
// IsClosedScid checks whether a channel identified by the passed in scid is
3952
// closed. This helps avoid having to perform expensive validation checks.
3953
// TODO: Add an LRU cache to cut down on disc reads.
3954
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3955
        var isClosed bool
3✔
3956
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3957
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3958
                if closedScids == nil {
3✔
3959
                        return ErrClosedScidsNotFound
×
3960
                }
×
3961

3962
                var k [8]byte
3✔
3963
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3964

3✔
3965
                if closedScids.Get(k[:]) != nil {
3✔
UNCOV
3966
                        isClosed = true
×
UNCOV
3967
                        return nil
×
UNCOV
3968
                }
×
3969

3970
                return nil
3✔
3971
        }, func() {
3✔
3972
                isClosed = false
3✔
3973
        })
3✔
3974
        if err != nil {
3✔
3975
                return false, err
×
3976
        }
×
3977

3978
        return isClosed, nil
3✔
3979
}
3980

3981
// GraphSession will provide the call-back with access to a NodeTraverser
3982
// instance which can be used to perform queries against the channel graph.
3983
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error,
UNCOV
3984
        reset func()) error {
×
UNCOV
3985

×
UNCOV
3986
        return c.db.View(func(tx walletdb.ReadTx) error {
×
UNCOV
3987
                return cb(&nodeTraverserSession{
×
UNCOV
3988
                        db: c,
×
UNCOV
3989
                        tx: tx,
×
UNCOV
3990
                })
×
UNCOV
3991
        }, reset)
×
3992
}
3993

3994
// nodeTraverserSession implements the NodeTraverser interface but with a
3995
// backing read only transaction for a consistent view of the graph.
3996
type nodeTraverserSession struct {
3997
        tx kvdb.RTx
3998
        db *KVStore
3999
}
4000

4001
// ForEachNodeDirectedChannel calls the callback for every channel of the given
4002
// node.
4003
//
4004
// NOTE: Part of the NodeTraverser interface.
4005
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
UNCOV
4006
        cb func(channel *DirectedChannel) error, _ func()) error {
×
UNCOV
4007

×
UNCOV
4008
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb, func() {})
×
4009
}
4010

4011
// FetchNodeFeatures returns the features of the given node. If the node is
4012
// unknown, assume no additional features are supported.
4013
//
4014
// NOTE: Part of the NodeTraverser interface.
4015
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
UNCOV
4016
        *lnwire.FeatureVector, error) {
×
UNCOV
4017

×
UNCOV
4018
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
UNCOV
4019
}
×
4020

4021
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
4022
        node *models.LightningNode) error {
3✔
4023

3✔
4024
        var (
3✔
4025
                scratch [16]byte
3✔
4026
                b       bytes.Buffer
3✔
4027
        )
3✔
4028

3✔
4029
        pub, err := node.PubKey()
3✔
4030
        if err != nil {
3✔
4031
                return err
×
4032
        }
×
4033
        nodePub := pub.SerializeCompressed()
3✔
4034

3✔
4035
        // If the node has the update time set, write it, else write 0.
3✔
4036
        updateUnix := uint64(0)
3✔
4037
        if node.LastUpdate.Unix() > 0 {
6✔
4038
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
4039
        }
3✔
4040

4041
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
4042
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
4043
                return err
×
4044
        }
×
4045

4046
        if _, err := b.Write(nodePub); err != nil {
3✔
4047
                return err
×
4048
        }
×
4049

4050
        // If we got a node announcement for this node, we will have the rest
4051
        // of the data available. If not we don't have more data to write.
4052
        if !node.HaveNodeAnnouncement {
6✔
4053
                // Write HaveNodeAnnouncement=0.
3✔
4054
                byteOrder.PutUint16(scratch[:2], 0)
3✔
4055
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
4056
                        return err
×
4057
                }
×
4058

4059
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
4060
        }
4061

4062
        // Write HaveNodeAnnouncement=1.
4063
        byteOrder.PutUint16(scratch[:2], 1)
3✔
4064
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4065
                return err
×
4066
        }
×
4067

4068
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
4069
                return err
×
4070
        }
×
4071
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
4072
                return err
×
4073
        }
×
4074
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
4075
                return err
×
4076
        }
×
4077

4078
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
4079
                return err
×
4080
        }
×
4081

4082
        if err := node.Features.Encode(&b); err != nil {
3✔
4083
                return err
×
4084
        }
×
4085

4086
        numAddresses := uint16(len(node.Addresses))
3✔
4087
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
4088
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4089
                return err
×
4090
        }
×
4091

4092
        for _, address := range node.Addresses {
6✔
4093
                if err := SerializeAddr(&b, address); err != nil {
3✔
4094
                        return err
×
4095
                }
×
4096
        }
4097

4098
        sigLen := len(node.AuthSigBytes)
3✔
4099
        if sigLen > 80 {
3✔
4100
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4101
                        sigLen)
×
4102
        }
×
4103

4104
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
4105
        if err != nil {
3✔
4106
                return err
×
4107
        }
×
4108

4109
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4110
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4111
        }
×
4112
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
4113
        if err != nil {
3✔
4114
                return err
×
4115
        }
×
4116

4117
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
4118
                return err
×
4119
        }
×
4120

4121
        // With the alias bucket updated, we'll now update the index that
4122
        // tracks the time series of node updates.
4123
        var indexKey [8 + 33]byte
3✔
4124
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4125
        copy(indexKey[8:], nodePub)
3✔
4126

3✔
4127
        // If there was already an old index entry for this node, then we'll
3✔
4128
        // delete the old one before we write the new entry.
3✔
4129
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
6✔
4130
                // Extract out the old update time to we can reconstruct the
3✔
4131
                // prior index key to delete it from the index.
3✔
4132
                oldUpdateTime := nodeBytes[:8]
3✔
4133

3✔
4134
                var oldIndexKey [8 + 33]byte
3✔
4135
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
4136
                copy(oldIndexKey[8:], nodePub)
3✔
4137

3✔
4138
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4139
                        return err
×
4140
                }
×
4141
        }
4142

4143
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4144
                return err
×
4145
        }
×
4146

4147
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
4148
}
4149

4150
func fetchLightningNode(nodeBucket kvdb.RBucket,
4151
        nodePub []byte) (models.LightningNode, error) {
3✔
4152

3✔
4153
        nodeBytes := nodeBucket.Get(nodePub)
3✔
4154
        if nodeBytes == nil {
6✔
4155
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
4156
        }
3✔
4157

4158
        nodeReader := bytes.NewReader(nodeBytes)
3✔
4159

3✔
4160
        return deserializeLightningNode(nodeReader)
3✔
4161
}
4162

4163
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4164
        *lnwire.FeatureVector, error) {
3✔
4165

3✔
4166
        var (
3✔
4167
                pubKey      route.Vertex
3✔
4168
                features    = lnwire.EmptyFeatureVector()
3✔
4169
                nodeScratch [8]byte
3✔
4170
        )
3✔
4171

3✔
4172
        // Skip ahead:
3✔
4173
        // - LastUpdate (8 bytes)
3✔
4174
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
4175
                return pubKey, nil, err
×
4176
        }
×
4177

4178
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
4179
                return pubKey, nil, err
×
4180
        }
×
4181

4182
        // Read the node announcement flag.
4183
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
4184
                return pubKey, nil, err
×
4185
        }
×
4186
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4187

3✔
4188
        // The rest of the data is optional, and will only be there if we got a
3✔
4189
        // node announcement for this node.
3✔
4190
        if hasNodeAnn == 0 {
6✔
4191
                return pubKey, features, nil
3✔
4192
        }
3✔
4193

4194
        // We did get a node announcement for this node, so we'll have the rest
4195
        // of the data available.
4196
        var rgb uint8
3✔
4197
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4198
                return pubKey, nil, err
×
4199
        }
×
4200
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4201
                return pubKey, nil, err
×
4202
        }
×
4203
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4204
                return pubKey, nil, err
×
4205
        }
×
4206

4207
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4208
                return pubKey, nil, err
×
4209
        }
×
4210

4211
        if err := features.Decode(r); err != nil {
3✔
4212
                return pubKey, nil, err
×
4213
        }
×
4214

4215
        return pubKey, features, nil
3✔
4216
}
4217

4218
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4219
        var (
3✔
4220
                node    models.LightningNode
3✔
4221
                scratch [8]byte
3✔
4222
                err     error
3✔
4223
        )
3✔
4224

3✔
4225
        // Always populate a feature vector, even if we don't have a node
3✔
4226
        // announcement and short circuit below.
3✔
4227
        node.Features = lnwire.EmptyFeatureVector()
3✔
4228

3✔
4229
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4230
                return models.LightningNode{}, err
×
4231
        }
×
4232

4233
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4234
        node.LastUpdate = time.Unix(unix, 0)
3✔
4235

3✔
4236
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4237
                return models.LightningNode{}, err
×
4238
        }
×
4239

4240
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4241
                return models.LightningNode{}, err
×
4242
        }
×
4243

4244
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4245
        if hasNodeAnn == 1 {
6✔
4246
                node.HaveNodeAnnouncement = true
3✔
4247
        } else {
6✔
4248
                node.HaveNodeAnnouncement = false
3✔
4249
        }
3✔
4250

4251
        // The rest of the data is optional, and will only be there if we got a
4252
        // node announcement for this node.
4253
        if !node.HaveNodeAnnouncement {
6✔
4254
                return node, nil
3✔
4255
        }
3✔
4256

4257
        // We did get a node announcement for this node, so we'll have the rest
4258
        // of the data available.
4259
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
3✔
4260
                return models.LightningNode{}, err
×
4261
        }
×
4262
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
3✔
4263
                return models.LightningNode{}, err
×
4264
        }
×
4265
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4266
                return models.LightningNode{}, err
×
4267
        }
×
4268

4269
        node.Alias, err = wire.ReadVarString(r, 0)
3✔
4270
        if err != nil {
3✔
4271
                return models.LightningNode{}, err
×
4272
        }
×
4273

4274
        err = node.Features.Decode(r)
3✔
4275
        if err != nil {
3✔
4276
                return models.LightningNode{}, err
×
4277
        }
×
4278

4279
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4280
                return models.LightningNode{}, err
×
4281
        }
×
4282
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4283

3✔
4284
        var addresses []net.Addr
3✔
4285
        for i := 0; i < numAddresses; i++ {
6✔
4286
                address, err := DeserializeAddr(r)
3✔
4287
                if err != nil {
3✔
4288
                        return models.LightningNode{}, err
×
4289
                }
×
4290
                addresses = append(addresses, address)
3✔
4291
        }
4292
        node.Addresses = addresses
3✔
4293

3✔
4294
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4295
        if err != nil {
3✔
4296
                return models.LightningNode{}, err
×
4297
        }
×
4298

4299
        // We'll try and see if there are any opaque bytes left, if not, then
4300
        // we'll ignore the EOF error and return the node as is.
4301
        extraBytes, err := wire.ReadVarBytes(
3✔
4302
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4303
        )
3✔
4304
        switch {
3✔
4305
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4306
        case errors.Is(err, io.EOF):
×
4307
        case err != nil:
×
4308
                return models.LightningNode{}, err
×
4309
        }
4310

4311
        if len(extraBytes) > 0 {
3✔
UNCOV
4312
                node.ExtraOpaqueData = extraBytes
×
UNCOV
4313
        }
×
4314

4315
        return node, nil
3✔
4316
}
4317

4318
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4319
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4320

3✔
4321
        var b bytes.Buffer
3✔
4322

3✔
4323
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4324
                return err
×
4325
        }
×
4326
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4327
                return err
×
4328
        }
×
4329
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4330
                return err
×
4331
        }
×
4332
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4333
                return err
×
4334
        }
×
4335

4336
        var featureBuf bytes.Buffer
3✔
4337
        if err := edgeInfo.Features.Encode(&featureBuf); err != nil {
3✔
4338
                return fmt.Errorf("unable to encode features: %w", err)
×
4339
        }
×
4340

4341
        if err := wire.WriteVarBytes(&b, 0, featureBuf.Bytes()); err != nil {
3✔
4342
                return err
×
4343
        }
×
4344

4345
        authProof := edgeInfo.AuthProof
3✔
4346
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4347
        if authProof != nil {
6✔
4348
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4349
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4350
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4351
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4352
        }
3✔
4353

4354
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4355
                return err
×
4356
        }
×
4357
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4358
                return err
×
4359
        }
×
4360
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4361
                return err
×
4362
        }
×
4363
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4364
                return err
×
4365
        }
×
4366

4367
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4368
                return err
×
4369
        }
×
4370
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
3✔
4371
        if err != nil {
3✔
4372
                return err
×
4373
        }
×
4374
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4375
                return err
×
4376
        }
×
4377
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4378
                return err
×
4379
        }
×
4380

4381
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4382
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4383
        }
×
4384
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4385
        if err != nil {
3✔
4386
                return err
×
4387
        }
×
4388

4389
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4390
}
4391

4392
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4393
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4394

3✔
4395
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4396
        if edgeInfoBytes == nil {
6✔
4397
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4398
        }
3✔
4399

4400
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4401

3✔
4402
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4403
}
4404

4405
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4406
        var (
3✔
4407
                err      error
3✔
4408
                edgeInfo models.ChannelEdgeInfo
3✔
4409
        )
3✔
4410

3✔
4411
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4412
                return models.ChannelEdgeInfo{}, err
×
4413
        }
×
4414
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4415
                return models.ChannelEdgeInfo{}, err
×
4416
        }
×
4417
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4418
                return models.ChannelEdgeInfo{}, err
×
4419
        }
×
4420
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4421
                return models.ChannelEdgeInfo{}, err
×
4422
        }
×
4423

4424
        featureBytes, err := wire.ReadVarBytes(r, 0, 900, "features")
3✔
4425
        if err != nil {
3✔
4426
                return models.ChannelEdgeInfo{}, err
×
4427
        }
×
4428

4429
        features := lnwire.NewRawFeatureVector()
3✔
4430
        err = features.Decode(bytes.NewReader(featureBytes))
3✔
4431
        if err != nil {
3✔
4432
                return models.ChannelEdgeInfo{}, fmt.Errorf("unable to decode "+
×
4433
                        "features: %w", err)
×
4434
        }
×
4435
        edgeInfo.Features = lnwire.NewFeatureVector(features, lnwire.Features)
3✔
4436

3✔
4437
        proof := &models.ChannelAuthProof{}
3✔
4438

3✔
4439
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4440
        if err != nil {
3✔
4441
                return models.ChannelEdgeInfo{}, err
×
4442
        }
×
4443
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4444
        if err != nil {
3✔
4445
                return models.ChannelEdgeInfo{}, err
×
4446
        }
×
4447
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4448
        if err != nil {
3✔
4449
                return models.ChannelEdgeInfo{}, err
×
4450
        }
×
4451
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4452
        if err != nil {
3✔
4453
                return models.ChannelEdgeInfo{}, err
×
4454
        }
×
4455

4456
        if !proof.IsEmpty() {
6✔
4457
                edgeInfo.AuthProof = proof
3✔
4458
        }
3✔
4459

4460
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4461
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4462
                return models.ChannelEdgeInfo{}, err
×
4463
        }
×
4464
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4465
                return models.ChannelEdgeInfo{}, err
×
4466
        }
×
4467
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4468
                return models.ChannelEdgeInfo{}, err
×
4469
        }
×
4470

4471
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4472
                return models.ChannelEdgeInfo{}, err
×
4473
        }
×
4474

4475
        // We'll try and see if there are any opaque bytes left, if not, then
4476
        // we'll ignore the EOF error and return the edge as is.
4477
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4478
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4479
        )
3✔
4480
        switch {
3✔
4481
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4482
        case errors.Is(err, io.EOF):
×
4483
        case err != nil:
×
4484
                return models.ChannelEdgeInfo{}, err
×
4485
        }
4486

4487
        return edgeInfo, nil
3✔
4488
}
4489

4490
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4491
        from, to []byte) error {
3✔
4492

3✔
4493
        var edgeKey [33 + 8]byte
3✔
4494
        copy(edgeKey[:], from)
3✔
4495
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4496

3✔
4497
        var b bytes.Buffer
3✔
4498
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
4499
                return err
×
4500
        }
×
4501

4502
        // Before we write out the new edge, we'll create a new entry in the
4503
        // update index in order to keep it fresh.
4504
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4505
        var indexKey [8 + 8]byte
3✔
4506
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4507
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4508

3✔
4509
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4510
        if err != nil {
3✔
4511
                return err
×
4512
        }
×
4513

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

3✔
4521
                // In order to delete the old entry, we'll need to obtain the
3✔
4522
                // *prior* update time in order to delete it. To do this, we'll
3✔
4523
                // need to deserialize the existing policy within the database
3✔
4524
                // (now outdated by the new one), and delete its corresponding
3✔
4525
                // entry within the update index. We'll ignore any
3✔
4526
                // ErrEdgePolicyOptionalFieldNotFound or ErrParsingExtraTLVBytes
3✔
4527
                // errors, as we only need the channel ID and update time to
3✔
4528
                // delete the entry.
3✔
4529
                //
3✔
4530
                // TODO(halseth): get rid of these invalid policies in a
3✔
4531
                // migration.
3✔
4532
                //
3✔
4533
                // NOTE: the above TODO was completed in the SQL migration and
3✔
4534
                // so such edge cases no longer need to be handled there.
3✔
4535
                oldEdgePolicy, err := deserializeChanEdgePolicy(
3✔
4536
                        bytes.NewReader(edgeBytes),
3✔
4537
                )
3✔
4538
                if err != nil &&
3✔
4539
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4540
                        !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4541

×
4542
                        return err
×
4543
                }
×
4544

4545
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4546

3✔
4547
                var oldIndexKey [8 + 8]byte
3✔
4548
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4549
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4550

3✔
4551
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4552
                        return err
×
4553
                }
×
4554
        }
4555

4556
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4557
                return err
×
4558
        }
×
4559

4560
        err = updateEdgePolicyDisabledIndex(
3✔
4561
                edges, edge.ChannelID,
3✔
4562
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4563
                edge.IsDisabled(),
3✔
4564
        )
3✔
4565
        if err != nil {
3✔
4566
                return err
×
4567
        }
×
4568

4569
        return edges.Put(edgeKey[:], b.Bytes())
3✔
4570
}
4571

4572
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4573
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4574
// one.
4575
// The direction represents the direction of the edge and disabled is used for
4576
// deciding whether to remove or add an entry to the bucket.
4577
// In general a channel is disabled if two entries for the same chanID exist
4578
// in this bucket.
4579
// Maintaining the bucket this way allows a fast retrieval of disabled
4580
// channels, for example when prune is needed.
4581
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4582
        direction bool, disabled bool) error {
3✔
4583

3✔
4584
        var disabledEdgeKey [8 + 1]byte
3✔
4585
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4586
        if direction {
6✔
4587
                disabledEdgeKey[8] = 1
3✔
4588
        }
3✔
4589

4590
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4591
                disabledEdgePolicyBucket,
3✔
4592
        )
3✔
4593
        if err != nil {
3✔
4594
                return err
×
4595
        }
×
4596

4597
        if disabled {
6✔
4598
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4599
        }
3✔
4600

4601
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4602
}
4603

4604
// putChanEdgePolicyUnknown marks the edge policy as unknown
4605
// in the edges bucket.
4606
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4607
        from []byte) error {
3✔
4608

3✔
4609
        var edgeKey [33 + 8]byte
3✔
4610
        copy(edgeKey[:], from)
3✔
4611
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4612

3✔
4613
        if edges.Get(edgeKey[:]) != nil {
3✔
4614
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4615
                        " when there is already a policy present", channelID)
×
4616
        }
×
4617

4618
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4619
}
4620

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

3✔
4624
        var edgeKey [33 + 8]byte
3✔
4625
        copy(edgeKey[:], nodePub)
3✔
4626
        copy(edgeKey[33:], chanID)
3✔
4627

3✔
4628
        edgeBytes := edges.Get(edgeKey[:])
3✔
4629
        if edgeBytes == nil {
3✔
4630
                return nil, ErrEdgeNotFound
×
4631
        }
×
4632

4633
        // No need to deserialize unknown policy.
4634
        if bytes.Equal(edgeBytes, unknownPolicy) {
6✔
4635
                return nil, nil
3✔
4636
        }
3✔
4637

4638
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4639

3✔
4640
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4641
        switch {
3✔
4642
        // If the db policy was missing an expected optional field, we return
4643
        // nil as if the policy was unknown.
UNCOV
4644
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
×
UNCOV
4645
                return nil, nil
×
4646

4647
        // If the policy contains invalid TLV bytes, we return nil as if
4648
        // the policy was unknown.
4649
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4650
                return nil, nil
×
4651

4652
        case err != nil:
×
4653
                return nil, err
×
4654
        }
4655

4656
        return ep, nil
3✔
4657
}
4658

4659
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4660
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4661
        error) {
3✔
4662

3✔
4663
        edgeInfo := edgeIndex.Get(chanID)
3✔
4664
        if edgeInfo == nil {
3✔
4665
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4666
                        chanID)
×
4667
        }
×
4668

4669
        // The first node is contained within the first half of the edge
4670
        // information. We only propagate the error here and below if it's
4671
        // something other than edge non-existence.
4672
        node1Pub := edgeInfo[:33]
3✔
4673
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4674
        if err != nil {
3✔
4675
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4676
                        node1Pub)
×
4677
        }
×
4678

4679
        // Similarly, the second node is contained within the latter
4680
        // half of the edge information.
4681
        node2Pub := edgeInfo[33:66]
3✔
4682
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4683
        if err != nil {
3✔
4684
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4685
                        node2Pub)
×
4686
        }
×
4687

4688
        return edge1, edge2, nil
3✔
4689
}
4690

4691
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4692
        to []byte) error {
3✔
4693

3✔
4694
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4695
        if err != nil {
3✔
4696
                return err
×
4697
        }
×
4698

4699
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4700
                return err
×
4701
        }
×
4702

4703
        var scratch [8]byte
3✔
4704
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4705
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4706
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4707
                return err
×
4708
        }
×
4709

4710
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
3✔
4711
                return err
×
4712
        }
×
4713
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
3✔
4714
                return err
×
4715
        }
×
4716
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
3✔
4717
                return err
×
4718
        }
×
4719
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
3✔
4720
                return err
×
4721
        }
×
4722
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
3✔
4723
        if err != nil {
3✔
4724
                return err
×
4725
        }
×
4726
        err = binary.Write(
3✔
4727
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
3✔
4728
        )
3✔
4729
        if err != nil {
3✔
4730
                return err
×
4731
        }
×
4732

4733
        if _, err := w.Write(to); err != nil {
3✔
4734
                return err
×
4735
        }
×
4736

4737
        // If the max_htlc field is present, we write it. To be compatible with
4738
        // older versions that wasn't aware of this field, we write it as part
4739
        // of the opaque data.
4740
        // TODO(halseth): clean up when moving to TLV.
4741
        var opaqueBuf bytes.Buffer
3✔
4742
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4743
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4744
                if err != nil {
3✔
4745
                        return err
×
4746
                }
×
4747
        }
4748

4749
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4750
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4751
        }
×
4752
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4753
                return err
×
4754
        }
×
4755

4756
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4757
                return err
×
4758
        }
×
4759

4760
        return nil
3✔
4761
}
4762

4763
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
3✔
4764
        // Deserialize the policy. Note that in case an optional field is not
3✔
4765
        // found or if the edge has invalid TLV data, then both an error and a
3✔
4766
        // populated policy object are returned so that the caller can decide
3✔
4767
        // if it still wants to use the edge or not.
3✔
4768
        edge, err := deserializeChanEdgePolicyRaw(r)
3✔
4769
        if err != nil &&
3✔
4770
                !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
3✔
4771
                !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4772

×
4773
                return nil, err
×
4774
        }
×
4775

4776
        return edge, err
3✔
4777
}
4778

4779
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4780
        error) {
3✔
4781

3✔
4782
        edge := &models.ChannelEdgePolicy{}
3✔
4783

3✔
4784
        var err error
3✔
4785
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4786
        if err != nil {
3✔
4787
                return nil, err
×
4788
        }
×
4789

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

4794
        var scratch [8]byte
3✔
4795
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4796
                return nil, err
×
4797
        }
×
4798
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4799
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4800

3✔
4801
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4802
                return nil, err
×
4803
        }
×
4804
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4805
                return nil, err
×
4806
        }
×
4807
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4808
                return nil, err
×
4809
        }
×
4810

4811
        var n uint64
3✔
4812
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4813
                return nil, err
×
4814
        }
×
4815
        edge.MinHTLC = lnwire.MilliSatoshi(n)
3✔
4816

3✔
4817
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4818
                return nil, err
×
4819
        }
×
4820
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
4821

3✔
4822
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4823
                return nil, err
×
4824
        }
×
4825
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4826

3✔
4827
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4828
                return nil, err
×
4829
        }
×
4830

4831
        // We'll try and see if there are any opaque bytes left, if not, then
4832
        // we'll ignore the EOF error and return the edge as is.
4833
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4834
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4835
        )
3✔
4836
        switch {
3✔
4837
        case errors.Is(err, io.ErrUnexpectedEOF):
×
UNCOV
4838
        case errors.Is(err, io.EOF):
×
4839
        case err != nil:
×
4840
                return nil, err
×
4841
        }
4842

4843
        // See if optional fields are present.
4844
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4845
                // The max_htlc field should be at the beginning of the opaque
3✔
4846
                // bytes.
3✔
4847
                opq := edge.ExtraOpaqueData
3✔
4848

3✔
4849
                // If the max_htlc field is not present, it might be old data
3✔
4850
                // stored before this field was validated. We'll return the
3✔
4851
                // edge along with an error.
3✔
4852
                if len(opq) < 8 {
3✔
UNCOV
4853
                        return edge, ErrEdgePolicyOptionalFieldNotFound
×
UNCOV
4854
                }
×
4855

4856
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4857
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4858

3✔
4859
                // Exclude the parsed field from the rest of the opaque data.
3✔
4860
                edge.ExtraOpaqueData = opq[8:]
3✔
4861
        }
4862

4863
        // Attempt to extract the inbound fee from the opaque data. If we fail
4864
        // to parse the TLV here, we return an error we also return the edge
4865
        // so that the caller can still use it. This is for backwards
4866
        // compatibility in case we have already persisted some policies that
4867
        // have invalid TLV data.
4868
        var inboundFee lnwire.Fee
3✔
4869
        typeMap, err := edge.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
4870
        if err != nil {
3✔
4871
                return edge, fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
4872
        }
×
4873

4874
        val, ok := typeMap[lnwire.FeeRecordType]
3✔
4875
        if ok && val == nil {
6✔
4876
                edge.InboundFee = fn.Some(inboundFee)
3✔
4877
        }
3✔
4878

4879
        return edge, nil
3✔
4880
}
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